ledger.go137 lines, 4.4 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/fiston-user/payments/internal/platform/postgres" |
| 8 | "github.com/fiston-user/payments/internal/wallet/walletdb" |
| 9 | "github.com/fiston-user/payments/internal/wallet/walletevents" |
| 10 | "github.com/google/uuid" |
| 11 | "github.com/jackc/pgx/v5" |
| 12 | ) |
| 13 | |
| 14 | // Posting is one line of a transaction: money in or out of one account. |
| 15 | type Posting struct { |
| 16 | AccountID uuid.UUID |
| 17 | Direction Direction |
| 18 | Amount int64 |
| 19 | Currency string |
| 20 | } |
| 21 | |
| 22 | // NewTransaction is a transaction we want to record. |
| 23 | type NewTransaction struct { |
| 24 | Description string |
| 25 | Postings []Posting |
| 26 | } |
| 27 | |
| 28 | // Transaction is a posted journal entry, together with its entries. |
| 29 | type Transaction struct { |
| 30 | walletdb.Transaction |
| 31 | Entries []Entry `json:"entries"` |
| 32 | } |
| 33 | |
| 34 | // inTx runs fn inside a database transaction, handing it queries bound to that |
| 35 | // transaction. It commits when fn returns nil, and rolls back otherwise. If the |
| 36 | // transaction collides with another one, all of it runs again, fn included. |
| 37 | // A Store from WithTx is already inside its caller's transaction: fn just |
| 38 | // joins it. |
| 39 | func (s *Store) inTx(ctx context.Context, fn func(q *walletdb.Queries) error) error { |
| 40 | if s.tx != nil { |
| 41 | return fn(s.q) |
| 42 | } |
| 43 | return postgres.Retry(ctx, func() error { |
| 44 | return s.tryTx(ctx, fn) |
| 45 | }) |
| 46 | } |
| 47 | |
| 48 | // tryTx makes one attempt at running fn inside a database transaction. |
| 49 | func (s *Store) tryTx(ctx context.Context, fn func(q *walletdb.Queries) error) error { |
| 50 | // Our row locks rely on READ COMMITTED: every statement sees all the work |
| 51 | // committed before it started, even work we just waited for. Ask for it, |
| 52 | // so a different default on the server can't quietly break that. |
| 53 | tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.ReadCommitted}) |
| 54 | if err != nil { |
| 55 | return fmt.Errorf("begin: %w", err) |
| 56 | } |
| 57 | // Rollback is a no-op once the transaction has committed, so deferring it |
| 58 | // covers every early return, and even a panic, in one line. |
| 59 | defer tx.Rollback(ctx) |
| 60 | |
| 61 | if err := fn(s.q.WithTx(tx)); err != nil { |
| 62 | return err |
| 63 | } |
| 64 | // Deferred constraints, like our balance check, run here, at commit. |
| 65 | if err := tx.Commit(ctx); err != nil { |
| 66 | return fmt.Errorf("commit: %w", err) |
| 67 | } |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // PostTransaction records a transaction and all of its entries atomically: |
| 72 | // either every entry is stored, or none are. Postgres rejects the whole thing |
| 73 | // at commit if its debits and credits don't balance. |
| 74 | func (s *Store) PostTransaction(ctx context.Context, nt NewTransaction) (Transaction, error) { |
| 75 | var posted Transaction |
| 76 | err := s.inTx(ctx, func(q *walletdb.Queries) error { |
| 77 | var err error |
| 78 | posted, err = insertTransaction(ctx, q, nt) |
| 79 | return err |
| 80 | }) |
| 81 | if err != nil { |
| 82 | return Transaction{}, fmt.Errorf("post transaction: %w", err) |
| 83 | } |
| 84 | return posted, nil |
| 85 | } |
| 86 | |
| 87 | // Deposit records money arriving in w from outside, funded by a settlement |
| 88 | // account, together with its deposit.completed event. |
| 89 | func (s *Store) Deposit(ctx context.Context, settlement, w Account, amount int64) (Transaction, error) { |
| 90 | var posted Transaction |
| 91 | err := s.inTx(ctx, func(q *walletdb.Queries) error { |
| 92 | var err error |
| 93 | posted, err = insertTransaction(ctx, q, NewTransaction{ |
| 94 | Description: "deposit", |
| 95 | Postings: []Posting{ |
| 96 | {AccountID: settlement.ID, Direction: Debit, Amount: amount, Currency: w.Currency}, |
| 97 | {AccountID: w.ID, Direction: Credit, Amount: amount, Currency: w.Currency}, |
| 98 | }, |
| 99 | }) |
| 100 | if err != nil { |
| 101 | return err |
| 102 | } |
| 103 | return enqueue(ctx, q, walletevents.DepositCompleted, w.ID, walletevents.Deposit{ |
| 104 | TransactionID: posted.ID, |
| 105 | Wallet: eventWallet(w), |
| 106 | Amount: amount, |
| 107 | }) |
| 108 | }) |
| 109 | if err != nil { |
| 110 | return Transaction{}, fmt.Errorf("deposit: %w", err) |
| 111 | } |
| 112 | return posted, nil |
| 113 | } |
| 114 | |
| 115 | // insertTransaction inserts a transaction and its entries with q, which must |
| 116 | // be bound to a database transaction: on its own, it isn't atomic. |
| 117 | func insertTransaction(ctx context.Context, q *walletdb.Queries, nt NewTransaction) (Transaction, error) { |
| 118 | journal, err := q.CreateTransaction(ctx, nt.Description) |
| 119 | if err != nil { |
| 120 | return Transaction{}, fmt.Errorf("insert transaction: %w", err) |
| 121 | } |
| 122 | posted := Transaction{Transaction: journal} |
| 123 | for _, p := range nt.Postings { |
| 124 | entry, err := q.CreateEntry(ctx, walletdb.CreateEntryParams{ |
| 125 | TransactionID: journal.ID, |
| 126 | AccountID: p.AccountID, |
| 127 | Direction: p.Direction, |
| 128 | Amount: p.Amount, |
| 129 | Currency: p.Currency, |
| 130 | }) |
| 131 | if err != nil { |
| 132 | return Transaction{}, fmt.Errorf("insert entry: %w", err) |
| 133 | } |
| 134 | posted.Entries = append(posted.Entries, entry) |
| 135 | } |
| 136 | return posted, nil |
| 137 | } |