-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.go
More file actions
435 lines (391 loc) · 11.6 KB
/
Copy pathexecutor.go
File metadata and controls
435 lines (391 loc) · 11.6 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package executor
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
)
// ErrTaskSkipped is wrapped in the error passed to OnTaskFinish when a task is
// skipped because one of its dependencies failed (the task itself never ran).
var ErrTaskSkipped = errors.New("dependency failed")
// ExecutorOptions configures the executor
type ExecutorOptions struct {
MaxParallelization int // 0 = unlimited
// OnTaskStart is called just before a task begins executing.
OnTaskStart func(name string)
// OnTaskFinish is called when a task succeeds, fails, or is skipped.
// err is nil on success.
OnTaskFinish func(name string, err error, elapsed time.Duration)
// OnTaskReset is called when a task is re-queued for retry via RetryChannel.
OnTaskReset func(name string)
}
// Executor runs tasks with dependency resolution, parallelization, and retry
type Executor struct {
tasks map[string]*taskRun
dependents map[string][]string // task name → names of tasks that depend on it
outputHandler OutputHandler
opts ExecutorOptions
retryReqCh <-chan []string // receives batches of task names to re-queue mid-run
}
// NewExecutor creates an Executor from a list of tasks
func NewExecutor(tasks []Task, opts ExecutorOptions) (*Executor, error) {
if err := ValidateNoCycles(tasks); err != nil {
return nil, err
}
runs := make(map[string]*taskRun, len(tasks))
deps := make(map[string][]string, len(tasks))
for _, t := range tasks {
runs[t.Name] = &taskRun{
task: t,
status: statusPending,
attempt: 0,
}
for _, need := range t.Needs {
deps[need] = append(deps[need], t.Name)
}
}
return &Executor{
tasks: runs,
dependents: deps,
outputHandler: NoopOutputHandler{},
opts: opts,
}, nil
}
// WithRetryChannel sets a channel the caller can write task names into to re-queue
// failed tasks while Execute is running. Skipped dependents are re-queued automatically.
func (e *Executor) WithRetryChannel(ch <-chan []string) *Executor {
e.retryReqCh = ch
return e
}
// WithPreCompleted marks tasks as already completed before Execute is called.
// Succeeded and failed tasks are counted as finished from the start, allowing the
// executor to be created with a full task set while only running a subset.
func (e *Executor) WithPreCompleted(succeeded, failed []string) *Executor {
for _, name := range succeeded {
if run, ok := e.tasks[name]; ok {
run.status = statusSuccess
}
}
for _, name := range failed {
if run, ok := e.tasks[name]; ok {
run.status = statusFailed
}
}
return e
}
// WithOutputHandler sets the output handler for all tasks
func (e *Executor) WithOutputHandler(h OutputHandler) *Executor {
e.outputHandler = h
return e
}
// Execute runs all tasks respecting dependencies and returns the first error if any fail
func (e *Executor) Execute(ctx context.Context) error {
completionCh := make(chan CommandResult, len(e.tasks)*2)
outputCh := make(chan Output, 2000)
// internalRetryCh receives tasks whose retry delay has elapsed, ready to be re-queued.
// Using a channel ensures status mutations only happen on the main goroutine, avoiding data races.
internalRetryCh := make(chan *taskRun, len(e.tasks))
// executorDone is closed when Execute returns, allowing background goroutines to detect
// shutdown and avoid writing to channels that are no longer being read.
executorDone := make(chan struct{})
defer close(executorDone)
// Semaphore for max parallelization
var semaphore chan struct{}
if e.opts.MaxParallelization > 0 {
semaphore = make(chan struct{}, e.opts.MaxParallelization)
}
// Count pre-completed tasks before starting anything. startReadyTasks marks
// dependency-skipped tasks as failed *and* reports them on completionCh, so
// counting after it would count those tasks twice and end the run early.
finished := 0
for _, run := range e.tasks {
if run.status == statusSuccess || run.status == statusFailed {
finished++
}
}
total := len(e.tasks)
if err := e.startReadyTasks(ctx, completionCh, outputCh, semaphore, executorDone); err != nil {
return err
}
if err := e.ensureProgress(); err != nil {
return err
}
drainStop := make(chan struct{})
drainDone := make(chan struct{})
go func() {
e.drainOutput(ctx, outputCh, drainStop)
close(drainDone)
}()
var errs []error
for finished < total {
retryReqCh := e.retryReqCh // nil disables the select case
select {
case result := <-completionCh:
run, exists := e.tasks[result.Name]
if !exists {
return fmt.Errorf("completion for unknown task: %s", result.Name)
}
if result.Success {
run.status = statusSuccess
finished++
} else {
// Check retry
maxAttempts := run.task.Retry.Attempts
if maxAttempts < 1 {
maxAttempts = 1
}
run.attempt++
if run.attempt < maxAttempts {
// Schedule retry: goroutine waits for the delay, then notifies the main loop
// via internalRetryCh so all status mutations stay on the main goroutine.
delay := parseRetryDelay(run.task.Retry.Delay, run.task.Retry.Backoff, run.attempt)
go func(r *taskRun, d time.Duration) {
time.Sleep(d)
select {
case internalRetryCh <- r:
case <-executorDone:
}
}(run, delay)
} else {
run.status = statusFailed
finished++
if result.Error != nil {
errs = append(errs, result.Error)
}
}
}
case r := <-internalRetryCh:
r.status = statusPending
if e.opts.OnTaskReset != nil {
e.opts.OnTaskReset(r.task.Name)
}
case names := <-retryReqCh:
count := e.resetForRetry(names)
finished -= count
}
if finished < total {
if err := e.startReadyTasks(ctx, completionCh, outputCh, semaphore, executorDone); err != nil {
return err
}
if err := e.ensureProgress(); err != nil {
return err
}
}
}
close(drainStop)
<-drainDone // wait for all output to be processed before returning
return errors.Join(errs...)
}
// startReadyTasks finds all pending tasks whose deps are satisfied and starts them
func (e *Executor) startReadyTasks(ctx context.Context, completionCh chan<- CommandResult, outputCh chan<- Output, sem chan struct{}, executorDone <-chan struct{}) error {
for name, run := range e.tasks {
if run.status != statusPending {
continue
}
// Check if any dep failed (skip this task permanently).
// This must be checked before depsSatisfied because a failed dep also
// causes depsSatisfied to return false, which would leave the task stuck.
if e.depsHaveFailed(name) {
run.status = statusFailed
run.skipped = true
skipErr := fmt.Errorf("task %q skipped: %w", name, ErrTaskSkipped)
if e.opts.OnTaskFinish != nil {
e.opts.OnTaskFinish(name, skipErr, 0)
}
completionCh <- CommandResult{
Name: name,
Success: false,
Error: skipErr,
}
continue
}
if !e.depsSatisfied(name) {
continue
}
run.status = statusRunning
run.startedAt = time.Now()
if e.opts.OnTaskStart != nil {
e.opts.OnTaskStart(run.task.Name)
}
go func(r *taskRun) {
if sem != nil {
sem <- struct{}{}
defer func() { <-sem }()
}
handler := ToChannelOutputHandler{OutputCh: outputCh}
err := r.task.ExecuteFn(ctx, r.task.Name, handler)
elapsed := time.Since(r.startedAt)
if err != nil {
if e.opts.OnTaskFinish != nil {
e.opts.OnTaskFinish(r.task.Name, err, elapsed)
}
select {
case completionCh <- CommandResult{
Name: r.task.Name,
Success: false,
Error: fmt.Errorf("task %s failed: %w", r.task.Name, err),
}:
case <-executorDone:
}
return
}
if e.opts.OnTaskFinish != nil {
e.opts.OnTaskFinish(r.task.Name, nil, elapsed)
}
select {
case completionCh <- CommandResult{
Name: r.task.Name,
Success: true,
}:
case <-executorDone:
}
}(run)
}
return nil
}
// resetForRetry re-queues the named failed tasks and cascades to any skipped dependents.
// Returns the number of tasks reset (caller must decrement its finished counter by this amount).
func (e *Executor) resetForRetry(names []string) int {
toReset := make(map[string]bool, len(names))
queue := make([]string, 0, len(names))
for _, name := range names {
run, ok := e.tasks[name]
if ok && run.status == statusFailed && !run.skipped {
toReset[name] = true
queue = append(queue, name)
}
}
// Cascade: also reset skipped dependents whose dep is being retried.
for len(queue) > 0 {
name := queue[0]
queue = queue[1:]
for _, dep := range e.dependents[name] {
depRun, ok := e.tasks[dep]
if !ok || toReset[dep] || !depRun.skipped {
continue
}
toReset[dep] = true
queue = append(queue, dep)
}
}
count := 0
for name := range toReset {
run := e.tasks[name]
run.attempt = 0
run.status = statusPending
run.skipped = false
run.startedAt = time.Time{}
count++
if e.opts.OnTaskReset != nil {
e.opts.OnTaskReset(name)
}
}
return count
}
func (e *Executor) depsSatisfied(name string) bool {
run := e.tasks[name]
for _, dep := range run.task.Needs {
depRun, ok := e.tasks[dep]
if !ok || depRun.status != statusSuccess {
return false
}
}
return true
}
func (e *Executor) depsHaveFailed(name string) bool {
run := e.tasks[name]
for _, dep := range run.task.Needs {
depRun, ok := e.tasks[dep]
if ok && depRun.status == statusFailed {
return true
}
}
return false
}
func (e *Executor) ensureProgress() error {
for _, run := range e.tasks {
if run.status == statusRunning || run.status == statusSuccess || run.status == statusFailed {
return nil
}
}
// Check if all remaining pending tasks are blocked by failed deps
for _, run := range e.tasks {
if run.status == statusPending {
if !e.depsHaveFailed(run.task.Name) {
return fmt.Errorf("deadlock: no tasks running but pending tasks exist: %s", e.pendingNames())
}
}
}
return nil
}
func (e *Executor) pendingNames() string {
var names []string
for name, run := range e.tasks {
if run.status == statusPending {
names = append(names, name)
}
}
return strings.Join(names, ", ")
}
// drainOutput forwards task output to the output handler until stop is closed or
// ctx is cancelled. outputCh is deliberately never closed: a task goroutine that
// outlives the run would panic sending on a closed channel, so it is left open
// and such a send is simply dropped once draining has stopped.
func (e *Executor) drainOutput(ctx context.Context, outputCh <-chan Output, stop <-chan struct{}) {
// Drain any lines already queued before exiting so the last output of a
// failing command is not lost.
flush := func(handlerCtx context.Context) {
for {
select {
case out := <-outputCh:
_ = e.outputHandler.HandleOutput(handlerCtx, out)
default:
return
}
}
}
for {
select {
case out := <-outputCh:
_ = e.outputHandler.HandleOutput(ctx, out)
case <-stop:
flush(ctx)
return
case <-ctx.Done():
flush(context.Background())
return
}
}
}
// parseRetryDelay computes the delay for a given attempt with the configured backoff
func parseRetryDelay(delayStr, backoff string, attempt int) time.Duration {
base := parseDuration(delayStr)
switch backoff {
case "exponential":
multiplier := time.Duration(1)
for i := 0; i < attempt; i++ {
multiplier *= 2
}
return base * multiplier
case "linear":
return base * time.Duration(attempt+1)
default: // "none" or empty
return base
}
}
func parseDuration(s string) time.Duration {
if s == "" {
return 5 * time.Second
}
// Try to parse as integer seconds first
if n, err := strconv.Atoi(strings.TrimSuffix(s, "s")); err == nil {
return time.Duration(n) * time.Second
}
d, err := time.ParseDuration(s)
if err != nil {
return 5 * time.Second
}
return d
}