Skip to content

Commit ed2b123

Browse files
authored
fix(coderd/batchstats): fix init race and close flush (#9248)
1 parent 31ffb56 commit ed2b123

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

coderd/batchstats/batcher.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ func New(ctx context.Context, opts ...Option) (*Batcher, func(), error) {
105105
b.tickCh = b.ticker.C
106106
}
107107

108+
b.initBuf(b.batchSize)
109+
108110
cancelCtx, cancelFunc := context.WithCancel(ctx)
109111
done := make(chan struct{})
110112
go func() {
@@ -172,7 +174,6 @@ func (b *Batcher) Add(
172174

173175
// Run runs the batcher.
174176
func (b *Batcher) run(ctx context.Context) {
175-
b.initBuf(b.batchSize)
176177
// nolint:gocritic // This is only ever used for one thing - inserting agent stats.
177178
authCtx := dbauthz.AsSystemRestricted(ctx)
178179
for {
@@ -184,7 +185,13 @@ func (b *Batcher) run(ctx context.Context) {
184185
b.flush(authCtx, true, "reaching capacity")
185186
case <-ctx.Done():
186187
b.log.Debug(ctx, "context done, flushing before exit")
187-
b.flush(authCtx, true, "exit")
188+
189+
// We must create a new context here as the parent context is done.
190+
ctxTimeout, cancel := context.WithTimeout(context.Background(), 15*time.Second)
191+
defer cancel() //nolint:revive // We're returning, defer is fine.
192+
193+
// nolint:gocritic // This is only ever used for one thing - inserting agent stats.
194+
b.flush(dbauthz.AsSystemRestricted(ctxTimeout), true, "exit")
188195
return
189196
}
190197
}

coderd/batchstats/batcher_internal_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ func TestBatchStats(t *testing.T) {
3131
deps1 := setupDeps(t, store)
3232
deps2 := setupDeps(t, store)
3333
tick := make(chan time.Time)
34-
flushed := make(chan int)
34+
flushed := make(chan int, 1)
3535

3636
b, closer, err := New(ctx,
3737
WithStore(store),

0 commit comments

Comments
 (0)