reconcile.go121 lines, 4.9 KB
| 1 | package wallet |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "log/slog" |
| 7 | "math" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/jackc/pgx/v5" |
| 11 | "github.com/jackc/pgx/v5/pgxpool" |
| 12 | "github.com/prometheus/client_golang/prometheus" |
| 13 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 14 | ) |
| 15 | |
| 16 | // A Discrepancy is something in the ledger that shouldn't be: what a check |
| 17 | // expected, and what it found, in minor units of the currency. |
| 18 | type Discrepancy struct { |
| 19 | Check string `json:"check"` |
| 20 | Ref string `json:"ref"` // the transaction or account that's off |
| 21 | Currency string `json:"currency"` |
| 22 | Expected int64 `json:"expected"` |
| 23 | Actual int64 `json:"actual"` |
| 24 | } |
| 25 | |
| 26 | // A Reconciliation is what one run of every check found. |
| 27 | type Reconciliation struct { |
| 28 | Checks int `json:"checks"` |
| 29 | Discrepancies []Discrepancy `json:"discrepancies"` |
| 30 | } |
| 31 | |
| 32 | // signed is an entry's amount, as debits minus credits. |
| 33 | const signed = `CASE direction WHEN 'debit' THEN amount ELSE -amount END` |
| 34 | |
| 35 | // checks are the ledger's invariants. Each query returns whatever breaks |
| 36 | // one: a reference, the currency, what we expected, and what we found. |
| 37 | var checks = []struct{ name, query string }{ |
| 38 | // Debits equal credits in each currency, over every entry: the trial balance. |
| 39 | {"trial_balance", `SELECT 'all entries', currency, 0, sum(` + signed + `)::bigint |
| 40 | FROM entries GROUP BY currency HAVING sum(` + signed + `) <> 0`}, |
| 41 | // And in each transaction. |
| 42 | {"unbalanced_transaction", `SELECT transaction_id::text, currency, 0, sum(` + signed + `)::bigint |
| 43 | FROM entries GROUP BY transaction_id, currency HAVING sum(` + signed + `) <> 0`}, |
| 44 | // No customer's wallet is below zero. |
| 45 | {"overdrawn_wallet", `SELECT b.account_id::text, b.currency, 0, b.balance |
| 46 | FROM account_balances b JOIN accounts a ON a.id = b.account_id |
| 47 | WHERE a.kind = 'wallet' AND b.balance < 0`}, |
| 48 | // The holds account has exactly the money of the open holds. |
| 49 | {"holds_account", `SELECT b.account_id::text, b.currency, coalesce(h.held, 0)::bigint, b.balance |
| 50 | FROM account_balances b JOIN accounts a ON a.id = b.account_id |
| 51 | LEFT JOIN (SELECT currency, sum(amount) AS held FROM holds WHERE status = 'held' |
| 52 | GROUP BY currency) h ON h.currency = b.currency |
| 53 | WHERE a.kind = 'system' AND a.name = 'holds' AND b.balance <> coalesce(h.held, 0)`}, |
| 54 | // Events leave within five minutes: in seconds, the oldest one waiting. |
| 55 | {"outbox_lag", `SELECT 'outbox', '', 300, extract(epoch FROM now() - min(created_at))::bigint |
| 56 | FROM outbox WHERE published_at IS NULL HAVING min(created_at) < now() - interval '5 minutes'`}, |
| 57 | } |
| 58 | |
| 59 | // snapshot is a read-only transaction that sees the database as it was when |
| 60 | // it began: every query in it sees the same moment. |
| 61 | var snapshot = pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly} |
| 62 | |
| 63 | // Reconcile runs every check in one snapshot: a transfer that commits halfway |
| 64 | // through can't look like a discrepancy. A Store from WithTx runs them in its |
| 65 | // caller's transaction instead. |
| 66 | func (s *Store) Reconcile(ctx context.Context) (Reconciliation, error) { |
| 67 | tx := s.tx |
| 68 | if tx == nil { |
| 69 | var err error |
| 70 | if tx, err = s.reports.BeginTx(ctx, snapshot); err != nil { |
| 71 | return Reconciliation{}, fmt.Errorf("reconcile: %w", err) |
| 72 | } |
| 73 | defer tx.Rollback(ctx) |
| 74 | } |
| 75 | r := Reconciliation{Checks: len(checks), Discrepancies: []Discrepancy{}} |
| 76 | for _, c := range checks { |
| 77 | rows, _ := tx.Query(ctx, c.query) |
| 78 | found, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (Discrepancy, error) { |
| 79 | d := Discrepancy{Check: c.name} |
| 80 | return d, row.Scan(&d.Ref, &d.Currency, &d.Expected, &d.Actual) |
| 81 | }) |
| 82 | if err != nil { |
| 83 | return Reconciliation{}, fmt.Errorf("reconcile: %s: %w", c.name, err) |
| 84 | } |
| 85 | r.Discrepancies = append(r.Discrepancies, found...) |
| 86 | } |
| 87 | return r, nil |
| 88 | } |
| 89 | |
| 90 | // ReconcileJob is the reconciliation as a job: every discrepancy it finds is |
| 91 | // also logged, as an error, for whoever reads the logs first. |
| 92 | func ReconcileJob(s *Store, logger *slog.Logger) func(context.Context) (any, error) { |
| 93 | return func(ctx context.Context) (any, error) { |
| 94 | r, err := s.Reconcile(ctx) |
| 95 | for _, d := range r.Discrepancies { |
| 96 | logger.ErrorContext(ctx, "ledger discrepancy", "check", d.Check, "ref", d.Ref, |
| 97 | "currency", d.Currency, "expected", d.Expected, "actual", d.Actual) |
| 98 | } |
| 99 | return r, err |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | // RegisterMetrics reports what the last reconciliation found, read from the |
| 104 | // database at every scrape: every replica says the same, whichever one ran it. |
| 105 | func RegisterMetrics(pool *pgxpool.Pool) { |
| 106 | promauto.NewGaugeFunc(prometheus.GaugeOpts{ |
| 107 | Name: "reconciliation_discrepancies", |
| 108 | Help: "What the last reconciliation found. Anything but 0 needs a person.", |
| 109 | }, func() float64 { |
| 110 | ctx, cancel := context.WithTimeout(context.Background(), time.Second) |
| 111 | defer cancel() |
| 112 | var n float64 |
| 113 | err := pool.QueryRow(ctx, `SELECT jsonb_array_length(summary->'discrepancies')::float8 |
| 114 | FROM job_runs WHERE job = 'reconcile' AND status = 'succeeded' |
| 115 | ORDER BY slot DESC LIMIT 1`).Scan(&n) |
| 116 | if err != nil { |
| 117 | return math.NaN() // unknown, which isn't zero |
| 118 | } |
| 119 | return n |
| 120 | }) |
| 121 | } |