diff options
| author | sangtran <tranquangsang12.7@gmail.com> | 2026-09-03 23:10:33 +0700 |
|---|---|---|
| committer | sangtran <tranquangsang12.7@gmail.com> | 2026-09-03 23:10:33 +0700 |
| commit | 02123df8cc15896f97c1580e49d8e2a991e37ddd (patch) | |
| tree | d0c00bc3f65e5f5493a9dff8034c80640cb12960 /pipeline/batch.go | |
| signature | Verified sangtran <tranquangsang12.7@gmail.com> Key: 8DD79823D235E1BB ultimate trust | |
| download | quacker-main.tar.gz quacker-main.zip | |
Diffstat (limited to 'pipeline/batch.go')
| -rw-r--r-- | pipeline/batch.go | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/pipeline/batch.go b/pipeline/batch.go new file mode 100644 index 0000000..74b08f0 --- /dev/null +++ b/pipeline/batch.go | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | package pipeline | ||
| 2 | |||
| 3 | import ( | ||
| 4 | "context" | ||
| 5 | "time" | ||
| 6 | ) | ||
| 7 | |||
| 8 | // Batch collects items into slices of up to size, flushing when full or when timeout elapses. | ||
| 9 | func Batch[T any](ctx context.Context, in <-chan T, size int, timeout time.Duration) <-chan []T { | ||
| 10 | if in == nil { | ||
| 11 | panic("pipeline: Batch input channel must not be nil") | ||
| 12 | } | ||
| 13 | if size < 1 { | ||
| 14 | panic("pipeline: Batch size must be at least 1") | ||
| 15 | } | ||
| 16 | |||
| 17 | out := make(chan []T) | ||
| 18 | |||
| 19 | go func() { | ||
| 20 | defer close(out) | ||
| 21 | |||
| 22 | buf := make([]T, 0, size) | ||
| 23 | ticker := time.NewTicker(timeout) | ||
| 24 | defer ticker.Stop() | ||
| 25 | |||
| 26 | flush := func() bool { | ||
| 27 | if len(buf) == 0 { | ||
| 28 | return true | ||
| 29 | } | ||
| 30 | batch := buf | ||
| 31 | buf = make([]T, 0, size) | ||
| 32 | select { | ||
| 33 | case out <- batch: | ||
| 34 | return true | ||
| 35 | case <-ctx.Done(): | ||
| 36 | return false | ||
| 37 | } | ||
| 38 | } | ||
| 39 | |||
| 40 | for { | ||
| 41 | select { | ||
| 42 | case v, ok := <-in: | ||
| 43 | if !ok { | ||
| 44 | flush() | ||
| 45 | return | ||
| 46 | } | ||
| 47 | buf = append(buf, v) | ||
| 48 | if len(buf) >= size { | ||
| 49 | if !flush() { | ||
| 50 | return | ||
| 51 | } | ||
| 52 | } | ||
| 53 | case <-ticker.C: | ||
| 54 | if !flush() { | ||
| 55 | return | ||
| 56 | } | ||
| 57 | case <-ctx.Done(): | ||
| 58 | return | ||
| 59 | } | ||
| 60 | } | ||
| 61 | }() | ||
| 62 | |||
| 63 | return out | ||
| 64 | } | ||
