-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch.go
More file actions
129 lines (99 loc) · 2.24 KB
/
batch.go
File metadata and controls
129 lines (99 loc) · 2.24 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
package batchify
import (
"sync"
"time"
"github.com/samber/lo"
)
func newBatch[I comparable, O any](
bufferSize int,
ttl time.Duration,
do func([]I) (map[I]O, error),
) *batchImpl[I, O] {
b := &batchImpl[I, O]{
timer: nil,
mu: sync.RWMutex{},
// read-only
bufferSize: bufferSize,
ttl: ttl,
do: do,
buffer: newBuffer[I, O](bufferSize),
}
b.resetTimer()
return b
}
var _ Batch[string, int] = (*batchImpl[string, int])(nil)
type batchImpl[I comparable, O any] struct {
timer *time.Timer
mu sync.RWMutex
bufferSize int
ttl time.Duration
do func([]I) (map[I]O, error)
buffer *buffer[I, O]
}
func (b *batchImpl[I, O]) Do(input I) (output O, err error) {
b.mu.Lock()
currentBuffer := b.buffer
if _, ok := currentBuffer.values[input]; !ok {
currentBuffer.values[input] = lo.Empty[O]()
currentBuffer.size++
}
bufferIsFull := currentBuffer.size == b.bufferSize
if bufferIsFull {
b.buffer = newBuffer[I, O](b.bufferSize)
b.resetTimer()
}
b.mu.Unlock()
if bufferIsFull {
b.execCallback(currentBuffer)
}
// do not call wg.Wait() if `input` is the last element of the buffer
currentBuffer.wg.Wait()
// outputs[input] might be empty
return currentBuffer.values[input], currentBuffer.err
}
func (b *batchImpl[I, O]) Stop() {
if b.timer != nil {
b.timer.Stop()
}
b.mu.Lock()
b.timer = nil
currentBuffer := b.buffer
b.buffer = newBuffer[I, O](b.bufferSize)
b.mu.Unlock()
b.execCallback(currentBuffer)
currentBuffer.wg.Wait()
}
func (b *batchImpl[I, O]) Flush() {
b.mu.Lock()
currentBuffer := b.buffer
if currentBuffer.size == 0 {
b.resetTimer()
b.mu.Unlock()
return
}
b.buffer = newBuffer[I, O](b.bufferSize)
b.resetTimer()
b.mu.Unlock()
b.execCallback(currentBuffer)
}
// execCallback must be called out of mutex lock to prevent slowdown due to long-running callback.
func (b *batchImpl[I, O]) execCallback(buffer *buffer[I, O]) {
go buffer.once.Do(func() {
if buffer.size > 0 {
buffer.values, buffer.err = b.do(lo.Keys(buffer.values))
}
buffer.wg.Done()
})
}
func (b *batchImpl[I, O]) resetTimer() {
if b.ttl == 0 {
return
}
if b.timer != nil {
b.timer.Reset(b.ttl)
} else {
b.timer = time.AfterFunc(b.ttl, func() {
b.Flush()
})
}
}