-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatcher.go
105 lines (81 loc) · 1.75 KB
/
batcher.go
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
package batchease
import (
"sync"
"time"
)
type HandleFunc[T any] func(worker *Worker[T], data []T)
type Batcher[T any] struct {
// Size per batch
size int
// wait time before items processed
wait time.Duration
// items to be processed
items []T
// slice of available workers
workers []*Worker[T]
// maximum workers size the batcher has
workerSize int
// current active worker, selected by load balancer
currentWorker *Worker[T]
// load balancer, to determine who process the items
loadBalancer LoadBalancer[T]
mutex *sync.Mutex
}
func New[T any](opts ...BatcherOption[T]) (*Batcher[T], error) {
instance := Batcher[T]{
items: []T{},
mutex: &sync.Mutex{},
}
if len(opts) == 0 {
opts = append(opts, WithDefaultConfig[T]())
}
for _, opt := range opts {
if err := opt(&instance); err != nil {
return &Batcher[T]{}, err
}
}
return &instance, nil
}
func (b *Batcher[T]) AddWorker(w *Worker[T]) error {
b.workers = append(b.workers, w)
b.workerSize++
return nil
}
func (b *Batcher[T]) AddItem(item T) {
b.mutex.Lock()
defer b.mutex.Unlock()
// TODO: middlewares
b.items = append(b.items, item)
if len(b.items) >= b.size {
b.doWork()
}
}
func (b *Batcher[T]) SetHandleFn(handleFn HandleFunc[T]) {
b.mutex.Lock()
defer b.mutex.Unlock()
for _, worker := range b.workers {
worker.handleFn = handleFn
}
}
func (b *Batcher[T]) Run() {
for range time.Tick(b.wait) {
b.mutex.Lock()
b.doWork()
b.mutex.Unlock()
}
}
func (b *Batcher[T]) Shutdown() {
b.mutex.Lock()
defer b.mutex.Unlock()
b.doWork()
}
func (b *Batcher[T]) doWork() {
if len(b.items) == 0 {
return
}
go func(w Worker[T], data []T) {
w.do(data)
}(*b.currentWorker, b.items)
b.currentWorker = b.loadBalancer.Resolve(b.workers)
b.items = []T{}
}