-
Notifications
You must be signed in to change notification settings - Fork 8
/
tx.go
171 lines (137 loc) · 5.54 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// 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"
"fmt"
"github.com/cenkalti/backoff/v4"
"github.com/jackc/pgconn"
"github.com/jackc/pgx/v4"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"namespacelabs.dev/foundation/framework/tracing"
)
const (
pgSerializationFailure = "40001"
pgUniqueConstraintViolation = "23505"
)
func ReturnFromReadWriteTx[T any](ctx context.Context, db *DB, b backoff.BackOff, f func(context.Context, pgx.Tx) (T, error)) (T, error) {
return tracing.Collect1(ctx, db.Tracer(), tracing.Name("pg.TransactionWithRetries"), func(ctx context.Context) (T, error) {
var result T
err := backoff.Retry(func() error {
value, err := doTxFunc(ctx, db, pgx.TxOptions{IsoLevel: pgx.Serializable}, f)
if err == nil {
result = value
return nil
}
if !ErrorIsRetryable(err) {
return backoff.Permanent(err)
}
return err
}, b)
return result, err
})
}
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, pgx.TxOptions{IsoLevel: pgx.Serializable}, f)
}
func doTxFunc[T any](ctx context.Context, db *DB, txoptions pgx.TxOptions, f func(context.Context, pgx.Tx) (T, error)) (T, error) {
return tracing.Collect1(ctx, db.Tracer(), tracing.Name("pg.Transaction").Attribute(
attribute.String("pg.isolation-level", string(txoptions.IsoLevel)),
attribute.String("pg.access-mode", string(txoptions.AccessMode))),
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, tracingTx{base: tx, t: db.t})
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
}
// We need to check unique constraint here because some versions of postgres have an error where
// unique constraint violations are raised instead of serialization errors.
// (e.g. https://www.postgresql.org/message-id/flat/CAGPCyEZG76zjv7S31v_xPeLNRuzj-m%3DY2GOY7PEzu7vhB%3DyQog%40mail.gmail.com)
return pgerr.SQLState() == pgSerializationFailure || pgerr.SQLState() == pgUniqueConstraintViolation
}
type TransactionError struct {
InternalErr error
}
func (p TransactionError) Error() string { return p.InternalErr.Error() }
func (p TransactionError) Unwrap() error { return p.InternalErr }
type tracingTx struct {
base pgx.Tx
t trace.Tracer
}
func (tx tracingTx) Begin(ctx context.Context) (pgx.Tx, error) {
return returnWithSpan(ctx, tx.t, "tx.Begin", "", func(ctx context.Context) (pgx.Tx, error) {
newtx, err := tx.base.Begin(ctx)
return tracingTx{newtx, tx.t}, err
})
}
func (tx tracingTx) BeginFunc(ctx context.Context, f func(pgx.Tx) error) error {
return withSpan(ctx, tx.t, "tx.BeginFunc", "", func(ctx context.Context) error {
return tx.base.BeginFunc(ctx, func(newtx pgx.Tx) error {
return f(tracingTx{base: newtx, t: tx.t})
})
})
}
func (tx tracingTx) Commit(ctx context.Context) error {
return withSpan(ctx, tx.t, "tx.Commit", "", func(ctx context.Context) error {
return tx.base.Commit(ctx)
})
}
func (tx tracingTx) Rollback(ctx context.Context) error {
return withSpan(ctx, tx.t, "tx.Rollback", "", func(ctx context.Context) error {
return tx.base.Commit(ctx)
})
}
func (tx tracingTx) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) {
return returnWithSpan(ctx, tx.t, "tx.CopyFrom", "", func(ctx context.Context) (int64, error) {
return tx.base.CopyFrom(ctx, tableName, columnNames, rowSrc)
})
}
func (tx tracingTx) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults {
return tx.base.SendBatch(ctx, b)
}
func (tx tracingTx) LargeObjects() pgx.LargeObjects {
return tx.base.LargeObjects()
}
func (tx tracingTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) {
return returnWithSpan(ctx, tx.t, "tx.Prepare", fmt.Sprintf("%s = %s", name, sql), func(ctx context.Context) (*pgconn.StatementDescription, error) {
return tx.base.Prepare(ctx, name, sql)
})
}
func (tx tracingTx) Exec(ctx context.Context, sql string, arguments ...interface{}) (pgconn.CommandTag, error) {
return returnWithSpan(ctx, tx.t, "tx.Exec", sql, func(ctx context.Context) (pgconn.CommandTag, error) {
return tx.base.Exec(ctx, sql, arguments...)
})
}
func (tx tracingTx) Query(ctx context.Context, sql string, arguments ...interface{}) (pgx.Rows, error) {
return returnWithSpan(ctx, tx.t, "tx.Query", sql, func(ctx context.Context) (pgx.Rows, error) {
return tx.base.Query(ctx, sql, arguments...)
})
}
func (tx tracingTx) QueryRow(ctx context.Context, sql string, args ...interface{}) pgx.Row {
return queryRow(ctx, tx.t, tx.base, "tx.QueryRow", sql, args...)
}
func (tx tracingTx) QueryFunc(ctx context.Context, sql string, args []interface{}, scans []interface{}, f func(pgx.QueryFuncRow) error) (pgconn.CommandTag, error) {
return returnWithSpan(ctx, tx.t, "tx.QueryFunc", sql, func(ctx context.Context) (pgconn.CommandTag, error) {
return tx.base.QueryFunc(ctx, sql, args, scans, f)
})
}
func (tx tracingTx) Conn() *pgx.Conn { return tx.base.Conn() }