Skip to content
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

Mark net.Conn failed writes as recoverable when 0 bytes were written. #1013

Merged
merged 1 commit into from
Nov 23, 2020
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
13 changes: 12 additions & 1 deletion conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -891,9 +891,20 @@ func (cn *conn) Exec(query string, args []driver.Value) (res driver.Result, err
return r, err
}

type safeRetryError struct {
Err error
}

func (se *safeRetryError) Error() string {
return se.Err.Error()
}

func (cn *conn) send(m *writeBuf) {
_, err := cn.c.Write(m.wrap())
n, err := cn.c.Write(m.wrap())
if err != nil {
if n == 0 {
err = &safeRetryError{Err: err}
}
Copy link
Contributor Author

@dhermes dhermes Nov 19, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The motivation here is pgx:

The underlying connection just invokes Write() on a net.Conn and a "broken pipe" comes backs (same as here). But then a safeToRetry flag is set if exactly n == 0 bytes went through the write (https://github.com/jackc/pgconn/blob/cba610c245265ff50ea3c56a9961da218ed7d730/pgconn.go#L923).

Then in the high-level code used by the driver, if an error is detected but has safeToRetry set, a driver.ErrBadConn will be surfaced so the database/sql package can handle evicting the connection and replacing it in the pool (https://github.com/jackc/pgx/blob/1df45d758d4f57b45d56fbce1e5bb8cf9aabaaf0/stdlib/sql.go#L336).

panic(err)
}
}
Expand Down
3 changes: 3 additions & 0 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,9 @@ func (cn *conn) errRecover(err *error) {
case *net.OpError:
cn.bad = true
*err = v
case *safeRetryError:
cn.bad = true
*err = driver.ErrBadConn
case error:
if v == io.EOF || v.(error).Error() == "remote error: handshake failure" {
*err = driver.ErrBadConn
Expand Down