Debian Codegraph @

util/batching_queue.go

raw
1 package util
2
3 import (
4 "sync"
5 "time"
6 )
7
8 // BatchingQueue is a queue that creates batches of the enqueued elements based on a
9 // max batch size and a batch timeout.
10 //
11 // Example:
12 //
13 // q := NewBatchingQueue[int](2, 500 * time.Millisecond)
14 // go func() {
15 // for batch := range q.Dequeue() {
16 // fmt.Println(batch)
17 // }
18 // }()
19 // q.Enqueue(1)
20 // q.Enqueue(2)
21 // q.Enqueue(3)
22 // time.Sleep(time.Second)
23 //
24 // This example will emit batch [1, 2] immediately (because the batch size is 2), and
25 // a batch [3] after 500ms.
26 type BatchingQueue[T any] struct {
27 batchSize int
28 timeout time.Duration
29 in []T
30 out chan []T
31 mu sync.Mutex
32 }
33
34 // NewBatchingQueue creates a new BatchingQueue
35 func NewBatchingQueue[T any](batchSize int, timeout time.Duration) *BatchingQueue[T] {
36 q := &BatchingQueue[T]{
37 batchSize: batchSize,
38 timeout: timeout,
39 in: make([]T, 0),
40 out: make(chan []T),
41 }
42 go q.timeoutTicker()
43 return q
44 }
45
46 // Enqueue enqueues an element to the queue. If the configured batch size is reached,
47 // the batch will be emitted immediately.
48 func (q *BatchingQueue[T]) Enqueue(element T) {
49 q.mu.Lock()
50 q.in = append(q.in, element)
51 var elements []T
52 if len(q.in) == q.batchSize {
53 elements = q.dequeueAll()
54 }
55 q.mu.Unlock()
56 if len(elements) > 0 {
57 q.out <- elements
58 }
59 }
60
61 // Dequeue returns a channel emitting batches of elements
62 func (q *BatchingQueue[T]) Dequeue() <-chan []T {
63 return q.out
64 }
65
66 func (q *BatchingQueue[T]) dequeueAll() []T {
67 elements := make([]T, len(q.in))
68 copy(elements, q.in)
69 q.in = q.in[:0]
70 return elements
71 }
72
73 func (q *BatchingQueue[T]) timeoutTicker() {
74 if q.timeout == 0 {
75 return
76 }
77 ticker := time.NewTicker(q.timeout)
78 for range ticker.C {
79 q.mu.Lock()
80 elements := q.dequeueAll()
81 q.mu.Unlock()
82 if len(elements) > 0 {
83 q.out <- elements
84 }
85 }
86 }