-
Notifications
You must be signed in to change notification settings - Fork 0
/
batcher.go
112 lines (90 loc) · 1.99 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
106
107
108
109
110
111
112
package batcher
import (
"errors"
"sync"
"time"
)
type Function func(data []interface{}) bool
type BatchConfig struct {
MaxCapacity int
WaitTime time.Duration
function Function
batchChan chan interface{}
mutex sync.RWMutex
}
//Initialises a new instance
func NewBatcher(maxJobs int, waitTime time.Duration, f Function) (*BatchConfig, error) {
switch {
case maxJobs <= 0:
return &BatchConfig{}, errors.New("invalid size")
case waitTime <= 0:
return &BatchConfig{}, errors.New("invalid wait time")
}
return &BatchConfig{
MaxCapacity: maxJobs,
WaitTime: waitTime,
function: f,
}, nil
}
//This function helps to insert an item
func (b *BatchConfig) Insert(item interface{}) (bool, error) {
if item == nil {
return false, errors.New("item inserted is null")
}
b.mutex.Lock()
defer b.mutex.Unlock()
if b.batchChan == nil {
b.batchChan = make(chan interface{}, b.MaxCapacity)
go b.dumper()
}
b.batchChan <- item
return true, nil
}
func (b *BatchConfig) InsertItems(items []interface{}) (bool, error) {
if items == nil {
return false, errors.New("items inserted is null")
}
b.mutex.Lock()
defer b.mutex.Unlock()
batchLen := len(items)
// If the length of batch is larger than maxCapacity
if batchLen > b.MaxCapacity {
items = items[:b.MaxCapacity]
}
if b.batchChan == nil {
b.batchChan = make(chan interface{}, b.MaxCapacity)
go b.dumper()
}
for _, item := range items {
b.batchChan <- item
}
return true, nil
}
func (b *BatchConfig) dumper() {
var batch []interface{}
timer := time.NewTimer(b.WaitTime)
for {
select {
case <-timer.C:
b.function(batch)
b.close()
return
case item := <-b.batchChan:
batch = append(batch, item)
if len(batch) >= b.MaxCapacity {
// Callback with batch
b.function(batch)
// Init batch array
batch = []interface{}{}
}
}
}
}
func (b *BatchConfig) close() {
b.mutex.Lock()
defer b.mutex.Unlock()
if b.batchChan != nil {
close(b.batchChan)
b.batchChan = nil
}
}