Skip to content
Open
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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,27 @@ the first row read or close. This saves one network round trip while retaining
both protocol commands. Servers without this flag use separate requests.
To reduce the number of later `Fetch` commands, increase `fetch_batch_size`
(default: 400); larger batches can use more client memory.

### Server resource cleanup timeout

`cleanup_timeout` controls how long the driver allows for server resource cleanup
on a connection. Cleanup includes rolling back an internal transaction and
releasing statements or batches. When an operation fails or is canceled, the
driver can give cleanup a separate deadline so it can finish after the caller's
context is canceled. Use the operation's context to limit query execution time.

The default is `5s`. Set a Go duration in either connection string format, for
example `cleanup_timeout=250ms` or
`firebird://localhost:3050/employee?cleanup_timeout=250ms`. You can also set
`CleanupTimeout` on the config returned by `fbx.ParseConfig` or `fbconn.ParseConfig`
before connecting. An omitted, zero, or negative value uses `5s`. An invalid
duration in the connection string returns a parse error.

The timeout also applies when the driver rolls back the temporary transaction
used to prepare a batch, releases resources at the end of a batch operation, or
closes a physical connection opened through `database/sql`. A shorter timeout
reduces the time spent waiting for cleanup and can cause batch preparation or
connection close to return an error. Cleanup can also fail after SQL has already
executed. If the driver cannot confirm an internal rollback, it closes the
connection so that it cannot be reused. A longer timeout gives the server more
time to finish cleanup and can delay the return of an error.
4 changes: 2 additions & 2 deletions batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (c *Conn) execBatchRows(ctx context.Context, tx *dbTx, sql string, mode Que
// transaction, or an implicit transaction managed with Autocommit disabled.
releaseInternalTx := tx == nil && c.config.Autocommit && !c.fbConn.ActiveExplicitTx()
defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := c.fbConn.GetCleanupContext(ctx)
defer cancel()
cleanupErr := b.releaseWireResources(cleanupCtx)
if cleanupErr == nil && temporary {
Expand Down Expand Up @@ -462,7 +462,7 @@ func (b *PreparedBatch) resetAfterError(ctx context.Context, operationErr error)
if b.conn.IsClosed() {
return operationErr
}
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := b.conn.fbConn.GetCleanupContext(ctx)
defer cancel()
return operationerror.Join(operationErr, b.Cancel(cleanupCtx))
}
Expand Down
2 changes: 1 addition & 1 deletion batch_insert.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func (b *batchInsert) run(ctx context.Context) (affected int64, err error) {
}
sourceRead := false
defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := b.conn.fbConn.GetCleanupContext(ctx)
defer cancel()
cleanupErr := batch.Close(cleanupCtx)
if cleanupErr != nil && !b.conn.IsClosed() {
Expand Down
15 changes: 4 additions & 11 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,15 +127,8 @@ 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

// 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)
}
// defaultGracePeriod is used as the default timeout for clean up server resources.
const defaultGracePeriod = 5 * time.Second

// Connect establishes a connection with a Firebird server with a connection string. See
// [fbconn.Connect], [fbx.ParseConfig], [fbconn.ParseConfig] for details.
Expand Down Expand Up @@ -441,7 +434,7 @@ func (c *Conn) prepareBatchTx(ctx context.Context, tx *dbTx, sql string, opts Ba
}

if err != nil && st != nil {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := c.fbConn.GetCleanupContext(ctx)
defer cancel()
if deallocErr := st.Deallocate(cleanupCtx); deallocErr != nil {
c.die()
Expand Down Expand Up @@ -770,7 +763,7 @@ optionLoop:
invalidateSQL = st.Description.SQL
if temporary {
defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultGracePeriod)
defer cancel()
if cleanupErr := st.Deallocate(cleanupCtx); cleanupErr != nil {
err = operationerror.Join(err, cleanupErr)
Expand Down
2 changes: 1 addition & 1 deletion fbconn/batch.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ func (b *Batch) Execute(ctx context.Context, tx *FBTransaction) (*BatchCompletio
}

if execTx == b.st.conn.internalTransaction && b.st.conn.config.Autocommit && !b.st.conn.explicitTransaction {
commitCtx, cancel := cleanupContext(ctx)
commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultGracePeriod)
defer cancel()
if err := b.st.conn.commitInternalTx(commitCtx, execTx); err != nil {
return completion, err
Expand Down
17 changes: 17 additions & 0 deletions fbconn/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ type Config struct {
SystemHost string
Password string
ConnectTimeout time.Duration
// CleanupTimeout used to clean up server resources in the event of an error.
// The value must be greater than 0; otherwise, the default value of
// 5 seconds will be used.
CleanupTimeout time.Duration
DialFunc DialFunc // e.g. net.Dialer.DialContext
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
BuildFrontend BuildFrontendFunc
Expand Down Expand Up @@ -447,6 +451,18 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
config.DialFunc = defaultDialer.DialContext
}

if cleanupTimeoutSetting, present := settings["cleanup_timeout"]; present {
cleanupTimeout, err := time.ParseDuration(cleanupTimeoutSetting)
if err != nil {
return nil, &ParseConfigError{ConnString: connString, msg: "invalid cleanup_timeout", err: err}
}
if cleanupTimeout <= 0 {
config.CleanupTimeout = defaultGracePeriod
} else {
config.CleanupTimeout = cleanupTimeout
}
}

config.LookupFunc = makeDefaultResolver().LookupHost

notRuntimeParams := map[string]struct{}{
Expand Down Expand Up @@ -475,6 +491,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
"fetch_batch_size": {},
"target_session_attrs": {},
"page_size": {},
"cleanup_timeout": {},
}

for k, v := range settings {
Expand Down
40 changes: 40 additions & 0 deletions fbconn/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,46 @@ func TestParseConfigPageSize(t *testing.T) {
}
}

func TestParseConfigCleanupTimeout(t *testing.T) {
t.Parallel()

tests := []struct {
value string
want time.Duration
wantErr bool
}{
{value: "10s", want: 10 * time.Second},
{value: "150ns", want: 150 * time.Nanosecond},
{value: "250ms", want: 250 * time.Millisecond},
{value: "0s", want: 5 * time.Second},
{value: "-100s", want: 5 * time.Second},
{value: "-250ms", want: 5 * time.Second},
{value: "250", wantErr: true},
{value: "invalid", wantErr: true},
}

for _, tt := range tests {
for _, connString := range []string{
"cleanup_timeout=" + tt.value,
"firebird://localhost/testdb?cleanup_timeout=" + tt.value,
} {
t.Run(connString, func(t *testing.T) {
config, err := fbconn.ParseConfig(connString)
if tt.wantErr {
var parseErr *fbconn.ParseConfigError
require.ErrorAs(t, err, &parseErr)
require.ErrorContains(t, err, "invalid cleanup_timeout")
return
}

require.NoError(t, err)
assert.Equal(t, tt.want, config.CleanupTimeout)
require.NotContains(t, config.RuntimeParams, "cleanup_timeout")
})
}
}
}

func TestParseConfigKVTrailingWhitespace(t *testing.T) {
config, err := fbconn.ParseConfig("host=localhost port=3050 database=testdb \t\n")
require.NoError(t, err)
Expand Down
6 changes: 4 additions & 2 deletions fbconn/deferred_execute_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,11 @@ func respondToDeferredExecuteAndRollback(server net.Conn) error {
}

func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
const cleanupTimeout = 250 * time.Millisecond
for _, blockedAt := range []string{"flush", "response"} {
t.Run(blockedAt, func(t *testing.T) {
conn, st, server, _, canceled := newDeferredExecutePipe(t)
conn.config.CleanupTimeout = cleanupTimeout
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
require.NoError(t, conn.lock())
Expand All @@ -298,12 +300,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")
}
})
Expand Down
40 changes: 25 additions & 15 deletions fbconn/fbconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -1423,7 +1423,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(fbConn.GetCleanupTimeout())
} else {
fbConn.asyncClose()
}
Expand Down Expand Up @@ -2059,7 +2059,7 @@ func (fbConn *FbConn) ExecParamsTx(ctx context.Context, tx *FBTransaction, sql s

rr := st.Exec(ctx, paramValues)
if rr.err != nil {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
rr.err = operationerror.Join(rr.err, st.Deallocate(cleanupCtx))
cancel()

Expand Down Expand Up @@ -2198,7 +2198,7 @@ func (fbConn *FbConn) getArrayMetadata(ctx context.Context, tx *FBTransaction, s
}

defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
_ = st.deallocateLocked(cleanupCtx)
cancel()
}()
Expand Down Expand Up @@ -2294,7 +2294,7 @@ func (fbConn *FbConn) getArrayDimensions(ctx context.Context, tx *FBTransaction,
}

defer func() {
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
_ = st.deallocateLocked(cleanupCtx)
cancel()
}()
Expand Down Expand Up @@ -2867,14 +2867,13 @@ 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
// defaultGracePeriod is used as the default timeout for clean up server resources.
const defaultGracePeriod = 5 * time.Second

// cleanupContext detaches from parent cancellation but preserves Values, with a
// bounded timeout for the network call.
func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod)
// GetCleanupContext returns a context for releasing server-side resources after the
// user's request has finished.
func (fbConn *FbConn) GetCleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.WithoutCancel(parent), fbConn.GetCleanupTimeout())
}

// commitInternalTx rolls back a rejected implicit commit so the next request
Expand Down Expand Up @@ -2911,7 +2910,7 @@ func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransac
if !fbConn.config.Autocommit || fbConn.explicitTransaction || fbConn.IsClosed() {
return nil
}
cleanupCtx, cancel := cleanupContext(ctx)
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
defer cancel()
if err := tx.Rollback(cleanupCtx); err != nil {
// A failed rollback leaves the state of the implicit transaction unknown,
Expand All @@ -2931,7 +2930,7 @@ func (rr *ResultReader) Close() (QueryStatus, error) {
rr.fbConn.unlock()

if rr.ownsStatement != nil && !rr.ownsStatement.closed {
ctx, cancel := cleanupContext(rr.ctx)
ctx, cancel := rr.fbConn.GetCleanupContext(rr.ctx)
if dErr := rr.ownsStatement.Deallocate(ctx); dErr != nil {
rr.err = operationerror.Join(rr.err, dErr)
}
Expand Down Expand Up @@ -2962,7 +2961,7 @@ func (rr *ResultReader) closeWithoutCommit() (QueryStatus, error) {
rr.fbConn.contextWatcher.Unwatch()
cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{
Conn: rr.fbConn.conn,
DeadlineDelay: cleanupGracePeriod,
DeadlineDelay: rr.fbConn.GetCleanupTimeout(),
})
cleanupWatcher.Watch(rr.ctx)
defer cleanupWatcher.Unwatch()
Expand Down Expand Up @@ -3602,7 +3601,7 @@ func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() {
func (h *CancelRequestContextWatcherHandler) sendCancelOperationWithTimeout(kind int) error {
timeout := h.CancelResetTimeout
if timeout <= 0 {
timeout = 5 * time.Second
timeout = defaultGracePeriod
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
Expand Down Expand Up @@ -3746,3 +3745,14 @@ func cloneArrayDimensions(dimensions []map[string]int) []map[string]int {
}
return cloned
}

// GetCleanupTimeout returns the server resource cleanup timeout
// set in the current connection's configuration.
// If the timeout in the configuration is less than or equal to 0,
// the default timeout of 5 seconds is returned.
func (fbConn *FbConn) GetCleanupTimeout() time.Duration {
if fbConn.config.CleanupTimeout > 0 {
return fbConn.config.CleanupTimeout
}
return defaultGracePeriod
}
19 changes: 19 additions & 0 deletions fbconn/fbconn_private_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,25 @@ func TestCommandTag(t *testing.T) {
}
}

func TestGetCleanupTimeout(t *testing.T) {
t.Parallel()

for _, tt := range []struct {
name string
configured time.Duration
want time.Duration
}{
{name: "positive", configured: 250 * time.Millisecond, want: 250 * time.Millisecond},
{name: "zero", want: 5 * time.Second},
{name: "negative", configured: -time.Second, want: 5 * time.Second},
} {
t.Run(tt.name, func(t *testing.T) {
conn := &FbConn{config: &Config{CleanupTimeout: tt.configured}}
require.Equal(t, tt.want, conn.GetCleanupTimeout())
})
}
}

func TestBatchInvalidConfigDoesNotClaimStatement(t *testing.T) {
type testCase struct {
name string
Expand Down
2 changes: 1 addition & 1 deletion rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func (rows *baseRows) Close() {
var statementErr error
if rows.boundStatement != nil {
if rows.ownsStatement {
ctx, cancel := cleanupContext(rows.ctx)
ctx, cancel := context.WithTimeout(context.WithoutCancel(rows.ctx), defaultGracePeriod)
statementErr = rows.boundStatement.Deallocate(ctx)
cancel()
} else {
Expand Down
14 changes: 9 additions & 5 deletions stdlib/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,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 := conn.FbConn().GetCleanupContext(context.Background())
closeErr := conn.Close(closeCtx)
cancel()
if closeErr != nil {
Expand Down Expand Up @@ -538,10 +538,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 [fbconn.Config.CleanupTimeout] and defaults to 5 seconds.
func (c *Conn) Close() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
ctx, cancel := c.conn.FbConn().GetCleanupContext(context.Background())
defer cancel()
return c.close(ctx)
}
Expand Down Expand Up @@ -1221,7 +1221,11 @@ 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)
timeout := 5 * time.Second
if conn := wtx.tx.Conn(); conn != nil {
timeout = conn.FbConn().GetCleanupTimeout()
}
ctx, cancel := context.WithTimeout(context.WithoutCancel(wtx.ctx), timeout)
defer cancel()
return wtx.tx.Rollback(ctx)
}
Loading
Loading