-
Notifications
You must be signed in to change notification settings - Fork 8
/
tx.go
95 lines (76 loc) · 2.58 KB
/
tx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package postgres
import (
"context"
"errors"
"github.com/cenkalti/backoff/v4"
"github.com/jackc/pgerrcode"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/exp/slices"
"namespacelabs.dev/foundation/framework/tracing"
)
// https://www.postgresql.org/docs/current/mvcc-serialization-failure-handling.html
var retryableSqlStates = []string{
pgerrcode.SerializationFailure,
pgerrcode.DeadlockDetected,
pgerrcode.UniqueViolation,
pgerrcode.ExclusionViolation,
pgerrcode.AdminShutdown,
}
func ReturnFromReadWriteTx[T any](ctx context.Context, db *DB, b backoff.BackOff, f func(context.Context, pgx.Tx) (T, error)) (T, error) {
var attempt int64
return backoff.RetryWithData(func() (T, error) {
value, err := doTxFunc(ctx, db, pgx.TxOptions{IsoLevel: pgx.Serializable}, attempt, f)
if err == nil {
return value, nil
}
attempt++
if !ErrorIsRetryable(err) {
return value, backoff.Permanent(err)
}
return value, err
}, b)
}
func ReturnFromTx[T any](ctx context.Context, db *DB, txoptions pgx.TxOptions, f func(context.Context, pgx.Tx) (T, error)) (T, error) {
return doTxFunc(ctx, db, txoptions, 0, f)
}
func doTxFunc[T any](ctx context.Context, db *DB, txoptions pgx.TxOptions, attempt int64, f func(context.Context, pgx.Tx) (T, error)) (T, error) {
n := tracing.Name("pg.Transaction").Attribute(
attribute.String("pg.isolation-level", string(txoptions.IsoLevel)),
attribute.String("pg.access-mode", string(txoptions.AccessMode))).Attribute(db.traceAttributes()...)
if attempt > 0 {
n = n.Attribute(attribute.Int64("db.tx_attempt", attempt))
}
return tracing.Collect1(ctx, db.t, n, func(ctx context.Context) (T, error) {
var empty T
tx, err := db.base.BeginTx(ctx, txoptions)
if err != nil {
return empty, TransactionError{err}
}
defer func() { _ = tx.Rollback(ctx) }()
value, err := f(ctx, tx)
if err != nil {
return empty, err
}
if err := tx.Commit(ctx); err != nil {
return empty, TransactionError{err}
}
return value, nil
})
}
func ErrorIsRetryable(err error) bool {
var pgerr *pgconn.PgError
if !errors.As(err, &pgerr) {
return false
}
return slices.Contains(retryableSqlStates, pgerr.SQLState())
}
type TransactionError struct {
InternalErr error
}
func (p TransactionError) Error() string { return p.InternalErr.Error() }
func (p TransactionError) Unwrap() error { return p.InternalErr }