Skip to content

Commit

Permalink
Make it possible to configure maximum retry count when
Browse files Browse the repository at this point in the history
executing transactions.
  • Loading branch information
Yevgeniy Miretskiy committed Feb 4, 2022
1 parent 7a4e302 commit 7d9f19f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
5 changes: 2 additions & 3 deletions crdb/common.go
Expand Up @@ -62,8 +62,7 @@ func ExecuteInTx(ctx context.Context, tx Tx, fn func() error) (err error) {
return err
}

// TODO(rafi): make the maxRetryCount configurable. Maybe pass it in the context?)
const maxRetries = 50
maxRetries := numRetriesFromContext(ctx)
retryCount := 0
for {
releaseFailed := false
Expand All @@ -90,7 +89,7 @@ func ExecuteInTx(ctx context.Context, tx Tx, fn func() error) (err error) {
}

retryCount++
if retryCount > maxRetries {
if maxRetries > 0 && retryCount > maxRetries {
return newMaxRetriesExceededError(err, maxRetries)
}
}
Expand Down
20 changes: 20 additions & 0 deletions crdb/tx.go
Expand Up @@ -101,6 +101,26 @@ func Execute(fn func() error) (err error) {
}
}

type txConfigKey struct {}

// WithMaxRetries configures context so that ExecuteTx retries tx specified
// number of times when encountering retryable errors.
// Setting retries to 0 will retry indefinitely.
func WithMaxRetries(ctx context.Context, retries int) context.Context {
return context.WithValue(ctx, txConfigKey{}, retries)
}

func numRetriesFromContext(ctx context.Context) int {
const defaultRetries = 50

if v := ctx.Value(txConfigKey{}); v != nil {
if retries, ok := v.(int); ok && retries >= 0 {
return retries
}
}
return defaultRetries
}

// ExecuteTx runs fn inside a transaction and retries it as needed. On
// non-retryable failures, the transaction is aborted and rolled back; on
// success, the transaction is committed.
Expand Down

0 comments on commit 7d9f19f

Please sign in to comment.