Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .dependency-cruiser.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ const ENTRY = "(index|server|ui|client)(/index)?\\.tsx?$";

const SEE = "docs/adr/0003-package-shaped-layers.md";

/** Paths outside `src/modules` that a module owns, written by `npm run generate:modules` (ADR 0017 §4). */
const OWNED = require("./src/config/modules.owns.generated.json").owned;
/** The bell imports `notifications` until plan 006 M10 composes it from the modules' feeds; M10 deletes this list. */
const PENDING_M10 = [
"src/app/(main)/dashboard/layout.tsx",
"src/app/(main)/dashboard/_components/notification-actions.ts",
"src/app/(main)/dashboard/_components/notification-view.ts",
"src/app/(main)/dashboard/_components/notification-view.test.ts",
];
const exactPath = (path) => `^${path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(/|$)`;

const upwardRule = (name, from, higher) => ({
name,
severity: "error",
Expand All @@ -31,6 +42,22 @@ const upwardRule = (name, from, higher) => ({
/** @type {import('dependency-cruiser').IConfiguration} */
module.exports = {
forbidden: [
{
name: "modules-only-through-composition",
severity: "error",
comment:
"outside src/modules, only the generated composition, the presets and a module's owned paths import a module; add the path to the module's owns and run npm run generate:modules (docs/adr/0017-a-module-is-a-folder.md §4)",
from: {
path: "^(src|workers)/",
pathNot: [
"^src/modules/",
"^src/config/[^/]+\\.generated\\.ts$",
"^src/verticals/",
...[...OWNED, ...PENDING_M10].map(exactPath),
],
},
to: { path: "^src/modules/" },
},
upwardRule("no-upward-import-from-platform", PLATFORM, LAYERS),
...LAYERS.slice(0, -1).map((layer, i) =>
upwardRule(`no-upward-import-from-${layer}`, `^src/${layer}/`, LAYERS.slice(i + 1)),
Expand Down
2 changes: 1 addition & 1 deletion .gitattributes
Original file line number Diff line number Diff line change
@@ -1 +1 @@
src/config/*.generated.ts linguist-generated=true
src/config/*.generated.* linguist-generated=true
14 changes: 9 additions & 5 deletions scripts/generate-modules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { compositionProblems, type ModuleServer } from "@/core/module";
import {
type Generated,
generate,
MODULE_OWNS_PATH,
MODULE_SERVERS_PATH,
MODULE_UIS_PATH,
MODULES_PATH,
Expand Down Expand Up @@ -74,11 +75,14 @@ describe("the generated module list (ADR 0017 §5)", () => {
expect(generated.problems).toEqual([]);
});

it.each([MODULES_PATH, MODULE_SERVERS_PATH, MODULE_UIS_PATH])("%s matches the module folders", (path) => {
expect(readFileSync(join(ROOT, path), "utf8"), `${path} is stale: run npm run generate:modules`).toBe(
generated.files?.[path],
);
});
it.each([MODULES_PATH, MODULE_SERVERS_PATH, MODULE_UIS_PATH, MODULE_OWNS_PATH])(
"%s matches the module folders",
(path) => {
expect(readFileSync(join(ROOT, path), "utf8"), `${path} is stale: run npm run generate:modules`).toBe(
generated.files?.[path],
);
},
);

it("requires what the import graph shows (ADR 0017's first test, against census C0)", () => {
const installed = Object.keys(generated.graph);
Expand Down
9 changes: 9 additions & 0 deletions scripts/generate-modules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export const ROOT = fileURLToPath(new URL("..", import.meta.url));
export const MODULES_PATH = "src/config/modules.generated.ts";
export const MODULE_SERVERS_PATH = "src/config/modules.server.generated.ts";
export const MODULE_UIS_PATH = "src/config/modules.client.generated.ts";
/** The paths modules own outside their folders, which `.dependency-cruiser.cjs` allows to import them (ADR 0017 §4). */
export const MODULE_OWNS_PATH = "src/config/modules.owns.generated.json";

const HEADER =
"// Written by `npm run generate:modules` from the folders of src/modules; do not edit. A test fails when it is stale (ADR 0017 §5).";
Expand Down Expand Up @@ -188,6 +190,12 @@ function renderClient(folders: readonly string[]): string {
].join("\n");
}

/** The owned paths before Biome formats them: sorted, so the file changes only when an `owns` list does. */
function renderOwns(modules: readonly InstalledModule[]): string {
const owned = [...new Set(modules.flatMap(({ manifest }) => manifest.owns))].sort(byCode);
return `${JSON.stringify({ $comment: "Written by npm run generate:modules from the modules' owns; do not edit.", owned })}\n`;
}

/** The module list before Biome formats it. */
function render(modules: readonly InstalledModule[], graph: Readonly<Record<string, readonly string[]>>): string {
const names = modules.map(({ folder }) => [folder, manifestExportOf(folder)] as const);
Expand Down Expand Up @@ -248,6 +256,7 @@ export async function generate(root: string = ROOT): Promise<Generated> {
[MODULES_PATH]: formatted(root, MODULES_PATH, render(modules, graph)),
[MODULE_SERVERS_PATH]: formatted(root, MODULE_SERVERS_PATH, renderServers(modules)),
[MODULE_UIS_PATH]: formatted(root, MODULE_UIS_PATH, renderClient(uiFolders(root, modules))),
[MODULE_OWNS_PATH]: formatted(root, MODULE_OWNS_PATH, renderOwns(modules)),
},
}
: {}),
Expand Down
48 changes: 48 additions & 0 deletions src/config/modules.owns.generated.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 6 additions & 1 deletion src/modules/parties/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,10 @@ export const partiesModule = defineModule({
parties: { schema: partySchema, required: true, ext: { entity: "party", optional: true } },
},
references: [],
owns: ["src/config/approvals.parties.test.ts", "src/config/mcp.server.parties.test.ts"],
owns: [
"e2e/smoke/parties.spec.ts",
"src/app/(main)/dashboard/parties",
"src/config/approvals.parties.test.ts",
"src/config/mcp.server.parties.test.ts",
],
});
17 changes: 12 additions & 5 deletions workers/demo-store/src/demo-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,20 @@ import { createMockAdapter, createSessionStore, type DemoSession } from "@/core/
import { type CallResult, err } from "@/core/result";

import { boundSession } from "./bounds";
import { seedFingerprint } from "./seed-shape";
import { DurableObject } from "cloudflare:workers";

/** Bump by hand when the snapshot's own format changes (its approvals, replays or policy); the seeds need no bump. */
export const STORE_FORMAT = 7;

/**
* Bump when the shape of the persisted session changes: a mismatch resets the object to the seed. A test pins it to
* a fingerprint of the seeds' structure, so a seed change without a bump fails there.
* The version of a saved session (ADR 0017 §8): the snapshot format and the fingerprint of the seeds it was written
* against, compared as text. A mismatch resets the session to the seed. The `:` keeps it text in the INTEGER column,
* so a session saved under the old numeric version resets once.
*/
export const SCHEMA_VERSION = 6;
export const STORE_VERSION = `${STORE_FORMAT}:${seedFingerprint(
Object.fromEntries(Object.entries(DEMO).map(([vertical, { seed }]) => [vertical, seed])),
)}`;
/** A session is deleted this long after its last write; the demo cookie is renewed on each write for as long. */
const IDLE_MS = 2 * 60 * 60 * 1000;

Expand Down Expand Up @@ -159,7 +166,7 @@ export class DemoStore extends DurableObject implements DemoStoreRpc {
const row = this.readRow();
if (row === undefined) return store;
const saved =
row.schema_version === SCHEMA_VERSION && typeof row.snapshot === "string" ? snapshotOf(row.snapshot) : undefined;
row.schema_version === STORE_VERSION && typeof row.snapshot === "string" ? snapshotOf(row.snapshot) : undefined;
if (saved === undefined) {
this.ctx.storage.sql.exec("DELETE FROM session");
return store;
Expand All @@ -186,7 +193,7 @@ export class DemoStore extends DurableObject implements DemoStoreRpc {
});
this.ctx.storage.sql.exec(
"INSERT OR REPLACE INTO session (id, schema_version, owner, snapshot) VALUES (1, ?, ?, ?)",
SCHEMA_VERSION,
STORE_VERSION,
owner,
snapshot,
);
Expand Down
30 changes: 23 additions & 7 deletions workers/demo-store/src/seed-shape.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,31 @@ const shapeOf = (value: unknown): string => {
return value === null ? "null" : typeof value;
};

/** Every row id under a value, with where it sits: a row added to or removed from a collection moves the fingerprint. */
const idsOf = (value: unknown, path: string): string[] => {
if (Array.isArray(value)) return value.flatMap((item) => idsOf(item, `${path}[]`));
if (value === null || typeof value !== "object") return [];
const row = value as Readonly<Record<string, unknown>>;
const own = typeof row.id === "string" ? [`${path}#${row.id}`] : [];
return [
...own,
...Object.keys(row)
.sort()
.flatMap((key) => idsOf(row[key], `${path}.${key}`)),
];
};

/**
* A stable fingerprint (FNV-1a) of the seeds' structure. A saved session was written against one structure, so when
* this changes `SCHEMA_VERSION` must be bumped; a test pins both together and fails until they move as one.
* A stable fingerprint (FNV-1a) of the seeds: their structure and their row ids, not their other values (ADR 0017 §8).
* A saved session was written against one set of seeds, so the store's version carries this and resets a session
* saved against another, whether a module, a collection, a field or a row came or went.
*/
export function seedShapeHash(seeds: Readonly<Record<string, unknown>>): string {
const text = Object.keys(seeds)
.sort()
.map((name) => `${name}=${shapeOf(seeds[name])}`)
.join(";");
export function seedFingerprint(seeds: Readonly<Record<string, unknown>>): string {
const names = Object.keys(seeds).sort();
const text = [
...names.map((name) => `${name}=${shapeOf(seeds[name])}`),
...names.flatMap((name) => idsOf(seeds[name], name)).sort(),
].join(";");
let hash = 0x811c9dc5;
for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193) >>> 0;
return hash.toString(16);
Expand Down
6 changes: 3 additions & 3 deletions workers/demo-store/test/demo-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import { inputFor } from "@/config/adapter-contract.testkit";

import { MAX_REPLAYS } from "../src/bounds";
import { SCHEMA_VERSION } from "../src/demo-store";
import { STORE_VERSION } from "../src/demo-store";
import { clientFor, contextFor, stubFor } from "./support";
import { abortAllDurableObjects, runDurableObjectAlarm, runInDurableObject } from "cloudflare:test";

Expand Down Expand Up @@ -226,7 +226,7 @@ describe("DemoStore", () => {
);
state.storage.sql.exec(
"INSERT INTO session VALUES (1, ?, ?, 'not json')",
SCHEMA_VERSION,
STORE_VERSION,
`hospitality:${sessionId}`,
);
});
Expand Down Expand Up @@ -304,7 +304,7 @@ describe("DemoStore", () => {
const client = clientFor(sessionId);
await writeSequentially(client, MAX_REPLAYS + 1);

expect(await savedRow(sessionId)).toEqual({ schemaVersion: SCHEMA_VERSION, replays: MAX_REPLAYS });
expect(await savedRow(sessionId)).toEqual({ schemaVersion: STORE_VERSION, replays: MAX_REPLAYS });
});

it("refuses a caller from another catalogue with the way to fix it", async () => {
Expand Down
23 changes: 0 additions & 23 deletions workers/demo-store/test/schema-version.test.ts

This file was deleted.

38 changes: 38 additions & 0 deletions workers/demo-store/test/store-version.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";

import { DEMO } from "@/config/demo-kernel";

import { STORE_FORMAT, STORE_VERSION } from "../src/demo-store";
import { seedFingerprint } from "../src/seed-shape";

const seeds = Object.fromEntries(Object.entries(DEMO).map(([vertical, { seed }]) => [vertical, seed]));

/** ADR 0017 §8: a saved session resets when the snapshot format or the seeds it was written against change. */
describe("the demo store's version", () => {
it("is the snapshot format and the seeds' fingerprint, as text that never reads as a number", () => {
expect(STORE_VERSION).toBe(`${STORE_FORMAT}:${seedFingerprint(seeds)}`);
expect(Number.isNaN(Number(STORE_VERSION))).toBe(true);
});

it("moves when a collection gains a row", () => {
expect(seedFingerprint({ bookings: [{ id: "a" }] })).not.toBe(
seedFingerprint({ bookings: [{ id: "a" }, { id: "b" }] }),
);
});

it("moves when a collection gains a field", () => {
expect(seedFingerprint({ bookings: [{ id: "a" }] })).not.toBe(
seedFingerprint({ bookings: [{ id: "a", note: "x" }] }),
);
});

it("moves when a module's collection goes", () => {
expect(seedFingerprint({ hospitality: { bookings: [{ id: "a" }], stock: [{ id: "s" }] } })).not.toBe(
seedFingerprint({ hospitality: { bookings: [{ id: "a" }] } }),
);
});

it("ignores values other than ids, and the order of keys", () => {
expect(seedFingerprint({ bookings: [{ id: "a", n: 1 }] })).toBe(seedFingerprint({ bookings: [{ n: 2, id: "a" }] }));
});
});
Loading