Skip to content

Commit

Permalink
Always close io.Pipe when io.Copy is done (PostgresSQL engine) (#37220)
Browse files Browse the repository at this point in the history
* fix(postgres): close pipe after io.Copy is done

* chore(postgres): add comment
  • Loading branch information
gabrielcorado authored Jan 26, 2024
1 parent cb7adad commit 49c2be0
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/srv/db/postgres/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -419,8 +419,6 @@ func (e *Engine) receiveFromServer(serverConn *pgconn.PgConn, serverErrCh chan<-
// parse and count the messages from the server in a separate goroutine,
// operating on a copy of the server message stream. the copy is arranged below.
copyReader, copyWriter := io.Pipe()
defer copyWriter.Close()

closeChan := make(chan struct{})

go func() {
Expand Down Expand Up @@ -461,6 +459,12 @@ func (e *Engine) receiveFromServer(serverConn *pgconn.PgConn, serverErrCh chan<-
log.WithError(err).Warn("Server -> Client copy finished with unexpected error.")
}

// We need to close the writer half of the pipe to notify the analysis
// goroutine that the connection is done. This will result in the goroutine
// receiving an io.ErrClosedPipe error, which will cause it to finish its
// execution. After that, wait until the closeChan is closed to ensure the
// goroutine is completed, avoiding data races.
copyWriter.Close()
<-closeChan

serverErrCh <- trace.Wrap(err)
Expand Down

0 comments on commit 49c2be0

Please sign in to comment.