From 304697de36f37f92f8ad7b6eeb5061ea66324d3d Mon Sep 17 00:00:00 2001 From: Anton Levakin Date: Fri, 13 Oct 2023 19:31:41 +0200 Subject: [PATCH] CancelRequest: Wait for the cancel request to be acknowledged by the server --- pgconn/pgconn.go | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/pgconn/pgconn.go b/pgconn/pgconn.go index b6116d36a..1147ee2ea 100644 --- a/pgconn/pgconn.go +++ b/pgconn/pgconn.go @@ -942,18 +942,17 @@ func (pgConn *PgConn) CancelRequest(ctx context.Context) error { buf := make([]byte, 16) binary.BigEndian.PutUint32(buf[0:4], 16) binary.BigEndian.PutUint32(buf[4:8], 80877102) - binary.BigEndian.PutUint32(buf[8:12], uint32(pgConn.pid)) - binary.BigEndian.PutUint32(buf[12:16], uint32(pgConn.secretKey)) - _, err = cancelConn.Write(buf) - if err != nil { - return err - } + binary.BigEndian.PutUint32(buf[8:12], pgConn.pid) + binary.BigEndian.PutUint32(buf[12:16], pgConn.secretKey) - _, err = cancelConn.Read(buf) - if err != io.EOF { - return err + if _, err := cancelConn.Write(buf); err != nil { + return fmt.Errorf("write to connection for cancellation: %w", err) } + // Wait for the cancel request to be acknowledged by the server. + // It copies the behavior of the libpq: https://github.com/postgres/postgres/blob/REL_16_0/src/interfaces/libpq/fe-connect.c#L4946-L4960 + _, _ = cancelConn.Read(buf) + return nil }