-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
91 lines (78 loc) · 1.44 KB
/
main.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
package microbatching
import (
"log"
"sync"
"time"
)
type JobResult int
const (
OK = 0
BUSY = 1
)
type BatchProcessor func([]int) error
type Batcher struct {
sync.RWMutex
incoming chan int
done chan struct{}
buffer []int
outgoing BatchProcessor
freq *time.Ticker
}
func NewBatcher(size int, freq time.Duration, processor BatchProcessor) *Batcher {
b := Batcher{
incoming: make(chan int, 1),
done: make(chan struct{}),
buffer: make([]int, 0, size),
outgoing: processor,
freq: time.NewTicker(freq),
}
go func() {
for {
select {
case incoming := <-b.incoming:
b.Lock()
b.buffer = append(b.buffer, incoming)
b.Unlock()
if len(b.buffer) >= size {
log.Println("flushing due to limit")
b.flush()
b.freq.Reset(freq)
}
case <-b.freq.C:
log.Println("flushing due to timeout")
b.flush()
case <-b.done:
log.Println("flushing due to shutdown")
close(b.incoming)
b.freq.Stop()
b.flush()
close(b.done)
return
}
}
}()
return &b
}
func (b *Batcher) flush() {
if len(b.buffer) == 0 {
return
}
b.Lock()
defer b.Unlock()
if err := b.outgoing(b.buffer); err != nil {
log.Println("error submitting batch", err)
}
b.buffer = b.buffer[:0]
}
func (b *Batcher) Submit(payload int) JobResult {
select {
case b.incoming <- payload:
return OK
default:
return BUSY
}
}
func (b *Batcher) Shutdown() {
b.done <- struct{}{}
<-b.done
}