-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbatch.go
More file actions
344 lines (293 loc) · 8.65 KB
/
batch.go
File metadata and controls
344 lines (293 loc) · 8.65 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
package flyt
import (
"context"
"fmt"
"sync"
"time"
)
// BatchError aggregates multiple errors from batch operations.
type BatchError struct {
Errors []error
}
func (e *BatchError) Error() string {
if len(e.Errors) == 0 {
return "batch: no errors recorded"
}
if len(e.Errors) == 1 {
return fmt.Sprintf("batch: %v", e.Errors[0])
}
return fmt.Sprintf("batch: %d errors occurred, first: %v", len(e.Errors), e.Errors[0])
}
// BatchNode is a marker type that indicates batch processing.
// It embeds CustomNode and works exactly like a regular node,
// but the framework handles it specially.
type BatchNode struct {
*CustomNode
batchPrepFunc func(context.Context, *SharedStore) ([]Result, error)
batchPostFunc func(context.Context, *SharedStore, []Result, []Result) (Action, error)
}
// Prep delegates to batchPrepFunc if set
func (n *BatchNode) Prep(ctx context.Context, shared *SharedStore) (any, error) {
if n.batchPrepFunc != nil {
return n.batchPrepFunc(ctx, shared)
}
// Fallback to CustomNode's Prep
return n.CustomNode.Prep(ctx, shared)
}
// Post handles batch results
func (n *BatchNode) Post(ctx context.Context, shared *SharedStore, prepResult, execResult any) (Action, error) {
if n.batchPostFunc != nil {
prep := prepResult.([]Result)
exec := execResult.([]Result)
return n.batchPostFunc(ctx, shared, prep, exec)
}
return DefaultAction, nil
}
// BatchNodeBuilder provides fluent interface for BatchNode
type BatchNodeBuilder struct {
*BatchNode
}
// NewBatchNode creates a new batch node with fluent interface
// Usage: flyt.NewBatchNode() from outside the package
func NewBatchNode(opts ...any) *BatchNodeBuilder {
customNode := &CustomNode{
BaseNode: NewBaseNode(),
}
// Process options (similar to NewNode)
var baseOpts []NodeOption
for _, opt := range opts {
switch o := opt.(type) {
case NodeOption:
baseOpts = append(baseOpts, o)
case func(*BaseNode):
baseOpts = append(baseOpts, NodeOption(o))
}
}
for _, opt := range baseOpts {
opt(customNode.BaseNode)
}
return &BatchNodeBuilder{
BatchNode: &BatchNode{CustomNode: customNode},
}
}
// Implement Node interface
func (b *BatchNodeBuilder) Prep(ctx context.Context, shared *SharedStore) (any, error) {
return b.BatchNode.Prep(ctx, shared)
}
func (b *BatchNodeBuilder) Exec(ctx context.Context, prepResult any) (any, error) {
return b.BatchNode.Exec(ctx, prepResult)
}
func (b *BatchNodeBuilder) Post(ctx context.Context, shared *SharedStore, prepResult, execResult any) (Action, error) {
return b.BatchNode.Post(ctx, shared, prepResult, execResult)
}
// Fluent configuration methods
func (b *BatchNodeBuilder) WithMaxRetries(retries int) *BatchNodeBuilder {
WithMaxRetries(retries)(b.BaseNode)
return b
}
func (b *BatchNodeBuilder) WithWait(wait time.Duration) *BatchNodeBuilder {
WithWait(wait)(b.BaseNode)
return b
}
func (b *BatchNodeBuilder) WithBatchConcurrency(n int) *BatchNodeBuilder {
b.batchConcurrency = n
return b
}
func (b *BatchNodeBuilder) WithBatchErrorHandling(continueOnError bool) *BatchNodeBuilder {
if continueOnError {
b.batchErrorHandling = "continue"
} else {
b.batchErrorHandling = "stop"
}
return b
}
// Note: When used from outside the package, these will be:
// - func(context.Context, *flyt.SharedStore) ([]flyt.Result, error)
// - func(context.Context, flyt.Result) (flyt.Result, error)
// - func(context.Context, *flyt.SharedStore, []flyt.Result, []flyt.Result) (flyt.Action, error)
func (b *BatchNodeBuilder) WithPrepFunc(fn func(context.Context, *SharedStore) ([]Result, error)) *BatchNodeBuilder {
b.batchPrepFunc = fn
return b
}
func (b *BatchNodeBuilder) WithExecFunc(fn func(context.Context, Result) (Result, error)) *BatchNodeBuilder {
b.execFunc = fn
return b
}
func (b *BatchNodeBuilder) WithPostFunc(fn func(context.Context, *SharedStore, []Result, []Result) (Action, error)) *BatchNodeBuilder {
b.batchPostFunc = fn
return b
}
// Alternative: WithExecFuncAny for compatibility
func (b *BatchNodeBuilder) WithExecFuncAny(fn func(context.Context, any) (any, error)) *BatchNodeBuilder {
b.execFunc = func(ctx context.Context, prepResult Result) (Result, error) {
val, err := fn(ctx, prepResult.Value())
if err != nil {
return Result{}, err
}
return NewResult(val), nil
}
return b
}
// runBatch handles the execution of batch nodes
func runBatch(ctx context.Context, node Node, shared *SharedStore) (Action, error) {
// Prep phase - returns []Result
prepResult, err := node.Prep(ctx, shared)
if err != nil {
return "", fmt.Errorf("run: prep failed: %w", err)
}
// Convert to []Result
var items []Result
switch v := prepResult.(type) {
case []Result:
items = v
case []any:
items = make([]Result, len(v))
for i, item := range v {
items[i] = NewResult(item)
}
default:
// Try to convert using ToSlice
slice := ToSlice(prepResult)
items = make([]Result, len(slice))
for i, item := range slice {
items[i] = NewResult(item)
}
}
if len(items) == 0 {
// No items to process
action, err := node.Post(ctx, shared, []Result{}, []Result{})
if err != nil {
return "", fmt.Errorf("run: post failed: %w", err)
}
return action, nil
}
// Get batch configuration
var concurrency int
var errorHandling = "continue"
if baseNode, ok := node.(*BaseNode); ok {
concurrency = baseNode.GetBatchConcurrency()
errorHandling = baseNode.GetBatchErrorHandling()
} else if customNode, ok := node.(*CustomNode); ok {
concurrency = customNode.GetBatchConcurrency()
errorHandling = customNode.GetBatchErrorHandling()
} else if batchNode, ok := node.(*BatchNode); ok {
concurrency = batchNode.GetBatchConcurrency()
errorHandling = batchNode.GetBatchErrorHandling()
} else if batchBuilder, ok := node.(*BatchNodeBuilder); ok {
concurrency = batchBuilder.GetBatchConcurrency()
errorHandling = batchBuilder.GetBatchErrorHandling()
}
// Execute items
results := make([]Result, len(items))
if concurrency > 0 {
runBatchConcurrent(ctx, node, items, results, concurrency, errorHandling)
} else {
runBatchSequential(ctx, node, items, results, errorHandling)
}
// Post phase - called once with all results
action, err := node.Post(ctx, shared, items, results)
if err != nil {
return "", fmt.Errorf("run: post failed: %w", err)
}
if action == "" {
action = DefaultAction
}
return action, nil
}
func runBatchSequential(ctx context.Context, node Node, items []Result, results []Result, errorHandling string) {
for i, item := range items {
if ctx.Err() != nil {
results[i] = NewErrorResult(fmt.Errorf("context cancelled"))
if errorHandling == "stop" {
break
}
continue
}
execResult, err := runExecWithRetries(ctx, node, item)
if err != nil {
results[i] = NewErrorResult(err)
if errorHandling == "stop" {
break
}
} else {
if r, ok := execResult.(Result); ok {
results[i] = r
} else {
results[i] = NewResult(execResult)
}
}
}
}
func runBatchConcurrent(ctx context.Context, node Node, items []Result, results []Result, concurrency int, errorHandling string) {
pool := NewWorkerPool(concurrency)
defer pool.Close()
var mu sync.Mutex
shouldStop := false
for i, item := range items {
idx := i
itm := item
pool.Submit(func() {
mu.Lock()
if shouldStop && errorHandling == "stop" {
results[idx] = NewErrorResult(fmt.Errorf("batch stopped due to error"))
mu.Unlock()
return
}
mu.Unlock()
if ctx.Err() != nil {
results[idx] = NewErrorResult(fmt.Errorf("context cancelled"))
return
}
execResult, err := runExecWithRetries(ctx, node, itm)
mu.Lock()
if err != nil {
results[idx] = NewErrorResult(err)
if errorHandling == "stop" {
shouldStop = true
}
} else {
if r, ok := execResult.(Result); ok {
results[idx] = r
} else {
results[idx] = NewResult(execResult)
}
}
mu.Unlock()
})
}
pool.Wait()
}
func runExecWithRetries(ctx context.Context, node Node, item Result) (any, error) {
// Get retry settings
var maxRetries = 1
var wait time.Duration = 0
if retryable, ok := node.(RetryableNode); ok {
maxRetries = retryable.GetMaxRetries()
wait = retryable.GetWait()
}
var execResult any
var execErr error
for attempt := 0; attempt < maxRetries; attempt++ {
if ctx.Err() != nil {
return nil, fmt.Errorf("context cancelled during retry: %w", ctx.Err())
}
if attempt > 0 && wait > 0 {
select {
case <-time.After(wait):
case <-ctx.Done():
return nil, fmt.Errorf("context cancelled during wait: %w", ctx.Err())
}
}
execResult, execErr = node.Exec(ctx, item)
if execErr == nil {
break
}
}
if execErr != nil {
if fallback, ok := node.(FallbackNode); ok {
return fallback.ExecFallback(item, execErr)
}
return nil, execErr
}
return execResult, nil
}