Merge build/210-project-store: a project's state is hydrated and persisted in one transaction, the same on SQLite and in memory
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 8accdd2, 32ed63a · Browse files · 9 files·+1507 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+1507 added−0 removed
- tests:+613 added−0 removed
- other:+894 added−0 removed
Provenance
- Commit
625134d- Tree
3511b9e- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
8accdd2- Parent 2
32ed63a
9 files changed+1507 added−0 removed
added:packages/project/src/project-store/memory.ts+215 added
1+import { Array, Effect, Layer, Option, Order, SynchronizedRef } from "effect";2+3+import {4+ keptEvents,5+ ProjectStore,6+ snapshotLandings,7+} from "../project-store.ts";8+import type {9+ Committed,10+ ProjectSnapshot,11+ ProjectWrites,12+} from "../project-store.ts";13+import type { EventRow } from "./rows.ts";14+import {15+ EventTable,16+ ProjectTable,17+ QueueTable,18+ Tables,19+ writeAll,20+} from "./tables.ts";21+import type { Column, Table, Upsert } from "./tables.ts";22+23+/** A row as a table keeps it: its columns and its encoded body. */24+interface Stored {25+ readonly body: string;26+ readonly columns: Readonly<Record<string, Column>>;27+}28+29+/** A table's rows by key, in the order each key was first written. */30+type Rows = ReadonlyMap<string, Stored>;31+32+interface State {33+ readonly lastSeq: number;34+ /** Each table's rows by table name; the kept events too, oldest first. */35+ readonly tables: ReadonlyMap<string, Rows>;36+}37+38+const keyOf = <A>(table: Table<A>, columns: Stored["columns"]) =>39+ JSON.stringify(table.key.map((name) => columns[name]));40+41+const rowsIn = <A>(state: State, table: Table<A>): Rows =>42+ state.tables.get(table.name) ?? new Map();43+44+const decodeAll = <A>(table: Table<A>, stored: Iterable<Stored>) =>45+ Effect.forEach(stored, (row) => table.decode(row.body));46+47+const all = <A>(state: State, table: Table<A>) =>48+ decodeAll(table, rowsIn(state, table).values());49+50+/** A landing with the place it was first written in. */51+type Placed = readonly [index: number, row: Stored];52+53+/** Newest first: by landing time, then the later write, as `/sqlite` orders them. */54+const newestFirst = Order.combine(55+ Order.mapInput(Order.flip(Order.Number), ([, row]: Placed) =>56+ Number(row.columns.landed_at)57+ ),58+ Order.mapInput(Order.flip(Order.Number), ([index]: Placed) => index)59+);60+61+const snapshotOf = (state: State) =>62+ Effect.gen(function* () {63+ const placed = Array.map(64+ [...rowsIn(state, Tables.landings).values()],65+ (row, index): Placed => [index, row]66+ );67+68+ const newest = Array.take(69+ Array.sort(placed, newestFirst),70+ snapshotLandings71+ );72+73+ return {74+ answers: yield* all(state, Tables.answers),75+ asks: yield* all(state, Tables.asks),76+ budgetDays: yield* all(state, Tables.budgetDays),77+ claims: yield* all(state, Tables.claims),78+ decisions: yield* all(state, Tables.decisions),79+ landings: yield* decodeAll(80+ Tables.landings,81+ Array.map(newest, ([, row]) => row)82+ ),83+ lastSeq: state.lastSeq,84+ outbox: yield* all(state, Tables.outbox),85+ project: Array.head(yield* all(state, ProjectTable)),86+ proposals: yield* all(state, Tables.proposals),87+ queue: Option.getOrNull(Array.head(yield* all(state, QueueTable))),88+ ratchets: yield* all(state, Tables.ratchets),89+ } satisfies ProjectSnapshot;90+ });91+92+/** The push events in `writes` that `state` already holds, each once. */93+const seenIn = (state: State, writes: ProjectWrites) => {94+ const seen = rowsIn(state, Tables.pushEvents);95+96+ return Array.dedupe(97+ Array.flatMap(writes.pushEvents ?? [], (event) =>98+ seen.has(keyOf(Tables.pushEvents, { event_id: event.eventId }))99+ ? [event.eventId]100+ : []101+ )102+ );103+};104+105+/** Writes rows into copies of `tables`' maps, never into the maps themselves. */106+const upsertInto =107+ (tables: Map<string, Rows>): Upsert<never, never> =>108+ (table, rows) =>109+ Effect.gen(function* () {110+ const kept = new Map(tables.get(table.name));111+112+ for (const row of rows) {113+ const columns = table.columns(row);114+115+ kept.set(keyOf(table, columns), {116+ body: yield* table.encode(row),117+ columns,118+ });119+ }120+121+ tables.set(table.name, kept);122+ });123+124+/**125+ * The state after `writes`, built from copies through the write plan both126+ * adapters share. A row that won't encode dies before anything is swapped in.127+ */128+const written = (state: State, writes: ProjectWrites) =>129+ Effect.gen(function* () {130+ const tables = new Map(state.tables);131+ const seqs = yield* writeAll(writes, state.lastSeq, upsertInto(tables));132+ const events = [...(tables.get(EventTable.name) ?? [])];133+134+ tables.set(EventTable.name, new Map(events.slice(-keptEvents)));135+136+ const committed: Committed = { duplicatePushEvents: [], seqs };137+138+ const next: State = {139+ lastSeq: state.lastSeq + seqs.length,140+ tables,141+ };142+143+ return [committed, next] as const;144+ });145+146+/**147+ * A project's store in memory: the same tables, keys and encoded bodies as148+ * `/sqlite`, held in one `SynchronizedRef` the layer makes. A commit builds149+ * the next state from copies and swaps it in only when every row encoded, so150+ * a failed commit leaves the previous state whole.151+ */152+export const ProjectStoreMemory = Layer.effect(153+ ProjectStore,154+ Effect.gen(function* () {155+ const ref = yield* SynchronizedRef.make<State>({156+ lastSeq: 0,157+ tables: new Map(),158+ });159+160+ return ProjectStore.of({161+ ackOutbox: (ids) =>162+ SynchronizedRef.update(ref, (state) => {163+ const kept = new Map(rowsIn(state, Tables.outbox));164+165+ for (const id of ids) {166+ kept.delete(keyOf(Tables.outbox, { id }));167+ }168+169+ return {170+ ...state,171+ tables: new Map(state.tables).set(Tables.outbox.name, kept),172+ };173+ }),174+ commit: (writes) =>175+ SynchronizedRef.modifyEffect(ref, (state) => {176+ const duplicatePushEvents = seenIn(state, writes);177+178+ if (duplicatePushEvents.length > 0) {179+ const replay: Committed = { duplicatePushEvents, seqs: [] };180+181+ return Effect.succeed([replay, state] as const);182+ }183+184+ return written(state, writes);185+ }),186+ eventsSince: (seq, limit) =>187+ Effect.gen(function* () {188+ const events = yield* all(189+ yield* SynchronizedRef.get(ref),190+ EventTable191+ );192+193+ return Array.take(194+ Array.flatMap(events, (event): readonly EventRow[] =>195+ event.seq > seq ? [{ event, seq: event.seq }] : []196+ ),197+ limit198+ );199+ }),200+ landing: (sha) =>201+ Effect.gen(function* () {202+ const state = yield* SynchronizedRef.get(ref);203+204+ const row = rowsIn(state, Tables.landings).get(205+ keyOf(Tables.landings, { sha })206+ );207+208+ return row === undefined209+ ? Option.none()210+ : Option.some(yield* Tables.landings.decode(row.body));211+ }),212+ load: () => Effect.flatMap(SynchronizedRef.get(ref), snapshotOf),213+ });214+ })215+);added:packages/project/src/project-store/migrations.ts+79 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879import { Effect } from "effect";import * as Migrator from "effect/sql/Migrator";import { SqlClient } from "effect/sql/SqlClient";
// A project's tables. Each holds its key columns and `body`, the row's// encoded JSON (see `tables.ts`). A migration is never edited once it has// run anywhere: a change is a new numbered entry.
const projectState = Effect.gen(function* () { const sql = yield* SqlClient;
yield* sql`CREATE TABLE project ( id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL )`; yield* sql`CREATE TABLE asks (id TEXT PRIMARY KEY, body TEXT NOT NULL)`; yield* sql`CREATE TABLE claims ( ask TEXT NOT NULL, claimant TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY (ask, claimant) )`; yield* sql`CREATE TABLE answers ( request_id TEXT PRIMARY KEY, body TEXT NOT NULL )`; yield* sql`CREATE TABLE landing_queue ( id INTEGER PRIMARY KEY CHECK (id = 1), body TEXT NOT NULL )`; yield* sql`CREATE TABLE landings ( sha TEXT PRIMARY KEY, landed_at INTEGER NOT NULL, body TEXT NOT NULL )`; yield* sql`CREATE INDEX landings_newest ON landings (landed_at)`; yield* sql`CREATE TABLE proposals (id TEXT PRIMARY KEY, body TEXT NOT NULL)`; yield* sql`CREATE TABLE decisions (id TEXT PRIMARY KEY, body TEXT NOT NULL)`; yield* sql`CREATE TABLE budget_days ( decider TEXT NOT NULL, day TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY (decider, day) )`; yield* sql`CREATE TABLE ratchets ( ratchet TEXT NOT NULL, territory TEXT NOT NULL, body TEXT NOT NULL, PRIMARY KEY (ratchet, territory) )`; yield* sql`CREATE TABLE push_events ( event_id TEXT PRIMARY KEY, body TEXT NOT NULL )`; yield* sql`CREATE TABLE events ( seq INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL )`; yield* sql`CREATE TABLE outbox (id TEXT PRIMARY KEY, body TEXT NOT NULL)`;});
/** Every migration, by `<id>_<name>`, in the order they run. */const migrations = { "1_project_state": projectState };
/** * Brings a project's database up to date and returns the migrations it ran. * It records each one it runs (in `migrations`), so running it again runs * nothing. It needs no filesystem, so it runs in a Durable Object. A * migration that fails is a defect: the project cannot start without its * tables. */export const migrate: Effect.Effect< readonly (readonly [id: number, name: string])[], never, SqlClient> = Migrator.make({})({ loader: Migrator.fromRecord(migrations), table: "migrations",}).pipe(Effect.orDie);added:packages/project/src/project-store/rows.ts+151 added
1+import { Ask } from "@repo/protocol/domain/ask";2+import { Decision } from "@repo/protocol/domain/decision";3+import { ProjectEvent } from "@repo/protocol/domain/event";4+import { LandingView } from "@repo/protocol/domain/landing";5+import { Proposal } from "@repo/protocol/domain/proposal";6+import {7+ AskId,8+ CommitSha,9+ Handle,10+ LandedSha,11+ ProjectName,12+ RatchetName,13+ RepoName,14+ RequestId,15+} from "@repo/protocol/ids";16+import { Schema } from "effect";17+18+// One schema per table. Each row's encoded side is what the store holds as19+// the row's body, so a row reads back exactly as it was written. Lifecycle20+// states travel as encoded JSON: the store never decodes them, the project21+// service does, with the lifecycles' own schemas.22+23+/**24+ * A project: whether it waits for its initializer's first push or is live,25+ * the SHA the platform last landed, and the policy cached for one landed SHA.26+ */27+export const ProjectRow = Schema.Struct({28+ createdAt: Schema.DateTimeUtcFromString,29+ initializer: Handle,30+ landed: Schema.optionalKey(LandedSha),31+ /** The encoded `Policy` evaluated at `policyAt`. */32+ policy: Schema.optionalKey(Schema.Json),33+ policyAt: Schema.optionalKey(LandedSha),34+ project: ProjectName,35+ state: Schema.Literals(["awaitingFirstPush", "live"]),36+});37+38+export type ProjectRow = typeof ProjectRow.Type;39+40+/** An ask, as the domain types it. */41+export const AskRow = Ask;42+43+export type AskRow = typeof AskRow.Type;44+45+/** One person's claim on an ask, its lifecycle state encoded. */46+export const ClaimRow = Schema.Struct({47+ ask: AskId,48+ claimant: Handle,49+ /** The encoded claim lifecycle state. */50+ state: Schema.Json,51+ updatedAt: Schema.DateTimeUtcFromString,52+});53+54+export type ClaimRow = typeof ClaimRow.Type;55+56+/**57+ * One answer request, keyed by its `requestId` so a request sent twice is58+ * one row; its landing lifecycle state encoded.59+ */60+export const AnswerRow = Schema.Struct({61+ answerer: Handle,62+ ask: Schema.optionalKey(AskId),63+ head: CommitSha,64+ requestId: RequestId,65+ /** The encoded landing lifecycle state. */66+ state: Schema.Json,67+ updatedAt: Schema.DateTimeUtcFromString,68+});69+70+export type AnswerRow = typeof AnswerRow.Type;71+72+/** A landing, as the domain types it. */73+export const LandingRow = LandingView;74+75+export type LandingRow = typeof LandingRow.Type;76+77+/** A proposal, as the domain types it. */78+export const ProposalRow = Proposal;79+80+export type ProposalRow = typeof ProposalRow.Type;81+82+/** A decision, as the domain types it. */83+export const DecisionRow = Decision;84+85+export type DecisionRow = typeof DecisionRow.Type;86+87+/** How much of one decider's budget one day used, and how many finishes. */88+export const BudgetDayRow = Schema.Struct({89+ /** `YYYY-MM-DD`, in UTC. */90+ day: Schema.String,91+ decider: Handle,92+ finishes: Schema.Int,93+ used: Schema.Int,94+});95+96+export type BudgetDayRow = typeof BudgetDayRow.Type;97+98+/** A ratchet's count in one territory, as recorded at a landing. */99+export const RatchetRow = Schema.Struct({100+ at: LandedSha,101+ count: Schema.Int,102+ ratchet: RatchetName,103+ territory: Schema.NonEmptyString,104+});105+106+export type RatchetRow = typeof RatchetRow.Type;107+108+/**109+ * A push the project heard about, kept by its event id so the same event110+ * heard twice is acted on once (events arrive per ref, and may repeat).111+ */112+export const PushEventRow = Schema.Struct({113+ after: Schema.optionalKey(CommitSha),114+ at: Schema.DateTimeUtcFromString,115+ before: Schema.optionalKey(CommitSha),116+ eventId: Schema.NonEmptyString,117+ ref: Schema.NonEmptyString,118+ repo: RepoName,119+});120+121+export type PushEventRow = typeof PushEventRow.Type;122+123+/**124+ * A side effect still to run after its transition was persisted (a fork, a125+ * projection row), kept until it is acknowledged.126+ */127+export const OutboxRow = Schema.Struct({128+ attempts: Schema.Int,129+ body: Schema.Json,130+ id: Schema.NonEmptyString,131+ kind: Schema.NonEmptyString,132+ notBefore: Schema.DateTimeUtcFromString,133+});134+135+export type OutboxRow = typeof OutboxRow.Type;136+137+/** An event with the sequence number the store gave it. */138+export const EventRow = Schema.Struct({139+ event: ProjectEvent,140+ seq: Schema.Int,141+});142+143+export type EventRow = typeof EventRow.Type;144+145+/** Drops a key from each member of a union, not from the union as a whole. */146+type OmitEach<Union, Key extends PropertyKey> = Union extends unknown147+ ? Omit<Union, Key>148+ : never;149+150+/** An event before the store numbers it: every `ProjectEvent` but its `seq`. */151+export type ProjectEventInput = OmitEach<ProjectEvent, "seq">;added:packages/project/src/project-store/sqlite.ts+174 added
1+import { Array, Effect, Layer, Option, Schema } from "effect";2+import { SqlClient } from "effect/sql/SqlClient";3+import type { Statement } from "effect/sql/Statement";4+5+import {6+ keptEvents,7+ ProjectStore,8+ snapshotLandings,9+} from "../project-store.ts";10+import type { ProjectWrites } from "../project-store.ts";11+import { migrate } from "./migrations.ts";12+import {13+ EventTable,14+ ProjectTable,15+ QueueTable,16+ Tables,17+ writeAll,18+} from "./tables.ts";19+import type { Table } from "./tables.ts";20+21+// What SQLite hands back is decoded like any other outside input.22+const Bodies = Schema.Array(Schema.Struct({ body: Schema.String }));23+24+const decodeBodies = Schema.decodeUnknownEffect(Bodies);25+26+const EventIds = Schema.Array(Schema.Struct({ event_id: Schema.String }));27+28+const decodeEventIds = Schema.decodeUnknownEffect(EventIds);29+30+const LastSeq = Schema.Tuple([Schema.Struct({ last: Schema.Int })]);31+32+const decodeLastSeq = Schema.decodeUnknownEffect(LastSeq);33+34+/** The rows a query returns, each decoded from its body. */35+const bodiesOf = <A>(table: Table<A>, statement: Statement<object>) =>36+ statement.pipe(37+ Effect.flatMap(decodeBodies),38+ Effect.flatMap((rows) =>39+ Effect.forEach(rows, (row) => table.decode(row.body))40+ )41+ );42+43+/**44+ * A project's store on SQLite through `effect/sql`, so the same code runs on45+ * a Durable Object's SQLite (`@effect/sql-sqlite-do`, given the storage so46+ * transactions work) and on sqlite-node in tests. The layer runs the47+ * migrations first. `load` and `commit` each run in one transaction; a48+ * `SqlError` is a defect (see `ProjectStore`).49+ */50+export const ProjectStoreSqlite = Layer.effect(51+ ProjectStore,52+ Effect.gen(function* () {53+ const sql = yield* SqlClient;54+55+ yield* migrate;56+57+ const all = <A>(table: Table<A>) =>58+ bodiesOf(table, sql`SELECT body FROM ${sql(table.name)} ORDER BY rowid`);59+60+ const lastSeq = sql`SELECT COALESCE(MAX(seq), 0) AS last FROM events`.pipe(61+ Effect.flatMap(decodeLastSeq),62+ Effect.map(([row]) => row.last)63+ );64+65+ // One statement per row, so a key written twice in one commit replaces66+ // its first row in place, as it does in `/memory`.67+ const upsert = <A>(table: Table<A>, rows: readonly A[]) =>68+ Effect.forEach(69+ rows,70+ (row) =>71+ Effect.gen(function* () {72+ const columns = {73+ ...table.columns(row),74+ body: yield* table.encode(row),75+ };76+77+ const updates = Object.keys(columns)78+ .filter((column) => !table.key.includes(column))79+ .map((column) => `${column} = excluded.${column}`);80+81+ yield* sql`INSERT INTO ${sql(table.name)} ${sql.insert(columns)}82+ ON CONFLICT (${sql.literal(table.key.join(", "))})83+ DO UPDATE SET ${sql.literal(updates.join(", "))}`;84+ }),85+ { discard: true }86+ );87+88+ const seenPushEvents = (writes: ProjectWrites) => {89+ const ids = Array.map(writes.pushEvents ?? [], (event) => event.eventId);90+91+ return Array.isReadonlyArrayNonEmpty(ids)92+ ? sql`SELECT event_id FROM push_events WHERE ${sql.in("event_id", ids)}`.pipe(93+ Effect.flatMap(decodeEventIds),94+ Effect.map((rows) => {95+ const seen = new Set(rows.map((row) => row.event_id));96+97+ return Array.dedupe(ids.filter((id) => seen.has(id)));98+ })99+ )100+ : Effect.succeed([]);101+ };102+103+ const write = (writes: ProjectWrites) =>104+ Effect.gen(function* () {105+ const last = yield* lastSeq;106+ const seqs = yield* writeAll(writes, last, upsert);107+108+ yield* sql`DELETE FROM events WHERE seq <= ${last + seqs.length - keptEvents}`;109+110+ return { duplicatePushEvents: [], seqs };111+ });112+113+ return ProjectStore.of({114+ ackOutbox: (ids) =>115+ Array.isReadonlyArrayNonEmpty(ids)116+ ? sql`DELETE FROM outbox WHERE ${sql.in("id", ids)}`.pipe(117+ Effect.asVoid,118+ Effect.orDie119+ )120+ : Effect.void,121+ commit: (writes) =>122+ sql123+ .withTransaction(124+ Effect.gen(function* () {125+ const duplicatePushEvents = yield* seenPushEvents(writes);126+127+ return duplicatePushEvents.length > 0128+ ? { duplicatePushEvents, seqs: [] }129+ : yield* write(writes);130+ })131+ )132+ .pipe(Effect.orDie),133+ eventsSince: (seq, limit) =>134+ bodiesOf(135+ EventTable,136+ sql`SELECT body FROM events WHERE seq > ${seq} ORDER BY seq LIMIT ${limit}`137+ ).pipe(138+ Effect.map(Array.map((event) => ({ event, seq: event.seq }))),139+ Effect.orDie140+ ),141+ landing: (sha) =>142+ bodiesOf(143+ Tables.landings,144+ sql`SELECT body FROM landings WHERE sha = ${sha}`145+ ).pipe(Effect.map(Array.head), Effect.orDie),146+ load: () =>147+ sql148+ .withTransaction(149+ Effect.gen(function* () {150+ return {151+ answers: yield* all(Tables.answers),152+ asks: yield* all(Tables.asks),153+ budgetDays: yield* all(Tables.budgetDays),154+ claims: yield* all(Tables.claims),155+ decisions: yield* all(Tables.decisions),156+ landings: yield* bodiesOf(157+ Tables.landings,158+ sql`SELECT body FROM landings159+ ORDER BY landed_at DESC, rowid DESC160+ LIMIT ${snapshotLandings}`161+ ),162+ lastSeq: yield* lastSeq,163+ outbox: yield* all(Tables.outbox),164+ project: Array.head(yield* all(ProjectTable)),165+ proposals: yield* all(Tables.proposals),166+ queue: Option.getOrNull(Array.head(yield* all(QueueTable))),167+ ratchets: yield* all(Tables.ratchets),168+ };169+ })170+ )171+ .pipe(Effect.orDie),172+ });173+ })174+);added:packages/project/src/project-store/tables.ts+162 added
1+import { ProjectEvent } from "@repo/protocol/domain/event";2+import { Array, DateTime, Effect, Option, Schema } from "effect";3+4+import type { ProjectWrites } from "../project-store.ts";5+import {6+ AnswerRow,7+ AskRow,8+ BudgetDayRow,9+ ClaimRow,10+ DecisionRow,11+ LandingRow,12+ OutboxRow,13+ ProjectRow,14+ ProposalRow,15+ PushEventRow,16+ RatchetRow,17+} from "./rows.ts";18+19+// How each kind of row is kept, shared by every adapter: the table it lives20+// in, the columns a row is found by, its body (the row's encoded JSON), and21+// which tables a commit writes from which `ProjectWrites` field. The SQLite22+// tables themselves are created by `migrations.ts`.23+24+/** A column's value: text, or an integer. */25+export type Column = string | number;26+27+/** One table's rows: how a row becomes its key columns and body, and back. */28+export interface Table<A> {29+ /** Every column besides `body`, by name, for one row. */30+ readonly columns: (row: A) => Readonly<Record<string, Column>>;31+ readonly decode: (body: string) => Effect.Effect<A>;32+ readonly encode: (row: A) => Effect.Effect<string>;33+ /** The columns that make a row's key: writing a row again under it replaces it. */34+ readonly key: readonly string[];35+ readonly name: string;36+}37+38+// A body that won't encode or decode is a broken invariant, not an outcome a39+// caller can handle: it dies, and a commit that dies writes nothing.40+const tableOf = <A, I>(41+ name: string,42+ schema: Schema.Codec<A, I>,43+ key: readonly string[],44+ columns: (row: A) => Readonly<Record<string, Column>>45+): Table<A> => {46+ const body = Schema.fromJsonString(schema);47+ const encode = Schema.encodeEffect(body);48+ const decode = Schema.decodeEffect(body);49+50+ return {51+ columns,52+ decode: (text) => Effect.orDie(decode(text)),53+ encode: (row) => Effect.orDie(encode(row)),54+ key,55+ name,56+ };57+};58+59+/** The tables that hold many rows, by the `ProjectWrites` field that carries them. */60+export const Tables = {61+ answers: tableOf("answers", AnswerRow, ["request_id"], (row) => ({62+ request_id: row.requestId,63+ })),64+ asks: tableOf("asks", AskRow, ["id"], (row) => ({ id: row.id })),65+ budgetDays: tableOf(66+ "budget_days",67+ BudgetDayRow,68+ ["decider", "day"],69+ (row) => ({ day: row.day, decider: row.decider })70+ ),71+ claims: tableOf("claims", ClaimRow, ["ask", "claimant"], (row) => ({72+ ask: row.ask,73+ claimant: row.claimant,74+ })),75+ decisions: tableOf("decisions", DecisionRow, ["id"], (row) => ({76+ id: row.id,77+ })),78+ landings: tableOf("landings", LandingRow, ["sha"], (row) => ({79+ landed_at: DateTime.toEpochMillis(row.landedAt),80+ sha: row.sha,81+ })),82+ outbox: tableOf("outbox", OutboxRow, ["id"], (row) => ({ id: row.id })),83+ proposals: tableOf("proposals", ProposalRow, ["id"], (row) => ({84+ id: row.id,85+ })),86+ pushEvents: tableOf("push_events", PushEventRow, ["event_id"], (row) => ({87+ event_id: row.eventId,88+ })),89+ ratchets: tableOf(90+ "ratchets",91+ RatchetRow,92+ ["ratchet", "territory"],93+ (row) => ({ ratchet: row.ratchet, territory: row.territory })94+ ),95+} as const;96+97+/** A table with one row at most: the project, and the landing queue. */98+const single = { id: 1 } as const;99+100+/** The project's own row. */101+export const ProjectTable = tableOf(102+ "project",103+ ProjectRow,104+ ["id"],105+ () => single106+);107+108+/** The encoded landing queue, one row. */109+export const QueueTable = tableOf(110+ "landing_queue",111+ Schema.Json,112+ ["id"],113+ () => single114+);115+116+/** The project's events, each body carrying the `seq` it was given. */117+export const EventTable = tableOf("events", ProjectEvent, ["seq"], (event) => ({118+ seq: event.seq,119+}));120+121+/** How an adapter writes one table's rows, each replacing any row under its key. */122+export type Upsert<E, R> = <A>(123+ table: Table<A>,124+ rows: readonly A[]125+) => Effect.Effect<void, E, R>;126+127+/**128+ * Writes every row in `writes` through an adapter's `upsert`, table by129+ * table, with the events numbered on from `lastSeq`, and returns the numbers130+ * it gave them. Both adapters commit through it, so a table `ProjectWrites`131+ * gains is written by both or by neither.132+ */133+export const writeAll = <E, R>(134+ writes: ProjectWrites,135+ lastSeq: number,136+ upsert: Upsert<E, R>137+): Effect.Effect<readonly number[], E, R> =>138+ Effect.gen(function* () {139+ const events = Array.map(writes.events ?? [], (event, index) => ({140+ ...event,141+ seq: lastSeq + index + 1,142+ }));143+144+ yield* upsert(145+ ProjectTable,146+ Option.toArray(Option.fromUndefinedOr(writes.project))147+ );148+ yield* upsert(Tables.asks, writes.asks ?? []);149+ yield* upsert(Tables.claims, writes.claims ?? []);150+ yield* upsert(Tables.answers, writes.answers ?? []);151+ yield* upsert(QueueTable, writes.queue === undefined ? [] : [writes.queue]);152+ yield* upsert(Tables.landings, writes.landings ?? []);153+ yield* upsert(Tables.proposals, writes.proposals ?? []);154+ yield* upsert(Tables.decisions, writes.decisions ?? []);155+ yield* upsert(Tables.budgetDays, writes.budgetDays ?? []);156+ yield* upsert(Tables.ratchets, writes.ratchets ?? []);157+ yield* upsert(Tables.pushEvents, writes.pushEvents ?? []);158+ yield* upsert(EventTable, events);159+ yield* upsert(Tables.outbox, writes.outbox ?? []);160+161+ return Array.map(events, (event) => event.seq);162+ });added:packages/project/src/project-store.ts+113 added
1+import type { CommitSha } from "@repo/protocol/ids";2+import { Context } from "effect";3+import type { Effect, Option, Schema } from "effect";4+5+import type {6+ AnswerRow,7+ AskRow,8+ BudgetDayRow,9+ ClaimRow,10+ DecisionRow,11+ EventRow,12+ LandingRow,13+ OutboxRow,14+ ProjectEventInput,15+ ProjectRow,16+ ProposalRow,17+ PushEventRow,18+ RatchetRow,19+} from "./project-store/rows.ts";20+21+/** How many landings a snapshot carries, newest first; `landing` finds older ones. */22+export const snapshotLandings = 50;23+24+/** How many events a project keeps; a watcher resuming from an older one has missed some. */25+export const keptEvents = 500;26+27+/**28+ * A project's whole working state, read in one go at the start of a call29+ * (hydrate). Rows come back in the order they were first written, except30+ * `landings`.31+ */32+export interface ProjectSnapshot {33+ readonly answers: readonly AnswerRow[];34+ readonly asks: readonly AskRow[];35+ readonly budgetDays: readonly BudgetDayRow[];36+ readonly claims: readonly ClaimRow[];37+ readonly decisions: readonly DecisionRow[];38+ /** The newest `snapshotLandings` landings, newest first. */39+ readonly landings: readonly LandingRow[];40+ /** The sequence number of the newest event, or 0 before the first. */41+ readonly lastSeq: number;42+ /** Side effects not yet acknowledged, in the order they were written. */43+ readonly outbox: readonly OutboxRow[];44+ /** Absent until the project is initialized. */45+ readonly project: Option.Option<ProjectRow>;46+ readonly proposals: readonly ProposalRow[];47+ /** The encoded landing queue; `null` until a commit writes one. */48+ readonly queue: Schema.Json;49+ readonly ratchets: readonly RatchetRow[];50+}51+52+/**53+ * What one call changed. Every row is an upsert by its table's key (an ask54+ * by id, a claim by ask and claimant, an answer by `requestId`, a landing by55+ * SHA, an outbox entry by id); `events` are appended and numbered.56+ */57+export interface ProjectWrites {58+ readonly answers?: readonly AnswerRow[];59+ readonly asks?: readonly AskRow[];60+ readonly budgetDays?: readonly BudgetDayRow[];61+ readonly claims?: readonly ClaimRow[];62+ readonly decisions?: readonly DecisionRow[];63+ readonly events?: readonly ProjectEventInput[];64+ readonly landings?: readonly LandingRow[];65+ readonly outbox?: readonly OutboxRow[];66+ readonly project?: ProjectRow;67+ readonly proposals?: readonly ProposalRow[];68+ readonly pushEvents?: readonly PushEventRow[];69+ readonly queue?: Schema.Json;70+ readonly ratchets?: readonly RatchetRow[];71+}72+73+/** What a commit did: the numbers it gave its events, and the push events it had already seen. */74+export interface Committed {75+ /** Event ids already stored. When there is one, the commit wrote nothing. */76+ readonly duplicatePushEvents: readonly string[];77+ /** One per event written, in order. */78+ readonly seqs: readonly number[];79+}80+81+/**82+ * One project's state, hydrated and persisted per call (ADR 0012): `load`83+ * reads the whole working state, `commit` writes every row, outbox entry and84+ * event a transition produced in one transaction, so a crash between two85+ * calls never leaves half a transition.86+ *87+ * - `commit` is all or nothing. A commit that carries a push event already88+ * stored is a replay: it writes nothing, numbers no event, and lists the89+ * ids it had seen, so acting on one push event twice is a no-op.90+ * - Events are numbered from 1 in commit order; only the newest `keptEvents`91+ * are kept, which `eventsSince` reads for a watcher resuming from a number.92+ * - `ackOutbox` drops entries the settle step ran; unknown ids are ignored.93+ * - `landing` finds a landing by SHA, older than the snapshot's too.94+ * - The store reads no clock: every timestamp arrives in a row.95+ *96+ * Store failures are defects, not errors: a project whose storage fails can97+ * do nothing useful, and the platform's error boundary reports it.98+ */99+export class ProjectStore extends Context.Service<100+ ProjectStore,101+ {102+ readonly ackOutbox: (ids: readonly string[]) => Effect.Effect<void>;103+ readonly commit: (writes: ProjectWrites) => Effect.Effect<Committed>;104+ readonly eventsSince: (105+ seq: number,106+ limit: number107+ ) => Effect.Effect<readonly EventRow[]>;108+ readonly landing: (109+ sha: CommitSha110+ ) => Effect.Effect<Option.Option<LandingRow>>;111+ readonly load: () => Effect.Effect<ProjectSnapshot>;112+ }113+>()("project/ProjectStore") {}added:packages/project/test/project-store-memory.test.ts+4 added
1234import { ProjectStoreMemory } from "../src/project-store/memory.ts";import { describeProjectStore } from "./project-store.contract.ts";
describeProjectStore("memory", ProjectStoreMemory);added:packages/project/test/project-store-sqlite.test.ts+36 added
123456789101112131415161718192021222324252627282930313233343536import { SqliteClient } from "@effect/sql-sqlite-node";import { describe, expect, it } from "@effect/vitest";import { Effect, Layer } from "effect";
import { ProjectStore } from "../src/project-store.ts";import { migrate } from "../src/project-store/migrations.ts";import { ProjectStoreSqlite } from "../src/project-store/sqlite.ts";import { describeProjectStore } from "./project-store.contract.ts";
/** A fresh in-memory database each time the layer is built. */const database = SqliteClient.layer({ filename: ":memory:" }).pipe(Layer.orDie);
describeProjectStore( "sqlite", ProjectStoreSqlite.pipe(Layer.provide(database)));
describe("the project store's migrations", () => { it.effect("run each migration once on a fresh database", () => Effect.gen(function* () { expect(yield* migrate).toStrictEqual([[1, "project_state"]]); expect(yield* migrate).toStrictEqual([]); }).pipe(Effect.provide(database)) );
it.effect("run again over a store's rows, change nothing", () => Effect.gen(function* () { const store = yield* ProjectStore;
yield* store.commit({ queue: { order: [] } });
expect(yield* migrate).toStrictEqual([]); expect((yield* store.load()).queue).toStrictEqual({ order: [] }); }).pipe(Effect.provide(Layer.provideMerge(ProjectStoreSqlite, database))) );});added:packages/project/test/project-store.contract.ts+573 added
1+import { describe, expect, it } from "@effect/vitest";2+import { CheckSpec } from "@repo/protocol/domain/check";3+import { DecisionSubject } from "@repo/protocol/domain/decision";4+import { ProjectEvent } from "@repo/protocol/domain/event";5+import {6+ AskId,7+ CommitSha,8+ Handle,9+ ProposalId,10+ RepoPath,11+} from "@repo/protocol/ids";12+import { DateTime, Effect, Exit, Option, Schema, Struct } from "effect";13+import type { Layer } from "effect";14+15+import { ProjectStore } from "../src/project-store.ts";16+import type { ProjectWrites } from "../src/project-store.ts";17+import {18+ AnswerRow,19+ AskRow,20+ BudgetDayRow,21+ ClaimRow,22+ DecisionRow,23+ LandingRow,24+ OutboxRow,25+ ProjectRow,26+ ProposalRow,27+ PushEventRow,28+ RatchetRow,29+} from "../src/project-store/rows.ts";30+import type { ProjectEventInput } from "../src/project-store/rows.ts";31+32+// Rows are written here encoded, as the store keeps them, and decoded once;33+// a snapshot is compared encoded, so every field reads back as written.34+35+/** A minute after noon on the day the store was built. */36+const at = (minute: number) =>37+ `2026-10-07T12:${String(minute).padStart(2, "0")}:00.000Z`;38+39+/** A 40-hex commit id from a number, so each fixture SHA is distinct. */40+const sha = (n: number) => n.toString(16).padStart(40, "0");41+42+const decoded = <A, I>(schema: Schema.Codec<A, I>, value: NoInfer<I>): A =>43+ Schema.decodeSync(schema)(value);44+45+const decodedAll = <A, I>(46+ schema: Schema.Codec<A, I>,47+ values: readonly NoInfer<I>[]48+) => values.map((value) => decoded(schema, value));49+50+/** Lifecycle states are the service's JSON; the store never reads into them. */51+const json = (text: string) =>52+ Schema.decodeSync(Schema.fromJsonString(Schema.Json))(text);53+54+const askOf = (id: string) =>55+ ({56+ askedBy: "alice",57+ blockedBy: [],58+ brief: { want: "An empty date string is refused, not parsed as today" },59+ check: CheckSpec.cases.RedThenGreen.make({60+ path: RepoPath.make("test/parse.test.ts"),61+ }),62+ file: `asks/${id}.ask.ts`,63+ id,64+ kind: "fix",65+ openedAt: at(0),66+ openedIn: sha(1),67+ project: "datekit",68+ state: "open",69+ territory: { module: "core", paths: ["packages/core/**"] },70+ }) satisfies (typeof AskRow)["Encoded"];71+72+const project = {73+ createdAt: at(0),74+ initializer: "alice",75+ landed: sha(1),76+ policy: { budget: { decisionsPerDay: 5 } },77+ policyAt: sha(1),78+ project: "datekit",79+ state: "live",80+} satisfies (typeof ProjectRow)["Encoded"];81+82+const askA = askOf("empty-date");83+84+const askB = askOf("leap-day");85+86+// A lifecycle state's JSON with its keys out of order: the store keeps it87+// byte for byte, since the service decodes it with the lifecycle's schema.88+const claimState =89+ '{"_tag":"Live","warnsAt":"2026-10-07T14:00:00.000Z","base":"0000000000000000000000000000000000000001"}';90+91+const answerState = '{"_tag":"Queued","requestId":"req-00000001"}';92+93+const claim = {94+ ask: "empty-date",95+ claimant: "bob",96+ state: json(claimState),97+ updatedAt: at(1),98+} satisfies (typeof ClaimRow)["Encoded"];99+100+const answerOf = (state: Schema.Json) =>101+ ({102+ answerer: "bob",103+ ask: "empty-date",104+ head: sha(2),105+ requestId: "req-00000001",106+ state,107+ updatedAt: at(2),108+ }) satisfies (typeof AnswerRow)["Encoded"];109+110+const answer = answerOf(json(answerState));111+112+const queue = { active: "req-00000001", order: ["req-00000001"] };113+114+const outboxOf = (id: string) =>115+ ({116+ attempts: 0,117+ body: { fork: "datekit--empty-date--bob" },118+ id,119+ kind: "makeFork",120+ notBefore: at(1),121+ }) satisfies (typeof OutboxRow)["Encoded"];122+123+const firstOutbox = outboxOf("out-1");124+125+const secondOutbox = outboxOf("out-2");126+127+const landingOf = (n: number) =>128+ ({129+ assisted: [],130+ author: "bob",131+ credits: [{ handle: "alice", role: "Asked-by" }],132+ landedAt: at(n),133+ parent: sha(n),134+ project: "datekit",135+ sha: sha(n + 1),136+ }) satisfies (typeof LandingRow)["Encoded"];137+138+const proposal = {139+ expiresAt: at(30),140+ files: ["asks/time-zones.ask.ts"],141+ id: "prop-000001",142+ openedAt: at(3),143+ project: "datekit",144+ proposer: "carol",145+ state: "open",146+ want: "Dates keep their time zone when formatted",147+} satisfies (typeof ProposalRow)["Encoded"];148+149+const decision = {150+ deciders: ["alice"],151+ default: "decline",152+ evidence: [{ label: "proposer", value: "carol" }],153+ expiresAt: at(30),154+ id: "dec-000001",155+ openedAt: at(3),156+ project: "datekit",157+ subject: DecisionSubject.cases.OpenProposal.make({158+ proposal: ProposalId.make("prop-000001"),159+ }),160+} satisfies (typeof DecisionRow)["Encoded"];161+162+const budgetDay = {163+ day: "2026-10-07",164+ decider: "alice",165+ finishes: 0,166+ used: 1,167+} satisfies (typeof BudgetDayRow)["Encoded"];168+169+const ratchet = {170+ at: sha(1),171+ count: 12,172+ ratchet: "anyCount",173+ territory: "packages/core",174+} satisfies (typeof RatchetRow)["Encoded"];175+176+const pushEventOf = (eventId: string) =>177+ ({178+ after: sha(3),179+ at: at(4),180+ before: sha(2),181+ eventId,182+ ref: "refs/heads/main",183+ repo: "datekit--empty-date--bob",184+ }) satisfies (typeof PushEventRow)["Encoded"];185+186+// Events are written as the service hands them over: unnumbered.187+188+const claimed: ProjectEventInput = ProjectEvent.cases.Claimed.mapFields(189+ Struct.omit(["seq"])190+).make({191+ ask: AskId.make("empty-date"),192+ at: DateTime.makeUnsafe(at(1)),193+ claimant: Handle.make("bob"),194+});195+196+const pushed: ProjectEventInput = ProjectEvent.cases.Pushed.mapFields(197+ Struct.omit(["seq"])198+).make({199+ ask: AskId.make("empty-date"),200+ at: DateTime.makeUnsafe(at(2)),201+ head: CommitSha.make(sha(2)),202+});203+204+const pushes = (count: number) => Array.from({ length: count }, () => pushed);205+206+/** The writes most cases start from: one of each core row. */207+const everything: ProjectWrites = {208+ answers: decodedAll(AnswerRow, [answer]),209+ asks: decodedAll(AskRow, [askA, askB]),210+ claims: decodedAll(ClaimRow, [claim]),211+ events: [claimed, pushed],212+ outbox: decodedAll(OutboxRow, [firstOutbox, secondOutbox]),213+ project: decoded(ProjectRow, project),214+ queue,215+};216+217+/** A snapshot in its encoded form, so a comparison sees every field as stored. */218+const EncodedSnapshot = Schema.Struct({219+ answers: Schema.Array(AnswerRow),220+ asks: Schema.Array(AskRow),221+ budgetDays: Schema.Array(BudgetDayRow),222+ claims: Schema.Array(ClaimRow),223+ decisions: Schema.Array(DecisionRow),224+ landings: Schema.Array(LandingRow),225+ lastSeq: Schema.Int,226+ outbox: Schema.Array(OutboxRow),227+ project: Schema.OptionFromNullOr(ProjectRow),228+ proposals: Schema.Array(ProposalRow),229+ queue: Schema.Json,230+ ratchets: Schema.Array(RatchetRow),231+});232+233+const empty = {234+ answers: [],235+ asks: [],236+ budgetDays: [],237+ claims: [],238+ decisions: [],239+ landings: [],240+ lastSeq: 0,241+ outbox: [],242+ project: null,243+ proposals: [],244+ queue: null,245+ ratchets: [],246+};247+248+/** The store's snapshot, encoded. */249+const loaded = Effect.gen(function* () {250+ const store = yield* ProjectStore;251+252+ return yield* Schema.encodeEffect(EncodedSnapshot)(yield* store.load());253+});254+255+const since = (seq: number, limit: number) =>256+ ProjectStore.use((store) => store.eventsSince(seq, limit));257+258+/**259+ * What every ProjectStore adapter must do, written against the port.260+ * `/memory` and `/sqlite` (over sqlite-node) run it on every `verify`.261+ */262+export const describeProjectStore = (263+ adapter: string,264+ layer: Layer.Layer<ProjectStore>265+) => {266+ describe(`ProjectStore over ${adapter}`, () => {267+ it.effect("loads an empty snapshot before anything is written", () =>268+ Effect.gen(function* () {269+ expect(yield* loaded).toStrictEqual(empty);270+ expect(yield* since(0, 10)).toStrictEqual([]);271+ }).pipe(Effect.provide(layer))272+ );273+274+ it.effect("loads every row a commit wrote, and numbers its events", () =>275+ Effect.gen(function* () {276+ const store = yield* ProjectStore;277+278+ expect(yield* store.commit(everything)).toStrictEqual({279+ duplicatePushEvents: [],280+ seqs: [1, 2],281+ });282+283+ expect(yield* loaded).toStrictEqual({284+ ...empty,285+ answers: [answer],286+ asks: [askA, askB],287+ claims: [claim],288+ lastSeq: 2,289+ outbox: [firstOutbox, secondOutbox],290+ project,291+ queue,292+ });293+294+ expect(yield* since(0, 10)).toStrictEqual([295+ { event: { ...claimed, seq: 1 }, seq: 1 },296+ { event: { ...pushed, seq: 2 }, seq: 2 },297+ ]);298+ }).pipe(Effect.provide(layer))299+ );300+301+ it.effect("keeps a lifecycle state's JSON byte for byte", () =>302+ Effect.gen(function* () {303+ const store = yield* ProjectStore;304+305+ yield* store.commit(everything);306+307+ const snapshot = yield* store.load();308+309+ expect(310+ snapshot.claims.map((written) => JSON.stringify(written.state))311+ ).toStrictEqual([claimState]);312+ expect(313+ snapshot.answers.map((written) => JSON.stringify(written.state))314+ ).toStrictEqual([answerState]);315+ }).pipe(Effect.provide(layer))316+ );317+318+ it.effect(319+ "loads landings, proposals, decisions, budget days and ratchets",320+ () =>321+ Effect.gen(function* () {322+ const store = yield* ProjectStore;323+324+ yield* store.commit({325+ budgetDays: decodedAll(BudgetDayRow, [budgetDay]),326+ decisions: decodedAll(DecisionRow, [decision]),327+ landings: decodedAll(LandingRow, [landingOf(1), landingOf(2)]),328+ proposals: decodedAll(ProposalRow, [proposal]),329+ ratchets: decodedAll(RatchetRow, [ratchet]),330+ });331+332+ expect(yield* loaded).toStrictEqual({333+ ...empty,334+ budgetDays: [budgetDay],335+ decisions: [decision],336+ landings: [landingOf(2), landingOf(1)],337+ proposals: [proposal],338+ ratchets: [ratchet],339+ });340+ }).pipe(Effect.provide(layer))341+ );342+343+ it.effect("replaces a row written again under its key, in its place", () =>344+ Effect.gen(function* () {345+ const store = yield* ProjectStore;346+347+ const later = answerOf(348+ json('{"_tag":"Merging","requestId":"req-00000001"}')349+ );350+351+ const renamed = {352+ ...askA,353+ brief: { want: "An empty date is refused" },354+ };355+356+ const released = { ...claim, state: json('{"_tag":"Released"}') };357+ const spent = { ...budgetDay, used: 2 };358+ const lowered = { ...ratchet, count: 11 };359+ const retried = { ...firstOutbox, attempts: 1 };360+361+ yield* store.commit({362+ ...everything,363+ budgetDays: decodedAll(BudgetDayRow, [budgetDay]),364+ ratchets: decodedAll(RatchetRow, [ratchet]),365+ });366+367+ yield* store.commit({368+ answers: decodedAll(AnswerRow, [later]),369+ asks: decodedAll(AskRow, [renamed]),370+ budgetDays: decodedAll(BudgetDayRow, [spent]),371+ claims: decodedAll(ClaimRow, [released]),372+ outbox: decodedAll(OutboxRow, [retried]),373+ project: decoded(ProjectRow, { ...project, landed: sha(9) }),374+ queue: { order: [] },375+ ratchets: decodedAll(RatchetRow, [lowered]),376+ });377+378+ expect(yield* loaded).toStrictEqual({379+ ...empty,380+ answers: [later],381+ asks: [renamed, askB],382+ budgetDays: [spent],383+ claims: [released],384+ lastSeq: 2,385+ outbox: [retried, secondOutbox],386+ project: { ...project, landed: sha(9) },387+ queue: { order: [] },388+ ratchets: [lowered],389+ });390+ }).pipe(Effect.provide(layer))391+ );392+393+ it.effect("writes nothing for a push event it has already seen", () =>394+ Effect.gen(function* () {395+ const store = yield* ProjectStore;396+ const first = decodedAll(PushEventRow, [pushEventOf("evt-1")]);397+398+ expect(yield* store.commit({ pushEvents: first })).toStrictEqual({399+ duplicatePushEvents: [],400+ seqs: [],401+ });402+403+ // The replay carries a push event not seen yet, and the seen one twice:404+ // it still writes nothing, that new push event included.405+ expect(406+ yield* store.commit({407+ ...everything,408+ pushEvents: decodedAll(PushEventRow, [409+ pushEventOf("evt-1"),410+ pushEventOf("evt-2"),411+ pushEventOf("evt-1"),412+ ]),413+ })414+ ).toStrictEqual({ duplicatePushEvents: ["evt-1"], seqs: [] });415+416+ expect(yield* loaded).toStrictEqual(empty);417+ expect(yield* since(0, 10)).toStrictEqual([]);418+419+ expect(420+ yield* store.commit({421+ events: [pushed],422+ pushEvents: decodedAll(PushEventRow, [pushEventOf("evt-2")]),423+ })424+ ).toStrictEqual({ duplicatePushEvents: [], seqs: [1] });425+ }).pipe(Effect.provide(layer))426+ );427+428+ it.effect("keeps a push event sent twice in one commit once", () =>429+ Effect.gen(function* () {430+ const store = yield* ProjectStore;431+432+ const twice = decodedAll(PushEventRow, [433+ pushEventOf("evt-1"),434+ pushEventOf("evt-1"),435+ ]);436+437+ expect(yield* store.commit({ pushEvents: twice })).toStrictEqual({438+ duplicatePushEvents: [],439+ seqs: [],440+ });441+ expect(yield* store.commit({ pushEvents: twice })).toStrictEqual({442+ duplicatePushEvents: ["evt-1"],443+ seqs: [],444+ });445+ }).pipe(Effect.provide(layer))446+ );447+448+ it.effect("reads events after a sequence number, up to a limit", () =>449+ Effect.gen(function* () {450+ const store = yield* ProjectStore;451+452+ yield* store.commit(everything);453+454+ expect(yield* since(1, 10)).toStrictEqual([455+ { event: { ...pushed, seq: 2 }, seq: 2 },456+ ]);457+ expect(yield* since(0, 1)).toStrictEqual([458+ { event: { ...claimed, seq: 1 }, seq: 1 },459+ ]);460+ expect(yield* since(2, 10)).toStrictEqual([]);461+ }).pipe(Effect.provide(layer))462+ );463+464+ it.effect("keeps only the newest 500 events", () =>465+ Effect.gen(function* () {466+ const store = yield* ProjectStore;467+468+ yield* store.commit({ events: pushes(500) });469+470+ const { seqs } = yield* store.commit({ events: pushes(5) });471+472+ expect(seqs).toStrictEqual([501, 502, 503, 504, 505]);473+474+ const kept = yield* store.eventsSince(0, 1000);475+476+ expect(kept.length).toBe(500);477+ expect(kept.map((event) => event.seq).slice(0, 2)).toStrictEqual([478+ 6, 7,479+ ]);480+ expect((yield* store.load()).lastSeq).toBe(505);481+ }).pipe(Effect.provide(layer))482+ );483+484+ it.effect("drops acknowledged outbox entries from the next load", () =>485+ Effect.gen(function* () {486+ const store = yield* ProjectStore;487+488+ yield* store.commit(everything);489+ yield* store.ackOutbox(["out-1", "out-unknown"]);490+491+ expect((yield* loaded).outbox).toStrictEqual([secondOutbox]);492+ }).pipe(Effect.provide(layer))493+ );494+495+ it.effect(496+ "loads landings newest first, the later write first on a tie",497+ () =>498+ Effect.gen(function* () {499+ const store = yield* ProjectStore;500+ const earlier = landingOf(1);501+ const first = landingOf(5);502+ const second = { ...landingOf(5), sha: sha(40) };503+504+ yield* store.commit({505+ landings: decodedAll(LandingRow, [first, earlier]),506+ });507+ yield* store.commit({ landings: decodedAll(LandingRow, [second]) });508+509+ expect((yield* loaded).landings).toStrictEqual([510+ second,511+ first,512+ earlier,513+ ]);514+ }).pipe(Effect.provide(layer))515+ );516+517+ it.effect("finds a landing older than the snapshot's newest 50", () =>518+ Effect.gen(function* () {519+ const store = yield* ProjectStore;520+ const landings = Array.from({ length: 51 }, (_, n) => landingOf(n + 1));521+522+ yield* store.commit({ landings: decodedAll(LandingRow, landings) });523+524+ const snapshot = yield* loaded;525+526+ expect(snapshot.landings.length).toBe(50);527+ expect(snapshot.landings[0]).toStrictEqual(landingOf(51));528+ expect(snapshot.landings.at(-1)).toStrictEqual(landingOf(2));529+530+ const oldest = yield* store.landing(CommitSha.make(sha(2)));531+532+ expect(533+ yield* Schema.encodeEffect(Schema.OptionFromNullOr(LandingRow))(534+ oldest535+ )536+ ).toStrictEqual(landingOf(1));537+ expect(538+ Option.isNone(yield* store.landing(CommitSha.make(sha(999))))539+ ).toBe(true);540+ }).pipe(Effect.provide(layer))541+ );542+543+ it.effect(544+ "leaves the previous state whole when a commit fails part-way",545+ () =>546+ Effect.gen(function* () {547+ const store = yield* ProjectStore;548+549+ yield* store.commit(everything);550+551+ const before = yield* loaded;552+553+ // `attempts` must be an integer: the last row written breaks it, after554+ // the rows and events before it were already written.555+ const failed = yield* Effect.exit(556+ store.commit({557+ asks: decodedAll(AskRow, [askOf("time-zones")]),558+ events: [pushed],559+ outbox: [560+ decoded(OutboxRow, outboxOf("out-3")),561+ { ...decoded(OutboxRow, outboxOf("out-4")), attempts: 0.5 },562+ ],563+ project: decoded(ProjectRow, { ...project, landed: sha(9) }),564+ })565+ );566+567+ expect(Exit.isFailure(failed)).toBe(true);568+ expect(yield* loaded).toStrictEqual(before);569+ expect(yield* since(2, 10)).toStrictEqual([]);570+ }).pipe(Effect.provide(layer))571+ );572+ });573+};