-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
94 lines (86 loc) · 2.3 KB
/
helpers.go
File metadata and controls
94 lines (86 loc) · 2.3 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
package workers
import "time"
// EveryInterval wraps fn in a ticker loop that calls fn at the given interval.
// Returns when ctx is cancelled. If fn returns an error, EveryInterval returns
// that error (the supervisor decides whether to restart based on WithRestart).
func EveryInterval(d time.Duration, fn func(WorkerContext) error) func(WorkerContext) error {
return func(ctx WorkerContext) error {
ticker := time.NewTicker(d)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if err := fn(ctx); err != nil {
return err
}
}
}
}
}
// ChannelWorker consumes items from ch one at a time, calling fn for each.
// Returns when ctx is cancelled or ch is closed.
func ChannelWorker[T any](ch <-chan T, fn func(WorkerContext, T) error) func(WorkerContext) error {
return func(ctx WorkerContext) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case item, ok := <-ch:
if !ok {
return nil // channel closed
}
if err := fn(ctx, item); err != nil {
return err
}
}
}
}
}
// BatchChannelWorker collects items from ch into batches and calls fn when
// either the batch reaches maxSize or maxDelay elapses since the first item
// in the current batch — whichever comes first. Flushes any partial batch
// on context cancellation or channel close before returning.
func BatchChannelWorker[T any](ch <-chan T, maxSize int, maxDelay time.Duration, fn func(WorkerContext, []T) error) func(WorkerContext) error {
return func(ctx WorkerContext) error {
batch := make([]T, 0, maxSize)
timer := time.NewTimer(maxDelay)
timer.Stop() // don't start until first item
flush := func() error {
if len(batch) == 0 {
return nil
}
err := fn(ctx, batch)
batch = batch[:0]
return err
}
for {
select {
case <-ctx.Done():
// Flush remaining items before exit.
_ = flush()
return ctx.Err()
case item, ok := <-ch:
if !ok {
// Channel closed — flush and return.
return flush()
}
if len(batch) == 0 {
timer.Reset(maxDelay)
}
batch = append(batch, item)
if len(batch) >= maxSize {
timer.Stop()
if err := flush(); err != nil {
return err
}
}
case <-timer.C:
if err := flush(); err != nil {
return err
}
}
}
}
}