-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecution.go
More file actions
116 lines (101 loc) · 3.29 KB
/
execution.go
File metadata and controls
116 lines (101 loc) · 3.29 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
// Package concurrent provides utilities for executing multiple functions concurrently
// with error propagation, context cancellation, and panic recovery.
package concurrent
import (
"context"
"errors"
"fmt"
"sync"
)
// Func is a generic function type that accepts a context and returns a value of type T and an error.
type Func[T any] func(ctx context.Context) (T, error)
// ExecuteConcurrently executes multiple functions concurrently and collects their results.
//
// All functions receive a shared cancellable context. When any function returns an error
// or panics, the context is canceled to signal other goroutines to stop.
//
// Returns a map of results indexed by the provided keys, and the first causal error
// encountered (preferring real errors over context cancellation errors).
// If a function panics, the panic is recovered and converted to an error.
//
// Note: Only the first causal (non-context) error is returned. Secondary errors from other goroutines are discarded.
func ExecuteConcurrently[T any](ctx context.Context, funcs map[string]Func[T]) (map[string]T, error) {
for key, fn := range funcs {
if fn == nil {
return nil, fmt.Errorf("nil function provided for key %q", key)
}
}
ctxWithCancel, cancel := context.WithCancel(ctx)
defer cancel()
var wg sync.WaitGroup
wg.Add(len(funcs))
type result struct {
key string
value T
err error
}
resultCh := make(chan result, len(funcs))
for key, fn := range funcs {
go func(key string, fn Func[T]) {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
resultCh <- result{key: key, err: fmt.Errorf("panic in %q: %w", key, err)}
} else {
resultCh <- result{key: key, err: fmt.Errorf("panic in %q: %v", key, r)}
}
cancel()
}
}()
value, err := fn(ctxWithCancel)
resultCh <- result{key: key, value: value, err: err}
if err != nil {
cancel()
}
}(key, fn)
}
// The closer goroutine waits for all workers to complete before closing the channel.
// It terminates when all worker goroutines exit (which happens when context is canceled).
go func() {
wg.Wait()
close(resultCh)
}()
results := make(map[string]T)
var firstErr error
for res := range resultCh {
if res.err != nil {
// Prefer causal errors over context cancellation errors.
if firstErr == nil || (isContextErr(firstErr) && !isContextErr(res.err)) {
firstErr = res.err
}
} else {
results[res.key] = res.value
}
}
if firstErr != nil {
return nil, firstErr
}
return results, nil
}
// isContextErr reports whether the error is a context cancellation or deadline error.
func isContextErr(err error) bool {
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
// ExecuteConcurrentlyTyped executes multiple functions concurrently and transforms
// the results into a typed struct using the provided resultBuilder function.
//
// This is a more type-safe alternative to ExecuteConcurrently when you know the
// exact structure of the results.
func ExecuteConcurrentlyTyped[T any, R any](
ctx context.Context,
resultBuilder func(map[string]T) (R, error),
funcs map[string]Func[T],
) (R, error) {
var zero R
results, err := ExecuteConcurrently(ctx, funcs)
if err != nil {
return zero, err
}
return resultBuilder(results)
}