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
14 changes: 10 additions & 4 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions conn_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
})
}
4 changes: 2 additions & 2 deletions fbconn/deferred_execute_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
})
Expand Down
30 changes: 21 additions & 9 deletions fbconn/fbconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This helper is also used in Batch.Execute to commit a successful batch in autocommit mode. Changing the cleanup timeout now also changes how long that commit can wait, even though no error has occurred. I suggest keeping the existing five-second timeout for this commit separate from the cleanup setting for now.

}

// cleanupTimeout returns a timeout for releasing server-side resources after the
// user's request has finished.
func cleanupTimeout() time.Duration {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

getCleanupTimeout()

return cleanupctx.CleanupTimeout()
}

// commitInternalTx rolls back a rejected implicit commit so the next request
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Comment on lines -3605 to +3617

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This timeout is used to enable and disable server cancellation during normal request processing, not just during cleanup. There is already a separate CancelResetTimeout setting. I suggest keeping its five-second default independent from the new cleanup timeout.

}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
Expand Down
9 changes: 9 additions & 0 deletions fbconn/fbconn_private_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
33 changes: 33 additions & 0 deletions internal/cleanupctx/cleanupCtx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package cleanupctx

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Rename this file to match the naming style used in the project. We don't use camelCase for filenames in this project.


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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Why is the minimum timeout 150 ms? If the driver requires this limit, please explain why. Otherwise, I suggest accepting positive durations, treating zero as the default, and returning an error for negative values.

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)
}
42 changes: 42 additions & 0 deletions internal/cleanupctx/cleanup_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
13 changes: 7 additions & 6 deletions stdlib/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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)
}
Loading