fix(cli): fix flakes related to context cancellation when establishing pg connections (#18246)

Since https://github.com/coder/coder/pull/18195 was merged, we started
running CLI tests with postgres instead of just dbmem. This surfaced
errors related to context cancellation while establishing postgres
connections.

This PR should fix https://github.com/coder/internal/issues/672. Related
to https://github.com/coder/coder/issues/15109.
This commit is contained in:
Hugo Dutka
2025-06-05 15:54:13 +02:00
committed by GitHub
parent b5fd3dd855
commit 623dcd97dc
3 changed files with 17 additions and 9 deletions

View File

@ -552,15 +552,14 @@ func (p *PGPubsub) startListener(ctx context.Context, connectURL string) error {
sentErrCh = true
}),
}
select {
case err = <-errCh:
if err != nil {
_ = p.pgListener.Close()
return xerrors.Errorf("create pq listener: %w", err)
}
case <-ctx.Done():
// We don't respect context cancellation here. There's a bug in the pq library
// where if you close the listener before or while the connection is being
// established, the connection will be established anyway, and will not be
// closed.
// https://github.com/lib/pq/issues/1192
if err := <-errCh; err != nil {
_ = p.pgListener.Close()
return ctx.Err()
return xerrors.Errorf("create pq listener: %w", err)
}
return nil
}