Skip to content
Myr

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

9 files+1507 added−0 removed

added:packages/project/src/project-store/memory.ts+215 added
1import { Array, Effect, Layer, Option, Order, SynchronizedRef } from "effect";23import {4 keptEvents,5 ProjectStore,6 snapshotLandings,7} from "../project-store.ts";8import type {9 Committed,10 ProjectSnapshot,11 ProjectWrites,12} from "../project-store.ts";13import type { EventRow } from "./rows.ts";14import {15 EventTable,16 ProjectTable,17 QueueTable,18 Tables,19 writeAll,20} from "./tables.ts";21import type { Column, Table, Upsert } from "./tables.ts";2223/** A row as a table keeps it: its columns and its encoded body. */24interface Stored {25 readonly body: string;26 readonly columns: Readonly<Record<string, Column>>;27}2829/** A table's rows by key, in the order each key was first written. */30type Rows = ReadonlyMap<string, Stored>;3132interface 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}3738const keyOf = <A>(table: Table<A>, columns: Stored["columns"]) =>39 JSON.stringify(table.key.map((name) => columns[name]));4041const rowsIn = <A>(state: State, table: Table<A>): Rows =>42 state.tables.get(table.name) ?? new Map();4344const decodeAll = <A>(table: Table<A>, stored: Iterable<Stored>) =>45 Effect.forEach(stored, (row) => table.decode(row.body));4647const all = <A>(state: State, table: Table<A>) =>48 decodeAll(table, rowsIn(state, table).values());4950/** A landing with the place it was first written in. */51type Placed = readonly [index: number, row: Stored];5253/** Newest first: by landing time, then the later write, as `/sqlite` orders them. */54const 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);6061const 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 );6768 const newest = Array.take(69 Array.sort(placed, newestFirst),70 snapshotLandings71 );7273 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 });9192/** The push events in `writes` that `state` already holds, each once. */93const seenIn = (state: State, writes: ProjectWrites) => {94 const seen = rowsIn(state, Tables.pushEvents);9596 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};104105/** Writes rows into copies of `tables`' maps, never into the maps themselves. */106const 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));111112 for (const row of rows) {113 const columns = table.columns(row);114115 kept.set(keyOf(table, columns), {116 body: yield* table.encode(row),117 columns,118 });119 }120121 tables.set(table.name, kept);122 });123124/**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 */128const 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) ?? [])];133134 tables.set(EventTable.name, new Map(events.slice(-keptEvents)));135136 const committed: Committed = { duplicatePushEvents: [], seqs };137138 const next: State = {139 lastSeq: state.lastSeq + seqs.length,140 tables,141 };142143 return [committed, next] as const;144 });145146/**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 */152export 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 });159160 return ProjectStore.of({161 ackOutbox: (ids) =>162 SynchronizedRef.update(ref, (state) => {163 const kept = new Map(rowsIn(state, Tables.outbox));164165 for (const id of ids) {166 kept.delete(keyOf(Tables.outbox, { id }));167 }168169 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);177178 if (duplicatePushEvents.length > 0) {179 const replay: Committed = { duplicatePushEvents, seqs: [] };180181 return Effect.succeed([replay, state] as const);182 }183184 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 );192193 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);203204 const row = rowsIn(state, Tables.landings).get(205 keyOf(Tables.landings, { sha })206 );207208 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
added:packages/project/src/project-store/rows.ts+151 added
1import { Ask } from "@repo/protocol/domain/ask";2import { Decision } from "@repo/protocol/domain/decision";3import { ProjectEvent } from "@repo/protocol/domain/event";4import { LandingView } from "@repo/protocol/domain/landing";5import { Proposal } from "@repo/protocol/domain/proposal";6import {7 AskId,8 CommitSha,9 Handle,10 LandedSha,11 ProjectName,12 RatchetName,13 RepoName,14 RequestId,15} from "@repo/protocol/ids";16import { Schema } from "effect";1718// 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.2223/**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 */27export 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});3738export type ProjectRow = typeof ProjectRow.Type;3940/** An ask, as the domain types it. */41export const AskRow = Ask;4243export type AskRow = typeof AskRow.Type;4445/** One person's claim on an ask, its lifecycle state encoded. */46export 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});5354export type ClaimRow = typeof ClaimRow.Type;5556/**57 * One answer request, keyed by its `requestId` so a request sent twice is58 * one row; its landing lifecycle state encoded.59 */60export 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});6970export type AnswerRow = typeof AnswerRow.Type;7172/** A landing, as the domain types it. */73export const LandingRow = LandingView;7475export type LandingRow = typeof LandingRow.Type;7677/** A proposal, as the domain types it. */78export const ProposalRow = Proposal;7980export type ProposalRow = typeof ProposalRow.Type;8182/** A decision, as the domain types it. */83export const DecisionRow = Decision;8485export type DecisionRow = typeof DecisionRow.Type;8687/** How much of one decider's budget one day used, and how many finishes. */88export 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});9596export type BudgetDayRow = typeof BudgetDayRow.Type;9798/** A ratchet's count in one territory, as recorded at a landing. */99export const RatchetRow = Schema.Struct({100 at: LandedSha,101 count: Schema.Int,102 ratchet: RatchetName,103 territory: Schema.NonEmptyString,104});105106export type RatchetRow = typeof RatchetRow.Type;107108/**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 */112export 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});120121export type PushEventRow = typeof PushEventRow.Type;122123/**124 * A side effect still to run after its transition was persisted (a fork, a125 * projection row), kept until it is acknowledged.126 */127export 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});134135export type OutboxRow = typeof OutboxRow.Type;136137/** An event with the sequence number the store gave it. */138export const EventRow = Schema.Struct({139 event: ProjectEvent,140 seq: Schema.Int,141});142143export type EventRow = typeof EventRow.Type;144145/** Drops a key from each member of a union, not from the union as a whole. */146type OmitEach<Union, Key extends PropertyKey> = Union extends unknown147 ? Omit<Union, Key>148 : never;149150/** An event before the store numbers it: every `ProjectEvent` but its `seq`. */151export type ProjectEventInput = OmitEach<ProjectEvent, "seq">;
added:packages/project/src/project-store/sqlite.ts+174 added
1import { Array, Effect, Layer, Option, Schema } from "effect";2import { SqlClient } from "effect/sql/SqlClient";3import type { Statement } from "effect/sql/Statement";45import {6 keptEvents,7 ProjectStore,8 snapshotLandings,9} from "../project-store.ts";10import type { ProjectWrites } from "../project-store.ts";11import { migrate } from "./migrations.ts";12import {13 EventTable,14 ProjectTable,15 QueueTable,16 Tables,17 writeAll,18} from "./tables.ts";19import type { Table } from "./tables.ts";2021// What SQLite hands back is decoded like any other outside input.22const Bodies = Schema.Array(Schema.Struct({ body: Schema.String }));2324const decodeBodies = Schema.decodeUnknownEffect(Bodies);2526const EventIds = Schema.Array(Schema.Struct({ event_id: Schema.String }));2728const decodeEventIds = Schema.decodeUnknownEffect(EventIds);2930const LastSeq = Schema.Tuple([Schema.Struct({ last: Schema.Int })]);3132const decodeLastSeq = Schema.decodeUnknownEffect(LastSeq);3334/** The rows a query returns, each decoded from its body. */35const 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 );4243/**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 */50export const ProjectStoreSqlite = Layer.effect(51 ProjectStore,52 Effect.gen(function* () {53 const sql = yield* SqlClient;5455 yield* migrate;5657 const all = <A>(table: Table<A>) =>58 bodiesOf(table, sql`SELECT body FROM ${sql(table.name)} ORDER BY rowid`);5960 const lastSeq = sql`SELECT COALESCE(MAX(seq), 0) AS last FROM events`.pipe(61 Effect.flatMap(decodeLastSeq),62 Effect.map(([row]) => row.last)63 );6465 // 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 };7677 const updates = Object.keys(columns)78 .filter((column) => !table.key.includes(column))79 .map((column) => `${column} = excluded.${column}`);8081 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 );8788 const seenPushEvents = (writes: ProjectWrites) => {89 const ids = Array.map(writes.pushEvents ?? [], (event) => event.eventId);9091 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));9697 return Array.dedupe(ids.filter((id) => seen.has(id)));98 })99 )100 : Effect.succeed([]);101 };102103 const write = (writes: ProjectWrites) =>104 Effect.gen(function* () {105 const last = yield* lastSeq;106 const seqs = yield* writeAll(writes, last, upsert);107108 yield* sql`DELETE FROM events WHERE seq <= ${last + seqs.length - keptEvents}`;109110 return { duplicatePushEvents: [], seqs };111 });112113 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);126127 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
1import { ProjectEvent } from "@repo/protocol/domain/event";2import { Array, DateTime, Effect, Option, Schema } from "effect";34import type { ProjectWrites } from "../project-store.ts";5import {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";1819// 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`.2324/** A column's value: text, or an integer. */25export type Column = string | number;2627/** One table's rows: how a row becomes its key columns and body, and back. */28export 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}3738// 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.40const 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);4950 return {51 columns,52 decode: (text) => Effect.orDie(decode(text)),53 encode: (row) => Effect.orDie(encode(row)),54 key,55 name,56 };57};5859/** The tables that hold many rows, by the `ProjectWrites` field that carries them. */60export 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;9697/** A table with one row at most: the project, and the landing queue. */98const single = { id: 1 } as const;99100/** The project's own row. */101export const ProjectTable = tableOf(102 "project",103 ProjectRow,104 ["id"],105 () => single106);107108/** The encoded landing queue, one row. */109export const QueueTable = tableOf(110 "landing_queue",111 Schema.Json,112 ["id"],113 () => single114);115116/** The project's events, each body carrying the `seq` it was given. */117export const EventTable = tableOf("events", ProjectEvent, ["seq"], (event) => ({118 seq: event.seq,119}));120121/** How an adapter writes one table's rows, each replacing any row under its key. */122export type Upsert<E, R> = <A>(123 table: Table<A>,124 rows: readonly A[]125) => Effect.Effect<void, E, R>;126127/**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 */133export 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 }));143144 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 ?? []);160161 return Array.map(events, (event) => event.seq);162 });
added:packages/project/src/project-store.ts+113 added
1import type { CommitSha } from "@repo/protocol/ids";2import { Context } from "effect";3import type { Effect, Option, Schema } from "effect";45import 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";2021/** How many landings a snapshot carries, newest first; `landing` finds older ones. */22export const snapshotLandings = 50;2324/** How many events a project keeps; a watcher resuming from an older one has missed some. */25export const keptEvents = 500;2627/**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 */32export 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}5152/**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 */57export 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}7273/** What a commit did: the numbers it gave its events, and the push events it had already seen. */74export 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}8081/**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 */99export 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
added:packages/project/test/project-store-sqlite.test.ts+36 added
added:packages/project/test/project-store.contract.ts+573 added
1import { describe, expect, it } from "@effect/vitest";2import { CheckSpec } from "@repo/protocol/domain/check";3import { DecisionSubject } from "@repo/protocol/domain/decision";4import { ProjectEvent } from "@repo/protocol/domain/event";5import {6 AskId,7 CommitSha,8 Handle,9 ProposalId,10 RepoPath,11} from "@repo/protocol/ids";12import { DateTime, Effect, Exit, Option, Schema, Struct } from "effect";13import type { Layer } from "effect";1415import { ProjectStore } from "../src/project-store.ts";16import type { ProjectWrites } from "../src/project-store.ts";17import {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";30import type { ProjectEventInput } from "../src/project-store/rows.ts";3132// 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.3435/** A minute after noon on the day the store was built. */36const at = (minute: number) =>37 `2026-10-07T12:${String(minute).padStart(2, "0")}:00.000Z`;3839/** A 40-hex commit id from a number, so each fixture SHA is distinct. */40const sha = (n: number) => n.toString(16).padStart(40, "0");4142const decoded = <A, I>(schema: Schema.Codec<A, I>, value: NoInfer<I>): A =>43 Schema.decodeSync(schema)(value);4445const decodedAll = <A, I>(46 schema: Schema.Codec<A, I>,47 values: readonly NoInfer<I>[]48) => values.map((value) => decoded(schema, value));4950/** Lifecycle states are the service's JSON; the store never reads into them. */51const json = (text: string) =>52 Schema.decodeSync(Schema.fromJsonString(Schema.Json))(text);5354const 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"];7172const 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"];8182const askA = askOf("empty-date");8384const askB = askOf("leap-day");8586// 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.88const claimState =89 '{"_tag":"Live","warnsAt":"2026-10-07T14:00:00.000Z","base":"0000000000000000000000000000000000000001"}';9091const answerState = '{"_tag":"Queued","requestId":"req-00000001"}';9293const claim = {94 ask: "empty-date",95 claimant: "bob",96 state: json(claimState),97 updatedAt: at(1),98} satisfies (typeof ClaimRow)["Encoded"];99100const 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"];109110const answer = answerOf(json(answerState));111112const queue = { active: "req-00000001", order: ["req-00000001"] };113114const 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"];122123const firstOutbox = outboxOf("out-1");124125const secondOutbox = outboxOf("out-2");126127const 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"];137138const 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"];148149const 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"];161162const budgetDay = {163 day: "2026-10-07",164 decider: "alice",165 finishes: 0,166 used: 1,167} satisfies (typeof BudgetDayRow)["Encoded"];168169const ratchet = {170 at: sha(1),171 count: 12,172 ratchet: "anyCount",173 territory: "packages/core",174} satisfies (typeof RatchetRow)["Encoded"];175176const 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"];185186// Events are written as the service hands them over: unnumbered.187188const 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});195196const 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});203204const pushes = (count: number) => Array.from({ length: count }, () => pushed);205206/** The writes most cases start from: one of each core row. */207const 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};216217/** A snapshot in its encoded form, so a comparison sees every field as stored. */218const 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});232233const 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};247248/** The store's snapshot, encoded. */249const loaded = Effect.gen(function* () {250 const store = yield* ProjectStore;251252 return yield* Schema.encodeEffect(EncodedSnapshot)(yield* store.load());253});254255const since = (seq: number, limit: number) =>256 ProjectStore.use((store) => store.eventsSince(seq, limit));257258/**259 * What every ProjectStore adapter must do, written against the port.260 * `/memory` and `/sqlite` (over sqlite-node) run it on every `verify`.261 */262export 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 );273274 it.effect("loads every row a commit wrote, and numbers its events", () =>275 Effect.gen(function* () {276 const store = yield* ProjectStore;277278 expect(yield* store.commit(everything)).toStrictEqual({279 duplicatePushEvents: [],280 seqs: [1, 2],281 });282283 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 });293294 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 );300301 it.effect("keeps a lifecycle state's JSON byte for byte", () =>302 Effect.gen(function* () {303 const store = yield* ProjectStore;304305 yield* store.commit(everything);306307 const snapshot = yield* store.load();308309 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 );317318 it.effect(319 "loads landings, proposals, decisions, budget days and ratchets",320 () =>321 Effect.gen(function* () {322 const store = yield* ProjectStore;323324 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 });331332 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 );342343 it.effect("replaces a row written again under its key, in its place", () =>344 Effect.gen(function* () {345 const store = yield* ProjectStore;346347 const later = answerOf(348 json('{"_tag":"Merging","requestId":"req-00000001"}')349 );350351 const renamed = {352 ...askA,353 brief: { want: "An empty date is refused" },354 };355356 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 };360361 yield* store.commit({362 ...everything,363 budgetDays: decodedAll(BudgetDayRow, [budgetDay]),364 ratchets: decodedAll(RatchetRow, [ratchet]),365 });366367 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 });377378 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 );392393 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")]);397398 expect(yield* store.commit({ pushEvents: first })).toStrictEqual({399 duplicatePushEvents: [],400 seqs: [],401 });402403 // 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: [] });415416 expect(yield* loaded).toStrictEqual(empty);417 expect(yield* since(0, 10)).toStrictEqual([]);418419 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 );427428 it.effect("keeps a push event sent twice in one commit once", () =>429 Effect.gen(function* () {430 const store = yield* ProjectStore;431432 const twice = decodedAll(PushEventRow, [433 pushEventOf("evt-1"),434 pushEventOf("evt-1"),435 ]);436437 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 );447448 it.effect("reads events after a sequence number, up to a limit", () =>449 Effect.gen(function* () {450 const store = yield* ProjectStore;451452 yield* store.commit(everything);453454 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 );463464 it.effect("keeps only the newest 500 events", () =>465 Effect.gen(function* () {466 const store = yield* ProjectStore;467468 yield* store.commit({ events: pushes(500) });469470 const { seqs } = yield* store.commit({ events: pushes(5) });471472 expect(seqs).toStrictEqual([501, 502, 503, 504, 505]);473474 const kept = yield* store.eventsSince(0, 1000);475476 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 );483484 it.effect("drops acknowledged outbox entries from the next load", () =>485 Effect.gen(function* () {486 const store = yield* ProjectStore;487488 yield* store.commit(everything);489 yield* store.ackOutbox(["out-1", "out-unknown"]);490491 expect((yield* loaded).outbox).toStrictEqual([secondOutbox]);492 }).pipe(Effect.provide(layer))493 );494495 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) };503504 yield* store.commit({505 landings: decodedAll(LandingRow, [first, earlier]),506 });507 yield* store.commit({ landings: decodedAll(LandingRow, [second]) });508509 expect((yield* loaded).landings).toStrictEqual([510 second,511 first,512 earlier,513 ]);514 }).pipe(Effect.provide(layer))515 );516517 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));521522 yield* store.commit({ landings: decodedAll(LandingRow, landings) });523524 const snapshot = yield* loaded;525526 expect(snapshot.landings.length).toBe(50);527 expect(snapshot.landings[0]).toStrictEqual(landingOf(51));528 expect(snapshot.landings.at(-1)).toStrictEqual(landingOf(2));529530 const oldest = yield* store.landing(CommitSha.make(sha(2)));531532 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 );542543 it.effect(544 "leaves the previous state whole when a commit fails part-way",545 () =>546 Effect.gen(function* () {547 const store = yield* ProjectStore;548549 yield* store.commit(everything);550551 const before = yield* loaded;552553 // `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 );566567 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};