main.go269 lines, 7.6 KB
| 1 | // Command chaos is a game day in a box. It sends a steady stream of |
| 2 | // transfers through the gateway, the way a careful client does, while things |
| 3 | // break. Then it waits for the system to settle, and checks, against the |
| 4 | // ledger itself, that no money was lost, made up, or moved twice. |
| 5 | // |
| 6 | // go run ./cmd/chaos -duration 3m -faults chaos/gameday.sh |
| 7 | package main |
| 8 | |
| 9 | import ( |
| 10 | "bufio" |
| 11 | "context" |
| 12 | "flag" |
| 13 | "fmt" |
| 14 | "os" |
| 15 | "os/exec" |
| 16 | "os/signal" |
| 17 | "sync" |
| 18 | "time" |
| 19 | |
| 20 | "github.com/jackc/pgx/v5/pgxpool" |
| 21 | "github.com/nats-io/nats.go" |
| 22 | "github.com/nats-io/nats.go/jetstream" |
| 23 | ) |
| 24 | |
| 25 | // Where everything is, in docker-compose.yml: a test tool's defaults. |
| 26 | const ( |
| 27 | walletDB = "postgres://payments:payments@localhost:5432/wallet?sslmode=disable" |
| 28 | transferDB = "postgres://payments:payments@localhost:5432/transfer?sslmode=disable" |
| 29 | ) |
| 30 | |
| 31 | // deposit is what each customer starts with: $50, in cents. |
| 32 | const deposit = 5000 |
| 33 | |
| 34 | func main() { |
| 35 | gateway := flag.String("gateway", "http://localhost:8080", "the API") |
| 36 | customers := flag.Int("customers", 20, "how many customers send each other money") |
| 37 | rate := flag.Int("rate", 20, "transfers a second") |
| 38 | duration := flag.Duration("duration", time.Minute, "how long to send transfers for") |
| 39 | settle := flag.Duration("settle", 3*time.Minute, "how long the system gets to settle afterwards") |
| 40 | faults := flag.String("faults", "", "a script that breaks things while transfers are sent") |
| 41 | flag.Parse() |
| 42 | |
| 43 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) |
| 44 | defer stop() |
| 45 | g := gameDay{ |
| 46 | client: newClient(*gateway), customers: *customers, rate: *rate, |
| 47 | duration: *duration, settle: *settle, faults: *faults, |
| 48 | } |
| 49 | ok, err := g.run(ctx) |
| 50 | if err != nil { |
| 51 | fmt.Fprintln(os.Stderr, "chaos:", err) |
| 52 | os.Exit(2) |
| 53 | } |
| 54 | if !ok { |
| 55 | os.Exit(1) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // A gameDay is one run: customers, the load, the faults, and the checks. |
| 60 | type gameDay struct { |
| 61 | client *client |
| 62 | customers int |
| 63 | rate int |
| 64 | duration time.Duration |
| 65 | settle time.Duration |
| 66 | faults string |
| 67 | start time.Time |
| 68 | } |
| 69 | |
| 70 | // run reports whether every invariant held. An error means we couldn't tell. |
| 71 | func (g *gameDay) run(ctx context.Context) (bool, error) { |
| 72 | chk, err := connect(ctx) |
| 73 | if err != nil { |
| 74 | return false, err |
| 75 | } |
| 76 | l, err := g.signUp(ctx) |
| 77 | if err != nil { |
| 78 | return false, err |
| 79 | } |
| 80 | |
| 81 | // The load, the faults alongside it, and every five seconds, where things |
| 82 | // stand. |
| 83 | g.start = time.Now() |
| 84 | g.print("sending %d transfers a second, for %s", g.rate, g.duration) |
| 85 | var wg sync.WaitGroup |
| 86 | wg.Go(func() { l.run(ctx, g.rate, g.duration) }) |
| 87 | if g.faults != "" { |
| 88 | wg.Go(func() { g.breakThings(ctx) }) |
| 89 | } |
| 90 | done := make(chan struct{}) |
| 91 | go func() { wg.Wait(); close(done) }() |
| 92 | tick := time.NewTicker(5 * time.Second) |
| 93 | defer tick.Stop() |
| 94 | for running := true; running; { |
| 95 | select { |
| 96 | case <-tick.C: |
| 97 | g.progress(ctx, chk, l) |
| 98 | case <-done: |
| 99 | running = false |
| 100 | } |
| 101 | } |
| 102 | if ctx.Err() != nil { |
| 103 | return false, ctx.Err() |
| 104 | } |
| 105 | g.print("load done: %s transfers sent, %s retries", thousands(l.started.Load()), |
| 106 | thousands(g.client.retries.Load())) |
| 107 | |
| 108 | // Then the system gets time to finish what it started, and we check. |
| 109 | events, err := g.waitToSettle(ctx, chk, l) |
| 110 | if err != nil { |
| 111 | return false, err |
| 112 | } |
| 113 | verdicts, err := chk.verdicts(ctx, l, deposit) |
| 114 | if err != nil { |
| 115 | return false, err |
| 116 | } |
| 117 | g.print("waiting for the wallet's next reconciliation") |
| 118 | rec, err := chk.reconciled(ctx) |
| 119 | if err != nil { |
| 120 | return false, err |
| 121 | } |
| 122 | return scoreboard(append(verdicts, events, rec)), nil |
| 123 | } |
| 124 | |
| 125 | // connect opens pools on the wallet's and the transfer service's databases, |
| 126 | // and connects to NATS. |
| 127 | func connect(ctx context.Context) (*checker, error) { |
| 128 | wallet, err := pgxpool.New(ctx, walletDB) |
| 129 | if err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | transfer, err := pgxpool.New(ctx, transferDB) |
| 133 | if err != nil { |
| 134 | return nil, err |
| 135 | } |
| 136 | nc, err := nats.Connect(nats.DefaultURL, nats.MaxReconnects(-1)) |
| 137 | if err != nil { |
| 138 | return nil, err |
| 139 | } |
| 140 | js, err := jetstream.New(nc) |
| 141 | if err != nil { |
| 142 | return nil, err |
| 143 | } |
| 144 | return &checker{wallet: wallet, transfer: transfer, js: js}, nil |
| 145 | } |
| 146 | |
| 147 | // signUp creates the customers, with $50 each, and one more, whose wallet is |
| 148 | // in euros. |
| 149 | func (g *gameDay) signUp(ctx context.Context) (*load, error) { |
| 150 | l := &load{client: g.client} |
| 151 | run := time.Now().Unix() |
| 152 | for i := range g.customers { |
| 153 | c, err := g.client.signUp(ctx, fmt.Sprintf("chaos-%d-%d@example.com", run, i), "USD", deposit) |
| 154 | if err != nil { |
| 155 | return nil, err |
| 156 | } |
| 157 | l.customers = append(l.customers, c) |
| 158 | } |
| 159 | var err error |
| 160 | l.elsewhere, err = g.client.signUp(ctx, fmt.Sprintf("chaos-%d-eur@example.com", run), "EUR", 0) |
| 161 | if err != nil { |
| 162 | return nil, err |
| 163 | } |
| 164 | fmt.Printf("%d customers with %s each, and a wallet in euros\n", g.customers, dollars(deposit)) |
| 165 | return l, nil |
| 166 | } |
| 167 | |
| 168 | // breakThings runs the faults script, and prints each line it prints, when |
| 169 | // it prints it, in yellow. |
| 170 | func (g *gameDay) breakThings(ctx context.Context) { |
| 171 | cmd := exec.CommandContext(ctx, "sh", g.faults) |
| 172 | out, err := cmd.StdoutPipe() |
| 173 | if err == nil { |
| 174 | err = cmd.Start() |
| 175 | } |
| 176 | if err != nil { |
| 177 | g.print("\x1b[31mfaults: %v\x1b[0m", err) |
| 178 | return |
| 179 | } |
| 180 | lines := bufio.NewScanner(out) |
| 181 | for lines.Scan() { |
| 182 | g.print("\x1b[33m%s\x1b[0m", lines.Text()) |
| 183 | } |
| 184 | if err := cmd.Wait(); err != nil { |
| 185 | g.print("\x1b[31mfaults: %v\x1b[0m", err) |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | // waitToSettle waits until every saga is over, and every event delivered. |
| 190 | func (g *gameDay) waitToSettle(ctx context.Context, chk *checker, l *load) (verdict, error) { |
| 191 | deadline := time.Now().Add(g.settle) |
| 192 | for i := 1; ; i++ { |
| 193 | s, err := chk.status(ctx, l.wallets()) |
| 194 | consumers, pending := 0, 0 |
| 195 | if err == nil { |
| 196 | consumers, pending, err = chk.backlog(ctx) |
| 197 | } |
| 198 | if err == nil && s.inFlight() == 0 && s.outbox == 0 && pending == 0 { |
| 199 | g.print("settled") |
| 200 | return delivered(s.outbox, consumers, pending), nil |
| 201 | } |
| 202 | if time.Now().After(deadline) { |
| 203 | return verdict{}, fmt.Errorf("not settled after %s: %d in flight, %d events waiting (%v)", |
| 204 | g.settle, s.inFlight(), s.outbox+pending, err) |
| 205 | } |
| 206 | if i%5 == 0 { |
| 207 | g.progress(ctx, chk, l) |
| 208 | } |
| 209 | select { |
| 210 | case <-ctx.Done(): |
| 211 | return verdict{}, ctx.Err() |
| 212 | case <-time.After(time.Second): |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // progress prints what the load has sent, where our transfers are, and how |
| 218 | // many events wait in the outboxes. |
| 219 | func (g *gameDay) progress(ctx context.Context, chk *checker, l *load) { |
| 220 | ctx, cancel := context.WithTimeout(ctx, 2*time.Second) |
| 221 | defer cancel() |
| 222 | sent := fmt.Sprintf("sent %4d retried %4d", l.started.Load(), g.client.retries.Load()) |
| 223 | s, err := chk.status(ctx, l.wallets()) |
| 224 | if err != nil { |
| 225 | msg := err.Error() |
| 226 | g.print("%s │ \x1b[31m%s\x1b[0m", sent, msg[:min(len(msg), 60)]) |
| 227 | return |
| 228 | } |
| 229 | g.print("%s │ in flight %3d completed %4d failed %3d reversed %2d │ outbox %3d", |
| 230 | sent, s.inFlight(), s.states["completed"], s.states["failed"], s.states["reversed"], s.outbox) |
| 231 | } |
| 232 | |
| 233 | // print prints a line, after how long the run has been going. |
| 234 | func (g *gameDay) print(format string, args ...any) { |
| 235 | fmt.Printf("%4.0fs %s\n", time.Since(g.start).Seconds(), fmt.Sprintf(format, args...)) |
| 236 | } |
| 237 | |
| 238 | // scoreboard prints every verdict, and reports whether they all held. |
| 239 | func scoreboard(verdicts []verdict) bool { |
| 240 | fmt.Println() |
| 241 | ok := true |
| 242 | for _, v := range verdicts { |
| 243 | mark := "\x1b[32m✓\x1b[0m" |
| 244 | if !v.ok { |
| 245 | mark, ok = "\x1b[31m✗\x1b[0m", false |
| 246 | } |
| 247 | fmt.Printf(" %s %-36s %s\n", mark, v.promise, v.detail) |
| 248 | } |
| 249 | if ok { |
| 250 | fmt.Println("\n \x1b[1;32mNo money lost, made up, or moved twice.\x1b[0m") |
| 251 | } else { |
| 252 | fmt.Println("\n \x1b[1;31mSomething doesn't add up.\x1b[0m") |
| 253 | } |
| 254 | return ok |
| 255 | } |
| 256 | |
| 257 | // thousands formats n like 1,234. |
| 258 | func thousands[N int | int64](n N) string { |
| 259 | s := fmt.Sprint(n) |
| 260 | for i := len(s) - 3; i > 0; i -= 3 { |
| 261 | s = s[:i] + "," + s[i:] |
| 262 | } |
| 263 | return s |
| 264 | } |
| 265 | |
| 266 | // dollars formats cents like $1,234.56. |
| 267 | func dollars(cents int64) string { |
| 268 | return fmt.Sprintf("$%s.%02d", thousands(cents/100), cents%100) |
| 269 | } |