From 17d49957d8098a3f352d546c59dbe5445b1e6958 Mon Sep 17 00:00:00 2001 From: MrTeeett Date: Tue, 24 Nov 2026 11:44:36 +0300 Subject: [PATCH] Fix Prepare hang on array metadata cancellation. Keep the request watcher active while finishing the deferred Execute and dropping both statements. Share one five-second cleanup limit between those operations and rollback of the owned transaction. Close the transport if that limit expires. Use the current socket deadline for the next read when a background read times out without receiving any bytes. --- fbconn/batch.go | 11 +- fbconn/deferred_execute_internal_test.go | 366 ++++++++++++++++++++-- fbconn/doc.go | 3 + fbconn/errors.go | 21 ++ fbconn/errors_internal_test.go | 27 ++ fbconn/fbconn.go | 207 +++++++----- fbconn/internal/bgreader/bgreader.go | 25 +- fbconn/internal/bgreader/bgreader_test.go | 52 +++ fbconn/statement.go | 30 +- fbconn/transaction.go | 12 +- 10 files changed, 599 insertions(+), 155 deletions(-) diff --git a/fbconn/batch.go b/fbconn/batch.go index b2093896..5e0844bb 100644 --- a/fbconn/batch.go +++ b/fbconn/batch.go @@ -156,14 +156,11 @@ func (fbConn *FbConn) PrepareBatchStatement(ctx context.Context, sql string) (*S if err != nil { return nil, err } - st, err := fbConn.prepareTx(ctx, tx, sql, statementScopeConnection) + rollback := prepareKeepTx if startedTx { - err = operationerror.Join(err, fbConn.rollbackOwnedInternalTx(ctx, tx)) + rollback = prepareRollbackAlways } - if err != nil { - return nil, err - } - return st, nil + return fbConn.prepareTx(ctx, tx, sql, statementScopeConnection, rollback) } func (b *Batch) isClosed() bool { @@ -391,7 +388,7 @@ func (b *Batch) Execute(ctx context.Context, tx *FBTransaction) (*BatchCompletio err = operationerror.Join(errBatchExecutionFailed, normalizeTimeoutError(ctx, ctx.Err())) } if err != nil || completion.HasErrors() { - if rbErr := b.st.conn.rollbackOwnedInternalTx(ctx, execTx); rbErr != nil { + if rbErr := b.st.conn.rollbackOwnedInternalTx(ctx, execTx, false); rbErr != nil { if err == nil { err = errBatchExecutionFailed } diff --git a/fbconn/deferred_execute_internal_test.go b/fbconn/deferred_execute_internal_test.go index f9fd0aa4..e6f6baea 100644 --- a/fbconn/deferred_execute_internal_test.go +++ b/fbconn/deferred_execute_internal_test.go @@ -4,11 +4,14 @@ import ( "bytes" "context" "encoding/binary" + "errors" "fmt" "io" "net" + "os" "sync" "testing" + "testing/synctest" "time" "github.com/firebirdsql/fbx/fbconn/ctxwatch" @@ -124,6 +127,8 @@ func (h *deferredExecuteCancelHandler) HandleCancel(ctx context.Context) { close(h.canceled) } +const deferredExecuteTestCancelDelay = 50 * time.Millisecond + func newDeferredExecutePipe(t *testing.T) (*FbConn, *Statement, net.Conn, *deferredExecuteWriteConn, <-chan struct{}) { t.Helper() client, server := net.Pipe() @@ -133,7 +138,7 @@ func newDeferredExecutePipe(t *testing.T) (*FbConn, *Statement, net.Conn, *defer handler := &deferredExecuteCancelHandler{ CancelRequestContextWatcherHandler: &CancelRequestContextWatcherHandler{ Conn: conn, - DeadlineDelay: 50 * time.Millisecond, + DeadlineDelay: deferredExecuteTestCancelDelay, // Keep cancel state operations out of the scripted query exchange. sendCancelOperationFunc: func(context.Context, int) error { return nil }, }, @@ -273,39 +278,344 @@ func respondToDeferredExecuteAndRollback(server net.Conn) error { return nil } -func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) { +func TestDeferredExecuteInternalReadUsesRequestDeadline(t *testing.T) { for _, blockedAt := range []string{"flush", "response"} { t.Run(blockedAt, func(t *testing.T) { - conn, st, server, _, canceled := newDeferredExecutePipe(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - require.NoError(t, conn.lock()) - defer conn.unlock() - conn.contextWatcher.Watch(ctx) - rr := st.internalExecTx(ctx, st.transaction, &ResultReader{fbConn: conn, ctx: ctx}, nil) - cancel() - select { - case <-canceled: - case <-time.After(time.Second): - t.Fatal("context cancellation was not observed") - } - if blockedAt == "response" { - go func() { _, _ = io.Copy(io.Discard, server) }() - } - start := time.Now() - done := make(chan *Result, 1) - go func() { done <- rr.readWithoutCommit() }() - select { - case result := <-done: + synctest.Test(t, func(t *testing.T) { + conn, st, server, _, canceled := newDeferredExecutePipe(t) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + require.NoError(t, conn.lock()) + defer conn.unlock() + conn.contextWatcher.Watch(ctx) + rr := st.internalExecTx(ctx, st.transaction, &ResultReader{fbConn: conn, ctx: ctx}, nil) + cancel() + select { + case <-canceled: + case <-time.After(time.Second): + t.Fatal("context cancellation was not observed") + } + if blockedAt == "response" { + go func() { _, _ = io.Copy(io.Discard, server) }() + } + timer := time.AfterFunc(2*cleanupGracePeriod, func() { _ = server.Close() }) + defer timer.Stop() + + start := time.Now() + result := rr.readWithoutCommit() require.ErrorIs(t, result.Err, context.Canceled) - require.GreaterOrEqual(t, time.Since(start), cleanupGracePeriod, - "cleanup must replace the original short cancellation deadline") + require.Equal(t, deferredExecuteTestCancelDelay, time.Since(start)) require.True(t, conn.IsClosed(), "a missing Execute response prevents reuse") require.NoError(t, server.Close()) waitCleanupDone(t, conn) - case <-time.After(cleanupGracePeriod + 2*time.Second): - t.Fatal("internal read cleanup exceeded its timeout") - } + }) + }) + } +} + +type arrayPrepareCleanupConn struct { + net.Conn + dropped []int + rollbackSent bool + deadlineResetErr error + readDeadlineOnly bool + stallExecute bool +} + +func (c *arrayPrepareCleanupConn) SetDeadline(deadline time.Time) error { + if deadline.IsZero() && c.deadlineResetErr != nil { + return c.deadlineResetErr + } + if c.readDeadlineOnly { + return c.SetReadDeadline(deadline) + } + return c.Conn.SetDeadline(deadline) +} + +func (c *arrayPrepareCleanupConn) Write(p []byte) (int, error) { + if len(p) == 4 && binary.BigEndian.Uint32(p) == fbproto.Op_ping { + return c.Conn.Write(p) + } + if len(p) == 8 && binary.BigEndian.Uint32(p) == fbproto.Op_rollback { + c.rollbackSent = true + return c.Conn.Write(p) + } + if c.stallExecute && len(p) >= 4 && binary.BigEndian.Uint32(p) == fbproto.Op_execute { + return c.Conn.Write(p) + } + if len(p) == 12 && binary.BigEndian.Uint32(p) == fbproto.Op_free_statement && binary.BigEndian.Uint32(p[8:]) == fbproto.DSQL_drop { + handle := int(binary.BigEndian.Uint32(p[4:])) + c.dropped = append(c.dropped, handle) + return c.Conn.Write(p) + } + return len(p), nil +} + +type cancelBeforeArrayMetadataFetch struct { + context.Context + conn *FbConn + cancel context.CancelFunc +} + +func (c cancelBeforeArrayMetadataFetch) Err() error { + if c.conn.deferredExecutePending.Load() { + c.cancel() + synctest.Wait() + } + return c.Context.Err() +} + +type delayedPrepareCancelHandler struct { + *CancelRequestContextWatcherHandler + resume <-chan struct{} +} + +func (h *delayedPrepareCancelHandler) HandleCancel(ctx context.Context) { + <-h.resume + h.CancelRequestContextWatcherHandler.HandleCancel(ctx) +} + +type prepareCancelWithoutDeadline struct{} + +func (prepareCancelWithoutDeadline) HandleCancel(context.Context) {} +func (prepareCancelWithoutDeadline) HandleUnwatchAfterCancel() {} + +func TestPrepareBatchCleansUpNewTransactionAfterLockFailure(t *testing.T) { + conn := newDetachTestConn(&prepareCleanupTestConn{}) + t.Cleanup(func() { + conn.asyncClose() + waitCleanupDone(t, conn) + }) + conn.config.Autocommit = true + tx := &FBTransaction{Connection: conn, Handle: 1} + conn.internalTransaction = tx + // An event operation acquired the connection between Begin and Prepare. + require.NoError(t, conn.lock()) + defer conn.unlock() + + st, err := conn.prepareTx(context.Background(), tx, "select 1", statementScopeConnection, prepareRollbackAlways) + require.Nil(t, st) + require.ErrorContains(t, err, "conn busy") + require.True(t, SafeToRetry(err)) + require.True(t, conn.IsClosed(), "a failed rollback must discard the temporary transaction") +} + +func TestPrepareArrayMetadataCleanup(t *testing.T) { + const statementHandle, metadataHandle = 42, 43 + const slowDropDelay = cleanupGracePeriod + time.Second + const cancelDeadlineDelay = 2 * time.Second + const requestTimeout = 2 * cleanupGracePeriod + bothDrops := []int{metadataHandle, statementHandle} + resetErr := errors.New("reset deadline failed") + for _, tc := range []struct { + name string + dropsRead int + readDelay time.Duration + lateCancel bool + resetErr error + readDeadlineOnly bool + stallAt string + wantContextErr error + wantDropped []int + wantElapsed time.Duration + }{ + { + name: "successful cleanup after cancellation", dropsRead: 2, + wantContextErr: context.Canceled, wantDropped: bothDrops, + }, + { + name: "slow drop outlasts the read deadline", dropsRead: 2, readDeadlineOnly: true, + readDelay: cancelDeadlineDelay + time.Second, wantElapsed: cancelDeadlineDelay + time.Second, + wantContextErr: context.Canceled, wantDropped: bothDrops, + }, + { + name: "late cancel after dropping both statements", dropsRead: 2, lateCancel: true, + wantContextErr: context.Canceled, wantDropped: bothDrops, + }, + { + name: "metadata statement blocked", + wantContextErr: context.Canceled, wantDropped: []int{metadataHandle}, wantElapsed: cancelDeadlineDelay, + }, + { + name: "original statement blocked after metadata drop", dropsRead: 1, readDelay: time.Second, + wantContextErr: context.Canceled, wantDropped: bothDrops, wantElapsed: cancelDeadlineDelay, + }, + { + name: "caller deadline during metadata drop", + wantContextErr: context.DeadlineExceeded, wantDropped: []int{metadataHandle}, wantElapsed: requestTimeout + cancelDeadlineDelay, + }, + { + name: "deadline reset fails after both drops", dropsRead: 2, resetErr: resetErr, + wantContextErr: context.Canceled, wantDropped: bothDrops, + }, + { + name: "slow drop within caller deadline", dropsRead: 2, readDelay: slowDropDelay, + wantDropped: bothDrops, wantElapsed: slowDropDelay, + }, + { + name: "cleanup grace bounds deferred execute write", stallAt: "execute write", + wantContextErr: context.Canceled, wantElapsed: cleanupGracePeriod, + }, + { + name: "cleanup grace bounds deferred execute response", stallAt: "execute response", + wantContextErr: context.Canceled, wantElapsed: cleanupGracePeriod, + }, + { + name: "both drops share the cleanup grace", stallAt: "drop", dropsRead: 1, + readDelay: cleanupGracePeriod - time.Second, + wantContextErr: context.Canceled, wantDropped: bothDrops, wantElapsed: cleanupGracePeriod, + }, + { + name: "owned rollback shares the cleanup grace", stallAt: "rollback", dropsRead: 2, + readDelay: cleanupGracePeriod - time.Second, + wantContextErr: context.Canceled, wantDropped: bothDrops, wantElapsed: cleanupGracePeriod, + }, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var responses bytes.Buffer + w := fbproto.NewXDRWriter(&responses) + arrayInfo := tagLengthValue(fbproto.Isc_info_sql_stmt_type, fbproto.Isc_info_sql_stmt_select) + arrayInfo = append(arrayInfo, fbproto.Isc_info_sql_select) + arrayInfo = append(arrayInfo, tagLengthValue(fbproto.Isc_info_sql_describe_vars, 1)...) + arrayInfo = append(arrayInfo, tagLengthValue(fbproto.Isc_info_sql_sqlda_seq, 1)...) + arrayInfo = append(arrayInfo, tagLengthValue(fbproto.Isc_info_sql_type, fbproto.SQL_TYPE_ARRAY)...) + arrayInfo = append(arrayInfo, tagBufferValue(fbproto.Isc_info_sql_field, []byte("VAL"))...) + arrayInfo = append(arrayInfo, tagBufferValue(fbproto.Isc_info_sql_relation, []byte("T"))...) + arrayInfo = append(arrayInfo, fbproto.Isc_info_sql_describe_end, fbproto.Isc_info_end) + selectInfo := append(tagLengthValue(fbproto.Isc_info_sql_stmt_type, fbproto.Isc_info_sql_stmt_select), fbproto.Isc_info_end) + require.NoError(t, writeProbeResponse(w, statementHandle)) + require.NoError(t, writeProbeResponse(w, 0)) + require.NoError(t, writeProbeResponseData(w, 0, arrayInfo)) + require.NoError(t, writeProbeResponse(w, metadataHandle)) + require.NoError(t, writeProbeResponse(w, fbproto.StmtDeferExecute)) + require.NoError(t, writeProbeResponseData(w, 0, selectInfo)) + if tc.stallAt != "execute write" && tc.stallAt != "execute response" { + require.NoError(t, writeProbeResponse(w, 0)) // Deferred Execute completed. + } + if tc.stallAt == "rollback" { + for range tc.dropsRead { + require.NoError(t, writeProbeResponse(w, 0)) + } + } + cancelBeforeFetch := tc.wantContextErr == context.Canceled + if !cancelBeforeFetch { + require.NoError(t, w.WriteInt32(fbproto.Op_fetch_response)) + require.NoError(t, w.WriteInt32(100)) // End of an empty cursor. + require.NoError(t, w.WriteInt32(0)) + require.NoError(t, writeProbeResponseData(w, 0, []byte{fbproto.Isc_info_end})) // Records. + } + + client, server := net.Pipe() + wire := &arrayPrepareCleanupConn{ + Conn: client, deadlineResetErr: tc.resetErr, stallExecute: tc.stallAt == "execute write", + readDeadlineOnly: tc.readDeadlineOnly, + } + conn := newDetachTestConn(wire) + conn.config.Autocommit = tc.stallAt == "rollback" + peerDone := make(chan struct{}) + go func() { + defer close(peerDone) + time.Sleep(tc.readDelay) + _, _ = io.CopyN(io.Discard, server, int64(tc.dropsRead)*12) + if tc.stallAt == "rollback" { + _, _ = io.CopyN(io.Discard, server, 8) + } + }() + defer func() { + require.NoError(t, server.Close()) + <-peerDone + conn.asyncClose() + waitCleanupDone(t, conn) + }() + var cancelKinds []int + conn.contextHandler = &DeadlineContextWatcherHandler{Conn: wire, DeadlineDelay: cancelDeadlineDelay} + switch { + case tc.stallAt != "": + conn.contextHandler = prepareCancelWithoutDeadline{} + case tc.lateCancel: + conn.contextHandler = &delayedPrepareCancelHandler{ + CancelRequestContextWatcherHandler: &CancelRequestContextWatcherHandler{ + Conn: conn, DeadlineDelay: cancelDeadlineDelay, + sendCancelOperationFunc: func(_ context.Context, kind int) error { + cancelKinds = append(cancelKinds, kind) + return nil + }, + }, + resume: peerDone, + } + } + conn.contextWatcher = ctxwatch.NewContextWatcher(conn.contextHandler) + encoding, err := fbproto.NewEncoding("UTF8") + require.NoError(t, err) + conn.Encoding = encoding + conn.client = fbproto.NewClient(io.MultiReader(&responses, conn.bgReader), conn.writer, encoding) + conn.protocolVersion = fbproto.PROTOCOL_VERSION13 + conn.activeStatements = make(map[*Statement]struct{}) + conn.internalTransaction = &FBTransaction{Connection: conn, Handle: 1} + ctx, cancel := context.WithTimeout(context.Background(), requestTimeout) + defer cancel() + if cancelBeforeFetch { + ctx = cancelBeforeArrayMetadataFetch{ctx, conn, cancel} + } + // Release stalled I/O so the test can report a regression. + timer := time.AfterFunc(3*cleanupGracePeriod, func() { _ = server.Close() }) + defer timer.Stop() + + start := time.Now() + st, err := conn.Prepare(ctx, "select VAL from T") + require.Equal(t, tc.wantElapsed, time.Since(start), "Prepare cleanup duration") + require.Nil(t, st) + require.NotContains(t, cancelKinds, fbproto.Fb_cancel_raise) + if tc.wantContextErr != nil { + require.ErrorIs(t, err, tc.wantContextErr) + } else { + require.ErrorContains(t, err, "cannot resolve array metadata") + } + require.False(t, SafeToRetry(err)) + require.False(t, conn.IsBusy()) + require.False(t, conn.deferredExecutePending.Load()) + require.Empty(t, conn.activeStatements) + require.Equal(t, tc.wantDropped, wire.dropped) + if tc.stallAt == "rollback" { + require.True(t, wire.rollbackSent) + require.ErrorContains(t, err, "rollback internal tx") + } + require.Zero(t, responses.Len()) + switch { + case tc.stallAt != "": + require.True(t, conn.IsClosed()) + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + case tc.resetErr != nil: + require.True(t, conn.IsClosed()) + require.ErrorIs(t, err, tc.resetErr) + case tc.dropsRead < len(tc.wantDropped): + var timeoutErr net.Error + require.ErrorAs(t, err, &timeoutErr) + require.True(t, timeoutErr.Timeout()) + require.True(t, conn.IsClosed()) + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + if tc.wantContextErr == context.DeadlineExceeded { + require.True(t, Timeout(err)) + } + default: + cancel() + time.Sleep(cleanupGracePeriod) + require.False(t, conn.IsClosed()) + go func() { + if _, err := io.CopyN(io.Discard, server, 4); err != nil { + return + } + w := fbproto.NewXDRWriter(server) + for range tc.dropsRead + 1 { + if err := writeProbeResponse(w, 0); err != nil { + return + } + } + }() + require.NoError(t, conn.Ping(context.Background())) + } + }) }) } } diff --git a/fbconn/doc.go b/fbconn/doc.go index e98d1e03..533a4a78 100644 --- a/fbconn/doc.go +++ b/fbconn/doc.go @@ -26,6 +26,9 @@ This can be especially useful when queries that are frequently canceled and the a problem. DeadlineContextWatcherHandler and CancelRequestContextWatcherHandler can be used to introduce a delay before interrupting the query in such a way as to close the connection. +During statement preparation, the driver closes the transport if cancellation +leaves network cleanup blocked for five seconds. + The CancelRequest method may be used to request the server cancel an in-progress query without forcing the client to abort. diff --git a/fbconn/errors.go b/fbconn/errors.go index 65e8ab4b..a3e7eec8 100644 --- a/fbconn/errors.go +++ b/fbconn/errors.go @@ -11,6 +11,7 @@ import ( "syscall" "github.com/firebirdsql/fbx/fbproto" + "github.com/firebirdsql/fbx/internal/operationerror" ) // SafeToRetry reports whether the failed call is guaranteed not to have sent its @@ -226,6 +227,26 @@ func normalizeTimeoutError(ctx context.Context, err error) error { return err } +// withContextError retains the original failure and its retry policy when +// cancellation is reported as a server or transport error. +func withContextError(ctx context.Context, err error) error { + if err == nil { + return nil + } + ctxErr := ctx.Err() + if ctxErr == nil { + // A later cancellation must not replace the transport error. + return normalizeTimeoutError(context.Background(), err) + } + if !errors.Is(err, ctxErr) { + err = operationerror.Join(err, ctxErr) + } + if ctxErr == context.DeadlineExceeded && !Timeout(err) { + return &errTimeout{err: err} + } + return err +} + // normalizeConnClosedError converts transport-level connection breakage (EOF / reset / closed socket) // into an FbError with SQLSTATE 08006 so callers don't have to special-case io.EOF. // diff --git a/fbconn/errors_internal_test.go b/fbconn/errors_internal_test.go index b04f59f7..f141e265 100644 --- a/fbconn/errors_internal_test.go +++ b/fbconn/errors_internal_test.go @@ -3,6 +3,8 @@ package fbconn import ( "context" "errors" + "net" + "os" "testing" "github.com/stretchr/testify/require" @@ -22,6 +24,31 @@ func TestSyncConnClosedConnErrorIsErrConnClosed(t *testing.T) { require.ErrorIs(t, err, ErrConnClosed) } +type cancelingNetworkTimeout struct { + *net.OpError + cancel context.CancelFunc +} + +func (e *cancelingNetworkTimeout) Timeout() bool { + e.cancel() + return e.OpError.Timeout() +} + +func TestWithContextErrorRetainsTransportTimeoutDuringCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + transportErr := &cancelingNetworkTimeout{ + OpError: &net.OpError{Op: "write", Err: os.ErrDeadlineExceeded}, + cancel: cancel, + } + + err := withContextError(ctx, transportErr) + + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.ErrorIs(t, err, transportErr) + require.True(t, Timeout(err)) +} + func TestTargetSessionAttributeErrors(t *testing.T) { tests := []struct { name string diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index 91b2b607..e647fdee 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -74,8 +74,8 @@ type FbConn struct { slowWriteTimer *time.Timer bgReaderStarted chan struct{} writeInProgress atomic.Bool - // A deferred Execute has been written without an explicit flush. The - // cancellation callback races with the first Fetch or Close. + // Suppress op_cancel for a buffered Execute until the first Fetch takes + // over or the request finishes cleaning up the deferred execution. deferredExecutePending atomic.Bool attachmentHandle int attachmentID uint64 @@ -1675,14 +1675,7 @@ func (fbConn *FbConn) Prepare(ctx context.Context, sql string) (*Statement, erro if err != nil { return nil, err } - st, err := fbConn.prepareTx(ctx, tx, sql, statementScopeConnection) - if err != nil { - if rbErr := fbConn.rollbackInternalTxIfAutocommitOnError(ctx, tx, err); rbErr != nil { - err = operationerror.Join(err, fmt.Errorf("rollback internal tx: %w", rbErr)) - } - return nil, err - } - return st, nil + return fbConn.prepareTx(ctx, tx, sql, statementScopeConnection, prepareRollbackOnError) } type statementScope uint8 @@ -1692,9 +1685,17 @@ const ( statementScopeConnection ) +type prepareRollback uint8 + +const ( + prepareKeepTx prepareRollback = iota + prepareRollbackOnError + prepareRollbackAlways +) + // PrepareTx creates a prepared statement bound to tx. func (fbConn *FbConn) PrepareTx(ctx context.Context, tx *FBTransaction, sql string) (*Statement, error) { - return fbConn.prepareTx(ctx, tx, sql, statementScopeTransaction) + return fbConn.prepareTx(ctx, tx, sql, statementScopeTransaction, prepareKeepTx) } // PrepareTxForConnection creates a connection-scoped prepared statement using @@ -1703,20 +1704,57 @@ func (fbConn *FbConn) PrepareTx(ctx context.Context, tx *FBTransaction, sql stri // Callers must only retain the statement while its metadata remains valid // outside tx. func (fbConn *FbConn) PrepareTxForConnection(ctx context.Context, tx *FBTransaction, sql string) (*Statement, error) { - return fbConn.prepareTx(ctx, tx, sql, statementScopeConnection) + return fbConn.prepareTx(ctx, tx, sql, statementScopeConnection, prepareKeepTx) } -func (fbConn *FbConn) prepareTx(ctx context.Context, tx *FBTransaction, sql string, scope statementScope) (*Statement, error) { +func (fbConn *FbConn) prepareTx(ctx context.Context, tx *FBTransaction, sql string, scope statementScope, rollback prepareRollback) (st *Statement, err error) { if err := fbConn.lock(); err != nil { + // Batch preparation already started its temporary transaction. + if rollback == prepareRollbackAlways { + err = operationerror.Join(err, fbConn.rollbackOwnedInternalTx(ctx, tx, false)) + } return nil, err } defer fbConn.unlock() + var stopCleanup func() error + if ctx.Done() != nil { + stopCleanup = fbConn.watchPrepareCleanup(ctx) + } + defer func() { + // Keep op_cancel suppressed through both statement drops and Unwatch. + fbConn.deferredExecutePending.Store(false) + var cleanupErr error + if handler, ok := fbConn.contextHandler.(interface{ deadlineError() error }); ok && stopCleanup != nil { + cleanupErr = handler.deadlineError() + } + needsRollback := rollback == prepareRollbackAlways || (rollback == prepareRollbackOnError && err != nil && !SafeToRetry(err)) + if cleanupErr == nil && needsRollback { + if rbErr := fbConn.rollbackOwnedInternalTx(ctx, tx, true); rbErr != nil { + if rollback == prepareRollbackOnError { + rbErr = fmt.Errorf("rollback internal tx: %w", rbErr) + } + err = operationerror.Join(err, rbErr) + } + } + if stopCleanup != nil { + cleanupErr = operationerror.Join(stopCleanup(), cleanupErr) + } + if cleanupErr != nil { + fbConn.asyncClose() + err = withContextError(ctx, operationerror.Join(err, cleanupErr)) + } + if err != nil { + delete(fbConn.activeStatements, st) + st = nil + } + }() + if err := fbConn.beforeRequest(); err != nil { return nil, err } - if ctx != context.Background() { + if ctx.Done() != nil { select { case <-ctx.Done(): return nil, newContextAlreadyDoneError(ctx) @@ -1729,14 +1767,37 @@ func (fbConn *FbConn) prepareTx(ctx context.Context, tx *FBTransaction, sql stri return fbConn.internalPrepareTx(ctx, tx, sql, scope) } +// watchPrepareCleanup bounds the whole operation after cancellation, including +// an owned transaction's rollback, even when the request handler sets no deadline. +func (fbConn *FbConn) watchPrepareCleanup(ctx context.Context) func() error { + done := make(chan struct{}) + result := make(chan error, 1) + stop := context.AfterFunc(ctx, func() { + timer := time.NewTimer(cleanupGracePeriod) + select { + case <-done: + timer.Stop() + result <- nil + case <-timer.C: + _ = fbConn.conn.Close() + result <- fmt.Errorf("prepare cleanup: %w", os.ErrDeadlineExceeded) + } + }) + return func() error { + close(done) + if stop() { + return nil + } + return <-result + } +} + func (fbConn *FbConn) internalPrepareTx( ctx context.Context, tx *FBTransaction, sql string, scope statementScope, -) (*Statement, error) { - var err error - +) (st *Statement, err error) { if err = fbConn.withWriteLockAndFlush(func() error { if err := fbConn.client.WriteMessage(&fbproto.OpAllocateStatement{}); err != nil { return err @@ -1771,6 +1832,16 @@ func (fbConn *FbConn) internalPrepareTx( return nil, fmt.Errorf("unexpected statement allocation response %T", msg) } + var reportClosedConn bool + defer func() { + if err == nil || (!reportClosedConn && fbConn.IsClosed()) { + return + } + if cleanupErr := fbConn.freeStatementHandleLocked(ctx, statementHandle); cleanupErr != nil { + err = operationerror.Join(err, fmt.Errorf("free statement after prepare error: %w", cleanupErr)) + } + }() + msg, err = fbConn.receiveMessage() if err != nil { fbConn.asyncCloseAfterRead(err) @@ -1781,28 +1852,14 @@ func (fbConn *FbConn) internalPrepareTx( case *fbproto.OpResponse: deferExecute = m.Object&fbproto.StmtDeferExecute != 0 case *fbproto.ErrorResponse: - err = ErrorResponseToFbError(m) - if fbConn.IsClosed() { - return nil, err - } - if cleanupErr := fbConn.freeStatementHandleLocked(statementHandle); cleanupErr != nil { - return nil, operationerror.Join(err, fmt.Errorf("free statement after prepare error: %w", cleanupErr)) - } - return nil, err + return nil, ErrorResponseToFbError(m) default: fbConn.asyncClose() return nil, fmt.Errorf("unexpected statement prepare response %T", msg) } statementInfo := StatementInfo{} - err = fbConn.getInfoStatement(statementHandle, statementInfo.parseInfo) - if err != nil { - if fbConn.IsClosed() { - return nil, err - } - if cleanupErr := fbConn.freeStatementHandleLocked(statementHandle); cleanupErr != nil { - return nil, operationerror.Join(err, fmt.Errorf("free statement after prepare error: %w", cleanupErr)) - } + if err := fbConn.getInfoStatement(statementHandle, statementInfo.parseInfo); err != nil { return nil, err } @@ -1842,12 +1899,6 @@ func (fbConn *FbConn) internalPrepareTx( arrays, err = getArrayInfo(fbConn, ctx, tx, fields, tables) } if err != nil { - if fbConn.IsClosed() { - return nil, err - } - if cleanupErr := fbConn.freeStatementHandleLocked(statementHandle); cleanupErr != nil { - return nil, operationerror.Join(err, fmt.Errorf("free statement after prepare error: %w", cleanupErr)) - } return nil, err } @@ -1856,14 +1907,13 @@ func (fbConn *FbConn) internalPrepareTx( err = attachArrayMetadata(desc.Parameters, arrays, "parameter") } if err != nil { - if cleanupErr := fbConn.freeStatementHandleLocked(statementHandle); cleanupErr != nil { - return nil, operationerror.Join(err, fmt.Errorf("free statement after prepare error: %w", cleanupErr)) - } + // Preserve ErrConnClosed as a cleanup cause when attaching array metadata fails. + reportClosedConn = true return nil, err } } - st := &Statement{ + st = &Statement{ conn: fbConn, Description: desc, deferExecute: deferExecute && fbConn.protocolVersion >= fbproto.PROTOCOL_VERSION11, @@ -2043,11 +2093,8 @@ func (fbConn *FbConn) ExecParams(ctx context.Context, sql string, paramValues [] } func (fbConn *FbConn) ExecParamsTx(ctx context.Context, tx *FBTransaction, sql string, paramValues [][]byte) *ResultReader { - st, err := fbConn.PrepareTx(ctx, tx, sql) + st, err := fbConn.prepareTx(ctx, tx, sql, statementScopeTransaction, prepareRollbackOnError) if err != nil { - if rbErr := fbConn.rollbackInternalTxIfAutocommitOnError(ctx, tx, err); rbErr != nil { - err = operationerror.Join(err, fmt.Errorf("rollback internal tx: %w", rbErr)) - } res := ResultReader{ fbConn: fbConn, ctx: ctx, @@ -2197,12 +2244,6 @@ func (fbConn *FbConn) getArrayMetadata(ctx context.Context, tx *FBTransaction, s return nil, nil, err } - defer func() { - cleanupCtx, cancel := cleanupContext(ctx) - _ = st.deallocateLocked(cleanupCtx) - cancel() - }() - rr := &ResultReader{ fbConn: fbConn, ctx: ctx, @@ -2211,8 +2252,8 @@ func (fbConn *FbConn) getArrayMetadata(ctx context.Context, tx *FBTransaction, s result := st.internalExecTx(ctx, tx, rr, nil).readWithoutCommit() - if result.Err != nil { - return nil, nil, result.Err + if err := operationerror.Join(result.Err, st.deallocateLocked(ctx)); err != nil { + return nil, nil, err } metadataList := make([]map[string][]byte, 0) @@ -2293,12 +2334,6 @@ func (fbConn *FbConn) getArrayDimensions(ctx context.Context, tx *FBTransaction, return nil, err } - defer func() { - cleanupCtx, cancel := cleanupContext(ctx) - _ = st.deallocateLocked(cleanupCtx) - cancel() - }() - rr := &ResultReader{ fbConn: fbConn, ctx: ctx, @@ -2307,8 +2342,8 @@ func (fbConn *FbConn) getArrayDimensions(ctx context.Context, tx *FBTransaction, result := st.internalExecTx(ctx, tx, rr, nil).readWithoutCommit() - if result.Err != nil { - return nil, result.Err + if err := operationerror.Join(result.Err, st.deallocateLocked(ctx)); err != nil { + return nil, err } dimensions := map[dimensionsMapKey][][]int{} @@ -2693,7 +2728,6 @@ func (rr *ResultReader) finishDeferredExecute() error { if !rr.deferredExecute { return nil } - rr.fbConn.deferredExecutePending.Store(false) if rr.fbConn.IsClosed() { rr.deferredExecute = false return ErrConnClosed @@ -2885,7 +2919,7 @@ func (fbConn *FbConn) commitInternalTx(ctx context.Context, tx *FBTransaction) e return nil } if !fbConn.IsClosed() { - if rbErr := fbConn.rollbackOwnedInternalTx(ctx, tx); rbErr != nil { + if rbErr := fbConn.rollbackOwnedInternalTx(ctx, tx, false); rbErr != nil { err = operationerror.Join(err, fmt.Errorf("rollback internal tx: %w", rbErr)) } } @@ -2900,11 +2934,11 @@ func (fbConn *FbConn) rollbackInternalTxIfAutocommitOnError(ctx context.Context, if SafeToRetry(opErr) { return nil } - return fbConn.rollbackOwnedInternalTx(ctx, tx) + return fbConn.rollbackOwnedInternalTx(ctx, tx, false) } // rollbackOwnedInternalTx resolves the owned transaction independently of retry. -func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransaction) error { +func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransaction, locked bool) error { if tx == nil || tx != fbConn.internalTransaction || tx.Closed { return nil } @@ -2913,7 +2947,7 @@ func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransac } cleanupCtx, cancel := cleanupContext(ctx) defer cancel() - if err := tx.Rollback(cleanupCtx); err != nil { + if err := tx.rollback(cleanupCtx, locked); err != nil { // A failed rollback leaves the state of the implicit transaction unknown, // so the connection must not be reused even when the error is not fatal. fbConn.asyncClose() @@ -2926,7 +2960,7 @@ func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransac // error. func (rr *ResultReader) Close() (QueryStatus, error) { if !rr.closed { - _, _ = rr.closeWithoutCommit() + rr.closeWithDeferredExecuteCleanup() rr.fbConn.contextWatcher.Unwatch() rr.fbConn.unlock() @@ -2953,22 +2987,25 @@ func (rr *ResultReader) Close() (QueryStatus, error) { return rr.queryStatus, rr.err } +func (rr *ResultReader) closeWithDeferredExecuteCleanup() { + if rr.deferredExecute { + // A standalone Close can finish the buffered Execute after cancellation. + defer rr.fbConn.deferredExecutePending.Store(false) + rr.fbConn.contextWatcher.Unwatch() + cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{ + Conn: rr.fbConn.conn, + DeadlineDelay: cleanupGracePeriod, + }) + cleanupWatcher.Watch(rr.ctx) + defer cleanupWatcher.Unwatch() + } + _, _ = rr.closeWithoutCommit() +} + func (rr *ResultReader) closeWithoutCommit() (QueryStatus, error) { if !rr.closed { - if rr.deferredExecute { - // Stop the request watcher before flushing the buffered Execute. A - // canceled query must not cancel its own protocol cleanup. Internal - // metadata reads need the same bounded cleanup as public Close. - rr.fbConn.contextWatcher.Unwatch() - cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{ - Conn: rr.fbConn.conn, - DeadlineDelay: cleanupGracePeriod, - }) - cleanupWatcher.Watch(rr.ctx) - defer cleanupWatcher.Unwatch() - if err := rr.finishDeferredExecute(); err != nil { - rr.concludeCommand(QueryStatus{}, err) - } + if err := rr.finishDeferredExecute(); err != nil { + rr.concludeCommand(QueryStatus{}, err) } if rr.err == nil { rr.drainCurrentFetch() @@ -3433,6 +3470,10 @@ func (h *DeadlineContextWatcherHandler) HandleUnwatchAfterCancel() { } } +func (h *DeadlineContextWatcherHandler) deadlineError() error { + return h.err +} + // CancelRequestContextWatcherHandler manages cancel state around each watched request and handles canceled contexts by // sending a cancel request to the server. It also sets a deadline on a net.Conn as a fallback. type CancelRequestContextWatcherHandler struct { diff --git a/fbconn/internal/bgreader/bgreader.go b/fbconn/internal/bgreader/bgreader.go index 40d3ef61..5fe96f3e 100644 --- a/fbconn/internal/bgreader/bgreader.go +++ b/fbconn/internal/bgreader/bgreader.go @@ -2,7 +2,9 @@ package bgreader import ( + "errors" "io" + "os" "sync" "github.com/firebirdsql/fbx/internal/iobufpool" @@ -104,7 +106,13 @@ func (r *BGReader) bgRead() { *buf = (*buf)[:n] r.cond.L.Lock() - r.readResults = append(r.readResults, readResult{buf: buf, err: err}) + if n == 0 && errors.Is(err, os.ErrDeadlineExceeded) { + // A speculative read's socket deadline may be cleared before Read. + // Stop here so the caller reads under its current deadline. + iobufpool.Put(buf) + } else { + r.readResults = append(r.readResults, readResult{buf: buf, err: err}) + } if r.status == StatusStopping || err != nil { r.status = StatusStopped keepReading = false @@ -119,20 +127,13 @@ func (r *BGReader) Read(p []byte) (int, error) { r.cond.L.Lock() defer r.cond.L.Unlock() + for len(r.readResults) == 0 && r.status != StatusStopped { + r.cond.Wait() + } if len(r.readResults) > 0 { return r.readFromReadResults(p) } - - // There are no unread background read results and the background reader is stopped. - if r.status == StatusStopped { - return r.r.Read(p) - } - - // Wait for results from the background reader - for len(r.readResults) == 0 { - r.cond.Wait() - } - return r.readFromReadResults(p) + return r.r.Read(p) } // readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held. diff --git a/fbconn/internal/bgreader/bgreader_test.go b/fbconn/internal/bgreader/bgreader_test.go index 8d1df8a1..c3a40099 100644 --- a/fbconn/internal/bgreader/bgreader_test.go +++ b/fbconn/internal/bgreader/bgreader_test.go @@ -2,10 +2,14 @@ package bgreader_test import ( "bytes" + "context" "errors" "io" "math/rand/v2" + "net" + "os" "testing" + "testing/synctest" "time" "github.com/firebirdsql/fbx/fbconn/internal/bgreader" @@ -94,6 +98,54 @@ func TestBGReaderErrorWhenStopped(t *testing.T) { require.EqualError(t, err, "oops") } +func TestBGReaderUsesCurrentReadDeadline(t *testing.T) { + for _, mode := range []string{"expired", "cleared"} { + t.Run(mode, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + client, server := net.Pipe() + defer func() { _ = client.Close() }() + defer func() { _ = server.Close() }() + bgr := bgreader.New(client) + bgr.Start() + _, err := server.Write([]byte("ab")) + require.NoError(t, err) + synctest.Wait() // The next speculative read is blocked. + require.NoError(t, client.SetReadDeadline(time.Now())) + bgr.StopAndWait() + if mode == "cleared" { + require.NoError(t, client.SetReadDeadline(time.Time{})) + go func() { _, _ = server.Write([]byte("cd")) }() + } + buf := make([]byte, 4) + n, err := io.ReadFull(bgr, buf) + if mode == "cleared" { + require.NoError(t, err) + require.Equal(t, "abcd", string(buf[:n])) + } else { + require.ErrorIs(t, err, os.ErrDeadlineExceeded) + require.Equal(t, "ab", string(buf[:n])) + } + }) + }) + } +} + +func TestBGReaderPreservesBackgroundErrors(t *testing.T) { + for _, tc := range []struct { + data string + err error + }{{"abc", os.ErrDeadlineExceeded}, {"", context.DeadlineExceeded}} { + r := &mockReader{readFuncs: []mockReadFunc{ + func(p []byte) (int, error) { return copy(p, tc.data), tc.err }, + }} + bgr := bgreader.New(r) + bgr.Start() + data, err := io.ReadAll(bgr) + require.ErrorIs(t, err, tc.err) + require.Equal(t, tc.data, string(data)) + } +} + type numberReader struct { v uint8 rng *rand.Rand diff --git a/fbconn/statement.go b/fbconn/statement.go index 243cb7f9..ff8ecbf7 100644 --- a/fbconn/statement.go +++ b/fbconn/statement.go @@ -504,26 +504,13 @@ func (st *Statement) deallocateLocked(ctx context.Context) error { if st.closed { return nil } - if st.conn.IsClosed() { - return ErrConnClosed - } - if err := st.conn.client.WriteMessage(&fbproto.OpFreeStatement{ - StatementHandle: st.Description.StatementHandle, - Option: fbproto.DSQL_drop, - }); err != nil { - st.conn.asyncClose() - return err - } - if err := st.conn.flushWithPotentialWriteReadDeadlock(); err != nil { - st.conn.asyncClose() - st.cursorTransaction = nil - st.closed = true - return err - } st.cursorTransaction = nil st.closed = true delete(st.conn.activeStatements, st) - return nil + if st.conn.IsClosed() { + return nil + } + return st.conn.freeStatementHandleLocked(ctx, st.Description.StatementHandle) } // CloseCursor close opened cursor without deallocating statement on server @@ -531,10 +518,9 @@ func (st *Statement) CloseCursor(ctx context.Context) error { return st.internalClose(ctx, fbproto.DSQL_close) } -// freeStatementHandleLocked sends op_free_statement DSQL_drop for a raw server-side -// statement handle that has no corresponding *Statement Go object yet. Caller must -// hold the conn lock. On any wire error the conn is asyncClose'd. -func (fbConn *FbConn) freeStatementHandleLocked(handle int) error { +// freeStatementHandleLocked sends DSQL_drop for a server-side statement handle. +// The caller holds the conn lock and manages cancellation. +func (fbConn *FbConn) freeStatementHandleLocked(ctx context.Context, handle int) error { if fbConn.IsClosed() { return ErrConnClosed } @@ -545,7 +531,7 @@ func (fbConn *FbConn) freeStatementHandleLocked(handle int) error { }) }); err != nil { fbConn.asyncClose() - return err + return withContextError(ctx, err) } return nil } diff --git a/fbconn/transaction.go b/fbconn/transaction.go index ac32735b..6fd8eb4b 100644 --- a/fbconn/transaction.go +++ b/fbconn/transaction.go @@ -74,15 +74,21 @@ func (tx *FBTransaction) Commit(ctx context.Context) error { } func (tx *FBTransaction) Rollback(ctx context.Context) error { + return tx.rollback(ctx, false) +} + +func (tx *FBTransaction) rollback(ctx context.Context, locked bool) error { if tx.Closed { return ErrTransactionClosed } var err error - if err = tx.Connection.lock(); err != nil { - return err + if !locked { + if err = tx.Connection.lock(); err != nil { + return err + } + defer tx.Connection.unlock() } - defer tx.Connection.unlock() if err = tx.Connection.beforeRequest(); err != nil { return err