run runs the batcher loop, reading from the update channel and flushing periodically or when the batch reaches capacity.
(ctx context.Context)
| 262 | // run runs the batcher loop, reading from the update channel and flushing |
| 263 | // periodically or when the batch reaches capacity. |
| 264 | func (b *Batcher) run(ctx context.Context) { |
| 265 | // nolint:gocritic // This is only ever used for one thing - updating agent metadata. |
| 266 | authCtx := dbauthz.AsSystemRestricted(ctx) |
| 267 | for { |
| 268 | select { |
| 269 | case update := <-b.updateCh: |
| 270 | b.processUpdate(update) |
| 271 | |
| 272 | // Check if batch has reached capacity |
| 273 | if int(b.currentBatchLen.Load()) >= b.maxBatchSize { |
| 274 | b.flush(authCtx, flushCapacity) |
| 275 | // Reset timer so the next scheduled flush is interval duration |
| 276 | // from now, not from when it was originally scheduled. |
| 277 | b.timer.Reset(b.interval, "metadataBatcher", "capacityFlush") |
| 278 | } |
| 279 | |
| 280 | case <-b.timer.C: |
| 281 | b.flush(authCtx, flushTicker) |
| 282 | // Reset timer to schedule the next flush. |
| 283 | b.timer.Reset(b.interval, "metadataBatcher", "scheduledFlush") |
| 284 | |
| 285 | case <-ctx.Done(): |
| 286 | b.log.Debug(ctx, "context done, flushing before exit") |
| 287 | |
| 288 | // We must create a new context here as the parent context is done. |
| 289 | ctxTimeout, cancel := context.WithTimeout(context.Background(), finalFlushTimeout) |
| 290 | defer cancel() //nolint:revive // We're returning, defer is fine. |
| 291 | |
| 292 | // nolint:gocritic // This is only ever used for one thing - updating agent metadata. |
| 293 | b.flush(dbauthz.AsSystemRestricted(ctxTimeout), flushExit) |
| 294 | return |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | // flush flushes the current batch to the database and pubsub. |
| 300 | func (b *Batcher) flush(ctx context.Context, reason string) { |
no test coverage detected