|
| 1 | +package batchsender |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/cloudquery/plugin-sdk/v4/helpers" |
| 8 | +) |
| 9 | + |
| 10 | +const ( |
| 11 | + batchSize = 100 |
| 12 | + batchTimeout = 100 * time.Millisecond |
| 13 | +) |
| 14 | + |
| 15 | +// BatchSender is a helper struct that batches items and sends them in batches of batchSize or after batchTimeout. |
| 16 | +// |
| 17 | +// - If item is already a slice, it will be sent directly |
| 18 | +// - Otherwise, it will be added to the current batch |
| 19 | +// - If the current batch has reached the batch size, it will be sent immediately |
| 20 | +// - Otherwise, a timer will be started to send the current batch after the batch timeout |
| 21 | +type BatchSender struct { |
| 22 | + sendFn func(any) |
| 23 | + items []any |
| 24 | + timer *time.Timer |
| 25 | + itemsLock sync.Mutex |
| 26 | +} |
| 27 | + |
| 28 | +func NewBatchSender(sendFn func(any)) *BatchSender { |
| 29 | + return &BatchSender{sendFn: sendFn} |
| 30 | +} |
| 31 | + |
| 32 | +func (bs *BatchSender) Send(item any) { |
| 33 | + if bs.timer != nil { |
| 34 | + bs.timer.Stop() |
| 35 | + } |
| 36 | + |
| 37 | + items := helpers.InterfaceSlice(item) |
| 38 | + |
| 39 | + // If item is already a slice, send it directly |
| 40 | + // together with the current batch |
| 41 | + if len(items) > 1 { |
| 42 | + bs.flush(items...) |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + // Otherwise, add item to the current batch |
| 47 | + bs.appendToBatch(items...) |
| 48 | + |
| 49 | + // If the current batch has reached the batch size, send it |
| 50 | + if len(bs.items) >= batchSize { |
| 51 | + bs.flush() |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + // Otherwise, start a timer to send the current batch after the batch timeout |
| 56 | + bs.timer = time.AfterFunc(batchTimeout, func() { bs.flush() }) |
| 57 | +} |
| 58 | + |
| 59 | +func (bs *BatchSender) appendToBatch(items ...any) { |
| 60 | + bs.itemsLock.Lock() |
| 61 | + defer bs.itemsLock.Unlock() |
| 62 | + |
| 63 | + bs.items = append(bs.items, items...) |
| 64 | +} |
| 65 | + |
| 66 | +func (bs *BatchSender) flush(items ...any) { |
| 67 | + bs.itemsLock.Lock() |
| 68 | + defer bs.itemsLock.Unlock() |
| 69 | + |
| 70 | + bs.items = append(bs.items, items...) |
| 71 | + |
| 72 | + if len(bs.items) == 0 { |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + bs.sendFn(bs.items) |
| 77 | + bs.items = nil |
| 78 | +} |
| 79 | + |
| 80 | +func (bs *BatchSender) Close() { |
| 81 | + if bs.timer != nil { |
| 82 | + bs.timer.Stop() |
| 83 | + } |
| 84 | + bs.flush() |
| 85 | +} |
0 commit comments