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
43 changes: 43 additions & 0 deletions blob_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fbx

import (
"context"
"errors"
"fmt"
"io"
"os"
Expand All @@ -10,6 +11,7 @@ import (
"time"

"github.com/firebirdsql/fbx/fbconn"
"github.com/firebirdsql/fbx/fbconn/ctxwatch"
"github.com/firebirdsql/fbx/fbproto"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -214,3 +216,44 @@ func inlineBlobDataLen(handle any) (int, bool) {
}
return data.Len(), true
}

type cancelingBlobSource struct {
cancel context.CancelFunc
err error
}

func (r cancelingBlobSource) Read([]byte) (int, error) {
r.cancel()
return 0, r.err
}

func TestBlobParameterCleanupAfterCancellation(t *testing.T) {
ctx := context.Background()
var handler *cleanupDeadlineHandler
runWithBlobStreamModesInternal(ctx, t, func(config *ConnConfig) {
config.CleanupTimeout = time.Second
config.BuildContextWatcherHandler = func(conn *fbconn.FbConn) ctxwatch.Handler {
handler = &cleanupDeadlineHandler{DeadlineContextWatcherHandler: &fbconn.DeadlineContextWatcherHandler{Conn: conn.Conn()}}
return handler
}
}, func(ctx context.Context, t testing.TB, conn *Conn) {
tx, err := conn.Begin(ctx)
require.NoError(t, err)
defer func() { require.NoError(t, tx.Rollback(ctx)) }()
requestCtx, cancel := context.WithCancel(ctx)
defer cancel()
sourceErr := errors.New("source read failed")
handler.timeout = 0
var builder ExtendedQueryBuilder
_, err = builder.createBlobFromReader(requestCtx, conn, tx.(*dbTx), fbproto.BLOB_SUB_TYPE_BINARY, 0,
cancelingBlobSource{cancel: cancel, err: sourceErr})
require.ErrorIs(t, err, sourceErr)
require.False(t, fbconn.SafeToRetry(err))
require.InDelta(t, float64(time.Second), float64(handler.timeout), float64(100*time.Millisecond),
"CancelBlob must use a live cleanup context after the source cancels the query")
require.False(t, conn.IsClosed())
var n int
require.NoError(t, tx.QueryRow(ctx, "select 1 from rdb$database").Scan(&n))
require.Equal(t, 1, n)
})
}
14 changes: 10 additions & 4 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@ func DropDatabase(ctx context.Context, connString string) error {
}
err = conn.DropDatabase(ctx)
if !conn.IsClosed() {
err = errors.Join(err, conn.Close(context.Background()))
cleanupCtx, cancel := conn.fbConn.GetCleanupContext(ctx)
err = errors.Join(err, conn.Close(cleanupCtx))
cancel()
}
return err
}
Expand Down Expand Up @@ -203,7 +205,9 @@ func DropDatabaseWithOptions(ctx context.Context, connString string, options Par
}
err = conn.DropDatabase(ctx)
if !conn.IsClosed() {
err = errors.Join(err, conn.Close(context.Background()))
cleanupCtx, cancel := conn.fbConn.GetCleanupContext(ctx)
err = errors.Join(err, conn.Close(cleanupCtx))
cancel()
}
return err
}
Expand Down Expand Up @@ -238,7 +242,9 @@ func DropDatabaseConfig(ctx context.Context, connConfig *ConnConfig) error {
}
err = conn.DropDatabase(ctx)
if !conn.IsClosed() {
err = errors.Join(err, conn.Close(context.Background()))
cleanupCtx, cancel := conn.fbConn.GetCleanupContext(ctx)
err = errors.Join(err, conn.Close(cleanupCtx))
cancel()
}
return err
}
Expand Down Expand Up @@ -763,7 +769,7 @@ optionLoop:
invalidateSQL = st.Description.SQL
if temporary {
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), defaultGracePeriod)
cleanupCtx, cancel := c.fbConn.GetCleanupContext(ctx)
defer cancel()
if cleanupErr := st.Deallocate(cleanupCtx); cleanupErr != nil {
err = operationerror.Join(err, cleanupErr)
Expand Down
64 changes: 64 additions & 0 deletions exec_cleanup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,70 @@ import (
"github.com/stretchr/testify/require"
)

type cleanupDeadlineHandler struct {
*fbconn.DeadlineContextWatcherHandler
timeout time.Duration
}

func (h *cleanupDeadlineHandler) HandleWatch(ctx context.Context) {
if deadline, ok := ctx.Deadline(); ok {
h.timeout = time.Until(deadline)
}
}

func (h *cleanupDeadlineHandler) HandleUnwatch() {}

func TestCleanupTimeoutForExecAndRows(t *testing.T) {
if os.Getenv("FBX_TEST_DATABASE") == "" {
t.Skip("FBX_TEST_DATABASE is not configured")
}
ctx := context.Background()
config, err := ParseConfig(os.Getenv("FBX_TEST_DATABASE"))
require.NoError(t, err)
config.Autocommit = true
config.DefaultQueryExecMode = QueryExecModeExec
config.CleanupTimeout = time.Second
var handler *cleanupDeadlineHandler
config.BuildContextWatcherHandler = func(conn *fbconn.FbConn) ctxwatch.Handler {
handler = &cleanupDeadlineHandler{
DeadlineContextWatcherHandler: &fbconn.DeadlineContextWatcherHandler{Conn: conn.Conn()},
}
return handler
}
conn, err := ConnectConfig(ctx, config)
require.NoError(t, err)
defer func() { _ = conn.Close(ctx) }()

for _, operation := range []string{"Exec", "Rows.Scan"} {
for _, failed := range []bool{false, true} {
t.Run(fmt.Sprintf("%s/error=%t", operation, failed), func(t *testing.T) {
handler.timeout = 0
var operationErr error
if operation == "Exec" {
var value any = 1
if failed {
value = struct{}{}
}
_, operationErr = conn.Exec(ctx, "select cast(? as integer) from rdb$database", value)
} else {
var value int
var dst any = &value
if failed {
dst = struct{}{}
}
operationErr = conn.QueryRow(ctx, "select 1 from rdb$database").Scan(dst)
}
if failed {
require.Error(t, operationErr)
} else {
require.NoError(t, operationErr)
}
require.InDelta(t, float64(config.CleanupTimeout), float64(handler.timeout), float64(100*time.Millisecond))
})
}
}
}

// Fail the next protocol operation after a successful implicit commit. The
// failure happens before cleanup can send anything, but the INSERT is committed.
type cleanupFailureHandler struct {
Expand Down
28 changes: 18 additions & 10 deletions extended_query_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/firebirdsql/fbx/fbconn"
"github.com/firebirdsql/fbx/fbtype"
"github.com/firebirdsql/fbx/internal/operationerror"
)

// ExtendedQueryBuilder encodes parameters.
Expand Down Expand Up @@ -225,15 +226,13 @@ func (pb *ExtendedQueryBuilder) createBlobFromString(ctx context.Context, conn *
}
writer, err := blob.Writer(ctx)
if err != nil {
_ = blob.Cancel(ctx)
return nil, err
return nil, cancelBlobAfterError(ctx, blob, err)
}
if _, err := writer.WriteString(s); err != nil {
_ = writer.Cancel()
return nil, err
return nil, cancelBlobAfterError(ctx, blob, err)
}
if err := writer.Close(); err != nil {
return nil, err
return nil, cancelBlobAfterError(ctx, blob, err)
}
return fbconn.EncodeBlobID(int64(blob.ID())), nil
}
Expand All @@ -256,19 +255,28 @@ func (pb *ExtendedQueryBuilder) createBlobFromReader(ctx context.Context, conn *
}
writer, err := blob.Writer(ctx)
if err != nil {
_ = blob.Cancel(ctx)
return 0, err
return 0, cancelBlobAfterError(ctx, blob, err)
}
if _, err := io.Copy(writer, r); err != nil {
_ = writer.Cancel()
return 0, err
return 0, cancelBlobAfterError(ctx, blob, err)
}
if err := writer.Close(); err != nil {
return 0, err
return 0, cancelBlobAfterError(ctx, blob, err)
}
return blob.ID(), nil
}

// The driver owns parameter blobs until encoding succeeds. A canceled request
// must not prevent releasing an unfinished blob, including a failed Close.
func cancelBlobAfterError(ctx context.Context, blob *blob, cause error) error {
if blob.conn.IsClosed() {
return cause
}
cleanupCtx, cancel := blob.conn.fbConn.GetCleanupContext(ctx)
defer cancel()
return operationerror.Join(cause, blob.Cancel(cleanupCtx))
}

func resolveExecTx(ctx context.Context, conn *Conn, tx *dbTx) (*fbconn.FBTransaction, error) {
if conn == nil || conn.fbConn == nil {
return nil, errors.New("blob parameter requires connection")
Expand Down
1 change: 1 addition & 0 deletions fbconn/cancel_request_context_watcher_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ func (c *writeErrorConn) Write(_ []byte) (int, error) {

func newCancelOperationTestFbConn(conn net.Conn) *FbConn {
fbConn := &FbConn{
config: &Config{},
conn: conn,
writer: bufio.NewWriter(conn),
status: connStatusIdle,
Expand Down
8 changes: 5 additions & 3 deletions fbconn/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,11 @@ 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 limits each driver-managed resource cleanup after success or
// failure, including closes and rollbacks without a caller-supplied context.
// It does not limit the whole operation, commit, or cancellation control.
// Explicit Close, Deallocate, Cancel and Rollback calls use the supplied context.
// Values less than or equal to zero use the default of 5 seconds.
CleanupTimeout time.Duration
DialFunc DialFunc // e.g. net.Dialer.DialContext
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
Expand Down
78 changes: 75 additions & 3 deletions fbconn/deferred_execute_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func respondToDeferredExecuteAndRollback(server net.Conn) error {
return nil
}

func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
func TestDeferredExecuteInternalReadUsesRequestDeadline(t *testing.T) {
const cleanupTimeout = 250 * time.Millisecond
for _, blockedAt := range []string{"flush", "response"} {
t.Run(blockedAt, func(t *testing.T) {
Expand All @@ -300,8 +300,8 @@ func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
select {
case result := <-done:
require.ErrorIs(t, result.Err, context.Canceled)
require.GreaterOrEqual(t, time.Since(start), cleanupTimeout,
"cleanup must replace the original short cancellation deadline")
require.Less(t, time.Since(start), cleanupTimeout,
"internal reads must retain the request cancellation deadline")
require.True(t, conn.IsClosed(), "a missing Execute response prevents reuse")
require.NoError(t, server.Close())
waitCleanupDone(t, conn)
Expand All @@ -311,3 +311,75 @@ func TestDeferredExecuteInternalReadCleanupTimeout(t *testing.T) {
})
}
}

func TestDeferredExecuteCloseCleanupTimeout(t *testing.T) {
const cleanupTimeout = 150 * time.Millisecond
for _, blockedAt := range []string{"flush", "response"} {
t.Run(blockedAt, func(t *testing.T) {
conn, st, server, _, _ := newDeferredExecutePipe(t)
conn.config.CleanupTimeout = cleanupTimeout
require.NoError(t, conn.lock())
defer conn.unlock()
ctx := context.Background()
rr := st.internalExecTx(ctx, st.transaction, &ResultReader{fbConn: conn, ctx: ctx}, nil)
if blockedAt == "response" {
go func() { _, _ = io.Copy(io.Discard, server) }()
}
start := time.Now()
done := make(chan error, 1)
go func() {
_, err := rr.closeWithoutCommit(true)
done <- err
}()
select {
case err := <-done:
require.Error(t, err)
require.True(t, Timeout(err))
require.GreaterOrEqual(t, time.Since(start), cleanupTimeout)
require.True(t, conn.IsClosed())
case <-time.After(cleanupTimeout + 2*time.Second):
_ = server.Close()
err := <-done
t.Fatalf("Close with Background did not enforce CleanupTimeout: %v", err)
}
require.NoError(t, server.Close())
waitCleanupDone(t, conn)
})
}
}

func TestInternalCleanupKeepsRequestWatcher(t *testing.T) {
var responses bytes.Buffer
require.NoError(t, writeProbeResponse(fbproto.NewXDRWriter(&responses), 0))
wire := &deferredExecuteScriptConn{responses: bytes.NewReader(responses.Bytes())}
conn := newDetachTestConn(wire)
handler := &deferredExecuteCancelHandler{
CancelRequestContextWatcherHandler: &CancelRequestContextWatcherHandler{
Conn: conn,
sendCancelOperationFunc: func(context.Context, int) error { return nil },
},
canceled: make(chan struct{}),
}
conn.contextWatcher = ctxwatch.NewContextWatcher(handler)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
conn.contextWatcher.Watch(ctx)
defer func() {
conn.contextWatcher.Unwatch()
conn.asyncClose()
waitCleanupDone(t, conn)
}()
require.NoError(t, conn.lock())
defer conn.unlock()
conn.deferredExecutePending.Store(true)
rr := &ResultReader{fbConn: conn, ctx: ctx, deferredExecute: true, rowsInfoPopulated: true}
_, err := rr.closeWithoutCommit(false)
require.NoError(t, err)
require.False(t, conn.IsClosed())
cancel()
select {
case <-handler.canceled:
case <-time.After(time.Second):
t.Fatal("internal cleanup stopped the outer request watcher")
}
}
Loading
Loading