Test the projection's cross-project credit guard, and keep the handle key and the D1 migration helper in one place each
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Review of W5 issue 514 on its own branch. - A landing whose LandingView names another project than the outbox that carried it credits nothing (ask ids are unique only within a project, as `areaOf` checks). That branch of `credited` had no test: a new case in projection-d1-credits.test.ts fails by assertion with the guard removed and passes with it. - `credits.handle_key` was computed twice, `handle.toLowerCase()` in the projection's writes and again in FrontPageD1's credits query, so the writer and the reader could drift apart. It is now `handleKey` in projection-d1/tables.ts, beside the column it defines, and both use it (the credited person's field is `person`, so nothing shadows it). - Three copies of "read a platform D1 migration file and run it statement by statement", two of them with the same hand-kept file list, are now one test fixture, packages/project/test/projection-d1.fixtures.ts (`migration`, `applied`, `migrated(files)`), used by projection-d1.test.ts and projection-d1-credits.test.ts. apps/platform/test/front-page.test.ts cannot import a package's test file, so it applies every `.sql` in apps/platform/migrations in file-name order, as `wrangler d1 migrations apply` does: a later migration needs no edit there. It drops comment lines before splitting on `;`, because 0002_accounts.sql has a `;` in a comment. - Kept as the builder left them, with reasons in the issue's Comments: the backfill INSERT at the end of 0004 (without it a live D1 loses its project list until each project's next event), the `handle_key` column and the missing extra index. - verify green; platform entry 1,599,456 of 1,665,000.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+144 added−96 removed
- tests:+126 added−89 removed
- other:+18 added−7 removed
Provenance
- Commit
7e05025- Tree
e27c318- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
6d721f1
7 files changed+144 added−96 removed
modified:apps/platform/test/front-page.test.ts+24 added-9 removed
40 unmodified lines41 import { RulesEvaluator } from "@repo/rules/rules-evaluator";42 import { advanceTo, at } from "@repo/testkit/clock";43 import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";44 import type { Scope } from "effect";45-import { Array, Context, Effect, FileSystem, Layer, Path } from "effect";45+import { Array, Context, Effect, FileSystem, Layer, Order, Path } from "effect";46 import { SqlClient } from "effect/sql/SqlClient";47 48 import { WorkerFetch } from "../src/adapters/fetch.ts";49 import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";19 unmodified lines69 const alice = Handle.make("alice");70 71 const noon = "2026-10-07T12:00:00Z";72 73-/** The front page's migrations, read from the platform's own folder in order and run statement by statement. */73+/**74+ * The platform's D1 database: every migration in its own folder, in75+ * file-name order as `wrangler d1 migrations apply` runs them, statement by76+ * statement. Comment lines go before the split: a comment may hold a `;`77+ * (`0002_accounts.sql`'s does).78+ */79 const migrated = Layer.effectDiscard(80 Effect.gen(function* () {81 const fs = yield* FileSystem.FileSystem;82 const path = yield* Path.Path;83 const sql = yield* SqlClient;84 80- for (const file of ["0001_front_page.sql", "0004_projects_credits.sql"]) {81- const text = yield* fs.readFileString(82- yield* path.fromFileUrl(83- new URL(`../migrations/${file}`, import.meta.url)84- )85+ const folder = yield* path.fromFileUrl(86+ new URL("../migrations", import.meta.url)87+ );85- );88 89+ const files = Array.sort(90+ (yield* fs.readDirectory(folder)).filter((file) => file.endsWith(".sql")),91+ Order.String92+ );93+94+ for (const file of files) {95+ const text = yield* fs.readFileString(path.join(folder, file));96+97+ const code = text98+ .split("\n")99+ .filter((line) => !line.trimStart().startsWith("--"))100+ .join("\n");101+87- for (const statement of text.split(";")) {102+ for (const statement of code.split(";")) {103 if (statement.trim().length > 0) {104 yield* sql.unsafe(statement);105 }106 }197 unmodified linesmodified:packages/project/src/projection-d1/front-page.ts+2 added-1 removed
23 unmodified lines242526272829303132104 unmodified linesExpand all1371381391401401411421431441454 unmodified lines23 unmodified linesimport { SqlClient } from "effect/sql/SqlClient";
import { FrontPage } from "../front-page.ts";import type { FrontPageFilter } from "../front-page.ts";import { handleKey } from "./tables.ts";
const AskIds = Schema.fromJsonString(Schema.Array(AskId));
/** One row of the front page query. */104 unmodified linesExpand all // By the key the projection keeps: the handle as `sameHandle` compares it. const credits = (handle: Handle) => sql`SELECT project, area, role, count FROM credits WHERE handle_key = ${handle.toLowerCase()} WHERE handle_key = ${handleKey(handle)} ORDER BY project, area, role`.pipe( Effect.flatMap(decodeCredits), Effect.orDie );4 unmodified linesmodified:packages/project/src/projection-d1/projection.ts+6 added-5 removed
40 unmodified lines41 import type { Statement } from "effect/sql/Statement";42 43 import type { OutboxRow } from "../project-store/rows.ts";44 import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";45+import { handleKey } from "./tables.ts";46 47 const decodeProjected = Schema.decodeUnknownEffect(48 Schema.toCodecJson(ProjectedEvent)49 );21 unmodified lines71 new Map(events.map(({ event, project }) => [project, event.seq]));72 73 /**74 * Each person a landing credits, once per role, by the key `sameHandle`74- * compares handles by (the handle lowercased): the rule of75+ * compares handles by (`handleKey`): the rule of76 * `creditsByArea` (`attention/credits.ts`, W2 220) for one landing, whose77 * area the projection reads from D1. Only `credits` counts: `assisted` (the78 * `Assisted-by` trailers) names agents, never people.79 */80 const creditedOn = (landing: Pick<LandingView, "credits">) =>81 Array.dedupeWith(82 landing.credits.map(({ handle, role }) => ({82- handleKey: handle.toLowerCase(),83+ person: handleKey(handle),84 role,85 })),85- (one, other) => one.handleKey === other.handleKey && one.role === other.role86+ (one, other) => one.person === other.person && one.role === other.role87 );88 89 export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =90 Layer.effect(42 unmodified lines133 const credited = ({ ask, ...landing }: LandingView) =>134 ask === undefined || landing.project !== project135 ? []136 : creditedOn(landing).map(136- ({ handleKey, role }) =>137+ ({ person, role }) =>138 sql`INSERT INTO credits (handle_key, project, area, role, count)138- SELECT ${handleKey}, ${project}, page.territory, ${role}, 1139+ SELECT ${person}, ${project}, page.territory, ${role}, 1140 FROM front_page AS page141 WHERE page.project = ${project} AND page.ask = ${ask} AND ${next}142 ON CONFLICT (handle_key, project, area, role)143 DO UPDATE SET count = credits.count + 1`120 unmodified linesmodified:packages/project/src/projection-d1/tables.ts+10 added-1 removed
12 unmodified lines13 *14 * A migration is never edited once it has run anywhere: W5 514 adds its15 * tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`).16 */17+import type { Handle } from "@repo/protocol/ids";18+19+/**20+ * The key `credits.handle_key` holds a person by: the handle lowercased,21+ * the rule protocol's `sameHandle` compares by. The projection writes it and22+ * the credits query reads by it, so both take it from here.23+ */24+export const handleKey = (handle: Handle): string => handle.toLowerCase();25+26 export const FrontPageDdl = `-- The front page: every open ask of every project, projected from each27 -- project's outbox by packages/project/src/projection-d1 (its tables.ts28 -- holds this text). The projection is the only writer.29 30 unmodified lines60 * posture (`open` until a `PostureChanged` ledger entry), its open asks61 * (counted from `front_page` whenever an ask opens or closes), and when62 * it last landed (null before its first landing).63 * - `credits`: how many landings credit a person (by `handle_key`, the55- * handle lowercased) in one role, in one area of one project.64+ * handle lowercased: `handleKey`) in one role, in one area of one project.65 *66 * Its last statement lists the projects `cursor` already knows of, with67 * their open asks, so a database the front page's migration made keeps its68 * project list (W4 499's stopgap read it from `cursor`). Their credits and39 unmodified linesmodified:packages/project/test/projection-d1-credits.test.ts+45 added-47 removed
3 unmodified lines4 * go in through `ProjectionD1`, and `FrontPageD1` reads every project, and5 * one person's credits by project, area and role, back out in one query6 * each.7 */8-import { NodeServices } from "@effect/platform-node";9-import { SqliteClient } from "@effect/sql-sqlite-node";8 import { describe, expect, it } from "@effect/vitest";9 import type { AskListing } from "@repo/protocol/domain/ask";10 import type { Credit } from "@repo/protocol/domain/credit";11 import { ProjectEvent } from "@repo/protocol/domain/event";5 unmodified lines17 KindName,18 LandedSha,19 ProjectName,20 } from "@repo/protocol/ids";23-import { DateTime, Effect, FileSystem, Layer, Path } from "effect";21+import { DateTime, Effect, Layer } from "effect";22 import { SqlClient } from "effect/sql/SqlClient";23 24 import { FrontPage } from "../src/front-page.ts";25 import { projectedRows } from "../src/outbox.ts";1 unmodified line27 import { FrontPageD1 } from "../src/projection-d1/front-page.ts";28 import { ProjectionD1 } from "../src/projection-d1/projection.ts";29 import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";30 import { Projection } from "../src/projection.ts";31+import {32+ applied,33+ frontPageMigration,34+ migrated,35+ migration,36+ projectsMigration,37+} from "./projection-d1.fixtures.ts";38 34-/** A migration of the platform's D1 database, as its file holds it. */35-const migration = (file: string) =>36- Effect.gen(function* () {37- const fs = yield* FileSystem.FileSystem;38- const path = yield* Path.Path;39-40- return yield* fs.readFileString(41- yield* path.fromFileUrl(42- new URL(`../../../apps/platform/migrations/${file}`, import.meta.url)43- )44- );45- }).pipe(Effect.provide(NodeServices.layer), Effect.orDie);46-47-/** Runs a migration's statements in order, as `wrangler d1 migrations apply` does. */48-const applied = (file: string) =>49- Effect.gen(function* () {50- const sql = yield* SqlClient;51-52- for (const statement of (yield* migration(file)).split(";")) {53- if (statement.trim().length > 0) {54- yield* sql.unsafe(statement);55- }56- }57- }).pipe(Effect.orDie);58-59-const frontPageMigration = "0001_front_page.sql";60-61-const projectsMigration = "0004_projects_credits.sql";62-63-/** A fresh in-memory database each time, with the projection's migrations applied. */64-const database = Layer.effectDiscard(65- Effect.andThen(applied(frontPageMigration), applied(projectsMigration))66-).pipe(67- Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),68- Layer.orDie69-);70-39 const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(72- Layer.provideMerge(database)40+ Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))41 );42 43 /** A database the front page's migration alone made, as W3 and W4 left it. */44 const beforeProjects = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(77- Layer.provideMerge(78- Layer.effectDiscard(applied(frontPageMigration)).pipe(79- Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),80- Layer.orDie81- )82- )45+ Layer.provideMerge(migrated([frontPageMigration]))46 );47 48 const datekit = ProjectName.make("datekit");49 304 unmodified lines354 }).pipe(Effect.provide(world))355 );356 357 it.effect(358+ "credits nothing for a landing that names another project than the one whose outbox carried it",359+ () =>360+ Effect.gen(function* () {361+ // Ask ids are unique only within a project: datekit's `parse-iso`362+ // is no area of burrow's.363+ yield* apply(364+ rows(datekit, 1, [365+ opened(listing(parseIso, "src"), 1),366+ (seq) =>367+ ProjectEvent.cases.Landed.make({368+ at: at(30),369+ landing: {370+ ask: parseIso,371+ assisted: [],372+ author: bram,373+ credits: parseIsoCredits,374+ landedAt: at(30),375+ project: burrow,376+ sha: landing,377+ },378+ seq,379+ }),380+ ])381+ );382+383+ const front = yield* FrontPage;384+385+ expect({386+ bram: yield* front.credits(bram),387+ ines: yield* front.credits(ines),388+ }).toStrictEqual({ bram: [], ines: [] });389+ }).pipe(Effect.provide(world))390+ );391+392+ it.effect(393 "moves a project's posture when its ledger records a posture change, on its list row and its asks",394 () =>395 Effect.gen(function* () {396 yield* apply(40 unmodified linesadded:packages/project/test/projection-d1.fixtures.ts+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748/** * The platform's D1 database as the projection's tests make it: migration * files read from `apps/platform/migrations` and run statement by statement * on a fresh sqlite-node database in memory, as `wrangler d1 migrations * apply` runs them in order. */import { NodeServices } from "@effect/platform-node";import { SqliteClient } from "@effect/sql-sqlite-node";import { Effect, FileSystem, Layer, Path } from "effect";import { SqlClient } from "effect/sql/SqlClient";
/** The front page's migration (W3 309; `FrontPageDdl`). */export const frontPageMigration = "0001_front_page.sql";
/** The project list's and the credits' migration (W5 514; `ProjectsCreditsDdl`). */export const projectsMigration = "0004_projects_credits.sql";
/** A migration of the platform's D1 database, as its file holds it. */export const migration = (file: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path;
return yield* fs.readFileString( yield* path.fromFileUrl( new URL(`../../../apps/platform/migrations/${file}`, import.meta.url) ) ); }).pipe(Effect.provide(NodeServices.layer), Effect.orDie);
/** Runs a migration's statements in order. */export const applied = (file: string) => Effect.gen(function* () { const sql = yield* SqlClient;
for (const statement of (yield* migration(file)).split(";")) { if (statement.trim().length > 0) { yield* sql.unsafe(statement); } } }).pipe(Effect.orDie);
/** A fresh in-memory database each time, with `files` applied in order. */export const migrated = (files: readonly string[]) => Layer.effectDiscard(Effect.forEach(files, applied, { discard: true })).pipe( Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })), Layer.orDie );modified:packages/project/test/projection-d1.test.ts+9 added-33 removed
2 unmodified lines3 * migrations for it applied from their files: projects' outbox rows go in4 * through `ProjectionD1`, and `FrontPageD1` reads every open ask back out,5 * as the anonymous viewer may take it.6 */7-import { NodeServices } from "@effect/platform-node";8-import { SqliteClient } from "@effect/sql-sqlite-node";7 import { describe, expect, it } from "@effect/vitest";8 import type { AskListing } from "@repo/protocol/domain/ask";9 import { ProjectEvent } from "@repo/protocol/domain/event";10 import type { FrontPageEntry } from "@repo/protocol/domain/front-page";3 unmodified lines14 KindName,15 LandedSha,16 ProjectName,17 } from "@repo/protocol/ids";20-import { DateTime, Effect, FileSystem, Layer, Path } from "effect";18+import { DateTime, Effect, Layer } from "effect";19 import { SqlClient } from "effect/sql/SqlClient";20 21 import { FrontPage } from "../src/front-page.ts";22 import type { FrontPageFilter } from "../src/front-page.ts";2 unmodified lines25 import { FrontPageD1 } from "../src/projection-d1/front-page.ts";26 import { ProjectionD1 } from "../src/projection-d1/projection.ts";27 import { FrontPageDdl } from "../src/projection-d1/tables.ts";28 import { Projection, ProjectionFailed } from "../src/projection.ts";29+import {30+ frontPageMigration,31+ migrated,32+ migration,33+ projectsMigration,34+} from "./projection-d1.fixtures.ts";35 32-/** A migration the platform's D1 database applies, as its file holds it. */33-const migration = (file: string) =>34- Effect.gen(function* () {35- const fs = yield* FileSystem.FileSystem;36- const path = yield* Path.Path;37-38- return yield* fs.readFileString(39- yield* path.fromFileUrl(40- new URL(`../../../apps/platform/migrations/${file}`, import.meta.url)41- )42- );43- }).pipe(Effect.provide(NodeServices.layer));44-36 /**37 * A fresh in-memory database each time, with the projection's migration38 * files applied in order: the front page's, then the project list's and39 * the credits'.40 */50-const database = Layer.effectDiscard(51- Effect.gen(function* () {52- const sql = yield* SqlClient;41+const database = migrated([frontPageMigration, projectsMigration]);42 54- for (const file of ["0001_front_page.sql", "0004_projects_credits.sql"]) {55- for (const statement of (yield* migration(file)).split(";")) {56- if (statement.trim().length > 0) {57- yield* sql.unsafe(statement);58- }59- }60- }61- })62-).pipe(63- Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),64- Layer.orDie65-);66-43 const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(44 Layer.provideMerge(database)45 );46 336 unmodified lines383 );384 385 it.effect("reads the migration the platform's D1 applies", () =>386 Effect.gen(function* () {411- expect(yield* migration("0001_front_page.sql")).toBe(FrontPageDdl);387+ expect(yield* migration(frontPageMigration)).toBe(FrontPageDdl);388 })389 );390 391 // A call without a project (`status`, `today`) reaches each project the25 unmodified lines