| 56 | } |
| 57 | |
| 58 | func (nb *notificationBatcher) start(ctx context.Context) error { |
| 59 | nb.mu.Lock() |
| 60 | if nb.running { |
| 61 | nb.mu.Unlock() |
| 62 | return ErrAlreadyRunning |
| 63 | } |
| 64 | nb.running = true |
| 65 | nb.done = make(chan struct{}) |
| 66 | nb.mu.Unlock() |
| 67 | |
| 68 | go func() { |
| 69 | defer func() { |
| 70 | nb.mu.Lock() |
| 71 | nb.running = false |
| 72 | nb.mu.Unlock() |
| 73 | close(nb.done) |
| 74 | }() |
| 75 | |
| 76 | ticker := time.NewTicker(notificationBatchInterval) |
| 77 | defer ticker.Stop() |
| 78 | |
| 79 | for { |
| 80 | select { |
| 81 | case <-ctx.Done(): |
| 82 | // We could do a final flush here. |
| 83 | // But it still would be an incomplete graceful shutdown without connection tracking. |
| 84 | // So we decided not to do it. |
| 85 | return |
| 86 | case <-ticker.C: |
| 87 | nb.flush(ctx) |
| 88 | } |
| 89 | } |
| 90 | }() |
| 91 | |
| 92 | return nil |
| 93 | } |
| 94 | |
| 95 | func (nb *notificationBatcher) flush(ctx context.Context) { |
| 96 | if len(nb.notifications) == 0 { |