Skip to content

Commit dda87e9

Browse files
committed
Add ability to configure timeout for clearing server resources.
1 parent 0f8b486 commit dda87e9

8 files changed

Lines changed: 141 additions & 21 deletions

File tree

‎conn.go‎

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

1414
"github.com/firebirdsql/fbx/fbconn"
1515
"github.com/firebirdsql/fbx/fbtype"
16+
"github.com/firebirdsql/fbx/internal/cleanupctx"
1617
"github.com/firebirdsql/fbx/internal/operationerror"
1718
"github.com/firebirdsql/fbx/internal/stmtcache"
1819
)
@@ -127,14 +128,19 @@ var (
127128
errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache")
128129
)
129130

130-
// cleanupGracePeriod bounds cleanup network calls (op_free_statement, etc.) that must
131-
// run even after the user's ctx has been cancelled.
132-
const cleanupGracePeriod = 5 * time.Second
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+
}
133139

134140
// cleanupContext returns a context for releasing server-side resources after the
135141
// user's request has finished.
136142
func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
137-
return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod)
143+
return cleanupctx.CleanupContext(parent)
138144
}
139145

140146
// Connect establishes a connection with a Firebird server with a connection string. See

‎conn_internal_test.go‎

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

1213
"github.com/firebirdsql/fbx/fbconn"
1314
"github.com/firebirdsql/fbx/fbconn/ctxwatch"
15+
"github.com/firebirdsql/fbx/internal/cleanupctx"
1416
"github.com/firebirdsql/fbx/internal/stmtcache"
1517
"github.com/stretchr/testify/assert"
1618
"github.com/stretchr/testify/require"
@@ -686,3 +688,18 @@ func TestExecTraceEndsWhenInvalidatedStatementDeallocateFails(t *testing.T) {
686688
require.Same(t, st, conn.statementCache.GetInvalidatedBySQL(cachedSQL))
687689
require.Nil(t, conn.statementCache.Get(notCachedSQL))
688690
}
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/deferred_execute_internal_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,12 +298,12 @@ func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
298298
select {
299299
case result := <-done:
300300
require.ErrorIs(t, result.Err, context.Canceled)
301-
require.GreaterOrEqual(t, time.Since(start), cleanupGracePeriod,
301+
require.GreaterOrEqual(t, time.Since(start), cleanupTimeout(),
302302
"cleanup must replace the original short cancellation deadline")
303303
require.True(t, conn.IsClosed(), "a missing Execute response prevents reuse")
304304
require.NoError(t, server.Close())
305305
waitCleanupDone(t, conn)
306-
case <-time.After(cleanupGracePeriod + 2*time.Second):
306+
case <-time.After(cleanupTimeout() + 2*time.Second):
307307
t.Fatal("internal read cleanup exceeded its timeout")
308308
}
309309
})

‎fbconn/fbconn.go‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ 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"
2526
"github.com/firebirdsql/fbx/internal/operationerror"
2627
)
2728

@@ -1423,7 +1424,7 @@ func (fbConn *FbConn) asyncClose() {
14231424
func (fbConn *FbConn) asyncCloseAfterRead(err error) {
14241425
var netErr net.Error
14251426
if errors.As(err, &netErr) && netErr.Timeout() {
1426-
fbConn.asyncCloseWithTimeout(cleanupGracePeriod)
1427+
fbConn.asyncCloseWithTimeout(cleanupTimeout())
14271428
} else {
14281429
fbConn.asyncClose()
14291430
}
@@ -2867,14 +2868,25 @@ func (rr *ResultReader) SetCallerErr(err error) {
28672868
}
28682869
}
28692870

2870-
// cleanupGracePeriod bounds cleanup network calls (e.g. op_free_statement) that
2871-
// must run even after the caller's ctx has been cancelled.
2872-
const cleanupGracePeriod = 5 * time.Second
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+
}
28732879

2874-
// cleanupContext detaches from parent cancellation but preserves Values, with a
2875-
// bounded timeout for the network call.
2880+
// cleanupContext returns a context for releasing server-side resources after the
2881+
// user's request has finished.
28762882
func cleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
2877-
return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod)
2883+
return cleanupctx.CleanupContext(parent)
2884+
}
2885+
2886+
// cleanupTimeout returns a timeout for releasing server-side resources after the
2887+
// user's request has finished.
2888+
func cleanupTimeout() time.Duration {
2889+
return cleanupctx.CleanupTimeout()
28782890
}
28792891

28802892
// commitInternalTx rolls back a rejected implicit commit so the next request
@@ -2962,7 +2974,7 @@ func (rr *ResultReader) closeWithoutCommit() (QueryStatus, error) {
29622974
rr.fbConn.contextWatcher.Unwatch()
29632975
cleanupWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{
29642976
Conn: rr.fbConn.conn,
2965-
DeadlineDelay: cleanupGracePeriod,
2977+
DeadlineDelay: cleanupTimeout(),
29662978
})
29672979
cleanupWatcher.Watch(rr.ctx)
29682980
defer cleanupWatcher.Unwatch()
@@ -3602,7 +3614,7 @@ func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() {
36023614
func (h *CancelRequestContextWatcherHandler) sendCancelOperationWithTimeout(kind int) error {
36033615
timeout := h.CancelResetTimeout
36043616
if timeout <= 0 {
3605-
timeout = 5 * time.Second
3617+
timeout = cleanupTimeout()
36063618
}
36073619
ctx, cancel := context.WithTimeout(context.Background(), timeout)
36083620
defer cancel()

‎fbconn/fbconn_private_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,3 +836,12 @@ func TestArrayGenerateSDLIncludesInt128Scale(t *testing.T) {
836836
})
837837
}
838838
}
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+
}

‎internal/cleanupctx/cleanupCtx.go‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package cleanupctx
2+
3+
import (
4+
"context"
5+
"errors"
6+
"time"
7+
)
8+
9+
var cleanupGracePeriod time.Duration = 5 * time.Second
10+
11+
// SetCleanupTimeout sets the timeout for the resource cleanup context in the event
12+
// of an error. The default timeout is 5 seconds.
13+
// It must be called before using the driver and must not be called
14+
// concurrently with driver operations.
15+
// The transmitted timeout must be at least 150 ms.
16+
func SetCleanupTimeout(timeout time.Duration) error {
17+
if timeout >= 150*time.Millisecond {
18+
cleanupGracePeriod = timeout
19+
return nil
20+
}
21+
return errors.New("timeout must be at least 150ms")
22+
}
23+
24+
// Returns the cleanup timeout, which defaults to 5 seconds but can be changed via [SetCleanupTimeout].
25+
func CleanupTimeout() time.Duration {
26+
return cleanupGracePeriod
27+
}
28+
29+
// Returns a context for clearing and a cancellation function for it; by default,
30+
// the context timeout is 5 seconds, but it can be changed via [SetCleanupTimeout].
31+
func CleanupContext(parent context.Context) (context.Context, context.CancelFunc) {
32+
return context.WithTimeout(context.WithoutCancel(parent), cleanupGracePeriod)
33+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package cleanupctx_test
2+
3+
import (
4+
"context"
5+
"testing"
6+
"testing/synctest"
7+
"time"
8+
9+
"github.com/firebirdsql/fbx"
10+
"github.com/firebirdsql/fbx/fbconn"
11+
"github.com/firebirdsql/fbx/internal/cleanupctx"
12+
"github.com/stretchr/testify/require"
13+
)
14+
15+
func TestConfiguredCleanupDeadline(t *testing.T) {
16+
previous := cleanupctx.CleanupTimeout()
17+
t.Cleanup(func() { require.NoError(t, fbx.SetCleanupTimeout(previous)) })
18+
const timeout = 150 * time.Millisecond
19+
require.NoError(t, fbx.SetCleanupTimeout(timeout))
20+
21+
synctest.Test(t, func(t *testing.T) {
22+
parent, cancelParent := context.WithCancel(context.Background())
23+
cancelParent()
24+
ctx, cancel := cleanupctx.CleanupContext(parent)
25+
defer cancel()
26+
27+
require.NoError(t, ctx.Err())
28+
deadline, ok := ctx.Deadline()
29+
require.True(t, ok)
30+
require.Equal(t, timeout, time.Until(deadline))
31+
})
32+
}
33+
34+
func TestInvalidCleanupTimeoutPreservesSetting(t *testing.T) {
35+
previous := cleanupctx.CleanupTimeout()
36+
t.Cleanup(func() { require.NoError(t, fbconn.SetCleanupTimeout(previous)) })
37+
const timeout = time.Second
38+
require.NoError(t, fbconn.SetCleanupTimeout(timeout))
39+
40+
require.Error(t, fbconn.SetCleanupTimeout(149*time.Millisecond))
41+
require.Equal(t, timeout, cleanupctx.CleanupTimeout())
42+
}

‎stdlib/sql.go‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ import (
124124
"github.com/firebirdsql/fbx/fbproto"
125125
"github.com/firebirdsql/fbx/fbtype"
126126
"github.com/firebirdsql/fbx/fbxpool"
127+
"github.com/firebirdsql/fbx/internal/cleanupctx"
127128
)
128129

129130
var (
@@ -320,7 +321,7 @@ func (c connector) Connect(ctx context.Context) (driver.Conn, error) {
320321
}
321322

322323
if err = c.afterConnect(ctx, conn); err != nil {
323-
closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
324+
closeCtx, cancel := cleanupctx.CleanupContext(context.Background())
324325
closeErr := conn.Close(closeCtx)
325326
cancel()
326327
if closeErr != nil {
@@ -538,10 +539,10 @@ func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, e
538539
return &Stmt{sd: sd, conn: c}, nil
539540
}
540541

541-
// Close implements [driver.Conn]. It allows up to five seconds to close or
542-
// release the underlying connection.
542+
// Close implements [driver.Conn]. The time limit for closing or releasing the base
543+
// connection is set using [fbx.SetCleanupTimeout] and defaults to 5 seconds.
543544
func (c *Conn) Close() error {
544-
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
545+
ctx, cancel := cleanupctx.CleanupContext(context.Background())
545546
defer cancel()
546547
return c.close(ctx)
547548
}
@@ -714,7 +715,7 @@ func (s *Stmt) Close() error {
714715
return nil
715716
}
716717

717-
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
718+
ctx, cancel := cleanupctx.CleanupContext(context.Background())
718719
defer cancel()
719720

720721
refCount, ok := s.conn.psRefCounts[s.sd]
@@ -1221,7 +1222,7 @@ func (wtx wrapTx) Commit() error { return wtx.tx.Commit(wtx.ctx) }
12211222
func (wtx wrapTx) Rollback() error {
12221223
// database/sql calls Rollback after the begin context is canceled. Give
12231224
// cleanup its own deadline so the server confirms the rollback before reuse.
1224-
ctx, cancel := context.WithTimeout(context.WithoutCancel(wtx.ctx), 5*time.Second)
1225+
ctx, cancel := cleanupctx.CleanupContext(wtx.ctx)
12251226
defer cancel()
12261227
return wtx.tx.Rollback(ctx)
12271228
}

0 commit comments

Comments
 (0)