Add the front page's D1 projection: every project's outbox feeds one table of open asks, read in one query
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- `ProjectionD1` (`packages/project/src/projection-d1/projection.ts`) implements W2 214's `Projection` over `effect/sql`'s `SqlClient`: per project, events apply in seq order, once each. Every statement is guarded by the project's `cursor` row ("the cursor stands just before this event") and each event's last statement moves the cursor on, so a replayed row, an older row after a newer one, or two racing deliveries change nothing (principle 8), with no read before the write.
- A row past a gap is not applied: `apply` writes what continues each cursor, then fails with `ProjectionFailed` naming where the project stands, so the outbox keeps the rows and sends them again after the missing one. Reason: the DO settles each commit's rows on their own and retries a failed row later, so "skip older seqs" alone would drop the failed event for good.
- One call is one atomic write: a D1 batch when a `D1Client` is in context (D1 has no interactive transactions; `withTransaction` dies there), a transaction otherwise (sqlite-node in tests, any other SQLite). 317 must compose both over `D1Client.layer({ db })`, which provides `D1Client` and `SqlClient` together.
- `claimed` counts live claims (`Claimed` +1, `Released`/`Lapsed` -1, floored at 0), since `Released` carries no claimant and a race ask may hold several claims; `AskClosed` deletes the row. Other events only move the cursor.
- `FrontPageD1` (`front-page.ts`) implements 301's `FrontPage`: `entries(filter)` is one query (filters by kind and reserve, newest first), rows decoded with the domain's schemas into `FrontPageEntry`. `blockedBy` names only blockers still on the front page; `takeable` is for the anonymous viewer: no live claim, no open blocker, no reserve. Posture reads `open` until W6 projects posture; `projects()` and `credits()` return `[]` until W5 514 adds their tables to this module. A failed read is a defect (the port's reads cannot fail).
- `tables.ts` holds the DDL; `apps/platform/migrations/0001_front_page.sql` holds the same text, and the test applies the file and checks it equals `FrontPageDdl` (one source). DDL as the issue gave it: `front_page(project, ask, kind, reserve, want, territory, claimed, blocked_by JSON, opened_at, PK(project, ask))` and `cursor(project PK, seq)`.
- Cartridge (spec §1.3, cut line 4): nothing but its test imports `packages/project/src/projection-d1/`. Deleting that folder, `packages/project/test/projection-d1.test.ts` and 317's one composition line leaves the platform serving `listProjects`/`frontPage` from 301's `FrontPageMemory` (the migration file may stay; it only creates tables).
- Outside the territory, one line group: `tsconfig.base.json` gets an override for `packages/project/src/projection-d1/**` allowing `effect/sql` and `@effect/sql-d1/D1Client#D1Client` (the batch needs the `D1Client` key, which `unstableApiUsage` flags). Per-path allow-lists are pre-approved (spec §7.3); recorded in the issue's Comments for 399.
- The read model rebuilds from events: clear `front_page` and `cursor`, then replay each project's events from seq 1 through `apply`.
- Tests: `packages/project/test/projection-d1.test.ts` (11) on sqlite-node with the migration file applied: two projects listed with one claimed, kind and reserve filters; release and lapse free an ask; a second live claim keeps it claimed; a landing's `AskClosed` drops it; blocked until its blockers land; replaying batches leaves both tables identical; an older seq after a newer one is ignored; a gap is refused and changes nothing, then applies once the missing row comes; a mixed batch applies the contiguous part and refuses the rest; the migration file equals the DDL; `projects()`/`credits()` are empty. Mutations checked by hand: dropping the cursor guard, making `claimed` a flag, and allowing gaps each fail a test.
- ASSUMPTION: front page order is newest ask first; no source sets one.
- ASSUMPTION: a blocker that is not on the front page has landed (the service counts an unknown blocker as blocking).
- ASSUMPTION: the D1 batch path is not run in Node here (no D1 in the package's tests without a new dependency); it is the same statements, and 317/310/311 exercise it.
1+-- The front page: every open ask of every project, projected from each2+-- project's outbox by packages/project/src/projection-d1 (its tables.ts3+-- holds this text). The projection is the only writer.4+5+CREATE TABLE front_page (6+ project TEXT NOT NULL,7+ ask TEXT NOT NULL,8+ kind TEXT NOT NULL,9+ reserve TEXT,10+ want TEXT NOT NULL,11+ territory TEXT NOT NULL,12+ -- how many live claims hold the ask13+ claimed INTEGER NOT NULL,14+ -- the asks it waits on, as a JSON array of ask ids15+ blocked_by TEXT NOT NULL,16+ opened_at TEXT NOT NULL,17+ PRIMARY KEY (project, ask)18+);19+20+-- The last event applied per project.21+CREATE TABLE cursor (22+ project TEXT PRIMARY KEY,23+ seq INTEGER NOT NULL24+);
1+/**2+ * `FrontPage` over D1: the open asks of every project in one query, read3+ * from the rows `ProjectionD1` keeps (`tables.ts`), so no project wakes.4+ *5+ * An entry is what the anonymous viewer sees: an ask is takeable when no6+ * live claim holds it, nothing it waits on is still open, and it is held for7+ * nobody. Its `blockedBy` names only the asks it still waits on: one that8+ * landed has left the front page. Newest asks come first. Every project's9+ * posture reads `open` until visibility (W6) projects a posture change, and10+ * `projects()` and `credits()` read nothing until W5 514 adds their tables to11+ * this module. A failed read is a defect: the port's reads cannot fail.12+ */13+import { Reserve } from "@repo/protocol/domain/ask";14+import type { FrontPageEntry } from "@repo/protocol/domain/front-page";15+import { AskId, KindName, ProjectName } from "@repo/protocol/ids";16+import { Effect, Layer, Schema } from "effect";17+import { SqlClient } from "effect/sql/SqlClient";18+19+import { FrontPage } from "../front-page.ts";20+import type { FrontPageFilter } from "../front-page.ts";21+22+const AskIds = Schema.fromJsonString(Schema.Array(AskId));23+24+/** One row of the front page query. */25+const EntryRow = Schema.Struct({26+ ask: AskId,27+ blocked_by: AskIds,28+ claimed: Schema.Int,29+ kind: KindName,30+ /** The asks it waits on that are still on the front page. */31+ open_blockers: AskIds,32+ project: ProjectName,33+ reserve: Schema.NullOr(Reserve),34+ territory: Schema.NonEmptyString,35+ want: Schema.NonEmptyString,36+});37+38+type EntryRow = typeof EntryRow.Type;39+40+const decodeRows = Schema.decodeUnknownEffect(Schema.Array(EntryRow));41+42+const entryOf = (row: EntryRow): FrontPageEntry => {43+ const blockedBy = row.blocked_by.filter((ask) =>44+ row.open_blockers.includes(ask)45+ );46+47+ const claimed = row.claimed > 0;48+49+ const listing = {50+ ask: row.ask,51+ blockedBy,52+ claimed,53+ kind: row.kind,54+ territory: row.territory,55+ want: row.want,56+ };57+58+ return {59+ ask: row.reserve === null ? listing : { ...listing, reserve: row.reserve },60+ posture: "open",61+ project: row.project,62+ takeable: !claimed && blockedBy.length === 0 && row.reserve === null,63+ };64+};65+66+export const FrontPageD1: Layer.Layer<FrontPage, never, SqlClient> =67+ Layer.effect(68+ FrontPage,69+ Effect.gen(function* () {70+ const sql = yield* SqlClient;71+72+ const entries = ({ kind, reserved }: FrontPageFilter) =>73+ sql`SELECT project, ask, kind, reserve, want, territory, claimed, blocked_by,74+ (SELECT json_group_array(blocker.value)75+ FROM json_each(page.blocked_by) AS blocker76+ WHERE EXISTS (77+ SELECT 1 FROM front_page AS other78+ WHERE other.project = page.project AND other.ask = blocker.value79+ )) AS open_blockers80+ FROM front_page AS page81+ WHERE ${sql.and([82+ ...(kind === undefined ? [] : [sql`kind = ${kind}`]),83+ ...(reserved === undefined ? [] : [sql`reserve = ${reserved}`]),84+ ])}85+ ORDER BY opened_at DESC, project, ask`.pipe(86+ Effect.flatMap(decodeRows),87+ Effect.map((rows) => rows.map(entryOf)),88+ Effect.orDie89+ );90+91+ return FrontPage.of({92+ credits: () => Effect.succeed([]),93+ entries,94+ projects: () => Effect.succeed([]),95+ });96+ })97+ );
1+/**2+ * `Projection` over D1: each project's outbox rows become the front page's3+ * rows (`tables.ts`). The Project DO stays the system of record; this is a4+ * read model it feeds through its outbox, and nothing else writes it.5+ *6+ * Events apply in their project's order, once each. Every statement is7+ * guarded by the project's cursor: it runs only if the cursor stands just8+ * before its event, and the event's last statement moves the cursor on. So a9+ * row seen again, or an older row after a newer one, changes nothing, and10+ * two deliveries racing each other apply each event once. A row past a gap11+ * (its project's cursor short of the event before it) is not applied, and12+ * `apply` fails with `ProjectionFailed` once the rest is in: the outbox keeps13+ * those rows and sends them again after the missing one.14+ *15+ * One call is one atomic write: a D1 batch when the `SqlClient` is D1's16+ * (D1 has no interactive transactions), and a transaction anywhere else,17+ * such as sqlite-node in tests. A failed write applies nothing.18+ */19+import { D1Client } from "@effect/sql-d1/D1Client";20+import { ProjectEvent } from "@repo/protocol/domain/event";21+import type { ProjectName } from "@repo/protocol/ids";22+import { Array, DateTime, Effect, Layer, Option, Order, Schema } from "effect";23+import { SqlClient } from "effect/sql/SqlClient";24+import type { SqlError } from "effect/sql/SqlError";25+import type { Statement } from "effect/sql/Statement";26+27+import type { OutboxRow } from "../project-store/rows.ts";28+import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";29+30+const decodeProjected = Schema.decodeUnknownEffect(31+ Schema.toCodecJson(ProjectedEvent)32+);33+34+const Cursors = Schema.Array(35+ Schema.Struct({ project: Schema.String, seq: Schema.Int })36+);37+38+const decodeCursors = Schema.decodeUnknownEffect(Cursors);39+40+const bySeq = Order.mapInput(41+ Order.Tuple([Order.String, Order.Number]),42+ ({ event, project }: ProjectedEvent) => [project, event.seq] as const43+);44+45+/** Each project, with the last event the rows carry for it. */46+const lastOf = (events: readonly ProjectedEvent[]) =>47+ new Map(events.map(({ event, project }) => [project, event.seq]));48+49+export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =50+ Layer.effect(51+ Projection,52+ Effect.gen(function* () {53+ const sql = yield* SqlClient;54+ const d1 = yield* Effect.serviceOption(D1Client);55+56+ /** The statements in order, all or none. */57+ const atomically = (58+ statements: readonly Statement<object>[]59+ ): Effect.Effect<readonly (readonly object[])[], SqlError> =>60+ Option.match(d1, {61+ onNone: () =>62+ sql.withTransaction(Effect.forEach(statements, (each) => each)),63+ onSome: (client) => client.batch(statements),64+ });65+66+ /** Whether the project's cursor stands just before event `seq`. */67+ const isNext = (project: ProjectName, seq: number) =>68+ sql`(SELECT COALESCE(MAX(seq), 0) FROM cursor WHERE project = ${project}) = ${seq - 1}`;69+70+ /** What one event changes on the front page, if anything. */71+ const writes = ({ event, project }: ProjectedEvent) => {72+ const next = isNext(project, event.seq);73+74+ const claims = (ask: string, change: number) =>75+ sql`UPDATE front_page SET claimed = MAX(claimed + ${change}, 0)76+ WHERE project = ${project} AND ask = ${ask} AND ${next}`;77+78+ return ProjectEvent.match(event, {79+ AskClosed: ({ ask }) => [80+ sql`DELETE FROM front_page81+ WHERE project = ${project} AND ask = ${ask} AND ${next}`,82+ ],83+ AskOpened: ({ ask, at }) => [84+ sql`INSERT INTO front_page85+ (project, ask, kind, reserve, want, territory, claimed, blocked_by, opened_at)86+ SELECT ${project}, ${ask.ask}, ${ask.kind}, ${ask.reserve ?? null},87+ ${ask.want}, ${ask.territory}, ${ask.claimed ? 1 : 0},88+ ${JSON.stringify(ask.blockedBy)}, ${DateTime.formatIso(at)}89+ WHERE ${next}90+ ON CONFLICT (project, ask) DO UPDATE SET91+ kind = excluded.kind, reserve = excluded.reserve,92+ want = excluded.want, territory = excluded.territory,93+ claimed = excluded.claimed, blocked_by = excluded.blocked_by,94+ opened_at = excluded.opened_at`,95+ ],96+ Claimed: ({ ask }) => [claims(ask, 1)],97+ Decided: () => [],98+ Judged: () => [],99+ Landed: () => [],100+ Lapsed: ({ ask }) => [claims(ask, -1)],101+ LedgerAppended: () => [],102+ ProposalOpened: () => [],103+ Pushed: () => [],104+ Released: ({ ask }) => [claims(ask, -1)],105+ Warned: () => [],106+ });107+ };108+109+ /** Moves the project's cursor on to `seq`, if it stands just before it. */110+ const advance = (project: ProjectName, seq: number) =>111+ sql`INSERT INTO cursor (project, seq)112+ SELECT ${project}, ${seq} WHERE ${isNext(project, seq)}113+ ON CONFLICT (project) DO UPDATE SET seq = excluded.seq`;114+115+ const cursorsOf = (projects: readonly ProjectName[]) =>116+ sql`SELECT project, seq FROM cursor WHERE ${sql.in("project", projects)}`;117+118+ /**119+ * Applies the events in one write, then reads where each project's120+ * cursor stands: short of a project's last event means a gap.121+ */122+ const deliver = (events: Array.NonEmptyReadonlyArray<ProjectedEvent>) =>123+ Effect.gen(function* () {124+ const last = lastOf(events);125+126+ const results = yield* atomically([127+ ...events.flatMap((projected) => [128+ ...writes(projected),129+ advance(projected.project, projected.event.seq),130+ ]),131+ cursorsOf([...last.keys()]),132+ ]).pipe(133+ Effect.mapError(134+ (failed) => new ProjectionFailed({ reason: failed.message })135+ )136+ );137+138+ const reached = new Map(139+ (yield* Effect.orDie(decodeCursors(results.at(-1) ?? []))).map(140+ ({ project, seq }) => [project, seq]141+ )142+ );143+144+ const short = [...last].filter(145+ ([project, seq]) => (reached.get(project) ?? 0) < seq146+ );147+148+ return yield* Array.isReadonlyArrayNonEmpty(short)149+ ? new ProjectionFailed({150+ reason: short151+ .map(152+ ([project, seq]) =>153+ `${project} stands at event ${reached.get(project) ?? 0}, short of ${seq}: an earlier event has not arrived`154+ )155+ .join("; "),156+ })157+ : Effect.void;158+ });159+160+ const apply = (rows: readonly OutboxRow[]) =>161+ Effect.forEach(rows, (row) =>162+ decodeProjected(row.body).pipe(163+ Effect.mapError(164+ (invalid) =>165+ new ProjectionFailed({166+ reason: `outbox row ${row.id} is no projected event: ${invalid.message}`,167+ })168+ )169+ )170+ ).pipe(171+ Effect.map((events) => Array.sort(events, bySeq)),172+ Effect.flatMap((events) =>173+ Array.isReadonlyArrayNonEmpty(events)174+ ? deliver(events)175+ : Effect.void176+ )177+ );178+179+ return Projection.of({ apply });180+ })181+ );