status.go55 lines, 1.5 KB
| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/google/uuid" |
| 8 | "github.com/jackc/pgx/v5" |
| 9 | "github.com/jackc/pgx/v5/pgxpool" |
| 10 | "github.com/nats-io/nats.go/jetstream" |
| 11 | ) |
| 12 | |
| 13 | // A checker looks at the system from the inside: the wallet's and the |
| 14 | // transfer service's databases, and NATS. |
| 15 | type checker struct { |
| 16 | wallet, transfer *pgxpool.Pool |
| 17 | js jetstream.JetStream |
| 18 | } |
| 19 | |
| 20 | // A status is where things stand right now: our transfers, by state, and the |
| 21 | // events still waiting in an outbox. |
| 22 | type status struct { |
| 23 | states map[string]int |
| 24 | outbox int |
| 25 | } |
| 26 | |
| 27 | // inFlight is how many of our transfers are still in their saga. |
| 28 | func (s status) inFlight() int { |
| 29 | return s.states["pending"] + s.states["in_review"] + s.states["funds_held"] + s.states["compensating"] |
| 30 | } |
| 31 | |
| 32 | // status asks both databases where our transfers are, and what's left in |
| 33 | // their outboxes. |
| 34 | func (c *checker) status(ctx context.Context, wallets []uuid.UUID) (status, error) { |
| 35 | s := status{states: map[string]int{}} |
| 36 | rows, _ := c.transfer.Query(ctx, `SELECT state, count(*) FROM transfers |
| 37 | WHERE from_wallet_id = ANY($1) GROUP BY state`, wallets) |
| 38 | var state string |
| 39 | var n int |
| 40 | _, err := pgx.ForEachRow(rows, []any{&state, &n}, func() error { |
| 41 | s.states[state] = n |
| 42 | return nil |
| 43 | }) |
| 44 | if err != nil { |
| 45 | return s, fmt.Errorf("transfers: %w", err) |
| 46 | } |
| 47 | for _, db := range []*pgxpool.Pool{c.wallet, c.transfer} { |
| 48 | err := db.QueryRow(ctx, "SELECT count(*) FROM outbox WHERE published_at IS NULL").Scan(&n) |
| 49 | if err != nil { |
| 50 | return s, fmt.Errorf("outbox: %w", err) |
| 51 | } |
| 52 | s.outbox += n |
| 53 | } |
| 54 | return s, nil |
| 55 | } |