-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatcher.go
70 lines (61 loc) · 1.48 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
package batbq
import (
"context"
"errors"
"sync"
"github.com/ubntc/go/batching/batbq/config"
"github.com/ubntc/go/batching/batbq/scaling"
)
// Putter provides a `Put` func as used by the `bigquery.Inserter`.
type Putter interface {
Put(ctx context.Context, src any) error
}
// InsertBatcher implements automatic batching with a batch capacity and flushInterval.
type InsertBatcher struct {
id string
cfg config.BatcherConfig
metrics *Metrics
input <-chan Message
output Putter
scaling scaling.Status
mu *sync.Mutex
}
// NewInsertBatcher returns an InsertBatcher.
func NewInsertBatcher(id string, opt ...BatcherOption) *InsertBatcher {
ins := &InsertBatcher{
id: id,
cfg: config.Default(),
mu: &sync.Mutex{},
}
for _, o := range opt {
o.apply(ins)
}
if ins.metrics == nil {
ins.metrics = NewMetrics()
}
return ins
}
// Metrics returns the metrics.
func (ins *InsertBatcher) Metrics() *Metrics {
return ins.metrics
}
// Process starts the batcher.
func (ins *InsertBatcher) Process(ctx context.Context, input <-chan Message, output Putter) error {
if input == nil {
return errors.New("input channel must not be nil")
}
if output == nil {
return errors.New("output Putter must not be nil")
}
// ensure ins.Process is not called concurrently
ins.mu.Lock()
defer ins.mu.Unlock()
ins.input = input
ins.output = output
if ins.cfg.AutoScale {
scaling.Autoscale(ctx, &ins.cfg, &ins.scaling, ins.worker)
return nil
}
ins.worker(ctx, 1)
return nil
}