Skip to content

Commit

Permalink
fix: avoid race condition in wg
Browse files Browse the repository at this point in the history
  • Loading branch information
jeroenrinzema committed Sep 1, 2023
1 parent 1913429 commit aafe144
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
4 changes: 4 additions & 0 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ func (srv *Server) consumeCommands(ctx context.Context, conn net.Conn, reader *b
return err
}

if srv.closing.Load() {
return nil
}

// NOTE: we increase the wait group by one in order to make sure that idle
// connections are not blocking a close.
srv.wg.Add(1)
Expand Down
7 changes: 7 additions & 0 deletions wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net"
"sync"
"sync/atomic"

"log/slog"

Expand Down Expand Up @@ -52,6 +53,7 @@ func NewServer(parse ParseFn, options ...OptionFn) (*Server, error) {

// Server contains options for listening to an address.
type Server struct {
closing atomic.Bool
wg sync.WaitGroup
logger *slog.Logger
types *pgtype.ConnInfo
Expand Down Expand Up @@ -165,6 +167,11 @@ func (srv *Server) serve(ctx context.Context, conn net.Conn) error {

// Close gracefully closes the underlaying Postgres server.
func (srv *Server) Close() error {
if srv.closing.Load() {
return nil
}

srv.closing.Store(true)
close(srv.closer)
srv.wg.Wait()
return nil
Expand Down

0 comments on commit aafe144

Please sign in to comment.