Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent e8acd94 · Browse files · 6 files+773 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

6 files+773 added−0 removed

  • tests:+421 added−0 removed
  • other:+352 added−0 removed

6 files+773 added−0 removed

added:apps/platform/migrations/0001_front_page.sql+24 added
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.45CREATE 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);1920-- The last event applied per project.21CREATE TABLE cursor (22 project TEXT PRIMARY KEY,23 seq INTEGER NOT NULL24);
added:packages/project/src/projection-d1/front-page.ts+97 added
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 */13import { Reserve } from "@repo/protocol/domain/ask";14import type { FrontPageEntry } from "@repo/protocol/domain/front-page";15import { AskId, KindName, ProjectName } from "@repo/protocol/ids";16import { Effect, Layer, Schema } from "effect";17import { SqlClient } from "effect/sql/SqlClient";1819import { FrontPage } from "../front-page.ts";20import type { FrontPageFilter } from "../front-page.ts";2122const AskIds = Schema.fromJsonString(Schema.Array(AskId));2324/** One row of the front page query. */25const 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});3738type EntryRow = typeof EntryRow.Type;3940const decodeRows = Schema.decodeUnknownEffect(Schema.Array(EntryRow));4142const entryOf = (row: EntryRow): FrontPageEntry => {43 const blockedBy = row.blocked_by.filter((ask) =>44 row.open_blockers.includes(ask)45 );4647 const claimed = row.claimed > 0;4849 const listing = {50 ask: row.ask,51 blockedBy,52 claimed,53 kind: row.kind,54 territory: row.territory,55 want: row.want,56 };5758 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};6566export const FrontPageD1: Layer.Layer<FrontPage, never, SqlClient> =67 Layer.effect(68 FrontPage,69 Effect.gen(function* () {70 const sql = yield* SqlClient;7172 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 );9091 return FrontPage.of({92 credits: () => Effect.succeed([]),93 entries,94 projects: () => Effect.succeed([]),95 });96 })97 );
added:packages/project/src/projection-d1/projection.ts+181 added
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 */19import { D1Client } from "@effect/sql-d1/D1Client";20import { ProjectEvent } from "@repo/protocol/domain/event";21import type { ProjectName } from "@repo/protocol/ids";22import { Array, DateTime, Effect, Layer, Option, Order, Schema } from "effect";23import { SqlClient } from "effect/sql/SqlClient";24import type { SqlError } from "effect/sql/SqlError";25import type { Statement } from "effect/sql/Statement";2627import type { OutboxRow } from "../project-store/rows.ts";28import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";2930const decodeProjected = Schema.decodeUnknownEffect(31 Schema.toCodecJson(ProjectedEvent)32);3334const Cursors = Schema.Array(35 Schema.Struct({ project: Schema.String, seq: Schema.Int })36);3738const decodeCursors = Schema.decodeUnknownEffect(Cursors);3940const bySeq = Order.mapInput(41 Order.Tuple([Order.String, Order.Number]),42 ({ event, project }: ProjectedEvent) => [project, event.seq] as const43);4445/** Each project, with the last event the rows carry for it. */46const lastOf = (events: readonly ProjectedEvent[]) =>47 new Map(events.map(({ event, project }) => [project, event.seq]));4849export 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);5556 /** 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 });6566 /** 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}`;6970 /** What one event changes on the front page, if anything. */71 const writes = ({ event, project }: ProjectedEvent) => {72 const next = isNext(project, event.seq);7374 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}`;7778 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 };108109 /** 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`;114115 const cursorsOf = (projects: readonly ProjectName[]) =>116 sql`SELECT project, seq FROM cursor WHERE ${sql.in("project", projects)}`;117118 /**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);125126 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 );137138 const reached = new Map(139 (yield* Effect.orDie(decodeCursors(results.at(-1) ?? []))).map(140 ({ project, seq }) => [project, seq]141 )142 );143144 const short = [...last].filter(145 ([project, seq]) => (reached.get(project) ?? 0) < seq146 );147148 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 });159160 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 );178179 return Projection.of({ apply });180 })181 );
added:packages/project/src/projection-d1/tables.ts+41 added
added:packages/project/test/projection-d1.test.ts+421 added
1/**2 * The front page's D1 projection over sqlite-node, with the platform's D13 * migration applied from its file: projects' outbox rows go in through4 * `ProjectionD1`, and `FrontPageD1` reads every open ask back out, as the5 * anonymous viewer may take it.6 */7import { NodeServices } from "@effect/platform-node";8import { SqliteClient } from "@effect/sql-sqlite-node";9import { describe, expect, it } from "@effect/vitest";10import type { AskListing } from "@repo/protocol/domain/ask";11import { ProjectEvent } from "@repo/protocol/domain/event";12import type { FrontPageEntry } from "@repo/protocol/domain/front-page";13import {14 AskId,15 Handle,16 KindName,17 LandedSha,18 ProjectName,19} from "@repo/protocol/ids";20import { DateTime, Effect, FileSystem, Layer, Path } from "effect";21import { SqlClient } from "effect/sql/SqlClient";2223import { FrontPage } from "../src/front-page.ts";24import type { FrontPageFilter } from "../src/front-page.ts";25import { projectedRows } from "../src/outbox.ts";26import type { OutboxRow } from "../src/project-store/rows.ts";27import { FrontPageD1 } from "../src/projection-d1/front-page.ts";28import { ProjectionD1 } from "../src/projection-d1/projection.ts";29import { FrontPageDdl } from "../src/projection-d1/tables.ts";30import { Projection, ProjectionFailed } from "../src/projection.ts";3132/** The migration the platform's D1 database applies, as its file holds it. */33const migration = Effect.gen(function* () {34 const fs = yield* FileSystem.FileSystem;35 const path = yield* Path.Path;3637 return yield* fs.readFileString(38 yield* path.fromFileUrl(39 new URL(40 "../../../apps/platform/migrations/0001_front_page.sql",41 import.meta.url42 )43 )44 );45}).pipe(Effect.provide(NodeServices.layer));4647/** A fresh in-memory database each time, with the migration file applied. */48const database = Layer.effectDiscard(49 Effect.gen(function* () {50 const sql = yield* SqlClient;5152 for (const statement of (yield* migration).split(";")) {53 if (statement.trim().length > 0) {54 yield* sql.unsafe(statement);55 }56 }57 })58).pipe(59 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),60 Layer.orDie61);6263const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(64 Layer.provideMerge(database)65);6667const datekit = ProjectName.make("datekit");6869const burrow = ProjectName.make("burrow");7071const fix = KindName.make("fix");7273const lintToZero = KindName.make("lintToZero");7475const parseIso = AskId.make("parse-iso");7677const weekStart = AskId.make("week-start");7879const noAny = AskId.make("no-any");8081const landing = LandedSha.make("a".repeat(40));8283const at = (minute: number) =>84 DateTime.makeUnsafe(`2026-10-08T09:${String(minute).padStart(2, "0")}:00Z`);8586const listing = (87 ask: AskId,88 kind: KindName,89 more: Partial<AskListing> = {}90): AskListing => ({91 ask,92 blockedBy: [],93 claimed: false,94 kind,95 territory: "src",96 want: `${ask} works`,97 ...more,98});99100/** One project's events, numbered from `first`, as outbox rows. */101const rows = (102 project: ProjectName,103 first: number,104 events: readonly ((seq: number) => ProjectEvent)[]105) =>106 projectedRows(107 project,108 events.map((event, index) => event(first + index)),109 at(59)110 );111112const opened =113 (ask: AskListing, minute: number) =>114 (seq: number): ProjectEvent =>115 ProjectEvent.cases.AskOpened.make({ ask, at: at(minute), seq });116117const claimed =118 (ask: AskId) =>119 (seq: number): ProjectEvent =>120 ProjectEvent.cases.Claimed.make({121 ask,122 at: at(30),123 claimant: Handle.make("bram"),124 seq,125 });126127const released =128 (ask: AskId) =>129 (seq: number): ProjectEvent =>130 ProjectEvent.cases.Released.make({ ask, at: at(31), seq });131132const lapsed =133 (ask: AskId) =>134 (seq: number): ProjectEvent =>135 ProjectEvent.cases.Lapsed.make({ ask, at: at(32), seq });136137const warned =138 (ask: AskId) =>139 (seq: number): ProjectEvent =>140 ProjectEvent.cases.Warned.make({ ask, at: at(32), seq });141142const closedBy =143 (ask: AskId) =>144 (seq: number): ProjectEvent =>145 ProjectEvent.cases.AskClosed.make({ ask, at: at(40), landing, seq });146147const landed =148 (project: ProjectName, ask: AskId) =>149 (seq: number): ProjectEvent =>150 ProjectEvent.cases.Landed.make({151 at: at(40),152 landing: {153 ask,154 assisted: [],155 author: Handle.make("bram"),156 credits: [{ handle: Handle.make("bram"), role: "Signed-off-by" }],157 landedAt: at(40),158 parent: LandedSha.make("b".repeat(40)),159 project,160 sha: landing,161 },162 seq,163 });164165const entry = (166 project: ProjectName,167 ask: AskListing,168 takeable: boolean169): FrontPageEntry => ({ ask, posture: "open", project, takeable });170171const apply = (batch: Effect.Effect<readonly OutboxRow[]>) =>172 Effect.flatMap(batch, (each) =>173 Projection.use((projection) => projection.apply(each))174 );175176const entries = (filter: FrontPageFilter = {}) =>177 FrontPage.use((front) => front.entries(filter));178179/** Every row of the projection's tables, to compare a replay against. */180const tables = Effect.gen(function* () {181 const sql = yield* SqlClient;182183 return {184 cursor: yield* sql`SELECT * FROM cursor ORDER BY project`,185 frontPage: yield* sql`SELECT * FROM front_page ORDER BY project, ask`,186 };187});188189const parseIsoAsk = listing(parseIso, fix);190191const weekStartAsk = listing(weekStart, fix, { reserve: "newcomers" });192193const noAnyAsk = listing(noAny, lintToZero, { territory: "packages/core" });194195describe("the front page's D1 projection", () => {196 it.effect("lists the open asks of every project, claimed or not", () =>197 Effect.gen(function* () {198 yield* apply(199 rows(datekit, 1, [200 opened(parseIsoAsk, 1),201 opened(weekStartAsk, 2),202 claimed(parseIso),203 ])204 );205 yield* apply(rows(burrow, 1, [opened(noAnyAsk, 3)]));206207 const parseIsoClaimed = entry(208 datekit,209 { ...parseIsoAsk, claimed: true },210 false211 );212213 const weekStartHeld = entry(datekit, weekStartAsk, false);214215 const noAnyOpen = entry(burrow, noAnyAsk, true);216217 expect(yield* entries()).toStrictEqual([218 noAnyOpen,219 weekStartHeld,220 parseIsoClaimed,221 ]);222 expect(yield* entries({ kind: fix })).toStrictEqual([223 weekStartHeld,224 parseIsoClaimed,225 ]);226 expect(yield* entries({ reserved: "newcomers" })).toStrictEqual([227 weekStartHeld,228 ]);229 expect(yield* entries({ kind: lintToZero })).toStrictEqual([noAnyOpen]);230 expect(yield* entries({ reserved: "people" })).toStrictEqual([]);231 }).pipe(Effect.provide(world))232 );233234 it.effect("frees an ask its claim released or let lapse", () =>235 Effect.gen(function* () {236 yield* apply(237 rows(datekit, 1, [238 opened(parseIsoAsk, 1),239 opened(listing(weekStart, fix), 2),240 claimed(parseIso),241 claimed(weekStart),242 warned(weekStart),243 released(parseIso),244 lapsed(weekStart),245 ])246 );247248 expect(yield* entries()).toStrictEqual([249 entry(datekit, listing(weekStart, fix), true),250 entry(datekit, parseIsoAsk, true),251 ]);252 }).pipe(Effect.provide(world))253 );254255 it.effect("keeps an ask claimed while a second claim on it is live", () =>256 Effect.gen(function* () {257 yield* apply(258 rows(datekit, 1, [259 opened(parseIsoAsk, 1),260 claimed(parseIso),261 claimed(parseIso),262 released(parseIso),263 ])264 );265266 expect(yield* entries()).toStrictEqual([267 entry(datekit, { ...parseIsoAsk, claimed: true }, false),268 ]);269 }).pipe(Effect.provide(world))270 );271272 it.effect("drops an ask its landing closed", () =>273 Effect.gen(function* () {274 yield* apply(275 rows(datekit, 1, [276 opened(parseIsoAsk, 1),277 opened(weekStartAsk, 2),278 claimed(parseIso),279 landed(datekit, parseIso),280 closedBy(parseIso),281 ])282 );283284 expect(yield* entries()).toStrictEqual([285 entry(datekit, weekStartAsk, false),286 ]);287 }).pipe(Effect.provide(world))288 );289290 it.effect("shows an ask blocked until the asks it waits on land", () =>291 Effect.gen(function* () {292 const last = listing(noAny, lintToZero, {293 blockedBy: [parseIso, weekStart],294 });295296 yield* apply(297 rows(datekit, 1, [298 opened(parseIsoAsk, 1),299 opened(listing(weekStart, fix), 2),300 opened(last, 3),301 closedBy(parseIso),302 ])303 );304305 expect(yield* entries({ kind: lintToZero })).toStrictEqual([306 entry(datekit, { ...last, blockedBy: [weekStart] }, false),307 ]);308309 yield* apply(rows(datekit, 5, [closedBy(weekStart)]));310311 expect(yield* entries({ kind: lintToZero })).toStrictEqual([312 entry(datekit, { ...last, blockedBy: [] }, true),313 ]);314 }).pipe(Effect.provide(world))315 );316317 it.effect("changes nothing when the same rows come again", () =>318 Effect.gen(function* () {319 const first = rows(datekit, 1, [320 opened(parseIsoAsk, 1),321 opened(weekStartAsk, 2),322 claimed(parseIso),323 ]);324325 yield* apply(first);326 yield* apply(rows(burrow, 1, [opened(noAnyAsk, 3)]));327 yield* apply(rows(datekit, 4, [released(parseIso)]));328329 const before = yield* tables;330331 yield* apply(first);332 yield* apply(first);333334 expect(yield* tables).toStrictEqual(before);335 expect(yield* entries({ kind: fix })).toStrictEqual([336 entry(datekit, weekStartAsk, false),337 entry(datekit, parseIsoAsk, true),338 ]);339 }).pipe(Effect.provide(world))340 );341342 it.effect("ignores an older event that arrives after a newer one", () =>343 Effect.gen(function* () {344 yield* apply(345 rows(datekit, 1, [346 opened(parseIsoAsk, 1),347 opened(weekStartAsk, 2),348 claimed(parseIso),349 ])350 );351352 const before = yield* tables;353354 yield* apply(rows(datekit, 2, [closedBy(weekStart)]));355356 expect(yield* tables).toStrictEqual(before);357 }).pipe(Effect.provide(world))358 );359360 it.effect(361 "refuses rows past a gap, so the outbox sends the missing one first",362 () =>363 Effect.gen(function* () {364 yield* apply(rows(datekit, 1, [opened(parseIsoAsk, 1)]));365366 const before = yield* tables;367368 const refused = yield* Effect.flip(369 apply(rows(datekit, 3, [claimed(parseIso)]))370 );371372 expect(refused).toBeInstanceOf(ProjectionFailed);373 expect(yield* tables).toStrictEqual(before);374375 yield* apply(376 rows(datekit, 2, [opened(weekStartAsk, 2), claimed(parseIso)])377 );378379 expect(yield* entries()).toStrictEqual([380 entry(datekit, weekStartAsk, false),381 entry(datekit, { ...parseIsoAsk, claimed: true }, false),382 ]);383 }).pipe(Effect.provide(world))384 );385386 it.effect("applies what it can of a batch and refuses only past a gap", () =>387 Effect.gen(function* () {388 const both = yield* Effect.zipWith(389 rows(datekit, 1, [opened(parseIsoAsk, 1)]),390 rows(burrow, 2, [opened(noAnyAsk, 3)]),391 (one, other) => [...one, ...other]392 );393394 const refused = yield* Effect.flip(395 Projection.use((projection) => projection.apply(both))396 );397398 expect(refused).toBeInstanceOf(ProjectionFailed);399 expect(yield* entries()).toStrictEqual([400 entry(datekit, parseIsoAsk, true),401 ]);402 }).pipe(Effect.provide(world))403 );404405 it.effect("reads the migration the platform's D1 applies", () =>406 Effect.gen(function* () {407 expect(yield* migration).toBe(FrontPageDdl);408 })409 );410411 it.effect("reads no projects and no credits until their tables exist", () =>412 Effect.gen(function* () {413 yield* apply(rows(datekit, 1, [opened(parseIsoAsk, 1)]));414415 const front = yield* FrontPage;416417 expect(yield* front.projects()).toStrictEqual([]);418 expect(yield* front.credits(Handle.make("bram"))).toStrictEqual([]);419 }).pipe(Effect.provide(world))420 );421});
modified:tsconfig.base.json+9 added
151 unmodified lines
152 "allowedUnstableApis": ["effect/sql"]153 }154 },155 {156 "include": ["packages/project/src/projection-d1/**/*.ts"],157 "options": {158 "allowedUnstableApis": [159 "effect/sql",160 "@effect/sql-d1/D1Client#D1Client"161 ]162 }163 },164 {165 "include": ["packages/project/test/**/*.ts"],166 "options": {167 "allowedUnstableApis": ["effect/Arbitrary", "effect/sql"]168 }
38 unmodified lines