Skip to content

fix: close pg PubSub listener to avoid race #11640

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 1 commit into from
Jan 18, 2024
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
36 changes: 26 additions & 10 deletions coderd/database/pubsub/pubsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,15 @@ func (q *msgQueue) dropped() {

// Pubsub implementation using PostgreSQL.
type pgPubsub struct {
ctx context.Context
cancel context.CancelFunc
listenDone chan struct{}
pgListener *pq.Listener
db *sql.DB
mut sync.Mutex
queues map[string]map[uuid.UUID]*msgQueue
ctx context.Context
cancel context.CancelFunc
listenDone chan struct{}
pgListener *pq.Listener
db *sql.DB
mut sync.Mutex
queues map[string]map[uuid.UUID]*msgQueue
closedListener bool
closeListenerErr error
}

// BufferSize is the maximum number of unhandled messages we will buffer
Expand Down Expand Up @@ -240,15 +242,29 @@ func (p *pgPubsub) Publish(event string, message []byte) error {
// Close closes the pubsub instance.
func (p *pgPubsub) Close() error {
p.cancel()
err := p.pgListener.Close()
err := p.closeListener()
<-p.listenDone
return err
}

// closeListener closes the pgListener, unless it has already been closed.
func (p *pgPubsub) closeListener() error {
p.mut.Lock()
defer p.mut.Unlock()
if p.closedListener {
return p.closeListenerErr
}
p.closeListenerErr = p.pgListener.Close()
p.closedListener = true
return p.closeListenerErr
}

// listen begins receiving messages on the pq listener.
func (p *pgPubsub) listen() {
defer close(p.listenDone)
defer p.pgListener.Close()
defer func() {
_ = p.closeListener()
close(p.listenDone)
}()

var (
notif *pq.Notification
Expand Down
Binary file modified helm/provisioner/charts/libcoder-0.1.0.tgz
Binary file not shown.