GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — workflow/flow_group.go at main · ubgo/workflow Expand file tree/ Copy pathflow_group.goMore file actions 222 lines (206 loc) · 8.21 KB / Copy pathflow_group.goFile metadata and controls222 lines (206 loc) · 8.21 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 package workflow import ( "context" "encoding/json" "errors" "fmt" "maps" "slices" "strconv" "strings" "time" ) // GroupSeparator joins a group's name and a step's name ("import/fetch"). // //ds:def id=groupseparator-3b7ayafp owner=@khanakia stability=stable const GroupSeparator = "/" // Group returns steps as one named group (WP-15): each step is renamed // "<name>/<step>", its After inside the group renamed with it, the steps // with no parent inside the group wait on after, and a join step named // name waits on the group's last steps and carries their output (one last // step: its output; several: a JSON object keyed by their names inside the // group). Later steps put the group's name in After as they would a step. // The group is ordinary steps, so it runs on every driver; retries and // timeouts stay per step. A whole sub-workflow with its own retries and // run is a child run instead (Spawn and AwaitChild). // // It returns an error wrapping ErrInvalid when name is empty or contains // GroupSeparator, a step name repeats, or an After inside the group names // no step of the group. // //ds:def id=group-3weve9ng owner=@khanakia stability=stable func Group(name string, after []string, steps []Step) ([]Step, error) { if name == "" || strings.Contains(name, GroupSeparator) || len(steps) == 0 { return nil, invalidf("group %q needs a name without %q and at least one step", name, GroupSeparator) } inner := map[string]bool{} for _, s := range steps { if s.Name == "" || inner[s.Name] { return nil, invalidf("group %q: step name %q is empty or repeats", name, s.Name) } inner[s.Name] = true } hasChild := map[string]bool{} out := make([]Step, 0, len(steps)+1) for _, s := range steps { s.Name = name + GroupSeparator + s.Name if len(s.After) == 0 { s.After = slices.Clone(after) } else { parents := make([]string, len(s.After)) for i, p := range s.After { if !inner[p] { return nil, invalidf("group %q: step %q waits on %q, which is not in the group", name, s.Name, p) } hasChild[p] = true parents[i] = name + GroupSeparator + p } s.After = parents } out = append(out, s) } var last, lastInner []string for _, s := range steps { if !hasChild[s.Name] { last = append(last, name+GroupSeparator+s.Name) lastInner = append(lastInner, s.Name) } } join := func(_ context.Context, in []byte) ([]byte, error) { if len(last) == 1 { return in, nil } raw := map[string]json.RawMessage{} if err := json.Unmarshal(in, &raw); err != nil { return nil, Permanent(fmt.Errorf("workflow: group %q: join input does not decode: %w", name, err)) } vals := make(map[string][]byte, len(raw)) for i, l := range last { if v := raw[l]; string(v) != "null" { vals[lastInner[i]] = v } } return StepInput(nil, lastInner, vals), nil } return append(out, Step{Name: name, After: last, Run: join}), nil } // LabelDepth is the nesting depth RecursionLimit writes on a job enqueued // from inside a step: one more than the depth of the run whose step // enqueued it (a run enqueued from outside any step has depth 0). // //ds:def id=labeldepth-8jqw8k4j owner=@khanakia stability=stable const LabelDepth = LabelPrefixInternal + "depth" // ErrDepth matches the refusal of RecursionLimit: the job would nest // deeper than the limit. // //ds:def id=errdepth-vpx26s3r owner=@khanakia stability=stable var ErrDepth = errors.New("workflow: nesting depth limit reached") // recursionPlugin is RecursionLimit. type recursionPlugin struct{ max int } // RecursionLimit returns a plugin that bounds recursion (WC-22): a step // may enqueue its own workflow (or any other), directly or with Spawn, and // each job enqueued from inside a step gets LabelDepth one deeper than its // parent run's; a job past max is refused with an error matching ErrDepth // and ErrInvalid, so a runaway recursion stops instead of filling the // queue. A job enqueued outside a step (no StepInfo on the ctx) is depth // 0. It is enqueue middleware, so it runs on every driver; a job enqueued // through a client without the plugin carries no depth. // //ds:def id=recursionlimit-3vtvbeup owner=@khanakia stability=stable func RecursionLimit(max int) Plugin { return recursionPlugin{max: max} } func (p recursionPlugin) Name() string { return "recursion-limit" } //ds:def id=recursionplugin-enqueuemiddleware-j2fzv4hn owner=@khanakia stability=stable func (p recursionPlugin) EnqueueMiddleware() []EnqueueMiddleware { return []EnqueueMiddleware{func(next EnqueueFunc) EnqueueFunc { return func(ctx context.Context, job Job) (RunRef, error) { info, ok := StepInfoFrom(ctx) if !ok { return next(ctx, job) } depth := 1 if d, err := strconv.Atoi(info.Labels[LabelDepth]); err == nil { depth = d + 1 } if depth > p.max { return RunRef{}, fmt.Errorf("%w: %w: job of %q would be at depth %d, over %d (enqueued by run %s, step %q)", ErrInvalid, ErrDepth, job.Workflow, depth, p.max, info.RunID, info.Step) } job.Labels = maps.Clone(job.Labels) if job.Labels == nil { job.Labels = map[string]string{} } job.Labels[LabelDepth] = strconv.Itoa(depth) return next(AllowReservedLabels(ctx, LabelDepth), job) } }} } // endRunData is the run data name EndRun sets. const endRunData = "ubgo.workflow/ended" // EndRun ends the run early and successfully (WC-43): every step that has // not started yet is skipped (it returns a nil output without running), // so the run finishes as soon as the steps already running return. Call it // from a step, then return that step's output as usual. It needs the // Journal plugin (it writes run data) and the EndRuns plugin, which does // the skipping; both run on every driver. Steps already running are not // cancelled: an explicit end is a decision, not an abort (Cancel is the // abort). A step skipped this way gives its children empty input, which // they skip too. // //ds:def id=endrun-m4p8qurp owner=@khanakia stability=stable func EndRun(ctx context.Context) error { return SetRunData(ctx, endRunData, true) } // endRunsPlugin is EndRuns. type endRunsPlugin struct{} // EndRuns returns the plugin that honours EndRun: step middleware that // skips a step of a run that has ended. Pass it to Use after Journal, so // the journal is on the ctx when it looks. // //ds:def id=endruns-yh863xn7 owner=@khanakia stability=stable func EndRuns() Plugin { return endRunsPlugin{} } func (endRunsPlugin) Name() string { return "end-runs" } //ds:def id=endrunsplugin-stepmiddleware-7fbyjspm owner=@khanakia stability=stable func (endRunsPlugin) StepMiddleware() []Middleware { return []Middleware{func(next Handler) Handler { return func(ctx context.Context, in []byte) ([]byte, error) { if _, err := journalFrom(ctx); err != nil { return next(ctx, in) } ended, _, err := RunData[bool](ctx, endRunData) if err != nil { return nil, err } if ended { return nil, nil } return next(ctx, in) } }} } // Boundary returns step middleware for a non-interrupting timer on a step // (WP-20): when the step is still running after d, onTimer is called once // (in its own goroutine, with the step's ctx and StepInfo) while the step // carries on: escalate, page someone, send a reminder. The interrupting // form is Step.Timeout, with WithRules to send the timeout to a branch // (RuleOneFailedOf(FailureTimeout)) on a driver with CapRunTimeout or on // the Hatchet driver (which enforces Step.Timeout in its worker), which // cancels the attempt with ErrStepTimeout for the tolerated step to record // (ClaimTimeout); elsewhere return TimeoutError from a deadline inside the // step. steps limits it to those step names; none means every step. The // timer is the step's own: it starts per attempt and stops when the // attempt returns. // //ds:def id=boundary-s3ak3b46 owner=@khanakia stability=stable func Boundary(d time.Duration, onTimer func(ctx context.Context, info StepInfo), steps ...string) Middleware { return func(next Handler) Handler { if d <= 0 || onTimer == nil { return next } return func(ctx context.Context, in []byte) ([]byte, error) { info, _ := StepInfoFrom(ctx) if len(steps) > 0 && !slices.Contains(steps, info.Step) { return next(ctx, in) } t := time.AfterFunc(d, func() { onTimer(ctx, info) }) defer t.Stop() return next(ctx, in) } } } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |