Debian Codegraph @

batcher/batcher.go

raw
1 // Package batcher implements the batching resiliency pattern for Go.
2 package batcher
3
4 import (
5 "sync"
6 "time"
7 )
8
9 type work struct {
10 param interface{}
11 future chan error
12 }
13
14 // Batcher implements the batching resiliency pattern
15 type Batcher struct {
16 timeout time.Duration
17 prefilter func(interface{}) error
18
19 lock sync.Mutex
20 submit chan *work
21 doWork func([]interface{}) error
22 batchCounter sync.WaitGroup
23 flushTimer *time.Timer
24 }
25
26 // New constructs a new batcher that will batch all calls to Run that occur within
27 // `timeout` time before calling doWork just once for the entire batch. The doWork
28 // function must be safe to run concurrently with itself as this may occur, especially
29 // when the doWork function is slow, or the timeout is small.
30 func New(timeout time.Duration, doWork func([]interface{}) error) *Batcher {
31 return &Batcher{
32 timeout: timeout,
33 doWork: doWork,
34 }
35 }
36
37 // Run runs the work function with the given parameter, possibly
38 // including it in a batch with other calls to Run that occur within the
39 // specified timeout. It is safe to call Run concurrently on the same batcher.
40 func (b *Batcher) Run(param interface{}) error {
41 if b.prefilter != nil {
42 if err := b.prefilter(param); err != nil {
43 return err
44 }
45 }
46
47 if b.timeout == 0 {
48 return b.doWork([]interface{}{param})
49 }
50
51 w := &work{
52 param: param,
53 future: make(chan error, 1),
54 }
55
56 b.submitWork(w)
57
58 return <-w.future
59 }
60
61 // Prefilter specifies an optional function that can be used to run initial checks on parameters
62 // passed to Run before being added to the batch. If the prefilter returns a non-nil error,
63 // that error is returned immediately from Run and the batcher is not invoked. A prefilter
64 // cannot safely be specified for a batcher if Run has already been invoked. The filter function
65 // specified must be concurrency-safe.
66 func (b *Batcher) Prefilter(filter func(interface{}) error) {
67 b.prefilter = filter
68 }
69
70 func (b *Batcher) submitWork(w *work) {
71 b.lock.Lock()
72 defer b.lock.Unlock()
73
74 // kick off a new batch if needed
75 if b.submit == nil {
76 b.batchCounter.Add(1)
77 b.submit = make(chan *work, 4)
78 go b.batch(b.submit)
79 b.flushTimer = time.AfterFunc(b.timeout, b.flushCurrentBatch)
80 }
81
82 // then add this work to the current batch
83 b.submit <- w
84 }
85
86 func (b *Batcher) batch(input <-chan *work) {
87 defer b.batchCounter.Done()
88
89 var params []interface{}
90 var futures []chan error
91
92 for work := range input {
93 params = append(params, work.param)
94 futures = append(futures, work.future)
95 }
96
97 ret := b.doWork(params)
98
99 for _, future := range futures {
100 future <- ret
101 close(future)
102 }
103 }
104
105 // Shutdown flushes and executes any pending batches. If wait is true, it also waits for the pending batches
106 // to finish executing before it returns. This can be used to avoid waiting for the timeout to expire when
107 // gracefully shutting down your application. Calling Run at any point after calling Shutdown will lead to
108 // undefined behaviour.
109 func (b *Batcher) Shutdown(wait bool) {
110 b.flushCurrentBatch()
111
112 if wait {
113 b.batchCounter.Wait()
114 }
115 }
116
117 func (b *Batcher) flushCurrentBatch() {
118 b.lock.Lock()
119 defer b.lock.Unlock()
120
121 if b.submit == nil {
122 return
123 }
124
125 // stop the timer to avoid spurious flushes and trigger immediate cleanup in case this flush was
126 // triggered manually by a call to Shutdown (it has to happen inside the lock, so it can't be done
127 // in the Shutdown method directly)
128 b.flushTimer.Stop()
129
130 close(b.submit)
131 b.submit = nil
132 }