| 1 |
// Copyright (c) 2023 Tulir Asokan |
| 2 |
// |
| 3 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
// file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
package dbutil |
| 8 |
|
| 9 |
import ( |
| 10 |
"context" |
| 11 |
"database/sql" |
| 12 |
"errors" |
| 13 |
"fmt" |
| 14 |
"runtime" |
| 15 |
"sync/atomic" |
| 16 |
"time" |
| 17 |
|
| 18 |
"github.com/petermattis/goid" |
| 19 |
"github.com/rs/zerolog" |
| 20 |
|
| 21 |
"go.mau.fi/util/exerrors" |
| 22 |
"go.mau.fi/util/random" |
| 23 |
) |
| 24 |
|
| 25 |
var ( |
| 26 |
ErrTxn = errors.New("transaction") |
| 27 |
ErrTxnBegin = fmt.Errorf("%w: begin", ErrTxn) |
| 28 |
ErrTxnCommit = fmt.Errorf("%w: commit", ErrTxn) |
| 29 |
) |
| 30 |
|
| 31 |
type contextKey int64 |
| 32 |
|
| 33 |
const ( |
| 34 |
ContextKeyDoTxnCallerSkip contextKey = 1 |
| 35 |
) |
| 36 |
|
| 37 |
var nextContextKeyDatabaseTransaction atomic.Uint64 |
| 38 |
|
| 39 |
func init() { |
| 40 |
nextContextKeyDatabaseTransaction.Store(1 << 61) |
| 41 |
} |
| 42 |
|
| 43 |
func (db *Database) Exec(ctx context.Context, query string, args ...any) (sql.Result, error) { |
| 44 |
return db.Execable(ctx).ExecContext(ctx, query, args...) |
| 45 |
} |
| 46 |
|
| 47 |
func (db *Database) Query(ctx context.Context, query string, args ...any) (Rows, error) { |
| 48 |
return db.Execable(ctx).QueryContext(ctx, query, args...) |
| 49 |
} |
| 50 |
|
| 51 |
func (db *Database) QueryRow(ctx context.Context, query string, args ...any) *sql.Row { |
| 52 |
return db.Execable(ctx).QueryRowContext(ctx, query, args...) |
| 53 |
} |
| 54 |
|
| 55 |
var ErrTransactionDeadlock = errors.New("attempt to start new transaction in goroutine with transaction") |
| 56 |
var ErrQueryDeadlock = errors.New("attempt to query without context in goroutine with transaction") |
| 57 |
var ErrAcquireDeadlock = errors.New("attempt to acquire connection without context in goroutine with transaction") |
| 58 |
|
| 59 |
func (db *Database) BeginTx(ctx context.Context, opts *TxnOptions) (*LoggingTxn, error) { |
| 60 |
if ctx == nil { |
| 61 |
panic("BeginTx() called with nil ctx") |
| 62 |
} |
| 63 |
return db.LoggingDB.BeginTx(ctx, opts) |
| 64 |
} |
| 65 |
|
| 66 |
func (db *Database) DoTxn(ctx context.Context, opts *TxnOptions, fn func(ctx context.Context) error) error { |
| 67 |
if ctx == nil { |
| 68 |
panic("DoTxn() called with nil ctx") |
| 69 |
} |
| 70 |
if ctx.Value(db.txnCtxKey) != nil { |
| 71 |
zerolog.Ctx(ctx).Trace().Msg("Already in a transaction, not creating a new one") |
| 72 |
return fn(ctx) |
| 73 |
} else if db.DeadlockDetection { |
| 74 |
goroutineID := goid.Get() |
| 75 |
if !db.txnDeadlockMap.Add(goroutineID) { |
| 76 |
panic(ErrTransactionDeadlock) |
| 77 |
} |
| 78 |
defer db.txnDeadlockMap.Remove(goroutineID) |
| 79 |
} |
| 80 |
|
| 81 |
log := zerolog.Ctx(ctx).With().Str("db_txn_id", random.String(12)).Logger() |
| 82 |
slowLog := log |
| 83 |
|
| 84 |
callerSkip := 1 |
| 85 |
if val := ctx.Value(ContextKeyDoTxnCallerSkip); val != nil { |
| 86 |
callerSkip += val.(int) |
| 87 |
} |
| 88 |
if pc, file, line, ok := runtime.Caller(callerSkip); ok { |
| 89 |
slowLog = log.With().Str(zerolog.CallerFieldName, zerolog.CallerMarshalFunc(pc, file, line)).Logger() |
| 90 |
} |
| 91 |
|
| 92 |
start := time.Now() |
| 93 |
deadlockCh := make(chan struct{}) |
| 94 |
go func() { |
| 95 |
ticker := time.NewTicker(5 * time.Second) |
| 96 |
defer ticker.Stop() |
| 97 |
|
| 98 |
for { |
| 99 |
select { |
| 100 |
case <-ticker.C: |
| 101 |
slowLog.Warn(). |
| 102 |
Float64("duration_seconds", time.Since(start).Seconds()). |
| 103 |
Msg("Transaction still running") |
| 104 |
case <-deadlockCh: |
| 105 |
return |
| 106 |
} |
| 107 |
} |
| 108 |
}() |
| 109 |
defer func() { |
| 110 |
close(deadlockCh) |
| 111 |
dur := time.Since(start) |
| 112 |
if dur > time.Second { |
| 113 |
slowLog.Warn(). |
| 114 |
Float64("duration_seconds", dur.Seconds()). |
| 115 |
Msg("Transaction took long") |
| 116 |
} |
| 117 |
}() |
| 118 |
tx, err := db.BeginTx(ctx, opts) |
| 119 |
if err != nil { |
| 120 |
log.Trace().Err(err).Msg("Failed to begin transaction") |
| 121 |
return exerrors.NewDualError(ErrTxnBegin, err) |
| 122 |
} |
| 123 |
logLevel := zerolog.TraceLevel |
| 124 |
if GlobalSafeQueryLog { |
| 125 |
logLevel = zerolog.DebugLevel |
| 126 |
} |
| 127 |
log.WithLevel(logLevel).Msg("Transaction started") |
| 128 |
tx.noTotalLog = true |
| 129 |
ctx = log.WithContext(ctx) |
| 130 |
ctx = context.WithValue(ctx, db.txnCtxKey, tx) |
| 131 |
err = fn(ctx) |
| 132 |
if err != nil { |
| 133 |
log.Trace().Err(err).Msg("Database transaction failed, rolling back") |
| 134 |
rollbackErr := tx.Rollback() |
| 135 |
if rollbackErr != nil { |
| 136 |
log.Warn().Err(rollbackErr).Msg("Rollback after transaction error failed") |
| 137 |
} else { |
| 138 |
log.WithLevel(logLevel).Msg("Rollback successful") |
| 139 |
} |
| 140 |
return err |
| 141 |
} |
| 142 |
err = tx.Commit() |
| 143 |
if err != nil { |
| 144 |
log.WithLevel(logLevel).Err(err).Msg("Commit failed") |
| 145 |
return exerrors.NewDualError(ErrTxnCommit, err) |
| 146 |
} |
| 147 |
log.WithLevel(logLevel).Msg("Commit successful") |
| 148 |
return nil |
| 149 |
} |
| 150 |
|
| 151 |
func (db *Database) Execable(ctx context.Context) Execable { |
| 152 |
if ctx == nil { |
| 153 |
panic("Conn() called with nil ctx") |
| 154 |
} |
| 155 |
txn, ok := ctx.Value(db.txnCtxKey).(Transaction) |
| 156 |
if ok { |
| 157 |
return txn |
| 158 |
} |
| 159 |
if db.DeadlockDetection && db.txnDeadlockMap.Has(goid.Get()) { |
| 160 |
panic(ErrQueryDeadlock) |
| 161 |
} |
| 162 |
return &db.LoggingDB |
| 163 |
} |
| 164 |
|
| 165 |
func (db *Database) AcquireConn(ctx context.Context) (Conn, error) { |
| 166 |
if ctx == nil { |
| 167 |
return nil, fmt.Errorf("AcquireConn() called with nil ctx") |
| 168 |
} |
| 169 |
_, ok := ctx.Value(db.txnCtxKey).(Transaction) |
| 170 |
if ok { |
| 171 |
return nil, fmt.Errorf("cannot acquire connection while in a transaction") |
| 172 |
} |
| 173 |
if db.DeadlockDetection && db.txnDeadlockMap.Has(goid.Get()) { |
| 174 |
panic(ErrAcquireDeadlock) |
| 175 |
} |
| 176 |
conn, err := db.RawDB.Conn(ctx) |
| 177 |
if err != nil { |
| 178 |
return nil, err |
| 179 |
} |
| 180 |
return &LoggingExecable{ |
| 181 |
UnderlyingExecable: conn, |
| 182 |
db: db, |
| 183 |
}, nil |
| 184 |
} |