Skip to content

fix(coderd/batchstats): fix init race and close flush #9248

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Aug 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions coderd/batchstats/batcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ func New(ctx context.Context, opts ...Option) (*Batcher, func(), error) {
b.tickCh = b.ticker.C
}

b.initBuf(b.batchSize)

cancelCtx, cancelFunc := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
Expand Down Expand Up @@ -172,7 +174,6 @@ func (b *Batcher) Add(

// Run runs the batcher.
func (b *Batcher) run(ctx context.Context) {
b.initBuf(b.batchSize)
// nolint:gocritic // This is only ever used for one thing - inserting agent stats.
authCtx := dbauthz.AsSystemRestricted(ctx)
for {
Expand All @@ -184,7 +185,13 @@ func (b *Batcher) run(ctx context.Context) {
b.flush(authCtx, true, "reaching capacity")
case <-ctx.Done():
b.log.Debug(ctx, "context done, flushing before exit")
b.flush(authCtx, true, "exit")

// We must create a new context here as the parent context is done.
ctxTimeout, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel() //nolint:revive // We're returning, defer is fine.

// nolint:gocritic // This is only ever used for one thing - inserting agent stats.
b.flush(dbauthz.AsSystemRestricted(ctxTimeout), true, "exit")
return
}
}
Expand Down
2 changes: 1 addition & 1 deletion coderd/batchstats/batcher_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func TestBatchStats(t *testing.T) {
deps1 := setupDeps(t, store)
deps2 := setupDeps(t, store)
tick := make(chan time.Time)
flushed := make(chan int)
flushed := make(chan int, 1)

b, closer, err := New(ctx,
WithStore(store),
Expand Down