-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallel_slice_action.go
More file actions
75 lines (64 loc) · 1.97 KB
/
parallel_slice_action.go
File metadata and controls
75 lines (64 loc) · 1.97 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
package chain
import (
"context"
"fmt"
internalErrors "github.com/JSYoo5B/chain/internal/errors"
"github.com/JSYoo5B/chain/internal/logger"
"runtime/debug"
"sync"
)
// AsParallelSliceAction creates an Action that processes a slice's elements in parallel.
// Each element is transformed by the given action concurrently, maintaining the original order.
//
// The action handles panics gracefully, continuing execution of other goroutines
// when one fails. If any error or panic occurs, the action returns an error
// but still provides the processed output for successful operations.
func AsParallelSliceAction[T any](name string, action Action[T]) Action[[]T] {
if action == nil {
panic("action cannot be nil")
}
return ¶llelSliceAction[T]{
name: name,
action: action,
}
}
type parallelSliceAction[T any] struct {
name string
action Action[T]
}
func (p parallelSliceAction[T]) Name() string { return p.name }
func (p parallelSliceAction[T]) Run(ctx context.Context, input []T) (output []T, err error) {
pCtx := logger.WithRunnerDepth(ctx, p.name)
output = make([]T, len(input))
copy(output, input)
wg := sync.WaitGroup{}
wg.Add(len(input))
runIndex := func(i int, in T) {
logger.Debugf(pCtx, "chain: running index %d", i)
c := logger.WithRunnerDepth(ctx, fmt.Sprintf("%s[%d]/%s", p.name, i, p.action.Name()))
runnerName, _ := logger.RunnerNameFromContext(c)
// Wrap panic handling for safe running in an action
defer func() {
if panicErr := recover(); panicErr != nil {
logger.Errorf(pCtx, "chain: panic occurred on running index %d, caused by %v", i, panicErr)
debug.PrintStack()
output[i] = in
err = internalErrors.NewPanicError(runnerName, panicErr)
wg.Done()
return
}
}()
out, e := p.action.Run(c, in)
if e != nil {
logger.Errorf(pCtx, "chain: error occurred in index %d: %v", i, e)
err = e
}
output[i] = out
wg.Done()
}
for i, in := range input {
go runIndex(i, in)
}
wg.Wait()
return output, err
}