-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmicrobatch.go
More file actions
125 lines (102 loc) · 2.3 KB
/
microbatch.go
File metadata and controls
125 lines (102 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
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
package microbatch
import (
"context"
"fmt"
"sync"
"time"
)
type Microbatch[T any] struct {
wg sync.WaitGroup
mu sync.Mutex
ctx context.Context
stop chan struct{}
isOpen bool
batchCtx context.Context
batchCancelCtx context.CancelFunc
batchTimeoutDuration time.Duration
eventStream chan Event[T]
ResultBatch chan Batch[T]
strategy FlushStrategy[T]
}
func (m *Microbatch[T]) Add(ctx context.Context, events ...T) error {
m.mu.Lock()
defer m.mu.Unlock()
if !m.isOpen {
return fmt.Errorf("%w: microbatch is closed", ErrCantAddJob)
}
for _, event := range events {
m.eventStream <- Event[T]{Payload: event, addedAt: time.Now()}
}
return nil
}
func (m *Microbatch[T]) Start() {
m.wg.Add(1)
go m.run()
}
func (m *Microbatch[T]) run() {
defer m.wg.Done()
batch := Batch[T]{}
flush := func() {
if len(batch) == 0 {
return
}
m.ResultBatch <- batch
batch = Batch[T]{}
}
for {
select {
case event, ok := <-m.eventStream:
if !ok {
return
}
batch = append(batch, event)
if !m.strategy.ShouldFlush(batch) {
continue
}
flush()
// TODO: implement context cancellation from m.ctx
case <-m.batchCtx.Done():
if len(batch) == 0 {
continue
}
flush()
m.batchCtx, m.batchCancelCtx = context.WithTimeout(m.ctx, m.batchTimeoutDuration)
case <-m.stop:
m.mu.Lock()
m.isOpen = false
m.mu.Unlock()
close(m.eventStream)
return
}
}
}
func (m *Microbatch[T]) Stop() {
close(m.stop)
m.wg.Wait()
}
type Config[T any] struct {
Strategy FlushStrategy[T]
BatchTimeout *time.Duration
}
func New[T any](ctx context.Context, p Config[T]) (*Microbatch[T], error) {
strategy := p.Strategy
if strategy == nil {
strategy = &SizeBasedStrategy[T]{MaxSize: defaultBatchMaxSize}
}
batchTimeout := defaultBatchTimeoutDuration
if p.BatchTimeout != nil {
batchTimeout = *p.BatchTimeout
}
batchCtx, batchCtxCancel := context.WithTimeout(ctx, batchTimeout)
return &Microbatch[T]{
ctx: ctx,
batchCtx: batchCtx,
batchCancelCtx: batchCtxCancel,
batchTimeoutDuration: batchTimeout,
stop: make(chan struct{}),
isOpen: true,
eventStream: make(chan Event[T]),
ResultBatch: make(chan Batch[T]),
strategy: strategy,
}, nil
}