Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent 6d721f1 · Browse files · 7 files+144 added−96 removed
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

7 files+144 added−96 removed

modified:apps/platform/test/front-page.test.ts+24 added-9 removed
40 unmodified lines
41import { RulesEvaluator } from "@repo/rules/rules-evaluator";42import { advanceTo, at } from "@repo/testkit/clock";43import { aProject, withAsk, withVouches } from "@repo/testkit/scenarios";44import type { Scope } from "effect";45import { Array, Context, Effect, FileSystem, Layer, Path } from "effect";45import { Array, Context, Effect, FileSystem, Layer, Order, Path } from "effect";46import { SqlClient } from "effect/sql/SqlClient";4748import { WorkerFetch } from "../src/adapters/fetch.ts";49import { MemoryRateLimits, WorkerCaps } from "../src/adapters/rate-limits.ts";
19 unmodified lines
69const alice = Handle.make("alice");7071const noon = "2026-10-07T12:00:00Z";7273/** 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 */79const migrated = Layer.effectDiscard(80 Effect.gen(function* () {81 const fs = yield* FileSystem.FileSystem;82 const path = yield* Path.Path;83 const sql = yield* SqlClient;8480 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 );8889 const files = Array.sort(90 (yield* fs.readDirectory(folder)).filter((file) => file.endsWith(".sql")),91 Order.String92 );9394 for (const file of files) {95 const text = yield* fs.readFileString(path.join(folder, file));9697 const code = text98 .split("\n")99 .filter((line) => !line.trimStart().startsWith("--"))100 .join("\n");10187 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 lines
modified:packages/project/src/projection-d1/front-page.ts+2 added-1 removed
modified:packages/project/src/projection-d1/projection.ts+6 added-5 removed
40 unmodified lines
41import type { Statement } from "effect/sql/Statement";4243import type { OutboxRow } from "../project-store/rows.ts";44import { Projection, ProjectedEvent, ProjectionFailed } from "../projection.ts";45import { handleKey } from "./tables.ts";4647const decodeProjected = Schema.decodeUnknownEffect(48 Schema.toCodecJson(ProjectedEvent)49);
21 unmodified lines
71 new Map(events.map(({ event, project }) => [project, event.seq]));7273/**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 */80const 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 );8889export const ProjectionD1: Layer.Layer<Projection, never, SqlClient> =90 Layer.effect(
42 unmodified lines
133 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 lines
modified:packages/project/src/projection-d1/tables.ts+10 added-1 removed
12 unmodified lines
13 *14 * A migration is never edited once it has run anywhere: W5 514 adds its15 * tables in `0004_projects_credits.sql` (`ProjectsCreditsDdl`).16 */17import type { Handle } from "@repo/protocol/ids";1819/**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 */24export const handleKey = (handle: Handle): string => handle.toLowerCase();2526export 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 lines
60 * 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 and
39 unmodified lines
modified:packages/project/test/projection-d1-credits.test.ts+45 added-47 removed
3 unmodified lines
4 * 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 */8import { NodeServices } from "@effect/platform-node";9import { SqliteClient } from "@effect/sql-sqlite-node";8import { describe, expect, it } from "@effect/vitest";9import type { AskListing } from "@repo/protocol/domain/ask";10import type { Credit } from "@repo/protocol/domain/credit";11import { ProjectEvent } from "@repo/protocol/domain/event";
5 unmodified lines
17 KindName,18 LandedSha,19 ProjectName,20} from "@repo/protocol/ids";23import { DateTime, Effect, FileSystem, Layer, Path } from "effect";21import { DateTime, Effect, Layer } from "effect";22import { SqlClient } from "effect/sql/SqlClient";2324import { FrontPage } from "../src/front-page.ts";25import { projectedRows } from "../src/outbox.ts";
1 unmodified line
27import { FrontPageD1 } from "../src/projection-d1/front-page.ts";28import { ProjectionD1 } from "../src/projection-d1/projection.ts";29import { ProjectsCreditsDdl } from "../src/projection-d1/tables.ts";30import { Projection } from "../src/projection.ts";31import {32 applied,33 frontPageMigration,34 migrated,35 migration,36 projectsMigration,37} from "./projection-d1.fixtures.ts";3834/** A migration of the platform's D1 database, as its file holds it. */35const migration = (file: string) =>36 Effect.gen(function* () {37 const fs = yield* FileSystem.FileSystem;38 const path = yield* Path.Path;3940 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);4647/** Runs a migration's statements in order, as `wrangler d1 migrations apply` does. */48const applied = (file: string) =>49 Effect.gen(function* () {50 const sql = yield* SqlClient;5152 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);5859const frontPageMigration = "0001_front_page.sql";6061const projectsMigration = "0004_projects_credits.sql";6263/** A fresh in-memory database each time, with the projection's migrations applied. */64const database = Layer.effectDiscard(65 Effect.andThen(applied(frontPageMigration), applied(projectsMigration))66).pipe(67 Layer.provideMerge(SqliteClient.layer({ filename: ":memory:" })),68 Layer.orDie69);7039const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(72 Layer.provideMerge(database)40 Layer.provideMerge(migrated([frontPageMigration, projectsMigration]))41);4243/** A database the front page's migration alone made, as W3 and W4 left it. */44const 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);4748const datekit = ProjectName.make("datekit");49
304 unmodified lines
354 }).pipe(Effect.provide(world))355 );356357 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 );382383 const front = yield* FrontPage;384385 expect({386 bram: yield* front.credits(bram),387 ines: yield* front.credits(ines),388 }).toStrictEqual({ bram: [], ines: [] });389 }).pipe(Effect.provide(world))390 );391392 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 lines
added:packages/project/test/projection-d1.fixtures.ts+48 added
modified:packages/project/test/projection-d1.test.ts+9 added-33 removed
2 unmodified lines
3 * 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 */7import { NodeServices } from "@effect/platform-node";8import { SqliteClient } from "@effect/sql-sqlite-node";7import { describe, expect, it } from "@effect/vitest";8import type { AskListing } from "@repo/protocol/domain/ask";9import { ProjectEvent } from "@repo/protocol/domain/event";10import type { FrontPageEntry } from "@repo/protocol/domain/front-page";
3 unmodified lines
14 KindName,15 LandedSha,16 ProjectName,17} from "@repo/protocol/ids";20import { DateTime, Effect, FileSystem, Layer, Path } from "effect";18import { DateTime, Effect, Layer } from "effect";19import { SqlClient } from "effect/sql/SqlClient";2021import { FrontPage } from "../src/front-page.ts";22import type { FrontPageFilter } from "../src/front-page.ts";
2 unmodified lines
25import { FrontPageD1 } from "../src/projection-d1/front-page.ts";26import { ProjectionD1 } from "../src/projection-d1/projection.ts";27import { FrontPageDdl } from "../src/projection-d1/tables.ts";28import { Projection, ProjectionFailed } from "../src/projection.ts";29import {30 frontPageMigration,31 migrated,32 migration,33 projectsMigration,34} from "./projection-d1.fixtures.ts";3532/** A migration the platform's D1 database applies, as its file holds it. */33const migration = (file: string) =>34 Effect.gen(function* () {35 const fs = yield* FileSystem.FileSystem;36 const path = yield* Path.Path;3738 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));4436/**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 */50const database = Layer.effectDiscard(51 Effect.gen(function* () {52 const sql = yield* SqlClient;41const database = migrated([frontPageMigration, projectsMigration]);4254 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);6643const world = Layer.mergeAll(ProjectionD1, FrontPageD1).pipe(44 Layer.provideMerge(database)45);46
336 unmodified lines
383 );384385 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 );390391 // A call without a project (`status`, `today`) reaches each project the
25 unmodified lines