Skip to content

Commit 7e697af

Browse files
committed
Move the cleanup timeout setting to config.
1 parent dda87e9 commit 7e697af

17 files changed

Lines changed: 129 additions & 158 deletions

‎batch.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ func (c *Conn) execBatchRows(ctx context.Context, tx *dbTx, sql string, mode Que
2929
// transaction, or an implicit transaction managed with Autocommit disabled.
3030
releaseInternalTx := tx == nil && c.config.Autocommit && !c.fbConn.ActiveExplicitTx()
3131
defer func() {
32-
cleanupCtx, cancel := cleanupContext(ctx)
32+
cleanupCtx, cancel := c.fbConn.GetCleanupContext(ctx)
3333
defer cancel()
3434
cleanupErr := b.releaseWireResources(cleanupCtx)
3535
if cleanupErr == nil && temporary {
@@ -462,7 +462,7 @@ func (b *PreparedBatch) resetAfterError(ctx context.Context, operationErr error)
462462
if b.conn.IsClosed() {
463463
return operationErr
464464
}
465-
cleanupCtx, cancel := cleanupContext(ctx)
465+
cleanupCtx, cancel := b.conn.fbConn.GetCleanupContext(ctx)
466466
defer cancel()
467467
return operationerror.Join(operationErr, b.Cancel(cleanupCtx))
468468
}

‎batch_insert.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ func (b *batchInsert) run(ctx context.Context) (affected int64, err error) {
146146
}
147147
sourceRead := false
148148
defer func() {
149-
cleanupCtx, cancel := cleanupContext(ctx)
149+
cleanupCtx, cancel := b.conn.fbConn.GetCleanupContext(ctx)
150150
defer cancel()
151151
cleanupErr := batch.Close(cleanupCtx)
152152
if cleanupErr != nil && !b.conn.IsClosed() {

‎conn.go‎

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313

1414
"github.com/firebirdsql/fbx/fbconn"
1515
"github.com/firebirdsql/fbx/fbtype"
16-
"github.com/firebirdsql/fbx/internal/cleanupctx"
1716
"github.com/firebirdsql/fbx/internal/operationerror"
1817
"github.com/firebirdsql/fbx/internal/stmtcache"
1918
)
@@ -128,20 +127,8 @@ var (
128127
errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache")
129128
)
130129

131-
// SetCleanupTimeout sets the timeout for the resource cleanup context.
132-
// The default timeout is 5 seconds.
133-
// It must be called before using the driver and must not be called
134-
// concurrently with driver operations.
135-
// The timeout must be at least 150 ms.
136-
func SetCleanupTimeout(timeout time.Duration) error {
137-
return cleanupctx.SetCleanupTimeout(timeout)
138-
}
139-
140-
// cleanupContext returns a context for releasing server-side resources after the
141-
// user's request has finished.
142-
func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
143-
return cleanupctx.CleanupContext(parent)
144-
}
130+
// defaultGracePeriod is used as the default timeout for clean up server resources.
131+
const defaultGracePeriod = 5 * time.Second
145132

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

449436
if err != nil && st != nil {
450-
cleanupCtx, cancel := cleanupContext(ctx)
437+
cleanupCtx, cancel := c.fbConn.GetCleanupContext(ctx)
451438
defer cancel()
452439
if deallocErr := st.Deallocate(cleanupCtx); deallocErr != nil {
453440
c.die()
@@ -776,7 +763,7 @@ optionLoop:
776763
invalidateSQL = st.Description.SQL
777764
if temporary {
778765
defer func() {
779-
cleanupCtx, cancel := cleanupContext(ctx)
766+
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultGracePeriod)
780767
defer cancel()
781768
if cleanupErr := st.Deallocate(cleanupCtx); cleanupErr != nil {
782769
err = operationerror.Join(err, cleanupErr)

‎conn_internal_test.go‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,10 @@ import (
77
"fmt"
88
"os"
99
"testing"
10-
"testing/synctest"
1110
"time"
1211

1312
"github.com/firebirdsql/fbx/fbconn"
1413
"github.com/firebirdsql/fbx/fbconn/ctxwatch"
15-
"github.com/firebirdsql/fbx/internal/cleanupctx"
1614
"github.com/firebirdsql/fbx/internal/stmtcache"
1715
"github.com/stretchr/testify/assert"
1816
"github.com/stretchr/testify/require"
@@ -688,18 +686,3 @@ func TestExecTraceEndsWhenInvalidatedStatementDeallocateFails(t *testing.T) {
688686
require.Same(t, st, conn.statementCache.GetInvalidatedBySQL(cachedSQL))
689687
require.Nil(t, conn.statementCache.Get(notCachedSQL))
690688
}
691-
692-
func TestSetCleanupTimeout(t *testing.T) {
693-
previous := cleanupctx.CleanupTimeout()
694-
t.Cleanup(func() { require.NoError(t, SetCleanupTimeout(previous)) })
695-
696-
const timeout = 300 * time.Millisecond
697-
require.NoError(t, SetCleanupTimeout(timeout))
698-
synctest.Test(t, func(t *testing.T) {
699-
ctx, cancel := cleanupContext(context.Background())
700-
defer cancel()
701-
deadline, ok := ctx.Deadline()
702-
require.True(t, ok)
703-
require.Equal(t, timeout, time.Until(deadline))
704-
})
705-
}

‎fbconn/batch.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ func (b *Batch) Execute(ctx context.Context, tx *FBTransaction) (*BatchCompletio
401401
}
402402

403403
if execTx == b.st.conn.internalTransaction && b.st.conn.config.Autocommit && !b.st.conn.explicitTransaction {
404-
commitCtx, cancel := cleanupContext(ctx)
404+
commitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultGracePeriod)
405405
defer cancel()
406406
if err := b.st.conn.commitInternalTx(commitCtx, execTx); err != nil {
407407
return completion, err

‎fbconn/config.go‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ type Config struct {
3838
SystemHost string
3939
Password string
4040
ConnectTimeout time.Duration
41+
// CleanupTimeout used to clean up server resources in the event of an error.
42+
// The value must be greater than 0; otherwise, the default value of
43+
// 5 seconds will be used. When parsing from a configuration string,
44+
// a parsing error will occur if the value is less than or equal to 0.
45+
CleanupTimeout time.Duration
4146
DialFunc DialFunc // e.g. net.Dialer.DialContext
4247
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
4348
BuildFrontend BuildFrontendFunc
@@ -447,6 +452,17 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
447452
config.DialFunc = defaultDialer.DialContext
448453
}
449454

455+
if cleanupTimeoutSetting, present := settings["cleanup_timeout"]; present {
456+
cleanupTimeout, err := time.ParseDuration(cleanupTimeoutSetting)
457+
if err != nil {
458+
return nil, &ParseConfigError{ConnString: connString, msg: "invalid cleanup_timeout", err: err}
459+
}
460+
if cleanupTimeout <= 0 {
461+
return nil, &ParseConfigError{ConnString: connString, msg: "invalid cleanup_timeout", err: errors.New("cleanup_timeout must be positive")}
462+
}
463+
config.CleanupTimeout = cleanupTimeout
464+
}
465+
450466
config.LookupFunc = makeDefaultResolver().LookupHost
451467

452468
notRuntimeParams := map[string]struct{}{
@@ -475,6 +491,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
475491
"fetch_batch_size": {},
476492
"target_session_attrs": {},
477493
"page_size": {},
494+
"cleanup_timeout": {},
478495
}
479496

480497
for k, v := range settings {

‎fbconn/config_test.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,40 @@ func TestParseConfigPageSize(t *testing.T) {
557557
}
558558
}
559559

560+
func TestParseConfigCleanupTimeout(t *testing.T) {
561+
t.Parallel()
562+
563+
for _, connString := range []string{
564+
"cleanup_timeout=250ms",
565+
"firebird://localhost/testdb?cleanup_timeout=250ms",
566+
} {
567+
t.Run(connString, func(t *testing.T) {
568+
config, err := fbconn.ParseConfig(connString)
569+
require.NoError(t, err)
570+
require.Equal(t, 250*time.Millisecond, config.CleanupTimeout)
571+
require.NotContains(t, config.RuntimeParams, "cleanup_timeout")
572+
})
573+
}
574+
}
575+
576+
func TestParseConfigInvalidCleanupTimeout(t *testing.T) {
577+
t.Parallel()
578+
579+
for _, value := range []string{"invalid", "250", "0s", "-250ms"} {
580+
for _, connString := range []string{
581+
"cleanup_timeout=" + value,
582+
"firebird://localhost/testdb?cleanup_timeout=" + value,
583+
} {
584+
t.Run(connString, func(t *testing.T) {
585+
_, err := fbconn.ParseConfig(connString)
586+
var parseErr *fbconn.ParseConfigError
587+
require.ErrorAs(t, err, &parseErr)
588+
require.ErrorContains(t, err, "invalid cleanup_timeout")
589+
})
590+
}
591+
}
592+
}
593+
560594
func TestParseConfigKVTrailingWhitespace(t *testing.T) {
561595
config, err := fbconn.ParseConfig("host=localhost port=3050 database=testdb \t\n")
562596
require.NoError(t, err)

‎fbconn/deferred_execute_internal_test.go‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -274,9 +274,11 @@ func respondToDeferredExecuteAndRollback(server net.Conn) error {
274274
}
275275

276276
func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
277+
const cleanupTimeout = 250 * time.Millisecond
277278
for _, blockedAt := range []string{"flush", "response"} {
278279
t.Run(blockedAt, func(t *testing.T) {
279280
conn, st, server, _, canceled := newDeferredExecutePipe(t)
281+
conn.config.CleanupTimeout = cleanupTimeout
280282
ctx, cancel := context.WithCancel(context.Background())
281283
defer cancel()
282284
require.NoError(t, conn.lock())
@@ -298,12 +300,12 @@ func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
298300
select {
299301
case result := <-done:
300302
require.ErrorIs(t, result.Err, context.Canceled)
301-
require.GreaterOrEqual(t, time.Since(start), cleanupTimeout(),
303+
require.GreaterOrEqual(t, time.Since(start), cleanupTimeout,
302304
"cleanup must replace the original short cancellation deadline")
303305
require.True(t, conn.IsClosed(), "a missing Execute response prevents reuse")
304306
require.NoError(t, server.Close())
305307
waitCleanupDone(t, conn)
306-
case <-time.After(cleanupTimeout() + 2*time.Second):
308+
case <-time.After(cleanupTimeout + 2*time.Second):
307309
t.Fatal("internal read cleanup exceeded its timeout")
308310
}
309311
})

‎fbconn/fbconn.go‎

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ import (
2222
"github.com/firebirdsql/fbx/fbproto"
2323
"github.com/firebirdsql/fbx/fbproto/auth"
2424
"github.com/firebirdsql/fbx/fbproto/wirecrypt"
25-
"github.com/firebirdsql/fbx/internal/cleanupctx"
2625
"github.com/firebirdsql/fbx/internal/operationerror"
2726
)
2827

@@ -1424,7 +1423,7 @@ func (fbConn *FbConn) asyncClose() {
14241423
func (fbConn *FbConn) asyncCloseAfterRead(err error) {
14251424
var netErr net.Error
14261425
if errors.As(err, &netErr) && netErr.Timeout() {
1427-
fbConn.asyncCloseWithTimeout(cleanupTimeout())
1426+
fbConn.asyncCloseWithTimeout(fbConn.GetCleanupTimeout())
14281427
} else {
14291428
fbConn.asyncClose()
14301429
}
@@ -2060,7 +2059,7 @@ func (fbConn *FbConn) ExecParamsTx(ctx context.Context, tx *FBTransaction, sql s
20602059

20612060
rr := st.Exec(ctx, paramValues)
20622061
if rr.err != nil {
2063-
cleanupCtx, cancel := cleanupContext(ctx)
2062+
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
20642063
rr.err = operationerror.Join(rr.err, st.Deallocate(cleanupCtx))
20652064
cancel()
20662065

@@ -2199,7 +2198,7 @@ func (fbConn *FbConn) getArrayMetadata(ctx context.Context, tx *FBTransaction, s
21992198
}
22002199

22012200
defer func() {
2202-
cleanupCtx, cancel := cleanupContext(ctx)
2201+
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
22032202
_ = st.deallocateLocked(cleanupCtx)
22042203
cancel()
22052204
}()
@@ -2295,7 +2294,7 @@ func (fbConn *FbConn) getArrayDimensions(ctx context.Context, tx *FBTransaction,
22952294
}
22962295

22972296
defer func() {
2298-
cleanupCtx, cancel := cleanupContext(ctx)
2297+
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
22992298
_ = st.deallocateLocked(cleanupCtx)
23002299
cancel()
23012300
}()
@@ -2868,25 +2867,13 @@ func (rr *ResultReader) SetCallerErr(err error) {
28682867
}
28692868
}
28702869

2871-
// SetCleanupTimeout sets the timeout for the resource cleanup context.
2872-
// The default timeout is 5 seconds.
2873-
// It must be called before using the driver and must not be called
2874-
// concurrently with driver operations.
2875-
// The transmitted timeout must be at least 150 ms.
2876-
func SetCleanupTimeout(timeout time.Duration) error {
2877-
return cleanupctx.SetCleanupTimeout(timeout)
2878-
}
2879-
2880-
// cleanupContext returns a context for releasing server-side resources after the
2881-
// user's request has finished.
2882-
func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
2883-
return cleanupctx.CleanupContext(parent)
2884-
}
2870+
// defaultGracePeriod is used as the default timeout for clean up server resources.
2871+
const defaultGracePeriod = 5 * time.Second
28852872

2886-
// cleanupTimeout returns a timeout for releasing server-side resources after the
2873+
// GetCleanupContext returns a context for releasing server-side resources after the
28872874
// user's request has finished.
2888-
func cleanupTimeout() time.Duration {
2889-
return cleanupctx.CleanupTimeout()
2875+
func (fbConn *FbConn) GetCleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
2876+
return context.WithTimeout(context.WithoutCancel(parent), fbConn.GetCleanupTimeout())
28902877
}
28912878

28922879
// commitInternalTx rolls back a rejected implicit commit so the next request
@@ -2923,7 +2910,7 @@ func (fbConn *FbConn) rollbackOwnedInternalTx(ctx context.Context, tx *FBTransac
29232910
if !fbConn.config.Autocommit || fbConn.explicitTransaction || fbConn.IsClosed() {
29242911
return nil
29252912
}
2926-
cleanupCtx, cancel := cleanupContext(ctx)
2913+
cleanupCtx, cancel := fbConn.GetCleanupContext(ctx)
29272914
defer cancel()
29282915
if err := tx.Rollback(cleanupCtx); err != nil {
29292916
// A failed rollback leaves the state of the implicit transaction unknown,
@@ -2943,7 +2930,7 @@ func (rr *ResultReader) Close() (QueryStatus, error) {
29432930
rr.fbConn.unlock()
29442931

29452932
if rr.ownsStatement != nil && !rr.ownsStatement.closed {
2946-
ctx, cancel := cleanupContext(rr.ctx)
2933+
ctx, cancel := rr.fbConn.GetCleanupContext(rr.ctx)
29472934
if dErr := rr.ownsStatement.Deallocate(ctx); dErr != nil {
29482935
rr.err = operationerror.Join(rr.err, dErr)
29492936
}
@@ -2974,7 +2961,7 @@ func (rr *ResultReader) closeWithoutCommit() (QueryStatus, error) {
29742961
rr.fbConn.contextWatcher.Unwatch()
29752962
cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{
29762963
Conn: rr.fbConn.conn,
2977-
DeadlineDelay: cleanupTimeout(),
2964+
DeadlineDelay: rr.fbConn.GetCleanupTimeout(),
29782965
})
29792966
cleanupWatcher.Watch(rr.ctx)
29802967
defer cleanupWatcher.Unwatch()
@@ -3614,7 +3601,7 @@ func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() {
36143601
func (h *CancelRequestContextWatcherHandler) sendCancelOperationWithTimeout(kind int) error {
36153602
timeout := h.CancelResetTimeout
36163603
if timeout <= 0 {
3617-
timeout = cleanupTimeout()
3604+
timeout = defaultGracePeriod
36183605
}
36193606
ctx, cancel := context.WithTimeout(context.Background(), timeout)
36203607
defer cancel()
@@ -3758,3 +3745,14 @@ func cloneArrayDimensions(dimensions []map[string]int) []map[string]int {
37583745
}
37593746
return cloned
37603747
}
3748+
3749+
// GetCleanupTimeout returns the server resource cleanup timeout
3750+
// set in the current connection's configuration.
3751+
// If the timeout in the configuration is less than or equal to 0,
3752+
// the default timeout of 5 seconds is returned.
3753+
func (fbConn *FbConn) GetCleanupTimeout() time.Duration {
3754+
if fbConn.config.CleanupTimeout > 0 {
3755+
return fbConn.config.CleanupTimeout
3756+
}
3757+
return defaultGracePeriod
3758+
}

‎fbconn/fbconn_private_test.go‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,25 @@ func TestCommandTag(t *testing.T) {
4444
}
4545
}
4646

47+
func TestGetCleanupTimeout(t *testing.T) {
48+
t.Parallel()
49+
50+
for _, tt := range []struct {
51+
name string
52+
configured time.Duration
53+
want time.Duration
54+
}{
55+
{name: "positive", configured: 250 * time.Millisecond, want: 250 * time.Millisecond},
56+
{name: "zero", want: 5 * time.Second},
57+
{name: "negative", configured: -time.Second, want: 5 * time.Second},
58+
} {
59+
t.Run(tt.name, func(t *testing.T) {
60+
conn := &FbConn{config: &Config{CleanupTimeout: tt.configured}}
61+
require.Equal(t, tt.want, conn.GetCleanupTimeout())
62+
})
63+
}
64+
}
65+
4766
func TestBatchInvalidConfigDoesNotClaimStatement(t *testing.T) {
4867
type testCase struct {
4968
name string
@@ -836,12 +855,3 @@ func TestArrayGenerateSDLIncludesInt128Scale(t *testing.T) {
836855
})
837856
}
838857
}
839-
840-
func TestSetCleanupTimeout(t *testing.T) {
841-
previous := cleanupTimeout()
842-
t.Cleanup(func() { require.NoError(t, SetCleanupTimeout(previous)) })
843-
844-
const timeout = 300 * time.Millisecond
845-
require.NoError(t, SetCleanupTimeout(timeout))
846-
require.Equal(t, timeout, cleanupTimeout())
847-
}

0 commit comments

Comments
 (0)