106 lines
3.5 KiB
Go
106 lines
3.5 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
// rollbackTimeout bounds a rollback that runs after the caller's context may
|
|
// already be canceled.
|
|
const rollbackTimeout = 5 * time.Second
|
|
|
|
// transactionOptions selects READ COMMITTED explicitly. Outbox writes are
|
|
// inserts guarded by unique constraints, and aggregate updates are expected to
|
|
// use optimistic version checks in their WHERE clause, so stricter isolation
|
|
// would only add serialization retries to every caller. A usecase that needs
|
|
// SERIALIZABLE should get an explicit option rather than a silent default.
|
|
var transactionOptions = pgx.TxOptions{
|
|
IsoLevel: pgx.ReadCommitted,
|
|
AccessMode: pgx.ReadWrite,
|
|
}
|
|
|
|
// Transactor implements outbound.Transactor with a pgx pool owned by the caller.
|
|
type Transactor struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewTransactor(pool *pgxpool.Pool) *Transactor {
|
|
return &Transactor{pool: pool}
|
|
}
|
|
|
|
var _ outbound.Transactor = (*Transactor)(nil)
|
|
|
|
// transactionContextKey marks a context passed to a transaction callback so a
|
|
// nested WithinTransaction call fails instead of opening a second connection.
|
|
type transactionContextKey struct{}
|
|
|
|
func (transactor *Transactor) WithinTransaction(
|
|
ctx context.Context,
|
|
fn func(ctx context.Context, unit outbound.UnitOfWork) error,
|
|
) error {
|
|
if ctx.Value(transactionContextKey{}) != nil {
|
|
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", outbound.ErrNestedTransaction)
|
|
}
|
|
tx, err := transactor.pool.BeginTx(ctx, transactionOptions)
|
|
if err != nil {
|
|
return fmt.Errorf("Transactor.WithinTransaction - begin transaction: %w", sanitizeConnectError(err))
|
|
}
|
|
finished := false
|
|
defer func() {
|
|
// Runs only when fn panics or calls runtime.Goexit. Not recovering
|
|
// keeps the original panic and its stack; the rollback error cannot
|
|
// change that outcome.
|
|
if !finished {
|
|
_ = rollback(ctx, tx)
|
|
}
|
|
}()
|
|
|
|
fnErr := fn(context.WithValue(ctx, transactionContextKey{}, true), &UnitOfWork{tx: tx, queries: sqlc.New(tx)})
|
|
finished = true
|
|
if fnErr != nil {
|
|
fnErr = markTransactionConflict(fnErr)
|
|
if rollbackErr := rollback(ctx, tx); rollbackErr != nil {
|
|
return errors.Join(fnErr, fmt.Errorf("Transactor.WithinTransaction - roll back transaction: %w", rollbackErr))
|
|
}
|
|
return fnErr
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
// pgx reports pgx.ErrTxCommitRollback when fn ignored a statement error
|
|
// and PostgreSQL rolled the aborted transaction back instead. After a
|
|
// network error the commit outcome is unknown; see outbound.Transactor.
|
|
return fmt.Errorf("Transactor.WithinTransaction - commit transaction: %w", markTransactionConflict(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func rollback(ctx context.Context, tx pgx.Tx) error {
|
|
rollbackContext, cancel := context.WithTimeout(context.WithoutCancel(ctx), rollbackTimeout)
|
|
defer cancel()
|
|
if err := tx.Rollback(rollbackContext); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
|
|
return fmt.Errorf("postgres.rollback - roll back: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UnitOfWork binds repositories to one transaction. Repositories in this
|
|
// adapter use tx directly; usecases depend on outbound.UnitOfWork and never
|
|
// see pgx types.
|
|
type UnitOfWork struct {
|
|
tx pgx.Tx
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
var _ outbound.UnitOfWork = (*UnitOfWork)(nil)
|
|
|
|
func (unit *UnitOfWork) Outbox() outbound.OutboxWriter {
|
|
return outboxWriter{queries: unit.queries}
|
|
}
|