From dda87e97ce81f7fbb938eb3447bee1f1c1183073 Mon Sep 17 00:00:00 2001 From: Matvey Gubanikhin Date: Tue, 24 Nov 2026 10:57:19 +0300 Subject: [PATCH] Add ability to configure timeout for clearing server resources. --- conn.go | 14 +++++--- conn_internal_test.go | 17 ++++++++++ fbconn/deferred_execute_internal_test.go | 4 +-- fbconn/fbconn.go | 30 ++++++++++++----- fbconn/fbconn_private_test.go | 9 +++++ internal/cleanupctx/cleanupCtx.go | 33 +++++++++++++++++++ internal/cleanupctx/cleanup_test.go | 42 ++++++++++++++++++++++++ stdlib/sql.go | 13 ++++---- 8 files changed, 141 insertions(+), 21 deletions(-) create mode 100644 internal/cleanupctx/cleanupCtx.go create mode 100644 internal/cleanupctx/cleanup_test.go diff --git a/conn.go b/conn.go index ee21eb2d..920d3776 100644 --- a/conn.go +++ b/conn.go @@ -13,6 +13,7 @@ import ( "github.com/firebirdsql/fbx/fbconn" "github.com/firebirdsql/fbx/fbtype" + "github.com/firebirdsql/fbx/internal/cleanupctx" "github.com/firebirdsql/fbx/internal/operationerror" "github.com/firebirdsql/fbx/internal/stmtcache" ) @@ -127,14 +128,19 @@ var ( errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache") ) -// cleanupGracePeriod bounds cleanup network calls (op_free_statement, etc.) that must -// run even after the user's ctx has been cancelled. -const cleanupGracePeriod = 5 * time.Second +// SetCleanupTimeout sets the timeout for the resource cleanup context. +// The default timeout is 5 seconds. +// It must be called before using the driver and must not be called +// concurrently with driver operations. +// The timeout must be at least 150 ms. +func SetCleanupTimeout(timeout time.Duration) error { + return cleanupctx.SetCleanupTimeout(timeout) +} // cleanupContext returns a context for releasing server-side resources after the // user's request has finished. func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) { - return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod) + return cleanupctx.CleanupContext(parent) } // Connect establishes a connection with a Firebird server with a connection string. See diff --git a/conn_internal_test.go b/conn_internal_test.go index c6b3cf92..67c5f18d 100644 --- a/conn_internal_test.go +++ b/conn_internal_test.go @@ -7,10 +7,12 @@ import ( "fmt" "os" "testing" + "testing/synctest" "time" "github.com/firebirdsql/fbx/fbconn" "github.com/firebirdsql/fbx/fbconn/ctxwatch" + "github.com/firebirdsql/fbx/internal/cleanupctx" "github.com/firebirdsql/fbx/internal/stmtcache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -686,3 +688,18 @@ func TestExecTraceEndsWhenInvalidatedStatementDeallocateFails(t *testing.T) { require.Same(t, st, conn.statementCache.GetInvalidatedBySQL(cachedSQL)) require.Nil(t, conn.statementCache.Get(notCachedSQL)) } + +func TestSetCleanupTimeout(t *testing.T) { + previous := cleanupctx.CleanupTimeout() + t.Cleanup(func() { require.NoError(t, SetCleanupTimeout(previous)) }) + + const timeout = 300 * time.Millisecond + require.NoError(t, SetCleanupTimeout(timeout)) + synctest.Test(t, func(t *testing.T) { + ctx, cancel := cleanupContext(context.Background()) + defer cancel() + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.Equal(t, timeout, time.Until(deadline)) + }) +} diff --git a/fbconn/deferred_execute_internal_test.go b/fbconn/deferred_execute_internal_test.go index f9fd0aa4..914d0374 100644 --- a/fbconn/deferred_execute_internal_test.go +++ b/fbconn/deferred_execute_internal_test.go @@ -298,12 +298,12 @@ func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) { select { case result := <-done: require.ErrorIs(t, result.Err, context.Canceled) - require.GreaterOrEqual(t, time.Since(start), cleanupGracePeriod, + require.GreaterOrEqual(t, time.Since(start), cleanupTimeout(), "cleanup must replace the original short cancellation deadline") 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): + case <-time.After(cleanupTimeout() + 2*time.Second): t.Fatal("internal read cleanup exceeded its timeout") } }) diff --git a/fbconn/fbconn.go b/fbconn/fbconn.go index 91b2b607..ff1bd9d4 100644 --- a/fbconn/fbconn.go +++ b/fbconn/fbconn.go @@ -22,6 +22,7 @@ import ( "github.com/firebirdsql/fbx/fbproto" "github.com/firebirdsql/fbx/fbproto/auth" "github.com/firebirdsql/fbx/fbproto/wirecrypt" + "github.com/firebirdsql/fbx/internal/cleanupctx" "github.com/firebirdsql/fbx/internal/operationerror" ) @@ -1423,7 +1424,7 @@ func (fbConn *FbConn) asyncClose() { func (fbConn *FbConn) asyncCloseAfterRead(err error) { var netErr net.Error if errors.As(err, &netErr) && netErr.Timeout() { - fbConn.asyncCloseWithTimeout(cleanupGracePeriod) + fbConn.asyncCloseWithTimeout(cleanupTimeout()) } else { fbConn.asyncClose() } @@ -2867,14 +2868,25 @@ func (rr *ResultReader) SetCallerErr(err error) { } } -// cleanupGracePeriod bounds cleanup network calls (e.g. op_free_statement) that -// must run even after the caller's ctx has been cancelled. -const cleanupGracePeriod = 5 * time.Second +// SetCleanupTimeout sets the timeout for the resource cleanup context. +// The default timeout is 5 seconds. +// It must be called before using the driver and must not be called +// concurrently with driver operations. +// The transmitted timeout must be at least 150 ms. +func SetCleanupTimeout(timeout time.Duration) error { + return cleanupctx.SetCleanupTimeout(timeout) +} -// cleanupContext detaches from parent cancellation but preserves Values, with a -// bounded timeout for the network call. +// cleanupContext returns a context for releasing server-side resources after the +// user's request has finished. func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) { - return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod) + return cleanupctx.CleanupContext(parent) +} + +// cleanupTimeout returns a timeout for releasing server-side resources after the +// user's request has finished. +func cleanupTimeout() time.Duration { + return cleanupctx.CleanupTimeout() } // commitInternalTx rolls back a rejected implicit commit so the next request @@ -2962,7 +2974,7 @@ func (rr *ResultReader) closeWithoutCommit() (QueryStatus, error) { rr.fbConn.contextWatcher.Unwatch() cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{ Conn: rr.fbConn.conn, - DeadlineDelay: cleanupGracePeriod, + DeadlineDelay: cleanupTimeout(), }) cleanupWatcher.Watch(rr.ctx) defer cleanupWatcher.Unwatch() @@ -3602,7 +3614,7 @@ func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() { func (h *CancelRequestContextWatcherHandler) sendCancelOperationWithTimeout(kind int) error { timeout := h.CancelResetTimeout if timeout <= 0 { - timeout = 5 * time.Second + timeout = cleanupTimeout() } ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() diff --git a/fbconn/fbconn_private_test.go b/fbconn/fbconn_private_test.go index 63d728b9..abe0619d 100644 --- a/fbconn/fbconn_private_test.go +++ b/fbconn/fbconn_private_test.go @@ -836,3 +836,12 @@ func TestArrayGenerateSDLIncludesInt128Scale(t *testing.T) { }) } } + +func TestSetCleanupTimeout(t *testing.T) { + previous := cleanupTimeout() + t.Cleanup(func() { require.NoError(t, SetCleanupTimeout(previous)) }) + + const timeout = 300 * time.Millisecond + require.NoError(t, SetCleanupTimeout(timeout)) + require.Equal(t, timeout, cleanupTimeout()) +} diff --git a/internal/cleanupctx/cleanupCtx.go b/internal/cleanupctx/cleanupCtx.go new file mode 100644 index 00000000..db3b2e60 --- /dev/null +++ b/internal/cleanupctx/cleanupCtx.go @@ -0,0 +1,33 @@ +package cleanupctx + +import ( + "context" + "errors" + "time" +) + +var cleanupGracePeriod time.Duration = 5 * time.Second + +// SetCleanupTimeout sets the timeout for the resource cleanup context in the event +// of an error. The default timeout is 5 seconds. +// It must be called before using the driver and must not be called +// concurrently with driver operations. +// The transmitted timeout must be at least 150 ms. +func SetCleanupTimeout(timeout time.Duration) error { + if timeout >= 150*time.Millisecond { + cleanupGracePeriod = timeout + return nil + } + return errors.New("timeout must be at least 150ms") +} + +// Returns the cleanup timeout, which defaults to 5 seconds but can be changed via [SetCleanupTimeout]. +func CleanupTimeout() time.Duration { + return cleanupGracePeriod +} + +// Returns a context for clearing and a cancellation function for it; by default, +// the context timeout is 5 seconds, but it can be changed via [SetCleanupTimeout]. +func CleanupContext(parent context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod) +} diff --git a/internal/cleanupctx/cleanup_test.go b/internal/cleanupctx/cleanup_test.go new file mode 100644 index 00000000..d1459183 --- /dev/null +++ b/internal/cleanupctx/cleanup_test.go @@ -0,0 +1,42 @@ +package cleanupctx_test + +import ( + "context" + "testing" + "testing/synctest" + "time" + + "github.com/firebirdsql/fbx" + "github.com/firebirdsql/fbx/fbconn" + "github.com/firebirdsql/fbx/internal/cleanupctx" + "github.com/stretchr/testify/require" +) + +func TestConfiguredCleanupDeadline(t *testing.T) { + previous := cleanupctx.CleanupTimeout() + t.Cleanup(func() { require.NoError(t, fbx.SetCleanupTimeout(previous)) }) + const timeout = 150 * time.Millisecond + require.NoError(t, fbx.SetCleanupTimeout(timeout)) + + synctest.Test(t, func(t *testing.T) { + parent, cancelParent := context.WithCancel(context.Background()) + cancelParent() + ctx, cancel := cleanupctx.CleanupContext(parent) + defer cancel() + + require.NoError(t, ctx.Err()) + deadline, ok := ctx.Deadline() + require.True(t, ok) + require.Equal(t, timeout, time.Until(deadline)) + }) +} + +func TestInvalidCleanupTimeoutPreservesSetting(t *testing.T) { + previous := cleanupctx.CleanupTimeout() + t.Cleanup(func() { require.NoError(t, fbconn.SetCleanupTimeout(previous)) }) + const timeout = time.Second + require.NoError(t, fbconn.SetCleanupTimeout(timeout)) + + require.Error(t, fbconn.SetCleanupTimeout(149*time.Millisecond)) + require.Equal(t, timeout, cleanupctx.CleanupTimeout()) +} diff --git a/stdlib/sql.go b/stdlib/sql.go index 2048ff60..80ea7b27 100644 --- a/stdlib/sql.go +++ b/stdlib/sql.go @@ -124,6 +124,7 @@ import ( "github.com/firebirdsql/fbx/fbproto" "github.com/firebirdsql/fbx/fbtype" "github.com/firebirdsql/fbx/fbxpool" + "github.com/firebirdsql/fbx/internal/cleanupctx" ) var ( @@ -320,7 +321,7 @@ func (c connector) Connect(ctx context.Context) (driver.Conn, error) { } if err = c.afterConnect(ctx, conn); err != nil { - closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + closeCtx, cancel := cleanupctx.CleanupContext(context.Background()) closeErr := conn.Close(closeCtx) cancel() if closeErr != nil { @@ -538,10 +539,10 @@ func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, e return &Stmt{sd: sd, conn: c}, nil } -// Close implements [driver.Conn]. It allows up to five seconds to close or -// release the underlying connection. +// Close implements [driver.Conn]. The time limit for closing or releasing the base +// connection is set using [fbx.SetCleanupTimeout] and defaults to 5 seconds. func (c *Conn) Close() error { - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + ctx, cancel := cleanupctx.CleanupContext(context.Background()) defer cancel() return c.close(ctx) } @@ -714,7 +715,7 @@ func (s *Stmt) Close() error { return nil } - ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + ctx, cancel := cleanupctx.CleanupContext(context.Background()) defer cancel() refCount, ok := s.conn.psRefCounts[s.sd] @@ -1221,7 +1222,7 @@ func (wtx wrapTx) Commit() error { return wtx.tx.Commit(wtx.ctx) } func (wtx wrapTx) Rollback() error { // database/sql calls Rollback after the begin context is canceled. Give // cleanup its own deadline so the server confirms the rollback before reuse. - ctx, cancel := context.WithTimeout(context.WithoutCancel(wtx.ctx), 5*time.Second) + ctx, cancel := cleanupctx.CleanupContext(wtx.ctx) defer cancel() return wtx.tx.Rollback(ctx) }