Skip to content

Commit

Permalink
processing of panics in retriers
Browse files Browse the repository at this point in the history
  • Loading branch information
asmyasnikov committed Jan 16, 2025
1 parent f3860a6 commit 5d13048
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 11 deletions.
12 changes: 1 addition & 11 deletions retry/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,17 +211,7 @@ func DoTxWithResult[T any](ctx context.Context, db *sql.DB, //nolint:funlen
return zeroValue, unwrapErrBadConn(xerrors.WithStackTrace(err))
}
defer func() {
if finalErr == nil {
return
}
errRollback := tx.Rollback()
if errRollback == nil {
return
}
finalErr = xerrors.NewWithIssues("",
xerrors.WithStackTrace(finalErr),
xerrors.WithStackTrace(fmt.Errorf("rollback failed: %w", errRollback)),
)
_ = tx.Rollback()
}()
v, err := op(xcontext.MarkRetryCall(ctx), tx)
if err != nil {
Expand Down
59 changes: 59 additions & 0 deletions retry/sql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"strconv"
"testing"
"time"
Expand Down Expand Up @@ -233,3 +234,61 @@ func TestDoTx(t *testing.T) {
})
}
}

func TestCleanUpResourcesOnPanicInRetryOperation(t *testing.T) {
panicErr := errors.New("test")
t.Run("Do", func(t *testing.T) {
m := &mockConnector{
t: t,
}
db := sql.OpenDB(m)
defer func() {
require.NoError(t, db.Close())
}()
require.Panics(t, func() {
require.Equal(t, 0, db.Stats().OpenConnections)
require.Equal(t, 0, db.Stats().Idle)
require.Equal(t, 0, db.Stats().InUse)
defer func() {
require.Equal(t, 1, db.Stats().OpenConnections)
require.Equal(t, 1, db.Stats().Idle)
require.Equal(t, 0, db.Stats().InUse)
}()
_ = Do(context.Background(), db,
func(ctx context.Context, cc *sql.Conn) error {
require.Equal(t, 1, db.Stats().OpenConnections)
require.Equal(t, 0, db.Stats().Idle)
require.Equal(t, 1, db.Stats().InUse)
panic(panicErr)
},
)
})
})
t.Run("DoTx", func(t *testing.T) {
m := &mockConnector{
t: t,
}
db := sql.OpenDB(m)
defer func() {
require.NoError(t, db.Close())
}()
require.Panics(t, func() {
require.Equal(t, 0, db.Stats().OpenConnections)
require.Equal(t, 0, db.Stats().Idle)
require.Equal(t, 0, db.Stats().InUse)
defer func() {
require.Equal(t, 1, db.Stats().OpenConnections)
require.Equal(t, 1, db.Stats().Idle)
require.Equal(t, 0, db.Stats().InUse)
}()
_ = DoTx(context.Background(), db,
func(ctx context.Context, tx *sql.Tx) error {
require.Equal(t, 1, db.Stats().OpenConnections)
require.Equal(t, 0, db.Stats().Idle)
require.Equal(t, 1, db.Stats().InUse)
panic(panicErr)
},
)
})
})
}

0 comments on commit 5d13048

Please sign in to comment.