Debian Codegraph @

pubsub/batcher/batcher.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package batcher supports batching of items. Create a Batcher with a handler and
16 // add items to it. Items are accumulated while handler calls are in progress; when
17 // the handler returns, it will be called again with items accumulated since the last
18 // call. Multiple concurrent calls to the handler are supported.
19 package batcher // import "gocloud.dev/pubsub/batcher"
20
21 import (
22 "context"
23 "errors"
24 "reflect"
25 "sync"
26 )
27
28 // Split determines how to split n (representing n items) into batches based on
29 // opts. It returns a slice of batch sizes.
30 //
31 // For example, Split(10) might return [10], [5, 5], or [2, 2, 2, 2, 2]
32 // depending on opts. opts may be nil to accept defaults.
33 //
34 // Split will return nil if n is less than o.MinBatchSize.
35 //
36 // The sum of returned batches may be less than n (e.g., if n is 10x larger
37 // than o.MaxBatchSize, but o.MaxHandlers is less than 10).
38 func Split(n int, opts *Options) []int {
39 o := newOptionsWithDefaults(opts)
40 if n < o.MinBatchSize {
41 // No batch yet.
42 return nil
43 }
44 if o.MaxBatchSize == 0 {
45 // One batch is fine.
46 return []int{n}
47 }
48
49 // TODO(rvangent): Consider trying to even out the batch sizes.
50 // For example, n=10 with MaxBatchSize 9 and MaxHandlers 2 will Split
51 // to [9, 1]; it could be [5, 5].
52 var batches []int
53 for n >= o.MinBatchSize && len(batches) < o.MaxHandlers {
54 b := min(o.MaxBatchSize, n)
55 batches = append(batches, b)
56 n -= b
57 }
58 return batches
59 }
60
61 // A Batcher batches items.
62 type Batcher struct {
63 opts Options
64 handler func(any) error
65 itemSliceZero reflect.Value // nil (zero value) for slice of items
66 wg sync.WaitGroup // tracks active Add calls
67
68 mu sync.Mutex
69 pending []waiter // items waiting to be handled
70 nHandlers int // number of currently running handler goroutines
71 shutdown bool
72 }
73
74 // Message is larger than the maximum batch byte size
75 var ErrMessageTooLarge = errors.New("batcher: message too large")
76
77 type sizableItem interface {
78 ByteSize() int
79 }
80
81 type waiter struct {
82 item any
83 errc chan error
84 }
85
86 // Options sets options for Batcher.
87 type Options struct {
88 // Maximum number of concurrent handlers. Defaults to 1.
89 MaxHandlers int
90 // Minimum size of a batch. Defaults to 1.
91 // May be ignored during shutdown.
92 MinBatchSize int
93 // Maximum size of a batch. 0 means no limit.
94 MaxBatchSize int
95 // Maximum bytesize of a batch. 0 means no limit.
96 MaxBatchByteSize int
97 }
98
99 // newOptionsWithDefaults returns Options with defaults applied to opts.
100 // opts may be nil to accept all defaults.
101 func newOptionsWithDefaults(opts *Options) Options {
102 var o Options
103 if opts != nil {
104 o = *opts
105 }
106 if o.MaxHandlers == 0 {
107 o.MaxHandlers = 1
108 }
109 if o.MinBatchSize == 0 {
110 o.MinBatchSize = 1
111 }
112 return o
113 }
114
115 // newMergedOptions returns o merged with opts.
116 func (o *Options) NewMergedOptions(opts *Options) *Options {
117 maxH := o.MaxHandlers
118 if opts.MaxHandlers != 0 && (maxH == 0 || opts.MaxHandlers < maxH) {
119 maxH = opts.MaxHandlers
120 }
121 minB := o.MinBatchSize
122 if opts.MinBatchSize != 0 && (minB == 0 || opts.MinBatchSize > minB) {
123 minB = opts.MinBatchSize
124 }
125 maxB := o.MaxBatchSize
126 if opts.MaxBatchSize != 0 && (maxB == 0 || opts.MaxBatchSize < maxB) {
127 maxB = opts.MaxBatchSize
128 }
129 maxBB := o.MaxBatchByteSize
130 if opts.MaxBatchByteSize != 0 && (maxBB == 0 || opts.MaxBatchByteSize < maxBB) {
131 maxBB = opts.MaxBatchByteSize
132 }
133 c := &Options{
134 MaxHandlers: maxH,
135 MinBatchSize: minB,
136 MaxBatchSize: maxB,
137 MaxBatchByteSize: maxBB,
138 }
139 return c
140 }
141
142 // New creates a new Batcher.
143 //
144 // itemType is type that will be batched. For example, if you
145 // want to create batches of *Entry, pass reflect.TypeOf(&Entry{}) for itemType.
146 //
147 // opts can be nil to accept defaults.
148 //
149 // handler is a function that will be called on each bundle. If itemExample is
150 // of type T, the argument to handler is of type []T.
151 func New(itemType reflect.Type, opts *Options, handler func(any) error) *Batcher {
152 return &Batcher{
153 opts: newOptionsWithDefaults(opts),
154 handler: handler,
155 itemSliceZero: reflect.Zero(reflect.SliceOf(itemType)),
156 }
157 }
158
159 // Add adds an item to the batcher. It blocks until the handler has
160 // processed the item and reports the error that the handler returned.
161 // If Shutdown has been called, Add immediately returns an error.
162 func (b *Batcher) Add(ctx context.Context, item any) error {
163 c := b.AddNoWait(item)
164 // Wait until either our result is ready or the context is done.
165 select {
166 case err := <-c:
167 return err
168 case <-ctx.Done():
169 return ctx.Err()
170 }
171 }
172
173 // AddNoWait adds an item to the batcher and returns immediately. When the handler is
174 // called on the item, the handler's error return value will be sent to the channel
175 // returned from AddNoWait.
176 func (b *Batcher) AddNoWait(item any) <-chan error {
177 b.mu.Lock()
178 defer b.mu.Unlock()
179
180 // Create a channel to receive the error from the handler.
181 c := make(chan error, 1)
182 if b.shutdown {
183 c <- errors.New("batcher: shut down")
184 return c
185 }
186
187 if b.opts.MaxBatchByteSize > 0 {
188 if sizable, ok := item.(sizableItem); ok {
189 if sizable.ByteSize() > b.opts.MaxBatchByteSize {
190 c <- ErrMessageTooLarge
191 return c
192 }
193 }
194 }
195
196 // Add the item to the pending list.
197 b.pending = append(b.pending, waiter{item, c})
198 if b.nHandlers < b.opts.MaxHandlers {
199 // If we can start a handler, do so with the item just added and any others that are pending.
200 b.handleBatch(b.nextBatch())
201 }
202 // If we can't start a handler, then one of the currently running handlers will
203 // take our item.
204 return c
205 }
206
207 // Requires b.mu be held.
208 func (b *Batcher) handleBatch(batch []waiter) {
209 if len(batch) == 0 {
210 return
211 }
212 b.wg.Add(1)
213 go func() {
214 b.callHandler(batch)
215 b.wg.Done()
216 }()
217 b.nHandlers++
218 }
219
220 // nextBatch returns the batch to process, and updates b.pending.
221 // It returns nil if there's no batch ready for processing.
222 // b.mu must be held.
223 func (b *Batcher) nextBatch() []waiter {
224 // If we're not shutting down, respect minimums. If we're shutting down
225 // though, we ignore minimums to make sure everything is flushed.
226 if !b.shutdown && len(b.pending) < b.opts.MinBatchSize {
227 return nil
228 }
229
230 if b.opts.MaxBatchByteSize == 0 && (b.opts.MaxBatchSize == 0 || len(b.pending) <= b.opts.MaxBatchSize) {
231 // Send it all!
232 batch := b.pending
233 b.pending = nil
234 return batch
235 }
236
237 batch := make([]waiter, 0, len(b.pending))
238 batchByteSize := 0
239 for _, msg := range b.pending {
240 itemByteSize := 0
241 if sizable, ok := msg.item.(sizableItem); ok {
242 itemByteSize = sizable.ByteSize()
243 }
244 reachedMaxSize := b.opts.MaxBatchSize > 0 && len(batch)+1 > b.opts.MaxBatchSize
245 reachedMaxByteSize := b.opts.MaxBatchByteSize > 0 && batchByteSize+itemByteSize > b.opts.MaxBatchByteSize
246
247 if reachedMaxSize || reachedMaxByteSize {
248 break
249 }
250 batch = append(batch, msg)
251 batchByteSize = batchByteSize + itemByteSize
252 }
253
254 b.pending = b.pending[len(batch):]
255 return batch
256 }
257
258 func (b *Batcher) callHandler(batch []waiter) {
259 for batch != nil {
260
261 // Collect the items into a slice of the example type.
262 items := b.itemSliceZero
263 for _, m := range batch {
264 items = reflect.Append(items, reflect.ValueOf(m.item))
265 }
266 // Call the handler and report the result to all waiting
267 // callers of Add.
268 err := b.handler(items.Interface())
269 for _, m := range batch {
270 m.errc <- err
271 }
272 b.mu.Lock()
273 // If there is more work, keep running; otherwise exit. Take the new batch
274 // and decrement the handler count atomically, so that newly added items will
275 // always get to run.
276 batch = b.nextBatch()
277 if batch == nil {
278 b.nHandlers--
279 }
280 b.mu.Unlock()
281 }
282 }
283
284 // Shutdown waits for all active calls to Add to finish, then
285 // returns. After Shutdown is called, all subsequent calls to Add fail.
286 // Shutdown should be called only once.
287 func (b *Batcher) Shutdown() {
288 b.mu.Lock()
289 b.shutdown = true
290 // If there aren't any handlers running, there might be a partial
291 // batch. Make sure it gets flushed even if it hasn't reached the
292 // minimums.
293 if b.nHandlers == 0 {
294 b.handleBatch(b.nextBatch())
295 }
296 b.mu.Unlock()
297 b.wg.Wait()
298 }