Skip to content

Commit fc2ee4c

Browse files
committed
merge: feat/event-sourced-ledger
2 parents a8d54be + a098b12 commit fc2ee4c

30 files changed

Lines changed: 4308 additions & 0 deletions
Lines changed: 210 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
1+
"""The cases of event-sourced-ledger-typescript expect balances and versions that the store's
2+
history adds up to: the events the baseline migration seeds, and the hidden ones `grade_setup`
3+
appends. These tests fold that history the way the statement defines a balance, check that each
4+
case reading an account it did not change expects what the events say, and check that the history
5+
is one a ledger could have written."""
6+
7+
import json
8+
import re
9+
from collections.abc import Mapping
10+
from datetime import datetime
11+
from itertools import accumulate
12+
from typing import Any
13+
14+
import pytest
15+
16+
from tests.helpers import REPOSITORY_ROOT
17+
18+
PROBLEM = REPOSITORY_ROOT / "problems" / "0287-event-sourced-ledger-typescript"
19+
STARTER_BASELINE = PROBLEM / "starter" / "migrations" / "0001_baseline.sql"
20+
GRADING_BASELINE = PROBLEM / "grading" / "baseline" / "0001_baseline.sql"
21+
SEED_ROW_START = " ("
22+
SEED_ROW = re.compile(
23+
r"^ {4}\('([^']+)', (\d+), '([^']+)', '([a-z_]+)', '(\{[^']*\})', '([^']+)'\)"
24+
)
25+
CREDITS = {"deposited", "transferred_in"}
26+
HIDDEN_PREFIX = "x-"
27+
ACCOUNT_PATH = re.compile(r"^/accounts/([^/]+)$")
28+
EVENTS_PATH = re.compile(r"^/accounts/([^/]+)/events$")
29+
30+
type Event = Mapping[str, Any]
31+
type Case = Mapping[str, Any]
32+
33+
34+
def seed_rows() -> list[str]:
35+
lines = STARTER_BASELINE.read_text(encoding="utf-8").splitlines()
36+
return [line for line in lines if line.startswith(SEED_ROW_START)]
37+
38+
39+
def seed_events() -> list[Event]:
40+
events: list[Event] = []
41+
for row in seed_rows():
42+
found = SEED_ROW.match(row)
43+
if found is None:
44+
continue
45+
stream_id, version, event_id, kind, data, recorded_at = found.groups()
46+
events.append(
47+
{
48+
"stream_id": stream_id,
49+
"version": int(version),
50+
"event_id": event_id,
51+
"type": kind,
52+
"data": json.loads(data),
53+
"recorded_at": recorded_at,
54+
}
55+
)
56+
return events
57+
58+
59+
SEED = seed_events()
60+
HIDDEN: list[Event] = json.loads(
61+
(PROBLEM / "grading" / "hidden_events.json").read_text(encoding="utf-8")
62+
)
63+
HISTORY = SEED + HIDDEN
64+
CASES: list[Case] = json.loads((PROBLEM / "tests.json").read_text(encoding="utf-8"))["cases"]
65+
STREAMS = sorted({event["stream_id"] for event in HISTORY})
66+
67+
68+
def moment(text: str) -> datetime:
69+
return datetime.fromisoformat(text)
70+
71+
72+
def stream(account: str) -> list[Event]:
73+
events = [event for event in HISTORY if event["stream_id"] == account]
74+
return sorted(events, key=lambda event: event["version"])
75+
76+
77+
def signed_amount(event: Event) -> int:
78+
amount: int = event["data"]["amount"]
79+
return amount if event["type"] in CREDITS else -amount
80+
81+
82+
def account_as_of(account: str, as_of: str | None) -> dict[str, Any] | None:
83+
"""The account as the statement defines it, after its events recorded by `as_of`, or None
84+
before its first event."""
85+
events = [
86+
event
87+
for event in stream(account)
88+
if as_of is None or moment(event["recorded_at"]) <= moment(as_of)
89+
]
90+
if not events:
91+
return None
92+
balance = sum(signed_amount(event) for event in events)
93+
return {"account": account, "balance": balance, "version": len(events)}
94+
95+
96+
def stored_events(account: str) -> list[dict[str, Any]]:
97+
return [
98+
{"version": event["version"], "type": event["type"], "data": event["data"]}
99+
for event in stream(account)
100+
]
101+
102+
103+
def reads_only(case: Case) -> bool:
104+
return "request" in case and "before" not in case and case["request"]["method"] == "GET"
105+
106+
107+
def untouched_reads(path: re.Pattern[str], status: int) -> list[Any]:
108+
"""Each case that only reads a path of this shape, with nothing sent before it, and expects
109+
`status`, as a `pytest.param` of its account, its query and its expected body."""
110+
return [
111+
pytest.param(
112+
found.group(1),
113+
case["request"].get("query", {}),
114+
case["expected"].get("body"),
115+
id=case["id"],
116+
)
117+
for case in CASES
118+
if reads_only(case)
119+
and case["expected"]["status"] == status
120+
and (found := path.match(case["request"]["path"])) is not None
121+
]
122+
123+
124+
def legs(kind: str) -> list[Event]:
125+
return [event for event in HISTORY if event["type"] == kind]
126+
127+
128+
def arrives_for(departure: Event, arrival: Event) -> bool:
129+
sent = {"amount": departure["data"]["amount"], "from": departure["stream_id"]}
130+
return (
131+
arrival["event_id"] == departure["event_id"]
132+
and arrival["stream_id"] == departure["data"]["to"]
133+
and arrival["data"] == sent
134+
and arrival["recorded_at"] == departure["recorded_at"]
135+
)
136+
137+
138+
def test_the_grading_baseline_is_the_starters():
139+
assert GRADING_BASELINE.read_bytes() == STARTER_BASELINE.read_bytes()
140+
141+
142+
def test_every_seeded_row_is_read():
143+
assert len(SEED) == len(seed_rows())
144+
145+
146+
def test_hidden_events_hold_only_reserved_accounts():
147+
assert all(event["stream_id"].startswith(HIDDEN_PREFIX) for event in HIDDEN)
148+
149+
150+
def test_seeded_events_hold_no_reserved_account():
151+
assert not any(event["stream_id"].startswith(HIDDEN_PREFIX) for event in SEED)
152+
153+
154+
@pytest.mark.parametrize("account", STREAMS)
155+
def test_a_stream_is_numbered_from_1_with_no_gap(account: str):
156+
versions = [event["version"] for event in stream(account)]
157+
assert versions == list(range(1, len(versions) + 1))
158+
159+
160+
@pytest.mark.parametrize("account", STREAMS)
161+
def test_a_stream_is_recorded_in_order(account: str):
162+
times = [moment(event["recorded_at"]) for event in stream(account)]
163+
assert times == sorted(times)
164+
165+
166+
@pytest.mark.parametrize("account", STREAMS)
167+
def test_a_stream_never_goes_below_zero(account: str):
168+
balances = accumulate(signed_amount(event) for event in stream(account))
169+
assert min(balances) >= 0
170+
171+
172+
@pytest.mark.parametrize("account", STREAMS)
173+
def test_an_event_id_is_used_once_in_a_stream(account: str):
174+
ids = [event["event_id"] for event in stream(account)]
175+
assert len(ids) == len(set(ids))
176+
177+
178+
@pytest.mark.parametrize(
179+
"departure",
180+
[pytest.param(event, id=event["event_id"]) for event in legs("transferred_out")],
181+
)
182+
def test_a_transfer_arrives_where_it_was_sent(departure: Event):
183+
assert any(arrives_for(departure, arrival) for arrival in legs("transferred_in"))
184+
185+
186+
def test_every_arrival_has_a_departure():
187+
assert len(legs("transferred_in")) == len(legs("transferred_out"))
188+
189+
190+
def test_some_cases_read_the_history_untouched():
191+
assert untouched_reads(ACCOUNT_PATH, 200)
192+
193+
194+
@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(ACCOUNT_PATH, 200))
195+
def test_a_read_account_is_what_its_events_add_up_to(
196+
account: str, query: Mapping[str, str], body: Any
197+
):
198+
assert body == account_as_of(account, query.get("as_of"))
199+
200+
201+
@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(ACCOUNT_PATH, 404))
202+
def test_an_unknown_account_has_no_events_by_then(
203+
account: str, query: Mapping[str, str], body: Any
204+
):
205+
assert account_as_of(account, query.get("as_of")) is None
206+
207+
208+
@pytest.mark.parametrize(("account", "query", "body"), untouched_reads(EVENTS_PATH, 200))
209+
def test_a_read_stream_is_the_stored_events(account: str, query: Mapping[str, str], body: Any):
210+
assert body == stored_events(account)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
-- Up Migration
2+
-- The event store and the club's history so far, and the problem's: leave this file as it is and
3+
-- add your own migrations after it. Grading appends more events to this table before your
4+
-- migrations run.
5+
CREATE TABLE events (
6+
position bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
7+
stream_id text NOT NULL,
8+
version integer NOT NULL,
9+
event_id text NOT NULL,
10+
type text NOT NULL,
11+
data jsonb NOT NULL,
12+
recorded_at timestamptz NOT NULL DEFAULT now()
13+
);
14+
15+
INSERT INTO events (stream_id, version, event_id, type, data, recorded_at) VALUES
16+
('ana', 1, 'seed-1', 'deposited', '{"amount": 5000}', '2026-01-05T09:00:00Z'),
17+
('ben', 1, 'seed-2', 'deposited', '{"amount": 2000}', '2026-01-20T10:00:00Z'),
18+
('ana', 2, 'seed-3', 'withdrawn', '{"amount": 1200}', '2026-02-10T18:30:00Z'),
19+
('ana', 3, 'seed-4', 'transferred_out', '{"amount": 800, "to": "ben"}', '2026-03-02T12:00:00Z'),
20+
('ben', 2, 'seed-4', 'transferred_in', '{"amount": 800, "from": "ana"}', '2026-03-02T12:00:00Z'),
21+
('cleo', 1, 'seed-5', 'deposited', '{"amount": 500}', '2026-04-01T08:15:00Z');
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Problem-owned `grade_setup`: node-pg-migrate, the project's own tool, applies only the baseline,
2+
// and records it as it records any migration; then the hidden events are appended to the store,
3+
// as another service writing to it would. `bootstrap` applies the rest afterwards, so your
4+
// projection must come from the events the store holds, not from what your code wrote. Hidden
5+
// account ids start with `x-`, which the statement reserves.
6+
//
7+
// The script lives outside the project, so it loads the project's packages from the project
8+
// folder, its working directory.
9+
10+
import { readFile } from "node:fs/promises";
11+
import { createRequire } from "node:module";
12+
import { join } from "node:path";
13+
import { pathToFileURL } from "node:url";
14+
15+
const projectRequire = createRequire(join(process.cwd(), "package.json"));
16+
const migrate = await import(pathToFileURL(projectRequire.resolve("node-pg-migrate")).href);
17+
const pg = await import(pathToFileURL(projectRequire.resolve("pg")).href);
18+
19+
const APPEND =
20+
"INSERT INTO events (stream_id, version, event_id, type, data, recorded_at) " +
21+
"VALUES ($1, $2, $3, $4, $5, $6)";
22+
23+
const hidden = JSON.parse(await readFile(join(import.meta.dirname, "hidden_events.json"), "utf8"));
24+
25+
await migrate.runner({
26+
databaseUrl: process.env.DATABASE_URL,
27+
dir: join(import.meta.dirname, "baseline"),
28+
direction: "up",
29+
count: 1,
30+
migrationsTable: "pgmigrations",
31+
log: () => {},
32+
});
33+
34+
const database = new pg.default.Client({ connectionString: process.env.DATABASE_URL });
35+
await database.connect();
36+
try {
37+
for (const event of hidden) {
38+
await database.query(APPEND, [
39+
event.stream_id,
40+
event.version,
41+
event.event_id,
42+
event.type,
43+
event.data,
44+
event.recorded_at,
45+
]);
46+
}
47+
} finally {
48+
await database.end();
49+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
[
2+
{"stream_id": "x-dana", "version": 1, "event_id": "x-1", "type": "deposited", "data": {"amount": 7000}, "recorded_at": "2026-01-10T08:00:00Z"},
3+
{"stream_id": "x-eli", "version": 1, "event_id": "x-2", "type": "deposited", "data": {"amount": 4000}, "recorded_at": "2026-01-15T08:00:00Z"},
4+
{"stream_id": "x-dana", "version": 2, "event_id": "x-3", "type": "withdrawn", "data": {"amount": 2500}, "recorded_at": "2026-02-01T08:00:00Z"},
5+
{"stream_id": "x-eli", "version": 2, "event_id": "x-4", "type": "transferred_out", "data": {"amount": 1500, "to": "x-dana"}, "recorded_at": "2026-02-20T12:00:00Z"},
6+
{"stream_id": "x-dana", "version": 3, "event_id": "x-4", "type": "transferred_in", "data": {"amount": 1500, "from": "x-eli"}, "recorded_at": "2026-02-20T12:00:00Z"},
7+
{"stream_id": "x-dana", "version": 4, "event_id": "x-5", "type": "transferred_out", "data": {"amount": 1000, "to": "x-eli"}, "recorded_at": "2026-03-15T12:00:00Z"},
8+
{"stream_id": "x-eli", "version": 3, "event_id": "x-5", "type": "transferred_in", "data": {"amount": 1000, "from": "x-dana"}, "recorded_at": "2026-03-15T12:00:00Z"},
9+
{"stream_id": "x-eli", "version": 4, "event_id": "x-6", "type": "withdrawn", "data": {"amount": 3500}, "recorded_at": "2026-04-01T08:00:00Z"}
10+
]
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# yaml-language-server: $schema=../../schemas/meta.schema.json
2+
id: "0287"
3+
slug: event-sourced-ledger-typescript
4+
title: Event-Sourced Ledger (TypeScript)
5+
status: ready
6+
difficulty: hard
7+
track: practical
8+
kind: project
9+
domains: [fintech, backend]
10+
job_roles: [backend]
11+
scope: project
12+
languages: [typescript]
13+
summary: Every change to a club's wallets is an event that is never changed or deleted. Build the ledger on Postgres so that balances come from those events, survive bursts of withdrawals, rebuild exactly, and answer for any moment in the past.
14+
levels:
15+
- {level: 1, title: Events and a balance projection}
16+
- {level: 2, title: One version at a time}
17+
- {level: 3, title: Rebuild and replay}
18+
- {level: 4, title: Balances in the past}
19+
comparator: {type: exact}
20+
project:
21+
grading: http
22+
image: node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9
23+
commands:
24+
install: [corepack, pnpm, install, --frozen-lockfile, --ignore-scripts]
25+
bootstrap: [node, node_modules/node-pg-migrate/bin/node-pg-migrate.js, up]
26+
run: [node, src/server.ts]
27+
test: [node, --test, --test-concurrency=1]
28+
reset: [node, scripts/reset.ts]
29+
grade_setup: [node, "{problem}/grading/grade_setup.ts"]
30+
app: {port_env: PORT, port: 8000, health: /health, ready_timeout_s: 60}
31+
env:
32+
PORT: "8000"
33+
DATABASE_URL: postgres://app:app@db:5432/app
34+
install_env:
35+
COREPACK_HOME: /cache/corepack
36+
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
37+
npm_config_store_dir: /cache/pnpm-store
38+
CI: "true"
39+
services: services/compose.yaml
40+
requires:
41+
lock: pnpm-lock.yaml
42+
services: [postgres]
43+
sizes: {install_mb: 37, images_mb: {app: 81, postgres: 117}, memory_mb: 150}
44+
approaches:
45+
- {id: reference, name: "One evolve function for every fold, and a unique index that lets one append win each version", role: optimal, time: "per request", space: "per request"}
46+
related: [inventory-reservations-typescript, transactional-outbox-typescript]
47+
estimate_minutes: 240

0 commit comments

Comments
 (0)