check.go243 lines, 7.0 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "time" |
| 8 | |
| 9 | "github.com/google/uuid" |
| 10 | "github.com/jackc/pgx/v5" |
| 11 | ) |
| 12 | |
| 13 | // backlog counts the consumers on every stream, and the messages they haven't |
| 14 | // acknowledged yet. |
| 15 | func (c *checker) backlog(ctx context.Context) (consumers, pending int, err error) { |
| 16 | streams := c.js.StreamNames(ctx) |
| 17 | for name := range streams.Name() { |
| 18 | stream, err := c.js.Stream(ctx, name) |
| 19 | if err != nil { |
| 20 | return 0, 0, fmt.Errorf("stream %s: %w", name, err) |
| 21 | } |
| 22 | infos := stream.ListConsumers(ctx) |
| 23 | for info := range infos.Info() { |
| 24 | consumers++ |
| 25 | pending += int(info.NumPending) + info.NumAckPending |
| 26 | } |
| 27 | if err := infos.Err(); err != nil { |
| 28 | return 0, 0, fmt.Errorf("consumers of %s: %w", name, err) |
| 29 | } |
| 30 | } |
| 31 | return consumers, pending, streams.Err() |
| 32 | } |
| 33 | |
| 34 | // A verdict is one invariant: what it promises, whether it held, and the |
| 35 | // numbers that say so. |
| 36 | type verdict struct { |
| 37 | ok bool |
| 38 | promise string |
| 39 | detail string |
| 40 | } |
| 41 | |
| 42 | // A record is one of our transfers, as the transfer service has it. |
| 43 | type record struct { |
| 44 | ID, From, To uuid.UUID |
| 45 | Key string |
| 46 | Amount int64 |
| 47 | State string |
| 48 | } |
| 49 | |
| 50 | // A hold is the wallet's side of a transfer: the money it set aside. |
| 51 | type hold struct { |
| 52 | status string |
| 53 | to *uuid.UUID |
| 54 | amount int64 |
| 55 | } |
| 56 | |
| 57 | // verdicts checks, once everything has settled, that the API, the sagas and |
| 58 | // the ledger all tell the same story about every cent. |
| 59 | func (c *checker) verdicts(ctx context.Context, l *load, deposit int64) ([]verdict, error) { |
| 60 | rows, _ := c.transfer.Query(ctx, `SELECT id, from_wallet_id, to_wallet_id, idempotency_key, |
| 61 | amount, state FROM transfers WHERE from_wallet_id = ANY($1)`, l.wallets()) |
| 62 | records, err := pgx.CollectRows(rows, pgx.RowToStructByPos[record]) |
| 63 | if err != nil { |
| 64 | return nil, fmt.Errorf("transfers: %w", err) |
| 65 | } |
| 66 | ids := make([]uuid.UUID, len(records)) |
| 67 | for i, r := range records { |
| 68 | ids[i] = r.ID |
| 69 | } |
| 70 | holds := map[uuid.UUID]hold{} |
| 71 | rows, _ = c.wallet.Query(ctx, `SELECT id, status, settled_to, amount FROM holds |
| 72 | WHERE id = ANY($1)`, ids) |
| 73 | var id uuid.UUID |
| 74 | var h hold |
| 75 | _, err = pgx.ForEachRow(rows, []any{&id, &h.status, &h.to, &h.amount}, func() error { |
| 76 | holds[id] = h |
| 77 | return nil |
| 78 | }) |
| 79 | if err != nil { |
| 80 | return nil, fmt.Errorf("holds: %w", err) |
| 81 | } |
| 82 | balances := map[uuid.UUID]int64{} |
| 83 | rows, _ = c.wallet.Query(ctx, `SELECT account_id, balance FROM account_balances |
| 84 | WHERE account_id = ANY($1)`, l.wallets()) |
| 85 | var balance int64 |
| 86 | _, err = pgx.ForEachRow(rows, []any{&id, &balance}, func() error { |
| 87 | balances[id] = balance |
| 88 | return nil |
| 89 | }) |
| 90 | if err != nil { |
| 91 | return nil, fmt.Errorf("balances: %w", err) |
| 92 | } |
| 93 | return []verdict{ |
| 94 | requests(l.sent, records), |
| 95 | sagas(records), |
| 96 | ledger(records, holds), |
| 97 | money(l, records, balances, deposit), |
| 98 | }, nil |
| 99 | } |
| 100 | |
| 101 | // requests: every request made exactly one transfer, the one the API told |
| 102 | // us about, however many times we had to send it. |
| 103 | func requests(sent []sent, records []record) verdict { |
| 104 | byKey := map[string]uuid.UUID{} |
| 105 | for _, r := range records { |
| 106 | byKey[r.Key] = r.ID |
| 107 | } |
| 108 | var answered, replayed int |
| 109 | for _, s := range sent { |
| 110 | if s.id != uuid.Nil && byKey[s.key] == s.id { |
| 111 | answered++ |
| 112 | } |
| 113 | if s.replayed { |
| 114 | replayed++ |
| 115 | } |
| 116 | } |
| 117 | return verdict{ |
| 118 | ok: answered == len(sent) && len(records) == len(sent), |
| 119 | promise: "every request made one transfer", |
| 120 | detail: fmt.Sprintf("%s sent · %s transfers · %d replayed", |
| 121 | thousands(len(sent)), thousands(len(records)), replayed), |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | // sagas: every saga has ended. Nothing is left half done. |
| 126 | func sagas(records []record) verdict { |
| 127 | n := map[string]int{} |
| 128 | for _, r := range records { |
| 129 | n[r.State]++ |
| 130 | } |
| 131 | return verdict{ |
| 132 | ok: n["completed"]+n["failed"]+n["reversed"] == len(records), |
| 133 | promise: "no transfer stuck", |
| 134 | detail: fmt.Sprintf("%s completed · %d failed · %d reversed", |
| 135 | thousands(n["completed"]), n["failed"], n["reversed"]), |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // ledger: the wallet agrees with every saga. A completed transfer's hold was |
| 140 | // captured, into its receiver's wallet, a reversed one's went back to its |
| 141 | // sender, and a failed transfer never held anything. |
| 142 | func ledger(records []record, holds map[uuid.UUID]hold) verdict { |
| 143 | var captured, released, never, wrong int |
| 144 | for _, r := range records { |
| 145 | h, held := holds[r.ID] |
| 146 | switch { |
| 147 | case !held: |
| 148 | if r.State != "failed" { |
| 149 | wrong++ |
| 150 | continue |
| 151 | } |
| 152 | never++ |
| 153 | case h.amount != r.Amount: |
| 154 | wrong++ |
| 155 | case r.State == "completed" && h.status == "captured" && *h.to == r.To: |
| 156 | captured++ |
| 157 | case r.State == "reversed" && h.status == "released" && *h.to == r.From: |
| 158 | released++ |
| 159 | default: |
| 160 | wrong++ |
| 161 | } |
| 162 | } |
| 163 | return verdict{ |
| 164 | ok: wrong == 0, |
| 165 | promise: "the ledger agrees with every saga", |
| 166 | detail: fmt.Sprintf("%s captured · %d released · %d never held · %d wrong", |
| 167 | thousands(captured), released, never, wrong), |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // money: every wallet holds exactly what its deposit and its completed |
| 172 | // transfers say, so the total is what we put in. Not a cent was lost, made |
| 173 | // up, or moved twice. |
| 174 | func money(l *load, records []record, balances map[uuid.UUID]int64, deposit int64) verdict { |
| 175 | want := map[uuid.UUID]int64{} |
| 176 | for _, c := range l.customers { |
| 177 | want[c.wallet] = deposit |
| 178 | } |
| 179 | for _, r := range records { |
| 180 | if r.State == "completed" { |
| 181 | want[r.From] -= r.Amount |
| 182 | want[r.To] += r.Amount |
| 183 | } |
| 184 | } |
| 185 | in := deposit * int64(len(l.customers)) |
| 186 | var now int64 |
| 187 | var off int |
| 188 | for _, w := range l.wallets() { |
| 189 | now += balances[w] |
| 190 | if balances[w] != want[w] { |
| 191 | off++ |
| 192 | } |
| 193 | } |
| 194 | return verdict{ |
| 195 | ok: off == 0 && now == in, |
| 196 | promise: "every balance matches its transfers", |
| 197 | detail: fmt.Sprintf("%d wallets · %d off · %s in · %s now", |
| 198 | len(l.wallets()), off, dollars(in), dollars(now)), |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // delivered: every event left its outbox, and every consumer has it. |
| 203 | func delivered(outbox, consumers, pending int) verdict { |
| 204 | return verdict{ |
| 205 | ok: outbox == 0 && pending == 0, |
| 206 | promise: "every event delivered", |
| 207 | detail: fmt.Sprintf("%d in outboxes · %d consumers · %d pending", outbox, consumers, pending), |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | // reconciled waits for the wallet's reconciliation job to run once more, from |
| 212 | // the start, and returns what it found. |
| 213 | func (c *checker) reconciled(ctx context.Context) (verdict, error) { |
| 214 | // It runs every fifteen seconds in Compose: a minute without a run is an error. |
| 215 | ctx, cancel := context.WithTimeout(ctx, time.Minute) |
| 216 | defer cancel() |
| 217 | var since time.Time |
| 218 | if err := c.wallet.QueryRow(ctx, "SELECT now()").Scan(&since); err != nil { |
| 219 | return verdict{}, fmt.Errorf("reconciliation: %w", err) |
| 220 | } |
| 221 | for { |
| 222 | var checks, found int |
| 223 | err := c.wallet.QueryRow(ctx, `SELECT (summary->>'checks')::int, |
| 224 | jsonb_array_length(summary->'discrepancies') FROM job_runs |
| 225 | WHERE job = 'reconcile' AND status = 'succeeded' AND started_at > $1 |
| 226 | ORDER BY id DESC LIMIT 1`, since).Scan(&checks, &found) |
| 227 | if err == nil { |
| 228 | return verdict{ |
| 229 | ok: found == 0, |
| 230 | promise: "the reconciliation finds nothing", |
| 231 | detail: fmt.Sprintf("%d checks · %d discrepancies", checks, found), |
| 232 | }, nil |
| 233 | } |
| 234 | if !errors.Is(err, pgx.ErrNoRows) { |
| 235 | return verdict{}, fmt.Errorf("reconciliation: %w", err) |
| 236 | } |
| 237 | select { |
| 238 | case <-ctx.Done(): |
| 239 | return verdict{}, ctx.Err() |
| 240 | case <-time.After(time.Second): |
| 241 | } |
| 242 | } |
| 243 | } |