-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmb.go
430 lines (386 loc) · 8.79 KB
/
mb.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Package mb - queue with message batching feature
package mb
import (
"context"
"errors"
"sort"
"sync"
"time"
)
// ErrClosed is returned when you add message to closed queue
var ErrClosed = errors.New("mb: MB closed")
// ErrTooManyMessages means that adding more messages (at one call) than the limit
var ErrTooManyMessages = errors.New("mb: too many messages")
// ErrOverflowed means new messages can't be added until there is free space in the queue
var ErrOverflowed = errors.New("mb: overflowed")
// New returns a new MB with given queue size.
// size <= 0 means unlimited
func New[T any](size int) *MB[T] {
mb := &MB[T]{
size: size,
}
return mb
}
func newWaiter[T any]() *waiter[T] {
return &waiter[T]{
data: make(chan []T, 1),
}
}
type waiter[T any] struct {
data chan []T
inUse bool
cond WaitCond[T]
}
type sortedWaiters[T any] []*waiter[T]
func (s sortedWaiters[T]) Len() int {
return len(s)
}
func (s sortedWaiters[T]) Less(i, j int) bool {
return s[i].cond.Priority > s[j].cond.Priority
}
func (s sortedWaiters[T]) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// MB - message batching object
type MB[T any] struct {
buf []T
mu sync.Mutex
size int
bufPrependCount int
addUnlock chan struct{}
waiters []*waiter[T]
paused, closed bool
addCount, getCount int64
addMsgsCount, getMsgsCount int64
}
// WaitCond describes condition for messages
type WaitCond[T any] struct {
Priority float64
Min int
Max int
Filter func(v T) bool
mb *MB[T]
}
// WithMax adds max to conditions
func (wc WaitCond[T]) WithMax(max int) WaitCond[T] {
c := wc
c.Max = max
return c
}
// WithMin adds min to conditions
func (wc WaitCond[T]) WithMin(min int) WaitCond[T] {
c := wc
c.Min = min
return c
}
// WithPriority adds priority to conditions
func (wc WaitCond[T]) WithPriority(priority float64) WaitCond[T] {
c := wc
c.Priority = priority
return c
}
// WithFilter adds filter to conditions
// filter function should return true for acceptable message and false for unacceptable
func (wc WaitCond[T]) WithFilter(f func(v T) bool) WaitCond[T] {
c := wc
c.Filter = f
return c
}
// Wait waits messages with defined condition
func (wc WaitCond[T]) Wait(ctx context.Context) (msgs []T, err error) {
return wc.mb.WaitCond(ctx, wc)
}
// WaitOne waits one message with defined condition
func (wc WaitCond[T]) WaitOne(ctx context.Context) (msg T, err error) {
msgs, err := wc.mb.WaitCond(ctx, wc.WithMax(1))
if err != nil {
return
}
return msgs[0], nil
}
func (wc WaitCond[T]) getMessages(mb *MB[T]) (toReturn, keep []T) {
keep = mb.buf
if wc.Min < 1 {
wc.Min = 1
}
bufLen := len(mb.buf)
if wc.Min > bufLen {
return
}
if wc.Filter == nil {
if wc.Max <= 0 || wc.Max >= bufLen {
toReturn = mb.buf
keep = nil
mb.bufPrependCount = 0
} else {
toReturn = mb.buf[:wc.Max]
mb.bufPrependCount += wc.Max
if mb.bufPrependCount > 10 {
keep = make([]T, len(mb.buf[wc.Max:]))
copy(keep, mb.buf[wc.Max:])
mb.bufPrependCount = 0
} else {
keep = mb.buf[wc.Max:]
}
}
} else {
toReturn = make([]T, 0, bufLen)
keep = make([]T, 0, bufLen)
for _, v := range mb.buf {
if (wc.Max <= 0 || len(toReturn) < wc.Max) && wc.Filter(v) {
toReturn = append(toReturn, v)
} else {
keep = append(keep, v)
}
}
if len(toReturn) > 0 && len(toReturn) < wc.Min {
toReturn = nil
keep = mb.buf
}
}
return
}
// NewCond creates new condition object
func (mb *MB[T]) NewCond() WaitCond[T] {
return WaitCond[T]{mb: mb}
}
// Wait until anybody add message
// Returning array of accumulated messages
func (mb *MB[T]) Wait(ctx context.Context) (msgs []T, err error) {
return mb.WaitCond(ctx, WaitCond[T]{})
}
// WaitOne waits one message
func (mb *MB[T]) WaitOne(ctx context.Context) (msg T, err error) {
return mb.NewCond().WaitOne(ctx)
}
// WaitCond waits new messages with given conditions
func (mb *MB[T]) WaitCond(ctx context.Context, cond WaitCond[T]) (msgs []T, err error) {
mb.mu.Lock()
checkBuf:
if !mb.paused {
select {
case <-ctx.Done():
mb.mu.Unlock()
return nil, ctx.Err()
default:
}
// check the work without waiter
if msgs, mb.buf = cond.getMessages(mb); len(msgs) > 0 {
mb.getMsgsCount += int64(len(msgs))
mb.unlockAdd()
mb.mu.Unlock()
return
}
}
if mb.closed {
mb.mu.Unlock()
return nil, ErrClosed
}
w := mb.allocWaiter()
w.cond = cond
// having waiters always priority sorted
sort.Sort(sortedWaiters[T](mb.waiters))
mb.mu.Unlock()
wait:
var timeLimit <-chan time.Time
if dur := getMBTimeLimit(ctx); dur > 0 {
timeLimit = time.After(dur)
}
var ok bool
select {
case msgs, ok = <-w.data:
if !ok {
return nil, ErrClosed
}
return msgs, nil
case <-timeLimit:
mb.mu.Lock()
if len(mb.buf) > 0 {
cond.Min = 1
mb.releaseWaiter(w)
goto checkBuf
} else {
w.cond.Min = 1
mb.mu.Unlock()
goto wait
}
case <-ctx.Done():
mb.mu.Lock()
mb.releaseWaiter(w)
mb.mu.Unlock()
return nil, ctx.Err()
}
}
func (mb *MB[T]) allocWaiter() *waiter[T] {
for _, w := range mb.waiters {
if !w.inUse {
w.inUse = true
return w
}
}
w := newWaiter[T]()
w.inUse = true
mb.waiters = append(mb.waiters, w)
return w
}
func (mb *MB[T]) releaseWaiter(w *waiter[T]) {
if len(w.data) == 1 {
// messages have been sent to the waiter, so let's return these to buf
mb.buf = append(<-w.data, mb.buf...)
}
w.inUse = false
}
// GetAll return all messages and flush queue
// Works on closed queue
func (mb *MB[T]) GetAll() (msgs []T) {
mb.mu.Lock()
msgs = mb.buf
mb.buf = nil
mb.getCount++
mb.getMsgsCount += int64(len(msgs))
mb.mu.Unlock()
return
}
// Add - adds new messages to queue.
// When queue is closed - returning ErrClosed
// When count messages bigger then queue size - returning ErrTooManyMessages
// When the queue is full - wait until will free place
func (mb *MB[T]) Add(ctx context.Context, msgs ...T) (err error) {
for {
mb.mu.Lock()
if err = mb.add(msgs...); err != nil {
if err == ErrOverflowed {
err = nil
if mb.addUnlock == nil {
mb.addUnlock = make(chan struct{})
}
addUnlock := mb.addUnlock
mb.mu.Unlock()
select {
case <-ctx.Done():
return ctx.Err()
case <-addUnlock:
}
continue
} else {
mb.mu.Unlock()
return
}
} else {
mb.mu.Unlock()
return
}
}
}
func (mb *MB[T]) unlockAdd() {
if mb.addUnlock != nil {
close(mb.addUnlock)
mb.addUnlock = nil
}
}
// TryAdd - adds new messages to queue.
// When queue is closed - returning ErrClosed
// When count messages bigger then queue size - returning ErrTooManyMessages
// When the queue is full - returning ErrOverflowed
func (mb *MB[T]) TryAdd(msgs ...T) (err error) {
mb.mu.Lock()
defer mb.mu.Unlock()
return mb.add(msgs...)
}
func (mb *MB[T]) add(msgs ...T) (err error) {
if mb.closed {
return ErrClosed
}
if mb.size > 0 && len(msgs) > mb.size {
return ErrTooManyMessages
}
if mb.size > 0 && len(msgs)+len(mb.buf) > mb.size {
return ErrOverflowed
}
// add to buf
mb.buf = append(mb.buf, msgs...)
if !mb.paused {
mb.trySendHeap()
}
return
}
func (mb *MB[T]) trySendHeap() {
var sent bool
for {
heapLen := len(mb.buf)
if heapLen == 0 {
break
}
for _, w := range mb.waiters {
// they are already sorted by priority
if (w.cond.Min < 1 || w.cond.Min <= heapLen) && w.inUse {
var msgs []T
if msgs, mb.buf = w.cond.getMessages(mb); len(msgs) > 0 {
mb.getMsgsCount += int64(len(msgs))
w.data <- msgs
w.inUse = false
sent = true
continue
}
}
}
// no messages processed
if heapLen == len(mb.buf) {
break
}
}
if sent {
mb.unlockAdd()
}
}
// Pause lock all "Wait" routines until call Resume
func (mb *MB[T]) Pause() {
mb.mu.Lock()
mb.paused = true
mb.mu.Unlock()
}
// Resume release all "Wait" routines
func (mb *MB[T]) Resume() {
mb.mu.Lock()
mb.trySendHeap()
mb.paused = false
mb.mu.Unlock()
}
// Len returning current size of queue
func (mb *MB[T]) Len() (l int) {
mb.mu.Lock()
l = len(mb.buf)
mb.mu.Unlock()
return
}
// Stats returning current statistic of queue usage
// addCount - count of calls Add
// addMsgsCount - count of added messages
// getCount - count of calls Wait
// getMsgsCount - count of issued messages
func (mb *MB[T]) Stats() (addCount, addMsgsCount, getCount, getMsgsCount int64) {
mb.mu.Lock()
addCount, addMsgsCount, getCount, getMsgsCount =
mb.addCount, mb.addMsgsCount, mb.getCount, mb.getMsgsCount
mb.mu.Unlock()
return
}
// Close closes the queue
// All added messages will be available for active Wait
// When queue is paused, messages do not be released for Wait (use GetAll for fetching them)
func (mb *MB[T]) Close() (err error) {
mb.mu.Lock()
if mb.closed {
mb.mu.Unlock()
return ErrClosed
}
mb.closed = true
if !mb.paused {
mb.trySendHeap()
}
for _, w := range mb.waiters {
close(w.data)
}
mb.mu.Unlock()
return
}