From 64b47cfe615fc77185baba857b94e39731532bfb Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:36:05 -0500 Subject: [PATCH 01/17] docs(adr-0066): state that input validation precedes the permission point, and its cost --- .../ADR-0066-business-rules-operations-and-lifecycles.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md index b99ce61ca..170103bd3 100644 --- a/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md +++ b/spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md @@ -286,7 +286,14 @@ service generator will be told so by `verify`, as an advisory, once that check l routes enforce nothing. This is what the shells are held to: 1. Load the row: 404 when it is absent. -2. Call the permission point: 403 `forbidden` when the policy refuses. +2. Validate the operation's `@inputRef` input, when it has one (400 `validation`), then call the + permission point: 403 `forbidden` when the policy refuses. The input is validated first because + the policy is handed it, so it can decide on what was asked as well as on the row. The cost is + stated, not hidden: a caller the policy would refuse can get a 400 with the validation detail + before it would get the 403. That detail describes the declared input's shape, which the + contract types already publish, as step 1's 404 already tells such a caller whether the row + exists. An app that must answer neither to an unauthorised caller refuses it before the service + is called, in its actor resolver or transport. 3. Check that the row's state is in the `@from` of a transition the operation may make: 409 `invalid_transition`. 4. Run the hand-written body, when the operation has one. It returns one of its declared From 972f9d3786f389bf024621361b1f34b909851da0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:47:36 -0500 Subject: [PATCH 02/17] feat(runtime-ts,codegen-ts): sync SQLite rollback in the service, and interactiveTransactions: false for D1 The generated service committed at its first await on a sync SQLite driver (bun:sqlite, better-sqlite3), so a refusal answered 409 over a row that stayed. The runtime now drives those drivers' transaction with BEGIN IMMEDIATE/COMMIT/ROLLBACK, serialized per handle, and the sqlite Db type accepts a sync driver again. serviceFile({ interactiveTransactions: false }) generates a service with no transaction, hooks or event hook for D1, and refuses a declared command with ERR_STORE_NO_INTERACTIVE_TX. ADR-0067 section 4 says so. --- CHANGELOG.md | 19 ++ docs/features/business-rules.md | 20 +- .../packages/codegen-ts/src/dialect-module.ts | 8 +- .../codegen-ts/src/generators/service-file.ts | 16 +- .../codegen-ts/src/reference/service.ts | 11 +- .../packages/codegen-ts/src/service-walk.ts | 5 + .../codegen-ts/src/templates/service-file.ts | 201 ++++++++++++------ .../codegen-ts/test/service-file.test.ts | 36 +++- .../test/service-compile.test.ts | 24 ++- .../test/service-sqlite-drivers.test.ts | 187 ++++++++++++++++ .../packages/runtime-ts/src/service/index.ts | 102 ++++++++- .../test/service-sync-sqlite.test.ts | 114 ++++++++++ .../ADR-0067-layering-and-the-service-seam.md | 23 +- 13 files changed, 679 insertions(+), 87 deletions(-) create mode 100644 server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts create mode 100644 server/typescript/packages/runtime-ts/test/service-sync-sqlite.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e72f2dbb..a3f9fec6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,25 @@ here.** ## [Unreleased] +- **runtime-ts: the generated service keeps its rollback guarantee on a sync SQLite driver.** On + bun:sqlite and better-sqlite3, Drizzle's `transaction()` commits when its callback returns, so a + service write that awaited inside it committed at its first `await`: a hook's or a body's refusal + answered 409 over a row that stayed. The service now drives those drivers' transaction itself + (`BEGIN IMMEDIATE`, `COMMIT`, `ROLLBACK`, one at a time per handle, a savepoint inside a caller's + transaction), and a read outside a transaction waits for the one in flight. The generated `Db` + type on SQLite accepts a sync driver again, as the flat queries module does. New + `withWriteTransaction(db, fn)` runs several operations atomically on any driver; on a sync + driver, pass its `tx` to each one inside it. +- **codegen-ts: `serviceFile({ interactiveTransactions: false })` for a store that holds no + transaction across application code (Cloudflare D1; ADR-0067 §4).** The service opens no + transaction: each derived write is its one statement and a transition is its guarded update. + It has no hooks and no event hook, and a package that declares a command fails generation with + `ERR_STORE_NO_INTERACTIVE_TX`, naming the package, the command and the option. Queries are + generated. Run end to end on Miniflare's local D1. +- **ADR-0066 §6 states that input validation precedes the permission point.** The policy is handed + the validated input, so an operation's `@inputRef` input is checked first; a caller the policy + would refuse can see a 400 with validation detail before the 403. An app that must answer + neither refuses that caller in its actor resolver or transport. - **codegen-ts: the service layer, part 2 — the rules run (ADR-0066 §6, ADR-0067 §4 and §7).** The `service` generator now writes a command per transition that derives one (`POST /{id}/`) and a shell per declared command and query, at its binding or diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 1a2f39445..d9a058156 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -363,9 +363,23 @@ savepoint inside it. A refusal rolls the transaction back. A query opens no writ An operation answers an `OpResult`: the value, or a failure carrying the code and the HTTP status the [API contract](api-contract.md) gives it, so every transport maps it the same way. -On SQLite the service needs an async Drizzle driver such as libsql: `ServiceDeps.db` is typed -`BaseSQLiteDatabase<"async", …>`, so a sync driver (better-sqlite3, bun:sqlite) fails to type-check, -because a write awaits inside its transaction callback. The flat generators still accept both. +On SQLite the service takes a sync or an async Drizzle driver, as the flat generators do. An async +one (libsql) runs Drizzle's own transaction. A sync one (bun:sqlite, better-sqlite3) cannot: its +`transaction()` commits when its callback returns, at the first `await`. So the runtime drives the +transaction with statements (`BEGIN IMMEDIATE`, `COMMIT`, `ROLLBACK`) and runs one at a time on each +database handle, since SQLite has one writer; a read waits for the transaction in flight. A job that +runs several operations atomically on any driver opens the transaction with +`withWriteTransaction(db, async (tx) => ...)` from `@metaobjectsdev/runtime-ts/service` and passes +`tx` as each operation's `opts.tx`. On a sync driver every operation inside must be passed that +`tx`: one that is not waits for the transaction it is inside, and never runs. + +Cloudflare D1 holds no transaction across application code: it refuses the `BEGIN` the service +opens. Generate its service with `serviceFile({ interactiveTransactions: false })` (ADR-0067 §4). +That service opens no transaction. Each derived write is its one statement after the load and the +checks, and a transition is its guarded update, which needs no transaction to hold. There are no +`Hooks` and no `Events`, since a hook's refusal could not undo the write it followed. A +package that declares a command fails generation with `ERR_STORE_NO_INTERACTIVE_TX`, naming the +package, the command and the option; queries are generated as usual. `serviceRoutesFile()` (stable name `service-routes`, layer `api`, Fastify) writes the thin transport (layer 5) beside it, `/transport/fastify.ts`: one plugin per package, diff --git a/server/typescript/packages/codegen-ts/src/dialect-module.ts b/server/typescript/packages/codegen-ts/src/dialect-module.ts index e7e83a3d9..50b4dee37 100644 --- a/server/typescript/packages/codegen-ts/src/dialect-module.ts +++ b/server/typescript/packages/codegen-ts/src/dialect-module.ts @@ -35,10 +35,10 @@ export function dialectModule(dialect: Dialect): DialectModule { * allows, so any driver's database handle assigns — a schema-carrying `drizzle(client, * { schema })` as well as a schema-less one. * - * SQLite accepts a sync and an async driver by default. `asyncOnly` narrows it to async drivers - * (libsql), for a tier that awaits inside a transaction callback, which a sync driver rejects. + * SQLite accepts a sync and an async driver: the service layer drives a sync driver's transaction + * itself (`@metaobjectsdev/runtime-ts/service`), so no tier needs to narrow it. */ -export function dbTypeBlock(dialect: Dialect, opts?: { asyncOnly?: boolean }): { import: string; alias: string } { +export function dbTypeBlock(dialect: Dialect): { import: string; alias: string } { switch (dialect) { case "postgres": return { @@ -53,7 +53,7 @@ export function dbTypeBlock(dialect: Dialect, opts?: { asyncOnly?: boolean }): { case "sqlite": return { import: `import type { BaseSQLiteDatabase } from "drizzle-orm/sqlite-core";`, - alias: `type Db = BaseSQLiteDatabase<${opts?.asyncOnly ? '"async"' : '"sync" | "async"'}, unknown, Record>;`, + alias: `type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;`, }; } } diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index a81e1b8a8..b11cd9a25 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -12,8 +12,9 @@ import { renderServiceFiles } from "../templates/service-file.js"; * The policy, bodies, hooks and event hook are passed in `deps`, through the interfaces the index * declares. Hand-written code calls the service; a transport (`serviceRoutesFile()`) mounts it. * - * SQLite needs an async Drizzle driver (libsql): the emitted `Db` type is `BaseSQLiteDatabase<"async", …>`, - * so a sync driver (better-sqlite3, bun:sqlite) fails to type-check instead of failing at run time. + * SQLite takes a sync or an async Drizzle driver: the runtime drives a sync driver's transaction + * (bun:sqlite, better-sqlite3) with statements. For Cloudflare D1, which holds no transaction across + * application code, pass `interactiveTransactions: false`. * * Imports the entity module (the Drizzle table and allowlists, `entityFile()`) and the contract * types (`contractTypes()`), so list both. The built-in twin of `src/reference/service.ts` @@ -28,6 +29,14 @@ export interface ServiceFileOpts { runtimeImport?: string; /** Named output target. It must be the entity module's target. */ target?: string; + /** + * False for a store that cannot hold a transaction across application code (Cloudflare D1). + * The service then opens no transaction: each derived write is its one statement, and a + * transition is its guarded update, which holds on its own. There are no hooks and no event + * hook, which would run inside the write's transaction, and a package that declares a command is + * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. + */ + interactiveTransactions?: boolean; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -38,7 +47,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { const model = serviceModelOf(ctx.loadedRoot, { matches }); if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service", opts?.runtimeImport); - return model.flatMap((pkg) => renderServiceFiles(pkg, rc)); + const interactiveTransactions = opts?.interactiveTransactions !== false; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/reference/service.ts b/server/typescript/packages/codegen-ts/src/reference/service.ts index d3faed08c..0169ac798 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service.ts @@ -47,6 +47,14 @@ export interface ServiceFileOpts { runtimeImport?: string; /** Named output target. It must be the entity module's target. */ target?: string; + /** + * False for a store that cannot hold a transaction across application code (Cloudflare D1). + * The service then opens no transaction: each derived write is its one statement, and a + * transition is its guarded update, which holds on its own. There are no hooks and no event + * hook, which would run inside the write's transaction, and a package that declares a command is + * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. + */ + interactiveTransactions?: boolean; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -59,7 +67,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { const runtimeImport = opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); const rc = serviceRenderContext(ctx, "service", runtimeImport); - return model.flatMap((pkg) => renderServiceFiles(pkg, rc)); + const interactiveTransactions = opts?.interactiveTransactions !== false; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 4ff7a087a..36f2a0dbe 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -149,6 +149,11 @@ export interface ServicePackage { readonly permissions: readonly string[]; /** The settings the model was loaded with (`rules.lifecycle.create` decides a create's states). */ readonly settings: RulesSettings; + /** + * False when the store cannot hold a transaction across application code (Cloudflare D1): the + * service generator's `interactiveTransactions` option, not the model's. Absent: true. + */ + readonly interactiveTransactions?: boolean; } export interface ServiceWalkOpts { diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index d8898f442..98d494ae3 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -41,6 +41,7 @@ import { type ServiceTransitionCommand, } from "../service-walk.js"; import { TsWriter, str } from "../writer/ts-writer.js"; +import { CodegenError } from "../errors.js"; /** One emitted file of the service or transport layer. */ export interface ServiceFile { @@ -89,8 +90,30 @@ export function wireMapperName(entityName: string): string { return `${lowerFirst(entityName)}ToWire`; } +/** Does the store hold a transaction across application code? (`interactiveTransactions`, default true) */ +function interactive(pkg: ServicePackage): boolean { + return pkg.interactiveTransactions !== false; +} + +/** The option a store without interactive transactions is declared with, as the refusal names it. */ +export const NO_INTERACTIVE_TX_OPTION = "serviceFile({ interactiveTransactions: false })"; + +/** The code generation answers a declared command with under that option (ADR-0067 §4). */ +export const ERR_STORE_NO_INTERACTIVE_TX = "ERR_STORE_NO_INTERACTIVE_TX"; + /** Every file of package `pkg`'s service module. */ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): ServiceFile[] { + if (!interactive(pkg)) { + const command = pkg.operations.find((op) => op.kind === "command"); + if (command !== undefined) { + throw new CodegenError( + `${ERR_STORE_NO_INTERACTIVE_TX}: ${pkg.package === "" ? "the model's root package" : `package ${pkg.package}`} declares command ` + + `${command.name}, and ${NO_INTERACTIVE_TX_OPTION} says the store cannot hold a transaction: a command's ` + + "body runs in its write's transaction, so a refusal after the body wrote could not undo the write. " + + "Run this package's service on a store with interactive transactions, or declare the operation a query.", + ); + } + } const files: ServiceFile[] = []; for (const e of pkg.entities) { for (const op of ["list", "get", "create", "update", "delete"] as const) { @@ -179,7 +202,11 @@ function renderOperation( return w.toString(); } - const inWriteTransaction = w.use("inWriteTransaction", runtime); + // Under `interactiveTransactions: false` a write opens no transaction and has no hooks or event + // hook to run inside one (ADR-0067 §4): it is its one statement, after the load and the checks. + const tx = interactive(pkg); + const inWriteTransaction = tx ? w.use("inWriteTransaction", runtime) : w.use("withoutTransaction", runtime); + const inOne = tx ? "In one transaction:" : "With no transaction (`interactiveTransactions: false`):"; if (op === "create" || op === "update") { const writeRules = w.useType("WriteBodyRules", runtime); const validateBody = w.use("validateBody", runtime); @@ -191,14 +218,20 @@ function renderOperation( const schema = w.use(`${name}InsertSchema`, mods.contract); const input = w.useType(`${name}Create`, mods.contract); w.doc( - `Create a ${name}. In one transaction: the before hook (it may replace the input or refuse),`, - "validate the input and stamp what the model declares (ADR-0045), insert it, the after hook", - "and the event hook; answer the written row.", + ...(tx + ? [ + `Create a ${name}. ${inOne} the before hook (it may replace the input or refuse),`, + "validate the input and stamp what the model declares (ADR-0045), insert it, the after hook", + "and the event hook; answer the written row.", + ] + : [`Create a ${name}. ${inOne} validate the input and stamp what the model declares`, "(ADR-0045), insert it; answer the written row."]), ); w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); - w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(input, ctx)) ?? input;`); + if (tx) { + w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); + w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(input, ctx)) ?? input;`); + } else w.line("const given = input;"); w.line(`const values: Record = ${validateBody}(${schema}, given, writeRules);`); if (e.lifecycles.length > 0) { if (pkg.settings.lifecycleCreate === "initial") { @@ -210,10 +243,12 @@ function renderOperation( } } w.line(`const row = (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); - w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, ctx);`); - w.line( - `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "create", entity: ${str(name)}, key: row.${e.keyField}, row, actor: opts.actor, at: new Date() }, tx);`, - ); + if (tx) { + w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, ctx);`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "create", entity: ${str(name)}, key: row.${e.keyField}, row, actor: opts.actor, at: new Date() }, tx);`, + ); + } w.line("return row;"); }, "});"); }); @@ -226,10 +261,18 @@ function renderOperation( const schema = w.use(`${name}UpdateSchema`, mods.contract); const patch = w.useType(`${name}Patch`, mods.contract); w.doc( - `Update the ${name} row \`id\` names with \`patch\`. In one transaction: load the row under a row`, - "lock (`not_found` when there is none), the before hook, validate the patch and stamp what the", - "model declares (ADR-0045), write it, the after hook and the event hook; answer the written row.", - "A patch with nothing to write answers the row and calls no after or event hook.", + ...(tx + ? [ + `Update the ${name} row \`id\` names with \`patch\`. ${inOne} load the row under a row`, + "lock (`not_found` when there is none), the before hook, validate the patch and stamp what the", + "model declares (ADR-0045), write it, the after hook and the event hook; answer the written row.", + "A patch with nothing to write answers the row and calls no after or event hook.", + ] + : [ + `Update the ${name} row \`id\` names with \`patch\`. ${inOne} load the row`, + "(`not_found` when there is none), validate the patch and stamp what the model declares", + "(ADR-0045), write it; answer the written row. A patch with nothing to write answers the row.", + ]), ); w.block( `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, @@ -238,8 +281,10 @@ function renderOperation( w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); - w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); - w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(patch, current, ctx)) ?? patch;`); + if (tx) { + w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); + w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(patch, current, ctx)) ?? patch;`); + } else w.line("const given = patch;"); w.line(`const data: Record = ${validateBody}(${schema}, given, writeRules);`); if (lifecycleFields.length > 0) { w.line("// A lifecycle moves only through its transitions (ADR-0066 §6 step 7)."); @@ -248,10 +293,12 @@ function renderOperation( w.line("if (Object.keys(data).length === 0) return current;"); w.line(`const row = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (row === undefined) ${notFound}();`); - w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, current, ctx);`); - w.line( - `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "update", entity: ${str(name)}, key: row.${e.keyField}, row, previous: current, actor: opts.actor, at: new Date() }, tx);`, - ); + if (tx) { + w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, current, ctx);`); + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "update", entity: ${str(name)}, key: row.${e.keyField}, row, previous: current, actor: opts.actor, at: new Date() }, tx);`, + ); + } w.line("return row;"); }, "});"); }, @@ -264,14 +311,22 @@ function renderOperation( const deleteRows = w.use("deleteRows", runtime); const notFound = w.use("notFound", runtime); w.doc( - `Delete the ${name} row \`id\` names. In one transaction: load it under a row lock (\`not_found\``, - "when there is none), the before hook, the delete, the after hook and the event hook.", + ...(tx + ? [ + `Delete the ${name} row \`id\` names. ${inOne} load it under a row lock (\`not_found\``, + "when there is none), the before hook, the delete, the after hook and the event hook.", + ] + : [`Delete the ${name} row \`id\` names. ${inOne} load it (\`not_found\` when there is`, "none), then the delete."]), ); w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); + if (!tx) { + w.line(`await ${deleteRows}(tx, ${table}, cond);`); + return; + } w.line(`const ctx = ${w.use("handlerContext", runtime)}(tx, opts.actor);`); w.line(`await deps.hooks?.before${toPascalCase(fn)}?.(current, ctx);`); w.line(`await ${deleteRows}(tx, ${table}, cond);`); @@ -361,14 +416,24 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, w.doc(`\`${t.field}\`: ${t.from.join(", ")} → ${t.to}.`); w.line(`const move: ${spec} = ${transitionLiteral(t)};`); w.blank(); + const inTx = interactive(pkg); w.doc( - `Make the ${name} row \`id\` names move \`${t.name}\`. In one transaction, in ADR-0066 §6's order: load it`, - "under a row lock (`not_found`), the permission point (`forbidden`), the state check", - "(`invalid_transition`), the guarded update (`invalid_transition` or", - "`transition_condition_failed` when it matches no row), the event hook. Answers the written row.", + ...(inTx + ? [ + `Make the ${name} row \`id\` names move \`${t.name}\`. In one transaction, in ADR-0066 §6's order: load it`, + "under a row lock (`not_found`), the permission point (`forbidden`), the state check", + "(`invalid_transition`), the guarded update (`invalid_transition` or", + "`transition_condition_failed` when it matches no row), the event hook. Answers the written row.", + ] + : [ + `Make the ${name} row \`id\` names move \`${t.name}\`. With no transaction (\`interactiveTransactions: false\`),`, + "in ADR-0066 §6's order: load it (`not_found`), the permission point (`forbidden`), the state check", + "(`invalid_transition`), the guarded update, which holds on its own (`invalid_transition` or", + "`transition_condition_failed` when it matches no row). Answers the written row.", + ]), ); w.block(`export async function ${c.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { - w.block(`return ${w.use("inWriteTransaction", runtime)}(deps.db, opts.tx, async (tx) => {`, () => { + w.block(`return ${w.use(inTx ? "inWriteTransaction" : "withoutTransaction", runtime)}(deps.db, opts.tx, async (tx) => {`, () => { w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id);`); w.line(`const current = (await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${w.use("notFound", runtime)}();`); @@ -376,9 +441,11 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, else w.line(`await ${w.use("checkPermission", runtime)}(deps.policy, ${str(c.permission)}, opts.actor, current, undefined, tx);`); w.line(`${w.use("checkState", runtime)}(current, [move]);`); w.line(`const row = (await ${w.use("makeTransition", runtime)}(tx, ${table}, cond, move, ${dialect})) as ${row};`); - w.line( - `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "transition", entity: ${str(name)}, key: current.${e.keyField}, lifecycle: move.field, transition: move.name, from: String(current.${t.field}), to: move.to, operation: ${str(c.fn)}, actor: opts.actor, at: new Date() }, tx);`, - ); + if (inTx) { + w.line( + `await ${w.use("emitWrite", runtime)}(deps.events, { kind: "transition", entity: ${str(name)}, key: current.${e.keyField}, lifecycle: move.field, transition: move.name, from: String(current.${t.field}), to: move.to, operation: ${str(c.fn)}, actor: opts.actor, at: new Date() }, tx);`, + ); + } w.line("return row;"); }, "});"); }); @@ -504,13 +571,12 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex const opResult = w.useType("OpResult", runtime); const listPage = w.useType("ListPage", runtime); const query = w.useType("ListQueryInput", runtime); - const hookContext = `${w.useType("HookContext", runtime)}`; const type = serviceTypeName(pkg.package); const stem = type.replace(/Service$/, ""); - const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect, { asyncOnly: true }); + const { import: dbImport, alias: dbAlias } = dbTypeBlock(ctx.dialect); - // The dialect's Drizzle base type, the queries generator's, except that SQLite is async-only: - // a write awaits inside its transaction callback, which a sync driver (better-sqlite3, bun:sqlite) rejects. + // The dialect's Drizzle base type, the queries generator's. A sync SQLite driver (bun:sqlite, + // better-sqlite3) is accepted: the runtime drives its transaction with statements. const dbModule = /from "([^"]+)"/.exec(dbImport)![1]!; for (const t of /import type \{ ([^}]+) \}/.exec(dbImport)![1]!.split(",").map((s) => s.trim())) w.useType(t, dbModule); w.line(dbAlias); @@ -530,35 +596,40 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex w.line(`export type ${stem}Policy = ${w.useType("Policy", runtime)}<${stem}Permission, A, Db>;`); } - w.blank(); - w.doc( - "Hooks on the derived writes, all optional: an absent hook does nothing. Each runs in the write's", - "transaction (`ctx.tx`); a before hook may return a replacement input, and any hook may refuse", - "(`ctx.refuse(code)`, 409), which rolls the whole write back.", - ); - w.block(`export interface ${stem}Hooks {`, () => { - for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const row = w.useType(e.obj.name, mods.contract); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); - const o = e.operations; - const P = (f: string) => toPascalCase(f); - w.line(`before${P(o.create)}?(input: ${create}, ctx: ${hookContext}): ${create} | void | Promise<${create} | void>;`); - w.line(`after${P(o.create)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); - w.line(`before${P(o.update)}?(patch: ${patch}, current: ${row}, ctx: ${hookContext}): ${patch} | void | Promise<${patch} | void>;`); - w.line(`after${P(o.update)}?(row: ${row}, previous: ${row}, ctx: ${hookContext}): void | Promise;`); - w.line(`before${P(o.delete)}?(current: ${row}, ctx: ${hookContext}): void | Promise;`); - w.line(`after${P(o.delete)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); - } - }); + // Under `interactiveTransactions: false` there are no hooks and no event hook: each would run in + // the write's transaction, and the store holds none (ADR-0067 §4). + if (interactive(pkg)) { + const hookContext = `${w.useType("HookContext", runtime)}`; + w.blank(); + w.doc( + "Hooks on the derived writes, all optional: an absent hook does nothing. Each runs in the write's", + "transaction (`ctx.tx`); a before hook may return a replacement input, and any hook may refuse", + "(`ctx.refuse(code)`, 409), which rolls the whole write back.", + ); + w.block(`export interface ${stem}Hooks {`, () => { + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const row = w.useType(e.obj.name, mods.contract); + const create = w.useType(`${e.obj.name}Create`, mods.contract); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const o = e.operations; + const P = (f: string) => toPascalCase(f); + w.line(`before${P(o.create)}?(input: ${create}, ctx: ${hookContext}): ${create} | void | Promise<${create} | void>;`); + w.line(`after${P(o.create)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`before${P(o.update)}?(patch: ${patch}, current: ${row}, ctx: ${hookContext}): ${patch} | void | Promise<${patch} | void>;`); + w.line(`after${P(o.update)}?(row: ${row}, previous: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`before${P(o.delete)}?(current: ${row}, ctx: ${hookContext}): void | Promise;`); + w.line(`after${P(o.delete)}?(row: ${row}, ctx: ${hookContext}): void | Promise;`); + } + }); - w.blank(); - w.doc( - "The write-event hook: told about every write, in its transaction, with the actor (ADR-0066 §7).", - "An outbox, a history table or an audit log is written here. Absent, nothing is told.", - ); - w.line(`export type ${stem}Events = ${w.useType("WriteEvents", runtime)};`); + w.blank(); + w.doc( + "The write-event hook: told about every write, in its transaction, with the actor (ADR-0066 §7).", + "An outbox, a history table or an audit log is written here. Absent, nothing is told.", + ); + w.line(`export type ${stem}Events = ${w.useType("WriteEvents", runtime)};`); + } if (hasBodies) { w.blank(); @@ -593,8 +664,10 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex w.line("readonly db: Db;"); if (hasPolicy) w.line(`readonly policy: ${stem}Policy;`); if (hasBodies) w.line(`readonly bodies: ${stem}Bodies;`); - w.line(`readonly hooks?: ${stem}Hooks;`); - w.line(`readonly events?: ${stem}Events;`); + if (interactive(pkg)) { + w.line(`readonly hooks?: ${stem}Hooks;`); + w.line(`readonly events?: ${stem}Events;`); + } }); const calls: string[] = []; diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index c5ed73111..e93541a0d 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -90,10 +90,10 @@ describe("service generators — what they write", () => { expect(files["acme/shop/service/createOrder.ts"]).toContain('from "../../../Order.js";'); }); - test("on sqlite the service takes an async Drizzle driver only; the flat queries module still takes both", async () => { + test("on sqlite the service takes a sync or an async Drizzle driver, as the flat queries module does", async () => { const root = await load("acme::shop", [entity("Order")]); const files = await gen(root, [entityFile(), contractTypes(), serviceFile(), queriesFile()], "package", { dialect: "sqlite" }); - expect(files["acme/shop/service/index.ts"]).toContain('type Db = BaseSQLiteDatabase<"async", unknown, Record>;'); + expect(files["acme/shop/service/index.ts"]).toContain('type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;'); expect(files["acme/shop/Order.queries.ts"]).toContain('type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record>;'); }); @@ -249,3 +249,35 @@ describe("service generators — lifecycles and declared operations (ADR-0066)", await expect(gen(root, tier())).rejects.toThrow(/command settle lists @transitions but addresses no row by key/); }); }); + +describe("service generator — a store without interactive transactions (ADR-0067 §4)", () => { + const noTx = (): Generator[] => [entityFile(), contractTypes(), serviceFile({ interactiveTransactions: false }), serviceRoutesFile()]; + const peek = { "operation.query": { name: "peek", "@objectRef": "Order", "@outputRef": "Order", "@public": true } }; + + test("a package that declares a command is refused, naming the package, the command and the option", async () => { + const root = await load("acme::shop", [order([pay]), settlement, api(settle)]); + await expect(gen(root, noTx())).rejects.toThrow( + /ERR_STORE_NO_INTERACTIVE_TX: package acme::shop declares command settle, and serviceFile\(\{ interactiveTransactions: false \}\)/, + ); + // The same package generates with interactive transactions, the default. + expect(servicePaths(await gen(root, tier()))).toContain("acme/shop/service/settle.ts"); + }); + + test("a declared query is generated; the service offers no hooks and no event hook, and opens no transaction", async () => { + const files = await gen(await load("acme::shop", [order([pay]), api(peek)]), noTx()); + expect(servicePaths(files)).toContain("acme/shop/service/peek.ts"); + const index = files["acme/shop/service/index.ts"]!; + expect(index).not.toContain("ShopHooks"); + expect(index).not.toContain("ShopEvents"); + expect(index).not.toContain("readonly hooks?"); + for (const op of ["createOrder", "updateOrder", "deleteOrder", "payOrder"]) { + const file = files[`acme/shop/service/${op}.ts`]!; + expect(file).toContain("withoutTransaction(deps.db, opts.tx,"); + expect(file).not.toContain("inWriteTransaction"); + expect(file).not.toContain("deps.hooks"); + expect(file).not.toContain("emitWrite"); + } + // The transition keeps its guarded update, which holds without a transaction. + expect(files["acme/shop/service/payOrder.ts"]).toContain("makeTransition("); + }); +}); diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts index 8f3aa3fe4..a72716d48 100644 --- a/server/typescript/packages/integration-tests/test/service-compile.test.ts +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -1,5 +1,6 @@ // The service tier's compile gate (ADR-0067 layers 4 and 5): the shared fitness corpus and the -// api-contract rules corpus, each generated +// api-contract rules corpus, each generated (and the fitness corpus again without interactive +// transactions, on SQLite) // with the entity module, the contract types, the service and its Fastify transport, compiled with // the real compiler in both profiles, every dialect and both output layouts. // @@ -81,11 +82,23 @@ const CORPORA = [ pkg: "acme/purchasing", present: ["acme/purchasing/service/submitPurchaseRequest.ts", "acme/purchasing/service/decide.ts", "acme/purchasing/service/requestTotals.ts"], }, + // A store without interactive transactions (Cloudflare D1, which generates as `sqlite`): the + // service with no transaction, no hooks and no event hook (ADR-0067 §4). + { + label: "the shared fitness corpus, without interactive transactions", + path: CORPUS, + pkg: "fitness", + present: ["fitness/service/createProgram.ts"], + interactiveTransactions: false, + dialects: ["sqlite"], + }, ] as const; +const ALL_DIALECTS = ["postgres", "sqlite", "mysql"] as const; + for (const corpus of CORPORA) describe(`service compile gate — ${corpus.label}`, () => { for (const layout of ["flat", "package"] as const satisfies readonly OutputLayout[]) { - for (const dialect of ["postgres", "sqlite", "mysql"] as const) { + for (const dialect of "dialects" in corpus ? corpus.dialects : ALL_DIALECTS) { for (const [profile, options] of PROFILES) { test(`${layout} / ${dialect} [${profile}]: the service and its transport compile with zero diagnostics`, async () => { const root = await loadCorpus(corpus.path); @@ -98,7 +111,12 @@ for (const corpus of CORPORA) describe(`service compile gate — ${corpus.label} dbImport: "~/db", dialect, outputLayout: layout, - generators: [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()], + generators: [ + entityFile(), + contractTypes(), + serviceFile("interactiveTransactions" in corpus ? { interactiveTransactions: corpus.interactiveTransactions } : undefined), + serviceRoutesFile(), + ], }), metadata: root, projectRoot: dir, diff --git a/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts b/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts new file mode 100644 index 000000000..96955547d --- /dev/null +++ b/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts @@ -0,0 +1,187 @@ +// The GENERATED service (ADR-0067 layer 4) on the two SQLite drivers that cannot run Drizzle's +// async transaction: +// +// - bun:sqlite, a SYNC driver. Drizzle's `transaction()` there commits when its callback returns, +// so before the runtime drove the transaction itself a hook's refusal after the insert answered +// 409 over a row that stayed. The default service must hold its rollback guarantee here. +// - Cloudflare D1 (Miniflare's local runtime), which holds no transaction across application code: +// it refuses `BEGIN`. The default service fails there on every write; the service generated with +// `interactiveTransactions: false` (ADR-0067 §4) runs, with no hooks, no event hook and no +// transaction, its transition still guarded by the one UPDATE. +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { drizzle as drizzleBunSqlite } from "drizzle-orm/bun-sqlite"; +import { drizzle as drizzleD1 } from "drizzle-orm/d1"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; +import { contractTypes, entityFile, serviceFile } from "@metaobjectsdev/codegen-ts/generators"; +import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; +import { loadMetadataFile } from "../src/load-metadata.ts"; +import { startLocalD1, type LocalD1 } from "../src/query-scenario-d1.ts"; + +const MODEL = { + "metadata.root": { + package: "acme::notes", + children: [ + { + "object.entity": { + name: "Note", + children: [ + { "source.rdb": { "@table": "notes" } }, + { "field.long": { name: "id" } }, + { "identity.primary": { name: "pk", "@fields": ["id"], "@generation": "increment" } }, + { "field.string": { name: "title", "@maxLength": 80, "@required": true } }, + { + "field.enum": { + name: "status", + "@values": ["draft", "published"], + "@default": "draft", + children: [{ "transition.action": { name: "publish", "@from": ["draft"], "@to": "published", "@public": true } }], + }, + }, + ], + }, + }, + ], + }, +}; + +const DDL = "CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, status TEXT DEFAULT 'draft')"; + +interface Result { + ok: boolean; + status?: number; + error?: { error: string }; + value?: unknown; +} +interface Ctx { + refuse(code: string): never; +} +interface NotesService { + createNote(input: { title: string }): Promise; + updateNote(id: number, patch: { title?: string; status?: string }): Promise; + deleteNote(id: number): Promise; + publishNote(id: number): Promise; + listNotes(query: Record): Promise; +} +type Factory = (deps: Record) => NotesService; + +const here = dirname(fileURLToPath(import.meta.url)); +let tmp: string; + +/** Generate the model's service for SQLite into its own folder and import its factory. */ +async function generate(folder: string, interactiveTransactions?: boolean): Promise { + const out = join(tmp, folder); + const root = await loadMetadataFile(join(tmp, "meta.json")); + root.physicalNaming = DEFAULT_PHYSICAL_NAMING; + const r = await runGen({ + config: defineConfig({ + outDir: out, + extStyle: "none", + dialect: "sqlite", + generators: [ + entityFile(), + contractTypes(), + serviceFile(interactiveTransactions === undefined ? undefined : { interactiveTransactions }), + ], + }), + metadata: root, + }); + if (r.warnings.length > 0) throw new Error(`codegen produced warnings: ${r.warnings.join("; ")}`); + const mod = (await import(pathToFileURL(join(out, "acme/notes/service/index.ts")).href)) as { createNotesService: Factory }; + return mod.createNotesService; +} + +beforeAll(() => { + const genTmpRoot = join(here, "..", ".gen-tmp"); + mkdirSync(genTmpRoot, { recursive: true }); + tmp = mkdtempSync(join(genTmpRoot, "service-sqlite-drivers-")); + writeFileSync(join(tmp, "meta.json"), JSON.stringify(MODEL), "utf8"); +}); + +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +const refuseTitle = { afterCreateNote: (row: { title: string }, ctx: Ctx) => { if (row.title === "REFUSE") ctx.refuse("title_refused"); } }; + +describe("the generated service on a sync SQLite driver (bun:sqlite)", () => { + let sqlite: Database; + let service: NotesService; + const titles = (): string[] => (sqlite.query("SELECT title FROM notes ORDER BY id").all() as { title: string }[]).map((r) => r.title); + + beforeAll(async () => { + sqlite = new Database(":memory:"); + sqlite.run(DDL); + const create = await generate("bun-sqlite"); + service = create({ db: drizzleBunSqlite(sqlite), hooks: refuseTitle }); + }); + afterAll(() => sqlite.close()); + + test("a create commits, starting in the initial state", async () => { + const r = await service.createNote({ title: "first" }); + expect(r).toMatchObject({ ok: true, value: { id: 1, title: "first", status: "draft" } }); + expect(titles()).toEqual(["first"]); + }); + + test("a hook that refuses after the insert undoes it", async () => { + const r = await service.createNote({ title: "REFUSE" }); + expect(r).toEqual({ ok: false, status: 409, error: { error: "title_refused" } }); + expect(titles()).toEqual(["first"]); + }); + + test("a transition moves the row once, and a second move is invalid_transition", async () => { + expect(await service.publishNote(1)).toMatchObject({ ok: true, value: { id: 1, status: "published" } }); + expect(await service.publishNote(1)).toEqual({ ok: false, status: 409, error: { error: "invalid_transition" } }); + }); + + test("operations running at once each keep their own guarantee", async () => { + const [kept, refused] = await Promise.all([service.createNote({ title: "kept" }), service.createNote({ title: "REFUSE" })]); + expect(kept.ok).toBe(true); + expect(refused).toMatchObject({ ok: false, status: 409 }); + expect(titles()).toEqual(["first", "kept"]); + }); +}); + +describe("the generated service on Cloudflare D1 (Miniflare)", () => { + let local: LocalD1; + let service: NotesService; + const titles = async (): Promise => + ((await local.d1.prepare("SELECT title FROM notes ORDER BY id").all()) as { results: { title: string }[] }).results.map((r) => r.title); + + beforeAll(async () => { + local = await startLocalD1(); + await local.d1.exec(DDL); + const create = await generate("d1", false); + service = create({ db: drizzleD1(local.d1 as never) }); + }, 60_000); + afterAll(async () => local.dispose()); + + test("the default service cannot run there: D1 refuses the transaction it opens", async () => { + const create = await generate("d1-default"); + const failing = create({ db: drizzleD1(local.d1 as never) }); + const quiet = console.error; + console.error = () => {}; + try { + await expect(failing.createNote({ title: "never" })).rejects.toThrow(); + } finally { + console.error = quiet; + } + expect(await titles()).toEqual([]); + }); + + test("with interactiveTransactions: false every derived write runs", async () => { + expect(await service.createNote({ title: "first" })).toMatchObject({ ok: true, value: { id: 1, title: "first", status: "draft" } }); + expect(await service.updateNote(1, { title: "renamed" })).toMatchObject({ ok: true, value: { id: 1, title: "renamed" } }); + expect(await service.createNote({ title: "second" })).toMatchObject({ ok: true, value: { id: 2 } }); + expect(await service.deleteNote(2)).toEqual({ ok: true, value: undefined }); + expect(await titles()).toEqual(["renamed"]); + }); + + test("the rules still hold: the lifecycle field is state_managed, and the transition is guarded", async () => { + expect(await service.updateNote(1, { status: "published" })).toEqual({ ok: false, status: 409, error: { error: "state_managed" } }); + expect(await service.publishNote(1)).toMatchObject({ ok: true, value: { status: "published" } }); + expect(await service.publishNote(1)).toEqual({ ok: false, status: 409, error: { error: "invalid_transition" } }); + expect(await service.publishNote(99)).toEqual({ ok: false, status: 404, error: { error: "not_found" } }); + }); +}); diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts index 722638806..bf93722bf 100644 --- a/server/typescript/packages/runtime-ts/src/service/index.ts +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -10,7 +10,7 @@ // The semantics are the ones `mountCrudRoutes` (../drizzle-fastify) has always answered with, so a // service behind the thin transport passes the same shared API tests the flat routes pass. -import { and, asc, count, eq, type SQL } from "drizzle-orm"; +import { and, asc, count, eq, sql, type SQL } from "drizzle-orm"; import type { ZodTypeAny, z } from "zod"; import { classifyConstraintError, logAndRedact, RedactedDatabaseError } from "../constraint-errors.js"; import { validationErrorBody } from "../route-errors.js"; @@ -100,7 +100,10 @@ export async function inWriteTransaction( ): Promise> { const scope: Drizzle = tx ?? db; try { - return { ok: true, value: await scope.transaction(fn) }; + const value = isSyncSqlite(scope) + ? await syncSqliteTransaction(scope, tx !== undefined, fn) + : await scope.transaction(fn); + return { ok: true, value }; } catch (e) { return failure(e); } @@ -108,6 +111,22 @@ export async function inWriteTransaction( /** Run a read operation on `tx` when the caller passed one, else on `db`. A query opens no write transaction. */ export async function inReadScope(db: unknown, tx: unknown, fn: (db: Drizzle) => Promise): Promise> { + try { + // On a sync SQLite handle a read with no transaction of its own waits for the one in flight: + // the connection is shared, so reading mid-transaction would see writes that may roll back. + const value = tx === undefined && isSyncSqlite(db) ? await serialized(db, () => fn(db)) : await fn(tx ?? db); + return { ok: true, value }; + } catch (e) { + return failure(e); + } +} + +/** + * Run a write with no transaction, for a store that cannot hold one across application code + * (Cloudflare D1; the service generator's `interactiveTransactions: false`). Each statement commits + * on its own; a refusal or a constraint failure is answered as `inWriteTransaction` answers it. + */ +export async function withoutTransaction(db: unknown, tx: unknown, fn: (db: Drizzle) => Promise): Promise> { try { return { ok: true, value: await fn(tx ?? db) }; } catch (e) { @@ -115,6 +134,85 @@ export async function inReadScope(db: unknown, tx: unknown, fn: (db: Drizzle) } } +/** + * Run `fn` in one write transaction on `db` and return what it returned, for a job that runs + * several operations atomically: pass the handle `fn` receives as each operation's `opts.tx`, and + * each runs in a savepoint inside it. On a driver with interactive transactions this is + * `db.transaction(fn)`. On a sync SQLite driver, whose own `transaction()` cannot await, it is the + * same transaction the service opens for one operation. A throw rolls it all back and is rethrown. + */ +export async function withWriteTransaction(db: unknown, fn: (tx: Drizzle) => Promise): Promise { + const handle: Drizzle = db; + return isSyncSqlite(handle) ? syncSqliteTransaction(handle, false, fn) : handle.transaction(fn); +} + +/** + * A sync SQLite handle (`bun:sqlite`, `better-sqlite3`): Drizzle's `resultKind` is "sync". Its + * `transaction()` runs its callback synchronously and commits when the callback returns, so an + * async callback would commit at its first `await` and a later refusal would roll nothing back. + */ +function isSyncSqlite(handle: Drizzle): boolean { + return handle !== null && typeof handle === "object" && handle.resultKind === "sync" && typeof handle.run === "function"; +} + +/** The transaction in flight on each sync SQLite handle, which the next one waits for. */ +const inFlight = new WeakMap>(); + +/** + * Run `fn` once every earlier `serialized` call on `handle` has settled. SQLite has one writer, + * and a sync driver one connection, so a transaction that awaits must not interleave with another + * operation on the same connection. + */ +async function serialized(handle: Drizzle, fn: () => Promise): Promise { + const before = inFlight.get(handle) ?? Promise.resolve(); + const run = before.then(fn, fn); + const settled = run.then( + () => undefined, + () => undefined, + ); + inFlight.set(handle, settled); + try { + return await run; + } finally { + if (inFlight.get(handle) === settled) inFlight.delete(handle); + } +} + +let savepoints = 0; + +/** + * One transaction on a sync SQLite handle, driven with statements: `BEGIN IMMEDIATE` (it takes + * the write lock at once, so two writers cannot both read and then collide on commit), `COMMIT`, + * `ROLLBACK` on a throw. Inside a caller's transaction (`nested`) it is a savepoint instead, and + * takes no turn of its own: the caller holds it. + */ +async function syncSqliteTransaction(handle: Drizzle, nested: boolean, fn: (tx: Drizzle) => Promise): Promise { + if (nested) { + const name = `mo_sp_${++savepoints}`; + handle.run(sql.raw(`SAVEPOINT ${name}`)); + try { + const value = await fn(handle); + handle.run(sql.raw(`RELEASE SAVEPOINT ${name}`)); + return value; + } catch (e) { + handle.run(sql.raw(`ROLLBACK TO SAVEPOINT ${name}`)); + handle.run(sql.raw(`RELEASE SAVEPOINT ${name}`)); + throw e; + } + } + return serialized(handle, async () => { + handle.run(sql.raw("BEGIN IMMEDIATE")); + try { + const value = await fn(handle); + handle.run(sql.raw("COMMIT")); + return value; + } catch (e) { + handle.run(sql.raw("ROLLBACK")); + throw e; + } + }); +} + function failure(e: unknown): OpResult { if (e instanceof Refusal) return { ok: false, status: e.status, error: e.body }; if (e instanceof FilterParseError) { diff --git a/server/typescript/packages/runtime-ts/test/service-sync-sqlite.test.ts b/server/typescript/packages/runtime-ts/test/service-sync-sqlite.test.ts new file mode 100644 index 000000000..2fab9cbac --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/service-sync-sqlite.test.ts @@ -0,0 +1,114 @@ +// A generated service's write transaction on a SYNC SQLite driver (`bun:sqlite`; `better-sqlite3` +// is the same Drizzle session kind). Drizzle's own `transaction()` there runs its callback +// synchronously and commits when it returns, so an operation that awaits inside it would commit at +// its first `await` and a refusal after that would roll nothing back. The service drives the +// transaction with statements instead; these tests hold it to what every other driver answers. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { drizzle } from "drizzle-orm/bun-sqlite"; +import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; +import { + inReadScope, + insertRow, + inWriteTransaction, + refuse, + withWriteTransaction, + type OpResult, +} from "../src/service/index.js"; + +const notes = sqliteTable("notes", { + id: integer("id").primaryKey({ autoIncrement: true }), + title: text("title").notNull(), +}); + +let sqlite: Database; +let db: ReturnType; + +beforeEach(() => { + sqlite = new Database(":memory:"); + sqlite.run("CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL)"); + db = drizzle(sqlite); +}); + +afterEach(() => sqlite.close()); + +const titles = (): string[] => (sqlite.query("SELECT title FROM notes ORDER BY id").all() as { title: string }[]).map((r) => r.title); +const tick = (): Promise => new Promise((r) => setTimeout(r, 5)); + +function failed(r: OpResult): { status: number; error: Record } { + if (r.ok) throw new Error(`expected a failure, got ${JSON.stringify(r.value)}`); + return r; +} + +describe("inWriteTransaction on a sync SQLite driver", () => { + test("a write commits and answers its value", async () => { + const r = await inWriteTransaction(db, undefined, (tx) => insertRow(tx, notes, { title: "a" }, "sqlite")); + expect(r).toEqual({ ok: true, value: { id: 1, title: "a" } }); + expect(titles()).toEqual(["a"]); + }); + + test("a refusal after an await undoes the write made before it", async () => { + // The defect this guards: with Drizzle's sync transaction() the insert below was committed at + // the `await`, and the refusal answered 409 over a row that stayed. + const r = await inWriteTransaction(db, undefined, async (tx) => { + await insertRow(tx, notes, { title: "written, then undone" }, "sqlite"); + await tick(); + refuse({ error: "not_allowed" }); + }); + expect(failed(r)).toEqual({ ok: false, status: 409, error: { error: "not_allowed" } } as never); + expect(titles()).toEqual([]); + }); + + test("two operations at once do not interleave: one's rollback leaves the other's row", async () => { + const [kept, undone] = await Promise.all([ + inWriteTransaction(db, undefined, async (tx) => { + await tick(); + return insertRow(tx, notes, { title: "kept" }, "sqlite"); + }), + inWriteTransaction(db, undefined, async (tx) => { + await insertRow(tx, notes, { title: "undone" }, "sqlite"); + await tick(); + refuse({ error: "not_allowed" }); + }), + ]); + expect(kept.ok).toBe(true); + expect(failed(undone).status).toBe(409); + expect(titles()).toEqual(["kept"]); + }); + + test("a read waits for the transaction in flight, so it never sees a write that rolls back", async () => { + const write = inWriteTransaction(db, undefined, async (tx) => { + await insertRow(tx, notes, { title: "never committed" }, "sqlite"); + await tick(); + refuse({ error: "not_allowed" }); + }); + const read = inReadScope(db, undefined, async (rd) => (await rd.select().from(notes)).length); + await write; + expect(await read).toEqual({ ok: true, value: 0 }); + }); + + test("inside a caller's transaction a refusal undoes this operation only, and the caller's commit keeps the rest", async () => { + await withWriteTransaction(db, async (outer) => { + await insertRow(outer, notes, { title: "the caller's" }, "sqlite"); + const r = await inWriteTransaction(db, outer, async (tx) => { + await insertRow(tx, notes, { title: "the operation's" }, "sqlite"); + await tick(); + refuse({ error: "not_allowed" }); + }); + expect(failed(r).status).toBe(409); + }); + expect(titles()).toEqual(["the caller's"]); + }); + + test("a throw in the caller's transaction undoes every operation that ran inside it", async () => { + await expect( + withWriteTransaction(db, async (outer) => { + const r = await inWriteTransaction(db, outer, (tx) => insertRow(tx, notes, { title: "inside" }, "sqlite")); + expect(r.ok).toBe(true); + await tick(); + throw new Error("the job failed"); + }), + ).rejects.toThrow("the job failed"); + expect(titles()).toEqual([]); + }); +}); diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index 2d1113f99..742b01a95 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -138,11 +138,24 @@ These calls are recorded here: (ADR-0066 O5). Queries open no write transaction and call no hooks. - **Stores without interactive transactions.** A store whose driver cannot hold a transaction across application code (Cloudflare D1 is one) is declared with an option on the TypeScript - service generator. Under it the generator refuses hooks and events with - `ERR_STORE_NO_INTERACTIVE_TX`, naming the package and the option. There is no storage kit. - - The option and the code `ERR_STORE_NO_INTERACTIVE_TX` are designed here and land with the - TypeScript service generator; nothing in 1.3.0 reads or reports them yet. + service generator, `serviceFile({ interactiveTransactions: false })`. There is no storage kit. + Under it the service opens no transaction, so the generator writes what needs none and refuses + what does: + + - Each derived write is its one statement, after the load and the checks. A transition is its + guarded update, which holds without a transaction (ADR-0066 §6 step 7). Queries are generated + as usual. + - The hook interfaces, the event hook and their `deps` slots are not generated. Each would run in + the write's transaction, so a hook's refusal or an event handler's rows could not be undone with + the write. Leaving them out is the refusal: there is nothing to wire that could not keep its + guarantee. The "always generated" rule above holds for every store that has the transaction. + - A package that declares a command fails generation with `ERR_STORE_NO_INTERACTIVE_TX`, naming the + package, the command and the option. A command's body runs in its write's transaction, and a + refusal after the body wrote must undo the write. + + A sync SQLite driver (bun:sqlite, better-sqlite3) is not such a store. The runtime drives its + transaction with statements (`BEGIN IMMEDIATE`, `COMMIT`, `ROLLBACK`, one at a time per handle), + so the full service runs on it. - **Kotlin** returns a sealed result for declared business errors, and the transport maps it. The result type is fixed as designed: a project that wants exceptions ejects the generator. - **Java's** generated `@Service` class is not `final`, so Spring's transaction proxy works. From f19a7c8b987078785fbb576fcb4ae7600e647816 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 06:03:10 -0500 Subject: [PATCH 03/17] no-mistakes(document): service tx and D1 facts current in docs --- docs/features/business-rules.md | 24 +++++++++++++----------- docs/ports/typescript.md | 7 ++++--- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index d9a058156..ba1943f51 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -355,13 +355,14 @@ directory in either layout. the `Service` interface, `createService(deps)` that binds the operations to it, and each entity's wire mapper. -Every write runs in one transaction, in ADR-0067's order: load the row under a row lock (`not_found` -when there is none), validate the input and stamp what the model declares (ADR-0045: `@autoSet`, -write-once fields, server-owned and unknown keys), then write it. A caller that runs several -operations atomically passes its own transaction as `opts.tx`, and each operation runs in a -savepoint inside it. A refusal rolls the transaction back. A query opens no write transaction. -An operation answers an `OpResult`: the value, or a failure carrying the code and the HTTP status -the [API contract](api-contract.md) gives it, so every transport maps it the same way. +By default every write runs in one transaction (Cloudflare D1 is the exception, below), in +ADR-0067's order: load the row under a row lock (`not_found` when there is none), validate the input +and stamp what the model declares (ADR-0045: `@autoSet`, write-once fields, server-owned and unknown +keys), then write it. A caller that runs several operations atomically passes its own transaction as +`opts.tx`, and each operation runs in a savepoint inside it. A refusal rolls the transaction back. A +query opens no write transaction. An operation answers an `OpResult`: the value, or a failure +carrying the code and the HTTP status the [API contract](api-contract.md) gives it, so every +transport maps it the same way. On SQLite the service takes a sync or an async Drizzle driver, as the flat generators do. An async one (libsql) runs Drizzle's own transaction. A sync one (bun:sqlite, better-sqlite3) cannot: its @@ -389,12 +390,13 @@ sends what it answered; it holds no rules and no database handle. ```ts import { createShopService } from "./generated/acme/shop/service/index.js"; import { shopServiceRoutes } from "./generated/acme/shop/transport/fastify.js"; +import { withWriteTransaction } from "@metaobjectsdev/runtime-ts/service"; const service = createShopService({ db }); await app.register(shopServiceRoutes, { service }); -// A job calls the same operations, here two in one transaction: -await db.transaction(async (tx) => { +// A job calls the same operations, here two in one transaction (on any driver): +await withWriteTransaction(db, async (tx) => { await service.createOrder({ title: "first" }, { tx }); await service.createOrder({ title: "second" }, { tx }); }); @@ -417,7 +419,7 @@ The service also writes what the rules on this page declare: addresses a row, `/` when it does not; a query is a `GET`, a command a `POST`). Two routes on one method and path are refused when the transport is generated. -Each one runs ADR-0066 §6's checks in this order, in one transaction (a query in the read scope): +Each one runs ADR-0066 §6's checks in this order, in one transaction unless the store has none (a query in the read scope): load the row (`not_found`), validate the input, the permission point (403 `forbidden`), the state check (409 `invalid_transition`), the hand-written body, the guarded update (409 `invalid_transition` or `transition_condition_failed` when it matches no row), and the event hook. @@ -435,7 +437,7 @@ What you write is passed to `createService(deps)`; there is no base class t | `hooks` | `Hooks` | Optional `before`/`after` hooks on each derived create, update and delete. A before hook may return a replacement input. | | `events` | `Events` | Optional `onWrite(event, ctx)`, told about every create, update, delete, transition and command, in its transaction, with the actor. An outbox, a history table or an audit log is written here. | -Every hook, body and event runs in the write's transaction (`ctx.tx`), and any of them may refuse +By default every hook, body and event runs in the write's transaction (`ctx.tx`), and any of them may refuse with `ctx.refuse(code)`, which answers 409 with that code and rolls the whole write back. A code the API contract reserves (`not_found`, `forbidden`, `validation`, ...) is not accepted. diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 7495488af..9f24133ad 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -754,15 +754,16 @@ and give it its own `target` to put the layer in a package the transport and cli `serviceFile()` (stable name `service`, layer `service`) is layer 4 of ADR-0067. It writes one module per metadata package, under the package's directory in either layout: a file per operation in `/service/` (each entity's derived list, get, create, update and delete, every write in -one transaction with the declared write rules) and `service/index.ts` with the `Service` +one transaction by default, with the declared write rules) and `service/index.ts` with the `Service` interface and `createService(deps)`. A model with ADR-0066 rules also gets a file per derived transition command and per declared command and query, each running the rules' checks around a hand-written body; the policy, bodies, hooks and event hook are passed in `deps`. `serviceRoutesFile()` (stable name `service-routes`) writes `/transport/fastify.ts`, the routes that call it, with a `getActor(request)` option for the app's actor. Both need `entity` and `contract-types` in the same target. Neither is scaffolded; add them to `generators` or `meta eject` -them. On SQLite the service needs an async Drizzle driver such as libsql (`Db` is -`BaseSQLiteDatabase<"async", …>`). See [Business rules](../features/business-rules.md#the-service-layer-typescript). +them. On SQLite the service takes a sync or an async Drizzle driver. A store that holds no +transaction across application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. +See [Business rules](../features/business-rules.md#the-service-layer-typescript). ### Prove it works From cc031dac5f924c798e480dc65a85907d4564a3b4 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 06:03:35 -0500 Subject: [PATCH 04/17] no-mistakes(document): service options list interactiveTransactions --- server/typescript/packages/codegen-ts/src/generator-registry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index 345295482..a16108cec 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -302,7 +302,7 @@ export const generatorRegistry: Record = { tier: "native", factory: () => serviceFile(), factoryExport: "serviceFile", - options: "filter?, runtimeImport?, target?", + options: "filter?, runtimeImport?, target?, interactiveTransactions?", requires: ["entity", "contract-types"], runtimePackages: ["@metaobjectsdev/runtime-ts"], runtimePeers: ["drizzle-orm", "zod"], From d4923db49ea19558dc7f23caf4b8600c0e14ad65 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 06:45:20 -0500 Subject: [PATCH 05/17] feat(codegen-ts,runtime-ts): service lane on the entity sub-corpora, and a Hono transport The generated service (ADR-0067 layer 4) is now held to more of the shared API tests. A shared integration-tests helper (`api-lane.ts`) boots each generated harness on the flat routes, the service behind its Fastify transport, or the service behind its Hono transport. list-query, api-settings, enum-default, jsonb and duration run on all three lanes on every engine their routes lane runs (D1 through `serviceFile({ interactiveTransactions: false })`). The root corpus and rules/ also run on Hono, with one actor resolver adapted to each framework's request. New generator `service-routes-hono` (`serviceRoutesHonoFile()`) writes `/transport/hono.ts`: `ServiceHonoRoutes(app, { service, getActor })`, the same routes as the Fastify transport, through the new `@metaobjectsdev/runtime-ts/service/hono` entry. Registered in the generator registry, reference templates, the cross-port manifest, and `meta eject`'s runtime copies. Routes are ordered so a fixed segment precedes a parameter where two could match one request, since Hono matches in registration order (rules/ public-query found it). The service compile gate compiles both transports. Projections, reports, TPH, M:N and write-through on the service, and the decimal and secret-fields sub-corpora that need them, follow in their own PR. --- CHANGELOG.md | 12 ++ bun.lock | 1 + docs/features/business-rules.md | 22 ++- docs/features/own-your-codegen.md | 1 + docs/ports/typescript.md | 8 +- .../registry.json | 7 + .../packages/cli/src/lib/runtime-eject.ts | 1 + .../cli/test/eject-templates-contract.test.ts | 1 + .../cli/test/unit/rules-inert.test.ts | 1 + .../codegen-ts/src/generator-registry.ts | 17 ++ .../codegen-ts/src/generators/index.ts | 1 + .../generators/service-routes-hono-file.ts | 37 ++++ .../packages/codegen-ts/src/owned-runtime.ts | 2 + .../codegen-ts/src/reference-templates.ts | 6 +- .../src/reference/service-routes-hono.ts | 62 ++++++ .../packages/codegen-ts/src/service-walk.ts | 15 ++ .../codegen-ts/src/templates/service-file.ts | 181 ++++++++++++++++-- .../test/generator-registry.test.ts | 7 +- .../test/reference-byte-identical.test.ts | 3 + .../test/reference-templates.test.ts | 2 +- .../codegen-ts/test/service-file.test.ts | 30 ++- .../packages/integration-tests/package.json | 1 + ...-contract-api-settings-generated-server.ts | 26 +-- .../src/api-contract-decimal-server.ts | 29 +-- ...-contract-enum-default-generated-server.ts | 26 +-- .../src/api-contract-generated-server.ts | 34 +--- .../api-contract-jsonb-generated-server.ts | 24 +-- ...pi-contract-list-query-generated-server.ts | 26 +-- .../api-contract-rules-generated-server.ts | 41 ++-- .../integration-tests/src/api-lane.ts | 150 +++++++++++++++ .../test/api-contract-api-settings.test.ts | 6 +- .../test/api-contract-duration.test.ts | 11 +- .../test/api-contract-enum-default.test.ts | 5 +- .../test/api-contract-jsonb.test.ts | 5 +- .../test/api-contract-list-query.test.ts | 5 +- .../test/api-contract-rules.test.ts | 5 +- .../test/api-contract-service.test.ts | 3 + .../test/service-compile.test.ts | 12 +- .../test/service-sqlite-drivers.test.ts | 2 +- .../packages/runtime-ts/package.json | 5 + .../packages/runtime-ts/src/service/hono.ts | 42 ++++ .../runtime-ts/test/service-hono.test.ts | 67 +++++++ .../ADR-0067-layering-and-the-service-seam.md | 6 +- 43 files changed, 782 insertions(+), 166 deletions(-) create mode 100644 server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts create mode 100644 server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts create mode 100644 server/typescript/packages/integration-tests/src/api-lane.ts create mode 100644 server/typescript/packages/runtime-ts/src/service/hono.ts create mode 100644 server/typescript/packages/runtime-ts/test/service-hono.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a3f9fec6a..c7c02fa87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,18 @@ here.** ## [Unreleased] +- **codegen-ts: `service-routes-hono`, the service's Hono transport (ADR-0067 layer 5).** + `serviceRoutesHonoFile()` writes `/transport/hono.ts`, the same routes as the Fastify + transport, as `ServiceHonoRoutes(app, { service, getActor })`, with the actor read by + `getActor(c)`. It imports the new `@metaobjectsdev/runtime-ts/service/hono` entry, and `meta eject + service-routes-hono` copies that source. A fixed path segment is added before a parameter wherever + two routes could match one request, so `GET /` is not taken for + `GET /{id}`, as Fastify's router already decides. +- **The service is held to more of the shared API tests.** Its lanes, on Fastify and on Hono, now + run the `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` and `duration/` corpora beside the + root and `rules/` corpora, on every engine the routes lane runs, D1 included through + `interactiveTransactions: false`. The service compile gate compiles both transports. + - **runtime-ts: the generated service keeps its rollback guarantee on a sync SQLite driver.** On bun:sqlite and better-sqlite3, Drizzle's `transaction()` commits when its callback returns, so a service write that awaited inside it committed at its first `await`: a hook's or a body's refusal diff --git a/bun.lock b/bun.lock index 33d1ecc97..489bf53ee 100644 --- a/bun.lock +++ b/bun.lock @@ -333,6 +333,7 @@ "@metaobjectsdev/test-generators": "workspace:*", "drizzle-orm": "^0.45.1", "fastify": "^5.6.2", + "hono": "^4.6.0", "js-yaml": "^4.1.0", "kysely": "^0.27.4", "pg": "^8.11.5", diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index ba1943f51..7f2b78384 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -23,8 +23,8 @@ entity's create and update records ([C# port](../ports/csharp.md)). The TypeScri guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the shared persistence scenario `guarded-update.yaml`. The service layer starts in TypeScript: `service` writes each package's derived list, get, create, update and delete, every write in one transaction with the -declared write rules, behind a thin Fastify transport (`service-routes`) that answers the shared API -tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). It also writes +declared write rules, behind a thin Fastify transport (`service-routes`) or Hono transport +(`service-routes-hono`) that answers the shared API tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). It also writes a command per transition and a shell per declared command and query, and enforces at run time what this page declares: the permission point, the state check, the guarded update, `state_managed` and the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are @@ -385,7 +385,9 @@ package, the command and the option; queries are generated as usual. `serviceRoutesFile()` (stable name `service-routes`, layer `api`, Fastify) writes the thin transport (layer 5) beside it, `/transport/fastify.ts`: one plugin per package, registered with the service it calls. Each route parses the request, calls one operation and -sends what it answered; it holds no rules and no database handle. +sends what it answered; it holds no rules and no database handle. `serviceRoutesHonoFile()` +(stable name `service-routes-hono`) writes the same routes for Hono, `/transport/hono.ts`, +as one function per package that adds them to your app: `shopServiceHonoRoutes(app, { service })`. ```ts import { createShopService } from "./generated/acme/shop/service/index.js"; @@ -404,9 +406,12 @@ await withWriteTransaction(db, async (tx) => { Both import the entity module (`entity`, for the table and the allowlists) and the contract types (`contract-types`), written to the same target, and `@metaobjectsdev/runtime-ts`'s `service` and -`service/fastify` entries; `meta eject service` and `meta eject service-routes` copy that source into -`codegen/runtime/` as they do for the routes. The service lane of the shared API tests runs the -corpus the flat routes pass against the service behind this transport, in both layouts. +`service/fastify` (or `service/hono`) entries; `meta eject service`, `meta eject service-routes` and +`meta eject service-routes-hono` copy that source into `codegen/runtime/` as they do for the routes. +The service lanes of the shared API tests run the corpora the flat routes pass against the service +behind each transport, in both layouts: the root corpus, `rules/`, `list-query/`, `api-settings/`, +`enum-default/`, `jsonb/`, and `duration/` on every engine the routes lane runs (D1 with +`interactiveTransactions: false`). ### Transitions, declared operations and what you write by hand @@ -443,7 +448,8 @@ API contract reserves (`not_found`, `forbidden`, `validation`, ...) is not accep The actor is a type you define, `A`. A caller passes it per call as `opts.actor`, and the service hands it to the policy, the bodies, the hooks and the event hook without looking inside it. The -Fastify transport takes a `getActor(request)` resolver of yours: +Fastify transport takes a `getActor(request)` resolver of yours, and the Hono transport a +`getActor(c)`: ```ts const service = createPurchasingService({ @@ -456,6 +462,8 @@ const service = createPurchasingService({ events: { onWrite: (event, ctx) => writeAudit(ctx.tx, event) }, }); await app.register(purchasingServiceRoutes, { service, getActor: (req) => actorFromSession(req) }); +// or, on Hono: +purchasingServiceHonoRoutes(app, { service, getActor: (c) => actorFromSession(c) }); ``` The shared API tests' `fixtures/api-contract-conformance/rules/` corpus runs a model with a diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index be473af5d..ccb03e5ae 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -398,6 +398,7 @@ calls it copies the adapter's source too: | `entity` | `entity.ts` | `drizzle-fastify/filter-allowlist.ts` — the `FilterAllowlist` / `SortAllowlist` types the entity module's allowlists are typed by | | `service` | `service.ts` | `service/index.ts` — the store mechanics the generated service modules call (transaction, row lock, write-rule stamping), and `service/rules.ts`, the business-rules mechanics it re-exports | | `service-routes` | `service-routes.ts` | `service/fastify.ts` — the request and reply helpers the generated Fastify transport imports | +| `service-routes-hono` | `service-routes-hono.ts` | `service/hono.ts` — the same helpers for the generated Hono transport, plus the Hono route guard and the shared list-query parser it reaches | The ejected generators point their output at that copy (`import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index.js"`), so diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 9f24133ad..74ec287eb 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -749,7 +749,7 @@ imports `zod` only. It is not scaffolded; add it to `generators` or `meta eject and give it its own `target` to put the layer in a package the transport and clients share. See [Business rules](../features/business-rules.md#the-contract-types-layer-typescript). -### `service/` and `transport/` — the service layer and its Fastify transport +### `service/` and `transport/` — the service layer and its Fastify or Hono transport `serviceFile()` (stable name `service`, layer `service`) is layer 4 of ADR-0067. It writes one module per metadata package, under the package's directory in either layout: a file per operation @@ -759,8 +759,10 @@ interface and `createService(deps)`. A model with ADR-0066 rules also gets derived transition command and per declared command and query, each running the rules' checks around a hand-written body; the policy, bodies, hooks and event hook are passed in `deps`. `serviceRoutesFile()` (stable name `service-routes`) writes `/transport/fastify.ts`, the -routes that call it, with a `getActor(request)` option for the app's actor. Both need `entity` and -`contract-types` in the same target. Neither is scaffolded; add them to `generators` or `meta eject` +routes that call it, with a `getActor(request)` option for the app's actor. +`serviceRoutesHonoFile()` (stable name `service-routes-hono`) writes the same routes for Hono, +`/transport/hono.ts`, with `getActor(c)`. Each needs `entity` and `contract-types` in the +same target. Neither is scaffolded; add them to `generators` or `meta eject` them. On SQLite the service takes a sync or an async Drizzle driver. A store that holds no transaction across application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. See [Business rules](../features/business-rules.md#the-service-layer-typescript). diff --git a/fixtures/generator-registry-conformance/registry.json b/fixtures/generator-registry-conformance/registry.json index 06727f26e..0a0f36569 100644 --- a/fixtures/generator-registry-conformance/registry.json +++ b/fixtures/generator-registry-conformance/registry.json @@ -132,6 +132,13 @@ "eject": "full", "ports": ["typescript"] }, + "service-routes-hono": { + "concept": "The `service-routes` transport on Hono: the same routes over the service layer (ADR-0067 layer 5), mounted on a Hono app, answering the shared REST contract the same way. TYPESCRIPT ONLY by design, as `routes-hono` is: Hono is a TypeScript framework.", + "tier": "native", + "layer": "api", + "eject": "full", + "ports": ["typescript"] + }, "prompt-render": { "concept": "Per-template.prompt render handle over the render engine, aggregated into one module. TYPESCRIPT ONLY by design: the other four ports emit a prompt's render helper from `render-helper` (see its note) rather than a second generator.", "tier": "native", diff --git a/server/typescript/packages/cli/src/lib/runtime-eject.ts b/server/typescript/packages/cli/src/lib/runtime-eject.ts index f1c02d362..b9736b5dc 100644 --- a/server/typescript/packages/cli/src/lib/runtime-eject.ts +++ b/server/typescript/packages/cli/src/lib/runtime-eject.ts @@ -41,6 +41,7 @@ export const RUNTIME_ENTRIES: Readonly = { "routes-hono": { runtimeImport: HTTP_RUNTIME_PACKAGE }, service: { runtimeImport: HTTP_RUNTIME_PACKAGE }, "service-routes": { runtimeImport: HTTP_RUNTIME_PACKAGE }, + "service-routes-hono": { runtimeImport: HTTP_RUNTIME_PACKAGE }, }; type Factory = (opts?: unknown) => Generator; diff --git a/server/typescript/packages/cli/test/unit/rules-inert.test.ts b/server/typescript/packages/cli/test/unit/rules-inert.test.ts index 7ea238840..1c42d8f56 100644 --- a/server/typescript/packages/cli/test/unit/rules-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/rules-inert.test.ts @@ -123,6 +123,7 @@ const SERVICE_LAYER: Record = { ], }, "service-routes": { added: [], changed: ["src/generated/acme/purchasing/transport/fastify.ts"] }, + "service-routes-hono": { added: [], changed: ["src/generated/acme/purchasing/transport/hono.ts"] }, }; let withRules: MetaRoot; diff --git a/server/typescript/packages/codegen-ts/src/generator-registry.ts b/server/typescript/packages/codegen-ts/src/generator-registry.ts index a16108cec..cc5861bd1 100644 --- a/server/typescript/packages/codegen-ts/src/generator-registry.ts +++ b/server/typescript/packages/codegen-ts/src/generator-registry.ts @@ -60,6 +60,7 @@ import { prismaSchemaFile, serviceFile, serviceRoutesFile, + serviceRoutesHonoFile, } from "./generators/index.js"; export type GeneratorTier = "native" | "neutral"; @@ -378,6 +379,22 @@ export const generatorRegistry: Record = { configKeys: ["apiPrefix", "extStyle", "outputLayout"], ejectable: ejectable("service-routes"), }, + "service-routes-hono": { + name: "service-routes-hono", + kind: "generator", + layer: "api", + description: "A thin Hono transport per package over the service layer: the service-routes routes on a Hono app.", + tier: "native", + factory: () => serviceRoutesHonoFile(), + factoryExport: "serviceRoutesHonoFile", + options: "filter?, runtimeImport?, target?", + framework: "hono", + requires: ["service", "contract-types"], + runtimePackages: ["@metaobjectsdev/runtime-ts"], + runtimePeers: ["hono"], + configKeys: ["apiPrefix", "extStyle", "outputLayout"], + ejectable: ejectable("service-routes-hono"), + }, "routes-hono": { name: "routes-hono", kind: "generator", diff --git a/server/typescript/packages/codegen-ts/src/generators/index.ts b/server/typescript/packages/codegen-ts/src/generators/index.ts index 237e1225d..7524bb13d 100644 --- a/server/typescript/packages/codegen-ts/src/generators/index.ts +++ b/server/typescript/packages/codegen-ts/src/generators/index.ts @@ -33,6 +33,7 @@ export { rulesNamesFile, type RulesNamesFileOpts } from "./rules-names-file.js"; export { contractTypes, type ContractTypesFileOpts } from "./contract-types-file.js"; export { serviceFile, type ServiceFileOpts } from "./service-file.js"; export { serviceRoutesFile, type ServiceRoutesFileOpts } from "./service-routes-file.js"; +export { serviceRoutesHonoFile, type ServiceRoutesHonoFileOpts } from "./service-routes-hono-file.js"; export { reportExport, type ReportExportOpts } from "./report-export-file.js"; export { promptRender, type PromptRenderOpts } from "./prompt-render-file.js"; export { outputParser, type OutputParserOpts } from "./output-parser-file.js"; diff --git a/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts new file mode 100644 index 000000000..5e656b394 --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/generators/service-routes-hono-file.ts @@ -0,0 +1,37 @@ +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; +import type { EmittedFile, GenContext, Generator } from "../generator.js"; +import { serviceModelOf, serviceRenderContext } from "../service-walk.js"; +import { renderHonoTransport } from "../templates/service-file.js"; + +/** + * The thin Hono transport of the service layer (ADR-0067 §1, layer 5): one file per metadata + * package, `/transport/hono.ts`, the `service-routes` routes on a Hono app. Each route reads a + * request, calls the package's service and answers what it answered. It holds no rules, and it + * imports the service module and the contract types only. Its `getActor(c)` option resolves who a + * request is for; two routes on one method and path are refused when it is generated. The + * built-in twin of `src/reference/service-routes-hono.ts`. + */ +export interface ServiceRoutesHonoFileOpts { + /** Narrow which entities get routes. Keep it the same as the service generator's. */ + filter?: (entity: MetaObject) => boolean; + /** Where the emitted file imports `@metaobjectsdev/runtime-ts/service/hono` from. Absent: the package. */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceRoutesHonoFile(opts?: ServiceRoutesHonoFileOpts): Generator { + const generator: Generator = { + name: "service-routes-hono", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const rc = serviceRenderContext(ctx, "service-routes-hono", opts?.runtimeImport); + return model.map((pkg) => renderHonoTransport(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/owned-runtime.ts b/server/typescript/packages/codegen-ts/src/owned-runtime.ts index b10d1a255..cbb6e1313 100644 --- a/server/typescript/packages/codegen-ts/src/owned-runtime.ts +++ b/server/typescript/packages/codegen-ts/src/owned-runtime.ts @@ -48,6 +48,8 @@ export const HTTP_RUNTIME_MODULES = { // What the service layer's thin Fastify transport (ADR-0067 layer 5) imports: its own entry, so // the flat routes' adapter is untouched. "service-fastify": { subpath: "service/fastify", file: "service/fastify" }, + // Its Hono twin, so a Hono app imports no Fastify. + "service-hono": { subpath: "service/hono", file: "service/hono" }, } as const; export type HttpRuntimeModule = keyof typeof HTTP_RUNTIME_MODULES; diff --git a/server/typescript/packages/codegen-ts/src/reference-templates.ts b/server/typescript/packages/codegen-ts/src/reference-templates.ts index 8e4ea735e..ca75366db 100644 --- a/server/typescript/packages/codegen-ts/src/reference-templates.ts +++ b/server/typescript/packages/codegen-ts/src/reference-templates.ts @@ -21,9 +21,9 @@ export const REFERENCE_GENERATOR_NAMES = [ // The contract types (ADR-0067 layer 1): the modules' shape is the adopter's, while which objects, // values and operations are covered stays the engine walk. "contract-types", - // The service layer and its Fastify transport (ADR-0067 layers 4 and 5): the operations' and the - // routes' shape is the adopter's, while which entities get operations stays the engine walk. - "service", "service-routes", + // The service layer and its Fastify and Hono transports (ADR-0067 layers 4 and 5): the operations' + // and the routes' shape is the adopter's, while which entities get operations stays the engine walk. + "service", "service-routes", "service-routes-hono", // The report export (`?format=csv|json|xml` on a served report): which reports get a module, the // column list and the CSV/XML writers, handed over as one file. "report-export", diff --git a/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts b/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts new file mode 100644 index 000000000..8bc6014fe --- /dev/null +++ b/server/typescript/packages/codegen-ts/src/reference/service-routes-hono.ts @@ -0,0 +1,62 @@ +// REFERENCE TEMPLATE — copy this into your repo (e.g. codegen/generators/service-routes-hono.ts) and own it. +// Then import it LOCALLY in metaobjects.config.ts: +// import { serviceRoutesHonoFile } from "./codegen/generators/service-routes-hono.js"; +// +// RUNTIME: this file executes under whatever runs `meta gen`, and the published CLI's +// shebang is `#!/usr/bin/env node` — so it runs under NODE even in a Bun project. Do not +// reach for `Bun.*` globals here; use `node:` builtins instead. +// targets: the emit step. Replace `renderHonoTransport` in `../templates/service-file.js` +// to change the routes' SHAPE (a hook on every route, another status); keep +// `serviceModelOf` so the routes cover exactly what the service does. +// use-when: the service layer (service.ts) is served over REST on Hono. +// emits: /transport/hono.ts per package with a covered entity: one function, +// `ServiceHonoRoutes`, that mounts the routes on a Hono app with the service +// they call (`blogServiceHonoRoutes(app, { service })`). Each route reads the +// request, calls one operation and answers what it answered; it holds no rules. +// runtime: the emitted file imports the request and reply helpers (`service/hono` of +// @metaobjectsdev/runtime-ts). `meta eject service-routes-hono` copies that source into +// `codegen/runtime/` and the file imports the copy; `runtimeImport: +// "@metaobjectsdev/runtime-ts"` goes back to the package. +// customize: swap the renderer; narrow with `filter` (keep it the same as the service's). +// composes-with: service.ts and contract-types.ts, in the same target. +import { + ownedRuntimeImport, + serviceModelOf, + serviceRenderContext, + type EmittedFile, + type GenContext, + type Generator, +} from "@metaobjectsdev/codegen-ts/engine"; +import { renderHonoTransport } from "../templates/service-file.js"; +import { isMetaObject, type MetaData, type MetaObject } from "@metaobjectsdev/metadata"; + +export interface ServiceRoutesHonoFileOpts { + /** Narrow which entities get routes. Keep it the same as the service generator's. */ + filter?: (entity: MetaObject) => boolean; + /** + * Where the emitted file imports the request and reply helpers from. Absent: the copy + * `meta eject service-routes-hono` placed in `codegen/runtime/`. `"@metaobjectsdev/runtime-ts"` + * imports the package instead. + */ + runtimeImport?: string; + /** Named output target. It must be the entity module's target. */ + target?: string; +} + +export function serviceRoutesHonoFile(opts?: ServiceRoutesHonoFileOpts): Generator { + const generator: Generator = { + name: "service-routes-hono", + generate: (ctx: GenContext): EmittedFile[] => { + const matches = (obj: MetaData): boolean => isMetaObject(obj) && ctx.matches(obj) && (ctx.selected?.(obj) ?? true); + const model = serviceModelOf(ctx.loadedRoot, { matches }); + if (model.length === 0) return []; + const runtimeImport = + opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); + const rc = serviceRenderContext(ctx, "service-routes-hono", runtimeImport); + return model.map((pkg) => renderHonoTransport(pkg, rc)); + }, + }; + if (opts?.filter) generator.filter = opts.filter; + if (opts?.target) generator.target = opts.target; + return generator; +} diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 36f2a0dbe..827495a83 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -353,6 +353,21 @@ export function fastifyTransportPath(pkg: string): string { return dir === "" ? `${TRANSPORT_DIR}/${FASTIFY_TRANSPORT_FILE}` : `${dir}/${TRANSPORT_DIR}/${FASTIFY_TRANSPORT_FILE}`; } +/** The function that mounts package `pkg`'s service routes on a Hono app: `HonoRoutes`. */ +export function serviceHonoRoutesName(pkg: string): string { + const type = serviceTypeName(pkg); + return `${type.charAt(0).toLowerCase()}${type.slice(1)}HonoRoutes`; +} + +/** The Hono transport's file in {@link TRANSPORT_DIR}. */ +export const HONO_TRANSPORT_FILE = "hono.ts"; + +/** Where package `pkg`'s Hono transport goes, relative to the target's outDir. */ +export function honoTransportPath(pkg: string): string { + const dir = packageToPath(pkg); + return dir === "" ? `${TRANSPORT_DIR}/${HONO_TRANSPORT_FILE}` : `${dir}/${TRANSPORT_DIR}/${HONO_TRANSPORT_FILE}`; +} + /** * The import specifier of a runtime module, as seen from the generated file at `fromFile` * (relative to the target's outDir). The service and transport files sit one folder below their diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index 98d494ae3..9eba35c74 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -28,6 +28,8 @@ import { DEFAULT_OUTPUT_LAYOUT, entityOutputPath } from "../import-path.js"; import { effectivePackage } from "../docs-paths.js"; import { fastifyTransportPath, + honoTransportPath, + serviceHonoRoutesName, runtimeSpecifierFrom, serviceFactoryName, serviceTypeName, @@ -751,6 +753,26 @@ function refuseRouteCollisions(routes: readonly MountedRoute[]): void { } } +/** Every route a transport of package `pkg` mounts, before the API prefix. */ +function transportRoutes(pkg: ServicePackage): MountedRoute[] { + const mounted: MountedRoute[] = []; + for (const e of pkg.entities) { + const base = restPath(e.obj); + const item = `${base}/:id`; + mounted.push( + { method: "GET", path: base, what: `${e.obj.name} list` }, + { method: "GET", path: item, what: `${e.obj.name} get` }, + { method: "POST", path: base, what: `${e.obj.name} create` }, + { method: "PATCH", path: item, what: `${e.obj.name} update` }, + { method: "PUT", path: item, what: `${e.obj.name} update` }, + { method: "DELETE", path: item, what: `${e.obj.name} delete` }, + ); + for (const c of e.commands) mounted.push({ method: "POST", path: `${item}/${c.transition.name}`, what: `transition ${e.obj.name}.${c.transition.name}` }); + } + for (const op of pkg.operations) mounted.push({ method: op.method, path: op.path, what: `operation ${op.name}` }); + return mounted; +} + /** The thin Fastify transport of package `pkg`: parse, resolve the actor, call the service, send what it answered. */ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): ServiceFile { const path = fastifyTransportPath(pkg.package); @@ -769,22 +791,7 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): const type = w.useType(serviceTypeName(pkg.package), serviceIndex); const routes = serviceRoutesName(pkg.package); - const mounted: MountedRoute[] = []; - for (const e of pkg.entities) { - const base = restPath(e.obj); - const item = `${base}/:id`; - mounted.push( - { method: "GET", path: base, what: `${e.obj.name} list` }, - { method: "GET", path: item, what: `${e.obj.name} get` }, - { method: "POST", path: base, what: `${e.obj.name} create` }, - { method: "PATCH", path: item, what: `${e.obj.name} update` }, - { method: "PUT", path: item, what: `${e.obj.name} update` }, - { method: "DELETE", path: item, what: `${e.obj.name} delete` }, - ); - for (const c of e.commands) mounted.push({ method: "POST", path: `${item}/${c.transition.name}`, what: `transition ${e.obj.name}.${c.transition.name}` }); - } - for (const op of pkg.operations) mounted.push({ method: op.method, path: op.path, what: `operation ${op.name}` }); - refuseRouteCollisions(mounted); + refuseRouteCollisions(transportRoutes(pkg)); w.doc("What the routes need: the service they call, and who is calling."); w.block(`export interface ${type}RoutesOptions {`, () => { @@ -861,3 +868,145 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): }); return { path, content: w.toString() }; } + +/** The thin Hono transport of package `pkg`: the Fastify transport's routes, on a Hono app. */ +export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): ServiceFile { + const path = honoTransportPath(pkg.package); + const w = new TsWriter(); + const label = pkg.package === "" ? "the model's root package" : `package ${pkg.package}`; + header(w, `${label} — Hono transport (ADR-0067 layer 5)`); + const runtime = runtimeSpecifierFrom(path, "service-hono", ctx); + const serviceRuntime = runtimeSpecifierFrom(path, "service", ctx); + const serviceIndex = contractSpecifier(path, servicePath(pkg.package, SERVICE_INDEX_FILE), ctx.extStyle); + const hono = w.useType("Hono", "hono"); + const context = w.useType("Context", "hono"); + const send = w.use("sendOpResult", runtime); + const guard = w.use("guardRoute", runtime); + const readBody = w.use("readBody", runtime); + const parseQuery = w.use("parseListQueryString", runtime); + const rawQuery = w.use("rawQueryOf", runtime); + const type = w.useType(serviceTypeName(pkg.package), serviceIndex); + const routes = serviceHonoRoutesName(pkg.package); + const prefix = ctx.apiPrefix ?? ""; + const at = (p: string) => str(`${prefix}${p}`); + + refuseRouteCollisions(transportRoutes(pkg)); + + w.doc("What the routes need: the service they call, and who is calling."); + w.block(`export interface ${type}HonoRoutesOptions {`, () => { + w.line(`readonly service: ${type};`); + w.doc( + "Who a request is for (ADR-0067 §7): the app's own resolver, from its own authentication. The", + "service never looks inside the actor; it hands it to the policy, the bodies, the hooks and the", + "event hook. Absent, every operation runs with no actor, which a policy may refuse.", + ); + w.line(`readonly getActor?: (c: ${context}) => A | undefined | Promise;`); + }); + w.blank(); + w.doc( + `Mount the REST routes of ${label} on \`app\`. Each route reads the request, resolves the actor,`, + "calls one operation of the service and answers what it answered; it holds no rules. Call it", + `with the service: \`${routes}(app, { service, getActor })\`.`, + ); + w.block(`export function ${routes}(app: ${hono}, opts: ${type}HonoRoutesOptions): void {`, () => { + w.line("const { service } = opts;"); + w.line(`const actorOf = async (c: ${context}): Promise<${w.useType("OpOptions", serviceRuntime)}> => ({ actor: (await opts.getActor?.(c)) as A | undefined });`); + // Hono tries routes in the order they are added, where Fastify's router prefers a fixed path + // segment to a parameter wherever two paths differ. So the routes are added in that order, + // `/requests/totals` before `/requests/:id`, and answer as the Fastify transport's do. + const routes: Array<{ path: string; emit: () => void }> = []; + const route = (path: string, emit: () => void) => routes.push({ path, emit }); + for (const e of pkg.entities) { + const mods = modulesOf(path, e.obj, ctx); + const create = w.useType(`${e.obj.name}Create`, mods.contract); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); + const o = e.operations; + const base = at(restPath(e.obj)); + const item = at(`${restPath(e.obj)}/:id`); + const id = `c.req.param("id") ?? ""`; + const basePath = restPath(e.obj); + const itemPath = `${basePath}/:id`; + route(basePath, () => { + w.block(`app.get(${base}, ${guard}(async (c) => {`, () => { + w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(c.req.url)), await actorOf(c));`); + w.line( + `return ${send}(c, result, 200, (page) => (page.total === undefined ? page.rows.map(${toWire}) : { rows: page.rows.map(${toWire}), total: page.total }));`, + ); + }, "}));"); + w.block(`app.post(${base}, ${guard}(async (c) => {`, () => { + w.line(`const read = await ${readBody}(c);`); + w.line("if (!read.ok) return read.response;"); + w.line(`return ${send}(c, await service.${o.create}(read.body as ${create}, await actorOf(c)), 201, ${toWire});`); + }, "}));"); + }); + route(itemPath, () => { + w.line(`app.get(${item}, ${guard}(async (c) => ${send}(c, await service.${o.get}(${id}, await actorOf(c)), 200, ${toWire})));`); + w.line("// The update is reachable by PATCH and by PUT, as in every port."); + for (const verb of ["patch", "put"]) { + w.block(`app.${verb}(${item}, ${guard}(async (c) => {`, () => { + w.line(`const read = await ${readBody}(c);`); + w.line("if (!read.ok) return read.response;"); + w.line(`return ${send}(c, await service.${o.update}(${id}, read.body as ${patch}, await actorOf(c)), 200, ${toWire});`); + }, "}));"); + } + w.line(`app.delete(${item}, ${guard}(async (c) => ${send}(c, await service.${o.delete}(${id}, await actorOf(c)), 204)));`); + }); + for (const c of e.commands) { + const path = `${itemPath}/${c.transition.name}`; + route(path, () => + w.line(`app.post(${at(path)}, ${guard}(async (c) => ${send}(c, await service.${c.fn}(${id}, await actorOf(c)), 200, ${toWire})));`), + ); + } + } + for (const op of pkg.operations) { + const key = op.keyed ? op.target!.keyField : undefined; + const fromGet = op.method === "GET" || op.method === "DELETE"; + const readsBody = op.input !== undefined && !fromGet; + const args = [ + ...(key === undefined ? [] : [`c.req.param(${str(key)}) ?? ""`]), + ...(op.input !== undefined ? [`(${fromGet ? "c.req.query()" : "read.body ?? {}"}) as never`] : []), + ...(op.kind === "query" && op.many ? [`${parseQuery}(${rawQuery}(c.req.url))`] : []), + "await actorOf(c)", + ]; + const result = `await service.${op.name}(${args.join(", ")})`; + const wire = outputIsTargetRow(op) ? `, ${w.use(wireMapperName(op.target!.obj.name), serviceIndex)}` : ""; + const status = op.output === undefined && op.kind === "command" ? "204" : "200"; + const head = `app.${op.method.toLowerCase()}(${at(op.path)}, ${guard}(async (c) => `; + route(op.path, () => { + if (!readsBody) { + w.line(`${head}${send}(c, ${result}, ${status}${wire})));`); + return; + } + w.block(`${head}{`, () => { + w.line(`const read = await ${readBody}(c);`); + w.line("if (!read.ok) return read.response;"); + w.line(`return ${send}(c, ${result}, ${status}${wire});`); + }, "}));"); + }); + } + for (const r of [...routes].sort((a, b) => fixedFirst(a.path, b.path))) r.emit(); + }); + return { path, content: w.toString() }; +} + +/** + * Order two route paths so that, wherever two of them could match one request, the one with a + * fixed segment comes first, as Fastify's router prefers it: at the first segment where they + * differ, a parameter sorts after any fixed text, and two fixed segments compare as text. A + * total order, so the emitted file is the same on every run. + */ +function fixedFirst(a: string, b: string): number { + const sa = a.split("/"); + const sb = b.split("/"); + for (let i = 0; i < Math.min(sa.length, sb.length); i++) { + const x = sa[i]!; + const y = sb[i]!; + if (x === y) continue; + const px = x.startsWith(":"); + const py = y.startsWith(":"); + if (px !== py) return px ? 1 : -1; + return x < y ? -1 : 1; + } + return sa.length - sb.length; +} diff --git a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts index 8b1267988..12b02f385 100644 --- a/server/typescript/packages/codegen-ts/test/generator-registry.test.ts +++ b/server/typescript/packages/codegen-ts/test/generator-registry.test.ts @@ -26,6 +26,7 @@ const EXPECTED_NATIVE = [ "contract-types", "service", "service-routes", + "service-routes-hono", "report-export", "prompt-render", "output-parser", @@ -184,13 +185,13 @@ describe("generator-registry (ADR-0021 D3)", () => { }); test("no entry declares a framework — every codegen-ts generator but the route tier is neutral", () => { - // The three `api`-layer route generators (the flat Fastify and Hono routes, and the service - // layer's Fastify transport) are the only framework-bearing entries in this package; + // The four `api`-layer route generators (the flat Fastify and Hono routes, and the service + // layer's Fastify and Hono transports) are the only framework-bearing entries in this package; // `client` (react/tanstack) lives in the other two slices. const framed = Object.values(generatorRegistry) .filter((e) => e.framework !== undefined) .map((e) => `${e.name}=${e.framework}`) .sort(); - expect(framed).toEqual(["routes-hono=hono", "routes=fastify", "service-routes=fastify"]); + expect(framed).toEqual(["routes-hono=hono", "routes=fastify", "service-routes-hono=hono", "service-routes=fastify"]); }); }); diff --git a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts index cca123817..b81cbfcb3 100644 --- a/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-byte-identical.test.ts @@ -30,6 +30,8 @@ import { serviceFile as builtinService } from "../src/generators/service-file.js import { serviceFile as refService } from "../src/reference/service.js"; import { serviceRoutesFile as builtinServiceRoutes } from "../src/generators/service-routes-file.js"; import { serviceRoutesFile as refServiceRoutes } from "../src/reference/service-routes.js"; +import { serviceRoutesHonoFile as builtinServiceRoutesHono } from "../src/generators/service-routes-hono-file.js"; +import { serviceRoutesHonoFile as refServiceRoutesHono } from "../src/reference/service-routes-hono.js"; import { reportExport as builtinReportExport } from "../src/generators/report-export-file.js"; import { reportExport as refReportExport } from "../src/reference/report-export.js"; import { promptRender as builtinPromptRender } from "../src/generators/prompt-render-file.js"; @@ -194,6 +196,7 @@ const PAIRS: Record Generator; ref: () // the copy `meta eject` places in `codegen/runtime/`. service: { builtin: builtinService, ref: () => refService(PKG) }, "service-routes": { builtin: builtinServiceRoutes, ref: () => refServiceRoutes(PKG) }, + "service-routes-hono": { builtin: builtinServiceRoutesHono, ref: () => refServiceRoutesHono(PKG) }, // Emits nothing over the entity-shaped fixtures (none declares a served report); the // describe after the route-composition one runs the pair, with the routes, over the report corpus. "report-export": { builtin: builtinReportExport, ref: refReportExport }, diff --git a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts index 38cb42475..16fe92d0b 100644 --- a/server/typescript/packages/codegen-ts/test/reference-templates.test.ts +++ b/server/typescript/packages/codegen-ts/test/reference-templates.test.ts @@ -13,7 +13,7 @@ import { join } from "node:path"; describe("reference-templates reader", () => { test("exposes the copyable generator names, entity first (reader sentinel)", () => { expect([...REFERENCE_GENERATOR_NAMES]).toEqual([ - "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "contract-types", "service", "service-routes", "report-export", + "entity", "queries", "routes", "routes-hono", "barrel", "names", "rules-names", "contract-types", "service", "service-routes", "service-routes-hono", "report-export", "prompt-render", "output-parser", "extractor", "output-prompt", "render-helper", "requirement-tests", "cube-model", "prisma-schema", "contract-schema", "openapi", "callable", "trace-helper", "shared-model", "docs", "api-docs", "requirements", "agent-docs", "metamodel-docs", diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index e93541a0d..763698359 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -6,9 +6,9 @@ import { describe, expect, test } from "bun:test"; import { join, resolve, dirname } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { InMemoryStringSource, loadUris, MetaDataLoader, type MetaRoot } from "@metaobjectsdev/metadata"; -import { contractTypes, entityFile, queriesFile, serviceFile, serviceRoutesFile } from "../src/generators/index.js"; +import { contractTypes, entityFile, queriesFile, serviceFile, serviceRoutesFile, serviceRoutesHonoFile } from "../src/generators/index.js"; import { defineConfig, runGen, type OutputLayout } from "../src/index.js"; -import { serviceModelOf, serviceRoutesName, serviceTypeName } from "../src/service-walk.js"; +import { serviceHonoRoutesName, serviceModelOf, serviceRoutesName, serviceTypeName } from "../src/service-walk.js"; import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; import type { Generator } from "../src/generator.js"; @@ -102,6 +102,7 @@ describe("service generators — what they write", () => { expect(serviceTypeName("acme::purchase_orders")).toBe("PurchaseOrdersService"); expect(serviceTypeName("")).toBe("ModelService"); expect(serviceRoutesName("acme::purchasing")).toBe("purchasingServiceRoutes"); + expect(serviceHonoRoutesName("acme::purchasing")).toBe("purchasingServiceHonoRoutes"); }); test("a model with no store-backed entity gets no file, and a project that lists none sees no change", async () => { @@ -137,6 +138,31 @@ describe("service generators — what they write", () => { }); }); +describe("service-routes-hono — the service's Hono transport", () => { + const hono = (): Generator[] => [entityFile(), contractTypes(), serviceFile(), serviceRoutesHonoFile()]; + + test("writes transport/hono.ts beside the service, in each layout, and no Fastify transport", async () => { + const root = await load("acme::shop", [entity("Order")]); + for (const layout of ["package", "flat"] as const) { + const paths = servicePaths(await gen(root, hono(), layout)).filter((p) => p.includes("/transport/")); + expect(paths).toEqual(["acme/shop/transport/hono.ts"]); + } + }); + + test("mounts the package's service on a Hono app through the runtime's service/hono helpers", async () => { + const root = await load("acme::shop", [entity("Order")]); + const file = (await gen(root, hono()))["acme/shop/transport/hono.ts"]!; + expect(file).toContain("export function shopServiceHonoRoutes"); + expect(file).toContain('from "@metaobjectsdev/runtime-ts/service/hono";'); + }); + + test("both transports can be written for one service", async () => { + const root = await load("acme::shop", [entity("Order")]); + const paths = servicePaths(await gen(root, [...tier(), serviceRoutesHonoFile()])).filter((p) => p.includes("/transport/")); + expect(paths).toEqual(["acme/shop/transport/fastify.ts", "acme/shop/transport/hono.ts"]); + }); +}); + describe("service walk — which entities get the derived operations", () => { test("over the fitness corpus: concrete, store-backed, single-key entities only", async () => { const result = await loadUris([pathToFileURL(FITNESS).href]); diff --git a/server/typescript/packages/integration-tests/package.json b/server/typescript/packages/integration-tests/package.json index ed5d398a6..3aaaaa27c 100644 --- a/server/typescript/packages/integration-tests/package.json +++ b/server/typescript/packages/integration-tests/package.json @@ -23,6 +23,7 @@ "@metaobjectsdev/test-generators": "workspace:*", "drizzle-orm": "^0.45.1", "fastify": "^5.6.2", + "hono": "^4.6.0", "js-yaml": "^4.1.0", "kysely": "^0.27.4", "pg": "^8.11.5", diff --git a/server/typescript/packages/integration-tests/src/api-contract-api-settings-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-api-settings-generated-server.ts index 27b45ee08..8045910ba 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-api-settings-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-api-settings-generated-server.ts @@ -7,13 +7,14 @@ // Same shape as api-contract-secret-fields-generated-server.ts: runGen over the corpus meta into // a temp dir, provision the table the emitted Drizzle binding reads, mount the EMITTED routes. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; import type pg from "pg"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import { executeSql } from "./postgres-sql.ts"; import { loadMetadataFile } from "./load-metadata.ts"; @@ -30,6 +31,7 @@ export interface GeneratedApiSettingsServerHandle { export async function startGeneratedApiSettingsServer( connectionUri: string, metaPath: string, + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -44,7 +46,7 @@ export async function startGeneratedApiSettingsServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -73,16 +75,16 @@ export const db = drizzle(pool); );`, ); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - const mod = (await import(pathToFileURL(join(tmp, "Item.routes.ts")).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - await fastify.register(mod["itemRoutes"]!); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const mod = (await import(pathToFileURL(join(tmp, "Item.routes.ts")).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + await fastify.register(mod["itemRoutes"]!); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -93,7 +95,7 @@ export const db = drizzle(pool); await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('items','id'), (SELECT MAX("id") FROM "items"));`); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts index ab17b0595..bd8b0a604 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts @@ -10,13 +10,14 @@ // between the HTTP request and the database, which is the point: the wire rule is a property of // the deployed artifact. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import mysql from "mysql2/promise"; import pg from "pg"; import { startLocalD1 } from "./query-scenario-d1.ts"; @@ -93,6 +94,7 @@ export async function startGeneratedCorpusServer( /** The Postgres or MySQL connection URL; unused by SQLite and D1. */ connectionUrl?: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const SERVED = spec.served; const TABLES = spec.tables; @@ -116,27 +118,28 @@ export async function startGeneratedCorpusServer( dbImport: "./db", dialect: engine === "d1" ? "sqlite" : engine, // codegen has no d1 dialect: D1 is SQLite to Drizzle apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()], { interactiveTransactions: engine !== "d1" }), }), metadata: root, }); let emitted: EmittedFiles; try { emitted = indexEmitted(tmp, lr.files, outputLayout); } catch (e) { return fail(e instanceof Error ? e.message : String(e)); } - for (const name of SERVED) if (!emitted.has(`${name}.routes.ts`)) fail(`codegen emitted no ${name}.routes.ts`); + if (lane === "routes") for (const name of SERVED) if (!emitted.has(`${name}.routes.ts`)) fail(`codegen emitted no ${name}.routes.ts`); if (lr.warnings.length > 0) fail(`codegen produced warnings: ${lr.warnings.join("; ")}`); const client = await openEngine(spec, engine, tmp, connectionUrl); for (const stmt of splitStatements(readFileSync(spec.schemaPath[engine], "utf8"))) await client.run(stmt); - const fastify = Fastify(); - for (const name of SERVED) { - const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record; - const registrar = Object.values(mod).find((v): v is (f: FastifyInstance) => Promise => typeof v === "function"); - if (registrar === undefined) fail(`${name}.routes.ts exports no registrar`); - await fastify.register(registrar!); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const { db } = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { db: unknown }; + const served = await serveApi(lane, tmp, db, async (fastify) => { + for (const name of SERVED) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record; + const registrar = Object.values(mod).find((v): v is (f: FastifyInstance) => Promise => typeof v === "function"); + if (registrar === undefined) fail(`${name}.routes.ts exports no registrar`); + await fastify.register(registrar!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -155,7 +158,7 @@ export async function startGeneratedCorpusServer( await client.afterSeed(); }, close: async () => { - await fastify.close(); + await served.close(); await client.close(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-enum-default-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-enum-default-generated-server.ts index 6f50cb3e4..c1b351aa9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-enum-default-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-enum-default-generated-server.ts @@ -4,13 +4,14 @@ // Same shape as api-contract-secret-fields-generated-server.ts: runGen over the corpus meta into // a temp dir, provision the table the emitted Drizzle binding reads, mount the EMITTED routes. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import type pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -30,6 +31,7 @@ export async function startGeneratedEnumDefaultServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -46,7 +48,7 @@ export async function startGeneratedEnumDefaultServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -79,16 +81,16 @@ export const db = drizzle(pool); );`, ); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - const mod = (await import(pathToFileURL(emitted.locate("Ticket.routes.ts")).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - await fastify.register(mod["ticketRoutes"]!); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const mod = (await import(pathToFileURL(emitted.locate("Ticket.routes.ts")).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + await fastify.register(mod["ticketRoutes"]!); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -102,7 +104,7 @@ export const db = drizzle(pool); await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('tickets','id'), (SELECT MAX("id") FROM "tickets"));`); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts index c7fc40051..3b6ba166d 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-generated-server.ts @@ -24,14 +24,14 @@ // within the temp dir, so the generated route is imported byte-for-byte as // emitted — no monkeypatching, no re-call of mountCrudRoutes here. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; -import { contractTypes, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -45,7 +45,6 @@ import type { AuthorRow } from "./api-contract-server.ts"; * hand-rolled ObjectManager server. */ export interface GeneratedServerHandle { - fastify: FastifyInstance; baseUrl: string; truncate(): Promise; applySeed(rows: AuthorRow[]): Promise; @@ -64,7 +63,7 @@ export interface GeneratedServerHandle { * layer behind its thin Fastify transport (`service`, ADR-0067 layers 4 and 5), which must answer * the same corpus the same way. */ -export type GeneratedLane = "routes" | "service"; +export type GeneratedLane = ApiLane; export async function startGeneratedServer( connectionUri: string, @@ -99,9 +98,7 @@ export async function startGeneratedServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: lane === "service" - ? [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()] - : [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -149,27 +146,16 @@ export const db = drizzle(pool); // 4. Import the EMITTED route file unmodified and mount it. const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - if (lane === "service") { - // The service is built at the composition root with its dependencies, and the transport is - // registered with the service: the routes hold no database handle of their own. - const service = (await import(pathToFileURL(join(tmp, "acme/blog/service/index.ts")).href)) as { - createBlogService: (deps: { db: unknown }) => unknown; - }; - const transport = (await import(pathToFileURL(join(tmp, "acme/blog/transport/fastify.ts")).href)) as { - blogServiceRoutes: (f: FastifyInstance, opts: { service: unknown }) => Promise; - }; - await fastify.register(transport.blogServiceRoutes, { service: service.createBlogService({ db: dbMod.db }) }); - } else { + // The service lanes build the service at the composition root with its dependencies and mount + // its transport with it: the routes hold no database handle of their own. + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { const routeUrl = pathToFileURL(emitted.locate("Author.routes.ts")).href; const mod = (await import(routeUrl)) as { authorRoutes: (f: FastifyInstance) => Promise }; await fastify.register(mod.authorRoutes); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + }); + const baseUrl = served.baseUrl; return { - fastify, baseUrl, truncate: async () => { await executeSql(connectionUri, 'TRUNCATE TABLE "authors" RESTART IDENTITY'); @@ -201,7 +187,7 @@ export const db = drizzle(pool); ); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts index 8f89e407c..e2f179fa9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-jsonb-generated-server.ts @@ -12,13 +12,14 @@ // // Mirrors api-contract-generated-server.ts (the Author generated lane). -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -26,7 +27,6 @@ import { loadMetadataFile } from "./load-metadata.ts"; import type { DocumentRow } from "./api-contract-jsonb-server.ts"; export interface GeneratedJsonbServerHandle { - fastify: FastifyInstance; baseUrl: string; truncate(): Promise; applySeed(rows: DocumentRow[]): Promise; @@ -37,6 +37,7 @@ export async function startGeneratedJsonbServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { // Emit INSIDE the package tree (under .gen-tmp/, gitignored) so the emitted // route's bare `@metaobjectsdev/runtime-ts/drizzle-fastify` import resolves @@ -59,7 +60,7 @@ export async function startGeneratedJsonbServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -100,17 +101,16 @@ export const db = drizzle(pool); )`, ); - const routeUrl = pathToFileURL(emitted.locate("Document.routes.ts")).href; - const mod = (await import(routeUrl)) as { documentRoutes: (f: FastifyInstance) => Promise }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - await fastify.register(mod.documentRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const routeUrl = pathToFileURL(emitted.locate("Document.routes.ts")).href; + const mod = (await import(routeUrl)) as { documentRoutes: (f: FastifyInstance) => Promise }; + await fastify.register(mod.documentRoutes); + }); + const baseUrl = served.baseUrl; return { - fastify, baseUrl, truncate: async () => { await executeSql(connectionUri, 'TRUNCATE TABLE "documents" RESTART IDENTITY'); @@ -135,7 +135,7 @@ export const db = drizzle(pool); ); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts index 074c6b34e..6e79d0f25 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-list-query-generated-server.ts @@ -5,13 +5,14 @@ // Same shape as api-contract-api-settings-generated-server.ts: runGen over the corpus meta into // a temp dir, provision the table the emitted Drizzle binding reads, mount the EMITTED routes. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; import type pg from "pg"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import { executeSql } from "./postgres-sql.ts"; import { loadMetadataFile } from "./load-metadata.ts"; @@ -28,6 +29,7 @@ export interface GeneratedListQueryServerHandle { export async function startGeneratedListQueryServer( connectionUri: string, metaPath: string, + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -43,7 +45,7 @@ export async function startGeneratedListQueryServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -76,16 +78,16 @@ export const db = drizzle(pool); );`, ); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - const mod = (await import(pathToFileURL(join(tmp, "Part.routes.ts")).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - await fastify.register(mod["partRoutes"]!); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const mod = (await import(pathToFileURL(join(tmp, "Part.routes.ts")).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + await fastify.register(mod["partRoutes"]!); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -101,7 +103,7 @@ export const db = drizzle(pool); ); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts index b67b18027..beb4fa7d3 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-rules-generated-server.ts @@ -1,6 +1,6 @@ // api-contract-rules-generated-server.ts — boots the GENERATED service of the rules corpus // (ADR-0066 lifecycles, declared operations and permission points; ADR-0067 layers 4 and 5) -// behind its emitted Fastify transport, and drives it against `fixtures/api-contract-conformance/rules/`. +// behind its emitted Fastify or Hono transport, and drives it against `fixtures/api-contract-conformance/rules/`. // // The shells are generated; what an app writes by hand is supplied here, exactly as the corpus // README specifies it so every port's lane implements the same behaviour: the actor resolver, @@ -8,12 +8,12 @@ // rule the shell owns: the check order, the guarded update, `state_managed` and the rollback are // all the emitted code's. -import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; -import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { entityFile } from "@metaobjectsdev/codegen-ts/generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { sql, type SQL } from "drizzle-orm"; import type pg from "pg"; @@ -74,6 +74,8 @@ export async function startGeneratedRulesServer( metaPath: string, configDir: string, outputLayout: OutputLayout = "flat", + /** The rules corpus is served by the service only: on Fastify, or on Hono. */ + lane: Exclude = "service", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -90,7 +92,7 @@ export async function startGeneratedRulesServer( dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), contractTypes(), serviceFile(), serviceRoutesFile()], + generators: apiGenerators(lane, [entityFile()], () => []), }), metadata: root, }); @@ -128,15 +130,8 @@ export const db = drizzle(pool); ); const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const service = (await import(pathToFileURL(join(tmp, "acme/purchasing/service/index.ts")).href)) as { - createPurchasingService: (deps: unknown) => unknown; - }; - const transport = (await import(pathToFileURL(join(tmp, "acme/purchasing/transport/fastify.ts")).href)) as { - purchasingServiceRoutes: (f: FastifyInstance, opts: unknown) => Promise; - }; - + // What the app writes by hand; the database is passed beside it. const deps = { - db: dbMod.db, // Allowed exactly when the actor holds the permission by name. policy: { allows: (permission: string, actor: Actor | undefined) => actor?.grants.includes(permission) ?? false }, bodies: { @@ -172,17 +167,19 @@ export const db = drizzle(pool); }, }; - const getActor = (req: FastifyRequest): Actor | undefined => { - const name = req.headers["x-actor"]; - if (typeof name !== "string" || name === "") return undefined; - const grants = req.headers["x-grants"]; - return { name, grants: typeof grants === "string" && grants !== "" ? grants.split(",").map((g) => g.trim()) : [] }; + // The README's actor resolver, read from the request's headers through each framework's own + // request object (the transport's `getActor`). + const actor = (header: (name: string) => string | undefined): Actor | undefined => { + const name = header("x-actor"); + if (name === undefined || name === "") return undefined; + const grants = header("x-grants"); + return { name, grants: grants !== undefined && grants !== "" ? grants.split(",").map((g) => g.trim()) : [] }; }; - const fastify = Fastify(); - await fastify.register(transport.purchasingServiceRoutes, { service: service.createPurchasingService(deps), getActor }); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async () => { + throw new Error("the rules corpus runs on the service lanes only"); + }, { deps, actor }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -199,7 +196,7 @@ export const db = drizzle(pool); await executeSql(connectionUri, `SELECT setval(pg_get_serial_sequence('purchase_requests','id'), (SELECT MAX("id") FROM "purchase_requests"));`); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-lane.ts b/server/typescript/packages/integration-tests/src/api-lane.ts new file mode 100644 index 000000000..a873dc84f --- /dev/null +++ b/server/typescript/packages/integration-tests/src/api-lane.ts @@ -0,0 +1,150 @@ +// api-lane.ts — which GENERATED API a sub-corpus harness boots: the flat per-entity routes, or +// the service (ADR-0067 layer 4) behind its thin Fastify or Hono transport (layer 5). The shared +// API tests run on all three, which is what proves that moving the rules out of the route into a +// service changed nothing a client can see, on either framework. + +import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify"; +import type { Context } from "hono"; +import { Hono } from "hono"; +import { readdirSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import type { Generator } from "@metaobjectsdev/codegen-ts"; +import { contractTypes, serviceFile, serviceRoutesFile, serviceRoutesHonoFile } from "@metaobjectsdev/codegen-ts/generators"; + +export type ApiLane = "routes" | "service" | "service-hono"; +export const API_LANES: readonly ApiLane[] = ["routes", "service", "service-hono"]; + +/** What a describe block calls the lane. */ +export function laneLabel(lane: ApiLane): string { + return lane === "routes" ? "GENERATED routes lane" : lane === "service" ? "GENERATED service lane" : "GENERATED service lane on Hono"; +} + +/** + * The generators the lane writes its API with. `model` is what both lanes share (the entity + * module and whatever else the corpus needs); `routes` makes the flat route generators, which the + * service lane replaces with the contract types, the service and its transport. + */ +export function apiGenerators( + lane: ApiLane, + model: Generator[], + routes: () => Generator[], + /** The store: Cloudflare D1 holds no transaction across application code (ADR-0067 §4). */ + store: { interactiveTransactions?: boolean } = {}, +): Generator[] { + if (lane === "routes") return [...model, ...routes()]; + const service = store.interactiveTransactions === false ? serviceFile({ interactiveTransactions: false }) : serviceFile(); + return [...model, contractTypes(), service, lane === "service" ? serviceRoutesFile() : serviceRoutesHonoFile()]; +} + +type Factory = (deps: Record) => unknown; + +/** Every emitted `/transport/` under `dir`. */ +function transports(dir: string, file: string): string[] { + const out: string[] = []; + const walk = (d: string): void => { + for (const n of readdirSync(d)) { + const f = join(d, n); + if (statSync(f).isDirectory()) { + if (n !== ".metaobjects") walk(f); + } else if (n === file && d.endsWith("/transport")) out.push(f); + } + }; + walk(dir); + return out.sort(); +} + +/** For each package the service generator wrote: its transport module and its service built with `deps`. */ +async function services(dir: string, file: string, deps: Record): Promise; service: unknown }>> { + const found = transports(dir, file); + if (found.length === 0) throw new Error(`the service lane wrote no transport/${file} under ${dir}`); + const out: Array<{ transport: Record; service: unknown }> = []; + for (const f of found) { + const transport = (await import(pathToFileURL(f).href)) as Record; + const index = (await import(pathToFileURL(join(f, "..", "..", "service", "index.ts")).href)) as Record; + const create = Object.entries(index).find(([k]) => /^create\w+Service$/.test(k))?.[1] as Factory | undefined; + if (create === undefined) throw new Error(`${f}: no service factory beside it`); + out.push({ transport, service: create(deps) }); + } + return out; +} + +/** The one export of `mod` whose name ends with `suffix`. */ +function exported(mod: Record, suffix: string, where: string): T { + const found = Object.entries(mod).find(([k]) => k.endsWith(suffix))?.[1]; + if (found === undefined) throw new Error(`${where}: no export named *${suffix}`); + return found as T; +} + +/** + * What a service lane is built with besides its database: the hand-written dependencies (the + * policy, the bodies, the hooks, the event hook), and who a request is for, read from its headers. + * Each transport is handed a `getActor` written against its own framework's request. + */ +export interface ServiceExtras { + deps?: Record; + actor?: (header: (name: string) => string | undefined) => unknown; +} + +/** + * Mount the service lane's API on `fastify`: for each package the generator wrote, build its + * service with `deps` at the composition root and register its transport with it. The routes hold + * no database handle of their own. Refuses an output with no transport, so a lane cannot pass on + * an empty API. + */ +export async function mountServiceApi( + fastify: FastifyInstance, + dir: string, + db: unknown, + extra: ServiceExtras = {}, +): Promise { + const actor = extra.actor; + const getActor = + actor && + ((req: FastifyRequest) => + actor((name) => { + const v = req.headers[name]; + return typeof v === "string" ? v : undefined; + })); + for (const { transport, service } of await services(dir, "fastify.ts", { db, ...extra.deps })) { + const plugin = exported<(f: FastifyInstance, opts: unknown) => Promise>(transport, "ServiceRoutes", dir); + await fastify.register(plugin, { service, getActor }); + } +} + +/** A server a harness booted: where it listens, and how to stop it. */ +export interface ServedApi { + baseUrl: string; + close(): Promise; +} + +/** + * Boot the lane's API over HTTP. `routes` mounts the flat routes on a Fastify app; the service + * lanes build each package's service with `db` (and `extra.deps`) and mount its Fastify or Hono + * transport, resolving the actor with `extra.getActor` when there is one. + */ +export async function serveApi( + lane: ApiLane, + dir: string, + db: unknown, + mountRoutes: (fastify: FastifyInstance) => Promise, + extra: ServiceExtras = {}, +): Promise { + if (lane !== "service-hono") { + const fastify = Fastify(); + if (lane === "routes") await mountRoutes(fastify); + else await mountServiceApi(fastify, dir, db, extra); + await fastify.ready(); + const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + return { baseUrl, close: () => fastify.close() }; + } + const app = new Hono(); + const actor = extra.actor; + const getActor = actor && ((c: Context) => actor((name) => c.req.header(name))); + for (const { transport, service } of await services(dir, "hono.ts", { db, ...extra.deps })) { + const mount = exported<(a: Hono, opts: unknown) => void>(transport, "HonoRoutes", dir); + mount(app, { service, getActor }); + } + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch }); + return { baseUrl: `http://127.0.0.1:${server.port}`, close: async () => { await server.stop(true); } }; +} diff --git a/server/typescript/packages/integration-tests/test/api-contract-api-settings.test.ts b/server/typescript/packages/integration-tests/test/api-contract-api-settings.test.ts index 6048c2062..93d973211 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-api-settings.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-api-settings.test.ts @@ -18,16 +18,18 @@ import { type ApiSettingsSeed, } from "../src/api-contract-api-settings-generated-server.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; + const SEED = JSON.parse(readFileSync(join(API_CONTRACT_API_SETTINGS_DIR, "seed.json"), "utf8")) as ApiSettingsSeed; const META_PATH = join(API_CONTRACT_API_SETTINGS_DIR, "meta.json"); -describe("api contract api-settings — GENERATED routes lane", () => { +for (const lane of API_LANES) describe(`api contract api-settings — ${laneLabel(lane)}`, () => { for (const scenario of loadScenarios(API_CONTRACT_API_SETTINGS_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startPostgres(); let server: GeneratedApiSettingsServerHandle | null = null; try { - server = await startGeneratedApiSettingsServer(pg.connectionUri, META_PATH); + server = await startGeneratedApiSettingsServer(pg.connectionUri, META_PATH, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-duration.test.ts b/server/typescript/packages/integration-tests/test/api-contract-duration.test.ts index b7a2515b1..be4c62843 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-duration.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-duration.test.ts @@ -21,9 +21,10 @@ import type { ReportSeed } from "../src/api-contract-report-generated-server.ts" import { startMysql, type MysqlContainerHandle } from "../src/mysql-container.ts"; import { OUTPUT_LAYOUTS, postgresFor, type OutputLayout } from "../src/output-layout.ts"; import type { RunningPg } from "../src/postgres-container.ts"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; /** Which output layout a lane generates in, and where its Postgres databases come from. */ -interface Lane { layout: OutputLayout; startPg: (() => Promise) | undefined } +interface Lane { layout: OutputLayout; startPg: (() => Promise) | undefined; api: ApiLane } const SEED = JSON.parse(readFileSync(join(API_CONTRACT_DURATION_DIR, "seed.json"), "utf8")) as ReportSeed; const META_PATH = join(API_CONTRACT_DURATION_DIR, "meta.json"); @@ -50,14 +51,14 @@ async function withServer(engine: CorpusEngine, lane: Lane, fn: (baseUrl: string if (engine === "postgres") { const pg = await lane.startPg!(); try { - const server = await startGeneratedCorpusServer(DURATION, engine, META_PATH, pg.connectionUri, lane.layout); + const server = await startGeneratedCorpusServer(DURATION, engine, META_PATH, pg.connectionUri, lane.layout, lane.api); try { await server.applySeed(SEED); await fn(server.baseUrl); } finally { await server.close(); } } finally { await pg.stop(); } return; } - const server = await startGeneratedCorpusServer(DURATION, engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout); + const server = await startGeneratedCorpusServer(DURATION, engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout, lane.api); try { await server.applySeed(SEED); await fn(server.baseUrl); } finally { await server.close(); } } @@ -65,8 +66,8 @@ const scenarios = loadScenarios(API_CONTRACT_DURATION_SCENARIOS_DIR); test("the duration corpus has scenarios", () => { expect(scenarios.length).toBeGreaterThan(0); }); -for (const layout of OUTPUT_LAYOUTS) for (const engine of ENGINES) describe(`api contract duration — GENERATED routes on ${engine} [${layout}]`, () => { - const lane: Lane = { layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined }; +for (const api of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of ENGINES) describe(`api contract duration — ${laneLabel(api)} on ${engine} [${layout}]`, () => { + const lane: Lane = { layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined, api }; for (const scenario of scenarios) { if (scenario.engines !== undefined && !scenario.engines.includes(engine)) continue; test(scenario.name, async () => { diff --git a/server/typescript/packages/integration-tests/test/api-contract-enum-default.test.ts b/server/typescript/packages/integration-tests/test/api-contract-enum-default.test.ts index be080f713..1a8d90b4f 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-enum-default.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-enum-default.test.ts @@ -15,18 +15,19 @@ import { type GeneratedEnumDefaultServerHandle, type EnumDefaultSeed, } from "../src/api-contract-enum-default-generated-server.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; const SEED = JSON.parse(readFileSync(join(API_CONTRACT_ENUM_DEFAULT_DIR, "seed.json"), "utf8")) as EnumDefaultSeed; const META_PATH = join(API_CONTRACT_ENUM_DEFAULT_DIR, "meta.json"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract enum default — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract enum default — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_ENUM_DEFAULT_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedEnumDefaultServerHandle | null = null; try { - server = await startGeneratedEnumDefaultServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedEnumDefaultServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-jsonb.test.ts b/server/typescript/packages/integration-tests/test/api-contract-jsonb.test.ts index 2e236be8c..1d96800d5 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-jsonb.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-jsonb.test.ts @@ -25,6 +25,7 @@ import { startGeneratedJsonbServer, type GeneratedJsonbServerHandle, } from "../src/api-contract-jsonb-generated-server.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; const SEED = JSON.parse(readFileSync(join(API_CONTRACT_JSONB_DIR, "seed.json"), "utf8")) as { rows: DocumentRow[] }; const META_PATH = join(API_CONTRACT_JSONB_DIR, "meta.json"); @@ -49,14 +50,14 @@ describe("api contract jsonb open-bag — hand-rolled reference lane", () => { } }); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract jsonb open-bag — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract jsonb open-bag — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_JSONB_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedJsonbServerHandle | null = null; try { - server = await startGeneratedJsonbServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedJsonbServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED.rows); await runScenario(scenario, server, openApiCheck("jsonb")); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts b/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts index e5cf79e26..1d8f28c6f 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-list-query.test.ts @@ -21,6 +21,7 @@ import { type GeneratedListQueryServerHandle, type ListQuerySeed, } from "../src/api-contract-list-query-generated-server.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; const SEED = JSON.parse(readFileSync(join(API_CONTRACT_LIST_QUERY_DIR, "seed.json"), "utf8")) as ListQuerySeed; const META_PATH = join(API_CONTRACT_LIST_QUERY_DIR, "meta.json"); @@ -30,13 +31,13 @@ const META_PATH = join(API_CONTRACT_LIST_QUERY_DIR, "meta.json"); // document rightly does not state it. const contractCheck = openApiCheck("list-query", { ignoredQuery: ["cb"] }); -describe("api contract list-query — GENERATED routes lane", () => { +for (const lane of API_LANES) describe(`api contract list-query — ${laneLabel(lane)}`, () => { let pg: Awaited> | null = null; let server: GeneratedListQueryServerHandle | null = null; beforeAll(async () => { pg = await startPostgres(); - server = await startGeneratedListQueryServer(pg.connectionUri, META_PATH); + server = await startGeneratedListQueryServer(pg.connectionUri, META_PATH, lane); }, 120_000); afterAll(async () => { diff --git a/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts b/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts index 629d76de5..e94913d53 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-rules.test.ts @@ -13,6 +13,7 @@ import { join } from "node:path"; import { API_CONTRACT_RULES_DIR, API_CONTRACT_RULES_SCENARIOS_DIR, API_CONTRACT_RULES_SETTINGS_DIR } from "../src/paths.ts"; import { loadScenarios, runScenario } from "../src/api-contract-scenario.ts"; import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { laneLabel } from "../src/api-lane.ts"; import { startGeneratedRulesServer, type GeneratedRulesServerHandle, type RulesSeed } from "../src/api-contract-rules-generated-server.ts"; const SEED = JSON.parse(readFileSync(join(API_CONTRACT_RULES_DIR, "seed.json"), "utf8")) as RulesSeed; @@ -25,7 +26,7 @@ const runs: Array<{ label: string; configDir: string; scenariosDir: string }> = .map((v) => ({ label: `settings/${v}`, configDir: join(API_CONTRACT_RULES_SETTINGS_DIR, v), scenariosDir: join(API_CONTRACT_RULES_SETTINGS_DIR, v, "scenarios") })), ]; -for (const layout of OUTPUT_LAYOUTS) describe(`api contract rules — GENERATED service lane [${layout}]`, () => { +for (const lane of ["service", "service-hono"] as const) for (const layout of OUTPUT_LAYOUTS) describe(`api contract rules — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const run of runs) { for (const scenario of loadScenarios(run.scenariosDir)) { @@ -33,7 +34,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`api contract rules — GENERATED const pg = await startDb(); let server: GeneratedRulesServerHandle | null = null; try { - server = await startGeneratedRulesServer(pg.connectionUri, META_PATH, run.configDir, layout); + server = await startGeneratedRulesServer(pg.connectionUri, META_PATH, run.configDir, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server.baseUrl); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-service.test.ts b/server/typescript/packages/integration-tests/test/api-contract-service.test.ts index f58e15030..b4d0eb59b 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-service.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-service.test.ts @@ -3,9 +3,12 @@ // The same corpus as the generated-routes lane, but the server under test is the emitted service // module (`/service/*.ts`: one function per operation, each write in one transaction with the // model's write rules) behind the emitted thin Fastify transport (`/transport/fastify.ts`), +// and again behind its Hono twin (`/transport/hono.ts`), // built with its database at the composition root. Passing it proves moving the rules out of the // route into a service changed nothing a client can see. import { describeGeneratedLane } from "../src/api-contract-generated-lane.ts"; describeGeneratedLane("service", "service"); +// The same service behind its thin Hono transport. +describeGeneratedLane("service-hono", "service on Hono"); diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts index a72716d48..410be3ad0 100644 --- a/server/typescript/packages/integration-tests/test/service-compile.test.ts +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -1,13 +1,13 @@ // The service tier's compile gate (ADR-0067 layers 4 and 5): the shared fitness corpus and the // api-contract rules corpus, each generated (and the fitness corpus again without interactive // transactions, on SQLite) -// with the entity module, the contract types, the service and its Fastify transport, compiled with +// with the entity module, the contract types, the service and its Fastify and Hono transports, compiled with // the real compiler in both profiles, every dialect and both output layouts. // // A separate gate from codegen-ts's `codegen-compile-conformance.test.ts`, which keeps its program // to drizzle and zod: a service imports the entity module's allowlists and -// `@metaobjectsdev/runtime-ts`, and its transport imports fastify, so its program has to resolve -// all three, which this package does. Behaviour is gated by the api-contract service +// `@metaobjectsdev/runtime-ts`, and its transports import fastify and hono, so its program has to resolve +// all of them, which this package does. Behaviour is gated by the api-contract service // lane (`integration-tests/test/api-contract-service.test.ts`); this asks only whether what it // runs BUILDS, which bun, running the emitted files unchecked, never asks. import { describe, test, expect, setDefaultTimeout } from "bun:test"; @@ -16,14 +16,14 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import ts from "typescript"; import { loadUris, type MetaRoot } from "@metaobjectsdev/metadata"; -import { contractTypes, entityFile, serviceFile, serviceRoutesFile } from "@metaobjectsdev/codegen-ts/generators"; +import { contractTypes, entityFile, serviceFile, serviceRoutesFile, serviceRoutesHonoFile } from "@metaobjectsdev/codegen-ts/generators"; import { runGen, defineConfig, type OutputLayout } from "@metaobjectsdev/codegen-ts"; import { rmSync } from "node:fs"; setDefaultTimeout(120_000); // Inside the package tree, so the emitted imports resolve through this package's node_modules -// (drizzle-orm, zod, fastify and the workspace's runtime-ts), as the generated api-contract lanes do. +// (drizzle-orm, zod, fastify, hono and the workspace's runtime-ts), as the generated api-contract lanes do. const GEN_TMP = join(dirname(fileURLToPath(import.meta.url)), "..", ".gen-tmp"); mkdirSync(GEN_TMP, { recursive: true }); @@ -116,6 +116,7 @@ for (const corpus of CORPORA) describe(`service compile gate — ${corpus.label} contractTypes(), serviceFile("interactiveTransactions" in corpus ? { interactiveTransactions: corpus.interactiveTransactions } : undefined), serviceRoutesFile(), + serviceRoutesHonoFile(), ], }), metadata: root, @@ -127,6 +128,7 @@ for (const corpus of CORPORA) describe(`service compile gate — ${corpus.label} expect(rel).toContain(`${corpus.pkg}/service/index.ts`); for (const p of corpus.present) expect(rel).toContain(p); expect(rel).toContain(`${corpus.pkg}/transport/fastify.ts`); + expect(rel).toContain(`${corpus.pkg}/transport/hono.ts`); writeFileSync(join(dir, "package.json"), JSON.stringify({ type: "module" })); const program = ts.createProgram(files, { ...options, noEmit: true }); const diagnostics = ts.getPreEmitDiagnostics(program).map((d) => { diff --git a/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts b/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts index 96955547d..c178f6643 100644 --- a/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts +++ b/server/typescript/packages/integration-tests/test/service-sqlite-drivers.test.ts @@ -147,7 +147,7 @@ describe("the generated service on Cloudflare D1 (Miniflare)", () => { let local: LocalD1; let service: NotesService; const titles = async (): Promise => - ((await local.d1.prepare("SELECT title FROM notes ORDER BY id").all()) as { results: { title: string }[] }).results.map((r) => r.title); + ((await local.d1.prepare("SELECT title FROM notes ORDER BY id").bind().all()) as { results: { title: string }[] }).results.map((r) => r.title); beforeAll(async () => { local = await startLocalD1(); diff --git a/server/typescript/packages/runtime-ts/package.json b/server/typescript/packages/runtime-ts/package.json index ec39aa536..0ccfd1dae 100644 --- a/server/typescript/packages/runtime-ts/package.json +++ b/server/typescript/packages/runtime-ts/package.json @@ -36,6 +36,11 @@ "types": "./dist/service/fastify.d.ts", "default": "./dist/service/fastify.js" }, + "./service/hono": { + "bun": "./src/service/hono.ts", + "types": "./dist/service/hono.d.ts", + "default": "./dist/service/hono.js" + }, "./hono": { "bun": "./src/hono/index.ts", "types": "./dist/hono/index.d.ts", diff --git a/server/typescript/packages/runtime-ts/src/service/hono.ts b/server/typescript/packages/runtime-ts/src/service/hono.ts new file mode 100644 index 000000000..63ba45640 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/service/hono.ts @@ -0,0 +1,42 @@ +// What a generated thin Hono transport over the service layer imports (ADR-0067 layer 5, +// `meta gen` generator `service-routes-hono`): read the request, call one service operation, send +// what it answered. The Hono twin of `./fastify.ts`, and its own entry, so a Hono app does not +// import Fastify and the flat routes' adapter (`../hono`) stays as it was. + +import type { Context } from "hono"; +import type { ContentfulStatusCode } from "hono/utils/http-status"; +import type { OpResult } from "./index.js"; +import { HTTP_STATUS_BAD_REQUEST, INVALID_JSON_BODY } from "../route-errors.js"; + +export { guardRoute } from "../hono/route-guard.js"; +export { parseListQueryString, rawQueryOf } from "../drizzle-fastify/list-query.js"; + +/** The outcome of reading a request body: the value (undefined when there is none), or the 400 to answer. */ +export type BodyRead = { ok: true; body: unknown } | { ok: false; response: Response }; + +/** + * Read the request body as the Fastify transport receives it. No body, with no JSON content type, + * reads as `undefined`, which the service answers as it answers a missing input. A body that does + * not parse, or an empty one sent as JSON, answers `400 { "error": "invalid_json" }`. + */ +export async function readBody(c: Context): Promise { + const text = await c.req.text(); + const json = (c.req.header("content-type") ?? "").toLowerCase().includes("json"); + if (text === "" && !json) return { ok: true, body: undefined }; + try { + return { ok: true, body: JSON.parse(text) }; + } catch { + return { ok: false, response: c.json(INVALID_JSON_BODY, HTTP_STATUS_BAD_REQUEST) }; + } +} + +/** + * Answer `result`: a failure with the status the service gave it and its body as is, a success + * with `okStatus` and the value mapped to the wire by `toWire` (absent, sent as is). `okStatus` + * 204 sends no body. + */ +export function sendOpResult(c: Context, result: OpResult, okStatus = 200, toWire?: (value: T) => unknown): Response { + if (!result.ok) return c.json(result.error, result.status as ContentfulStatusCode); + if (okStatus === 204) return c.body(null, 204); + return c.json(toWire === undefined ? result.value : toWire(result.value), okStatus as ContentfulStatusCode); +} diff --git a/server/typescript/packages/runtime-ts/test/service-hono.test.ts b/server/typescript/packages/runtime-ts/test/service-hono.test.ts new file mode 100644 index 000000000..d7b974b84 --- /dev/null +++ b/server/typescript/packages/runtime-ts/test/service-hono.test.ts @@ -0,0 +1,67 @@ +// The generated Hono service transport's helpers (`@metaobjectsdev/runtime-ts/service/hono`), +// driven through a real Hono app. The oracle is the api-contract corpus README: a body that does +// not parse answers `400 {"error": "invalid_json"}`, a refusal answers with the status and body the +// service gave it, and a delete answers 204 with no body. +import { describe, expect, test } from "bun:test"; +import { Hono } from "hono"; +import { readBody, sendOpResult } from "../src/service/hono.js"; + +function echoApp(): Hono { + const app = new Hono(); + app.post("/echo", async (c) => { + const read = await readBody(c); + if (!read.ok) return read.response; + return c.json({ body: read.body === undefined ? "" : read.body }); + }); + return app; +} + +describe("service/hono — readBody", () => { + test("a JSON body is parsed", async () => { + const res = await echoApp().request("/echo", { method: "POST", headers: { "content-type": "application/json" }, body: '{"a":1}' }); + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ body: { a: 1 } }); + }); + + test("no body and no JSON content type reads as no input", async () => { + const res = await echoApp().request("/echo", { method: "POST" }); + expect(await res.json()).toEqual({ body: "" }); + }); + + test("a body that does not parse answers 400 invalid_json", async () => { + const res = await echoApp().request("/echo", { method: "POST", headers: { "content-type": "application/json" }, body: "{not json" }); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ error: "invalid_json" }); + }); + + test("an empty body sent as JSON answers 400 invalid_json", async () => { + const res = await echoApp().request("/echo", { method: "POST", headers: { "content-type": "application/json" }, body: "" }); + expect(res.status).toBe(400); + expect(await res.json()).toEqual({ error: "invalid_json" }); + }); +}); + +describe("service/hono — sendOpResult", () => { + const app = new Hono(); + app.get("/ok", (c) => sendOpResult(c, { ok: true, value: { n: 1 } }, 201, (v) => ({ wire: v.n }))); + app.get("/refused", (c) => sendOpResult(c, { ok: false, status: 409, error: { error: "state_conflict" } })); + app.get("/gone", (c) => sendOpResult(c, { ok: true, value: undefined }, 204)); + + test("a success is sent with its status, mapped to the wire", async () => { + const res = await app.request("/ok"); + expect(res.status).toBe(201); + expect(await res.json()).toEqual({ wire: 1 }); + }); + + test("a refusal is sent with the service's status and body", async () => { + const res = await app.request("/refused"); + expect(res.status).toBe(409); + expect(await res.json()).toEqual({ error: "state_conflict" }); + }); + + test("204 sends no body", async () => { + const res = await app.request("/gone"); + expect(res.status).toBe(204); + expect(await res.text()).toBe(""); + }); +}); diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index 742b01a95..bd514cc78 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -18,8 +18,8 @@ and every generator below is a helper. Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in TypeScript, and C# writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: `service` writes each package's derived list, get, create, update and delete in one transaction with -the declared write rules, and `service-routes` the thin Fastify transport over it (the `service` -layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, +the declared write rules, and `service-routes` the thin Fastify transport over it, with +`service-routes-hono` its Hono twin (the `service` layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, with the policy, bodies, hooks and events interfaces, and enforce the rules at run time. The other ports' shells and the per-package choice of generators are later work. ADR-0066's vocabulary is inert at run time in any port whose service generator has not landed. @@ -104,7 +104,7 @@ shell's private state and could call around it. | Mapping (2) | Drizzle tables | EF Core entities and `AppDbContext` | none generated | Exposed `Table` objects | none generated | none: row types derive sqlx `FromRow` | | Data access (3) | query functions taking `db` | none: the context is the data layer | a generated repository implementation on `ObjectManagerDB`, with the guarded update as a method | Exposed repository functions | a generated repository over the abstract `ObjectManager`, implemented by `ObjectManagerDb` | generated repository functions on sqlx, with the guarded update | | Service (4) | a function per operation; `createXService(deps)` | `sealed class XService`, constructor-injected `IXPolicy`, `IXBodies`, `IXEvents`; `services.AddX()` | `@Service` class implementing a generated `XOperations`; constructor injection of `XPolicy` and `XBodies`; `@Transactional` per operation | `class XService(db, policy, bodies, events)`; each operation in `transaction {}`; returns a sealed `OpResult` | a module per package, a function per operation taking an `OpContext`; bodies and policy as `Protocol`s | `struct XService` over generated traits `XPolicy`, `XBodies`, `XEvents`; each operation takes the transaction and returns `Result` | -| Transport (5) | Fastify routes | minimal-API route groups | Spring MVC controllers | Spring controllers | FastAPI router with `Depends` | an axum router | +| Transport (5) | Fastify routes, or Hono routes | minimal-API route groups | Spring MVC controllers | Spring controllers | FastAPI router with `Depends` | an axum router | **Rust gets layered generators like every other port** (ruled 2026-11-20); it is not exempt. The Rust column above is the shape its generators are written to. From 6452eb1243c9d7320f23700e580fa9a779dcb7fc Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 06:58:12 -0500 Subject: [PATCH 06/17] no-mistakes(document): Document Hono transport and service lanes --- docs/features/business-rules.md | 15 +++++++-------- docs/features/own-your-codegen.md | 12 ++++++------ docs/ports/typescript.md | 6 +++--- fixtures/api-contract-conformance/README.md | 9 ++++++++- fixtures/codegen-noop/rules/README.md | 4 ++-- fixtures/generator-registry-conformance/README.md | 5 +++-- server/typescript/packages/runtime-ts/README.md | 5 +++-- .../ADR-0067-layering-and-the-service-seam.md | 5 +++-- 8 files changed, 35 insertions(+), 26 deletions(-) diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 7f2b78384..5d19aa142 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -24,10 +24,10 @@ guarded update a transition writes, `ObjectManager.guardedUpdate`, held to the s persistence scenario `guarded-update.yaml`. The service layer starts in TypeScript: `service` writes each package's derived list, get, create, update and delete, every write in one transaction with the declared write rules, behind a thin Fastify transport (`service-routes`) or Hono transport -(`service-routes-hono`) that answers the shared API tests as the flat routes do (see [The service layer](#the-service-layer-typescript)). It also writes -a command per transition and a shell per declared command and query, and enforces at run time what -this page declares: the permission point, the state check, the guarded update, `state_managed` and -the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are +(`service-routes-hono`) that answers the shared API tests as the flat routes do (see +[The service layer](#the-service-layer-typescript)). It also writes a command per transition and a +shell per declared command and query, and enforces at run time what this page declares: the +permission point, the state check, the guarded update, `state_managed` and the declared errors, held to the shared API tests' `rules/` corpus. The other ports' services are later 1.3.0 work. A lifecycle in a project that wires no service generator will be advised by `verify` once that check lands; until then the flat routes enforce nothing and `verify` says nothing about it. Every flat generator writes byte-identical code for @@ -408,10 +408,9 @@ Both import the entity module (`entity`, for the table and the allowlists) and t (`contract-types`), written to the same target, and `@metaobjectsdev/runtime-ts`'s `service` and `service/fastify` (or `service/hono`) entries; `meta eject service`, `meta eject service-routes` and `meta eject service-routes-hono` copy that source into `codegen/runtime/` as they do for the routes. -The service lanes of the shared API tests run the corpora the flat routes pass against the service -behind each transport, in both layouts: the root corpus, `rules/`, `list-query/`, `api-settings/`, -`enum-default/`, `jsonb/`, and `duration/` on every engine the routes lane runs (D1 with -`interactiveTransactions: false`). +The shared API tests run the service behind each transport over a subset of the corpora the flat +routes pass; the subset and its engines are listed in the +[API contract README](../../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail). ### Transitions, declared operations and what you write by hand diff --git a/docs/features/own-your-codegen.md b/docs/features/own-your-codegen.md index ccb03e5ae..ecaff6712 100644 --- a/docs/features/own-your-codegen.md +++ b/docs/features/own-your-codegen.md @@ -53,7 +53,7 @@ Every stock generator can be used two ways: | | Import it | Own a copy | |---|---|---| | How | `import { entityFile } from "@metaobjectsdev/codegen-ts/generators";` | `meta eject entity`, then `import { entityFile } from "./codegen/generators/entity.js";` | -| In your repo | the import, nothing else | `codegen/generators/entity.ts`, the template modules it calls under `codegen/templates/`, and for `entity`, `routes` and `routes-hono` the HTTP adapter source under `codegen/runtime/` | +| In your repo | the import, nothing else | `codegen/generators/entity.ts`, the template modules it calls under `codegen/templates/`, and, for the generators that copy runtime source (listed under [What `meta eject` hands over](#what-meta-eject-hands-over-and-what-stays-core-typescript)), that source under `codegen/runtime/` | | An upstream fix | arrives when you upgrade the package | arrives when you merge it into your copy | | Changing what it emits | only through its options (`filter`, `target`, `expose`, …) | edit the file | | After a package upgrade | output can change; `meta verify --codegen` reports it until you run `meta gen` | output changes only when your copy does | @@ -175,8 +175,8 @@ falls behind the reference. To drop one: imports your project's template modules where the reference imports the package's). - **A copy with lines of your own is a customization.** Keep it. - For `entity`, `routes` and `routes-hono`, check the adapter too. Ejecting one also - copied the HTTP adapter into `codegen/runtime/`, and a route fix is often made there + For each generator that copies runtime source, check the adapter too. Ejecting one also + copied that source into `codegen/runtime/`, and a route fix is often made there with the generator file left untouched. The text listing marks each of those files `identical`, `DIFFERS` or `not in the package`; `meta gen --list --format json` carries the same comparison as `source.runtimeCopy[]` on the generator's row, with a `verdict` @@ -215,8 +215,8 @@ What the diff in step 4 holds: catching up, and you can read it the way you would read an upgrade, only once step 1 has confirmed the copy carried no change of your own. A line you had removed from the copy comes back in this same diff, and nothing marks it as yours. -- **`entity`, `routes` and `routes-hono` also move one import.** An ejected `entity`, - `routes` or `routes-hono` points its output at the adapter copy in `codegen/runtime/`, +- **The generators that copy runtime source also move one import.** An ejected one + points its output at the copy in `codegen/runtime/`, and the packaged generator imports `@metaobjectsdev/runtime-ts`. So those import lines change, and the project needs `@metaobjectsdev/runtime-ts` installed again (`meta gen --list --format json` gives the @@ -398,7 +398,7 @@ calls it copies the adapter's source too: | `entity` | `entity.ts` | `drizzle-fastify/filter-allowlist.ts` — the `FilterAllowlist` / `SortAllowlist` types the entity module's allowlists are typed by | | `service` | `service.ts` | `service/index.ts` — the store mechanics the generated service modules call (transaction, row lock, write-rule stamping), and `service/rules.ts`, the business-rules mechanics it re-exports | | `service-routes` | `service-routes.ts` | `service/fastify.ts` — the request and reply helpers the generated Fastify transport imports | -| `service-routes-hono` | `service-routes-hono.ts` | `service/hono.ts` — the same helpers for the generated Hono transport, plus the Hono route guard and the shared list-query parser it reaches | +| `service-routes-hono` | `service-routes-hono.ts` | `service/hono.ts` — the same helpers for the generated Hono transport, plus the files it reaches: the Hono route guard, the shared list-query parser and the route-error constants | The ejected generators point their output at that copy (`import { mountCrudRoutes } from "../../codegen/runtime/drizzle-fastify/index.js"`), so diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 74ec287eb..7213596c8 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -762,9 +762,9 @@ around a hand-written body; the policy, bodies, hooks and event hook are passed routes that call it, with a `getActor(request)` option for the app's actor. `serviceRoutesHonoFile()` (stable name `service-routes-hono`) writes the same routes for Hono, `/transport/hono.ts`, with `getActor(c)`. Each needs `entity` and `contract-types` in the -same target. Neither is scaffolded; add them to `generators` or `meta eject` -them. On SQLite the service takes a sync or an async Drizzle driver. A store that holds no -transaction across application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. +same target. None is scaffolded; add them to `generators` or `meta eject` them. On SQLite the +service takes a sync or an async Drizzle driver. A store that holds no transaction across +application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. See [Business rules](../features/business-rules.md#the-service-layer-typescript). ### Prove it works diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 7adc4c522..5de4f7064 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -251,7 +251,7 @@ same per-port integration-tests lane of `scripts/ci-local.sh` — no separate op ### TS lanes (illustrative detail) On the TypeScript port the corpus is driven by **two** lanes, both -against a Postgres testcontainer over HTTP: +against a Postgres testcontainer over HTTP, and by service lanes beside the second (item 3): 1. **Hand-rolled reference lane** (`test/api-contract.test.ts`) — a server the integration-tests package wires up directly. It is the stable reference @@ -265,6 +265,13 @@ against a Postgres testcontainer over HTTP: over HTTP, so the deployed artifact — not a re-implementation — is what gets verified. (Building this lane surfaced and fixed real divergences between the generated routes / `drizzle-fastify` mount and the contract.) +3. **Service lanes** (`test/api-contract-service.test.ts`, `src/api-lane.ts`) — the + generated service (ADR-0067 layer 4) behind its thin Fastify transport, and behind its + Hono transport (layer 5). The `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` + and `duration/` corpora, the root corpus and `rules/` run on them, in both output layouts, + on every engine the generated-routes lane runs for the corpus. D1 generates its service + with `interactiveTransactions: false`. The `projection/`, `report/`, `tph/`, `m2m/`, + `write-through/`, `secret-fields/` and `decimal/` corpora stay on the generated-routes lane. Both lanes live in `server/typescript/packages/integration-tests/test/` and are run by the same `cd server/typescript/packages/integration-tests && bun test` diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index f7d6e8bca..f5ee25f27 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -29,8 +29,8 @@ operations module (and the value object only an operation reaches) does. The service generators (ADR-0067 layers 4 and 5) are the enforcing shells, so they also CHANGE files they write for `without/`: TypeScript's `service` adds a file per derived transition command and per declared operation and changes the package index (its policy, bodies and interfaces) and -the lifecycle entity's create and update (which check its state), and `service-routes` changes the -transport (the new routes). The test pins both lists, and every other file stays byte-identical. +the lifecycle entity's create and update (which check its state), and `service-routes` and `service-routes-hono` change their +transports (the new routes). The test pins both lists, and every other file stays byte-identical. A generator that started reading an operation or a transition by accident would emit something half-built; these tests are what notice: diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index d1595a21f..6d9b2ae2c 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -35,7 +35,7 @@ to make the choice cheap, and `layer` is the axis it is cheap along. | `model` | entity, names, rules-names, contract-types, barrel, dto, value-object | app shape | | `persistence` | queries, prisma-schema, db-context, repository, exposed-table, relations, stored-proc | app shape | | `service` | service | app shape: the operations a route, a job or an agent tool calls (ADR-0067 §5.6) | -| `api` | routes, routes-hono, service-routes, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | +| `api` | routes, routes-hono, service-routes, service-routes-hono, filter-allowlist, validator, spring-config, contract-schema, openapi | app shape | | `client` | form, hooks, grid, grid-hook, client, commands | app shape | | `docs` | docs, api-docs, requirements, agent-docs, metamodel-docs, docs-site, plantuml, html-docs, ai-docs | declared in the project's generator list like any other; nothing is generated that the list does not declare (ADR-0034 Amendment 9) | | `capability` | prompt-render, output-parser, output-prompt, extractor, render-helper, trace-helper, requirement-tests, cube-model, shared-model, template, callable, json-schema, mustache | `meta gen --list --probe` | @@ -138,7 +138,8 @@ mapping; C# so far writes the create and update records). Each other port adds i Two names are **TypeScript only for now**: `service`, layer 4 (one module per package, a function per operation, each write in one transaction with the declared write rules), and `service-routes`, its thin Fastify transport (layer 5). Each other port adds itself with its own -service-layer work. +service-layer work. `service-routes-hono`, its Hono transport, is **TypeScript only by design**, +as `routes-hono` is: Hono is a TypeScript framework. ## Changing the surface diff --git a/server/typescript/packages/runtime-ts/README.md b/server/typescript/packages/runtime-ts/README.md index 531be8a9a..071e84ca4 100644 --- a/server/typescript/packages/runtime-ts/README.md +++ b/server/typescript/packages/runtime-ts/README.md @@ -100,9 +100,10 @@ This package has two tiers, and only the first is a MetaObjects guarantee |---|---|---| | `.` and `./drivers` | **Core** | The metadata-driven runtime: `ObjectManager`, the query builder, the validator runner, the relation / M:N / TPH resolvers, type coercion, the constraint-error mapping, `extractObject`. Conformance-gated; a defect here is a MetaObjects bug. | | `./drizzle-fastify`, `./hono`, `./fastify` | **Helper** | The HTTP adapters that mount CRUD on a web framework: the mount helpers, the filter/sort parser, the error envelopes, pagination. Reference code, not a promise. | +| `./service`, `./service/fastify`, `./service/hono` | **Helper** | The service layer's store mechanics (transaction, write-rule stamping), and the request and reply helpers of its Fastify and Hono transports. Reference code, not a promise. | -Generated route files are the only callers of the helper tier, and they are yours once -you run `meta eject routes` (or `routes-hono`, or `entity` for the allowlist types). Eject +Generated route and transport files are the only callers of the helper tier, and they are yours once +you run `meta eject routes` (or `routes-hono`, `entity` for the allowlist types, or a service generator). Eject copies the adapter **source** the generated code calls — verbatim, from this package's `src/` — into your repo at `codegen/runtime/`, and the ejected generators point their output there. After that your generated and copied code import nothing from this package; diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index bd514cc78..2c41674db 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -19,8 +19,9 @@ Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in T writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: `service` writes each package's derived list, get, create, update and delete in one transaction with the declared write rules, and `service-routes` the thin Fastify transport over it, with -`service-routes-hono` its Hono twin (the `service` layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, -with the policy, bodies, hooks and events interfaces, and enforce the rules at run time. The other +`service-routes-hono` its Hono twin (the `service` layer label of §5.6). The same generators now +write ADR-0066's transitions and declared operations, with the policy, bodies, hooks and events +interfaces, and enforce the rules at run time. The other ports' shells and the per-package choice of generators are later work. ADR-0066's vocabulary is inert at run time in any port whose service generator has not landed. From 8ece420c671e093766527f0f02f3f5753230568f Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 06:58:36 -0500 Subject: [PATCH 07/17] no-mistakes(document): Document Hono transport and service lanes --- .claude/rules/cross-language-porting.md | 2 +- docs/CONFORMANCE.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.claude/rules/cross-language-porting.md b/.claude/rules/cross-language-porting.md index 22bafb024..dd4878474 100644 --- a/.claude/rules/cross-language-porting.md +++ b/.claude/rules/cross-language-porting.md @@ -26,7 +26,7 @@ Preserve the following contracts exactly across all language ports: - Relationship subtypes: `association`, `aggregation`, `composition`. Cardinality via `@cardinality: one|many`; target via `@objectRef`. **M:N (FR-018) slim vocabulary:** `@cardinality: "many"` + `@objectRef` (target) + `@through` (the junction/through entity — a third entity that MUST declare two `identity.reference` children, one per FK side). The relationship's FK fields are **derived** from those references (the `identity.reference` SSOT for FK direction), never restated. `@sourceRefField` (optional) disambiguates a *directed* self-join by naming the source-side FK field on the junction (the other reference is the target side); on a `@cardinality: one` relationship it instead names which of several `identity.reference` nodes onto the same target this relationship navigates, short-circuiting the unique-candidate/`@sourceRefField`/name-pairing ladder (#368, [ADR-0029](spec/decisions/ADR-0029-entity-child-extends-and-via-inference.md) Amendment 1) — an unresolvable 1:N reference set is `ERR_INVALID_RELATIONSHIP` at load. `@symmetric` (optional boolean) marks an *undirected* self-join (union-on-read) — valid only when `@objectRef` == the declaring entity, and mutually exclusive with `@sourceRefField`. The pre-FR-018 `@joinEntity`/`@joinFields` attrs are REMOVED. Validation errors: symmetric-on-hetero / symmetric+sourceRefField → `ERR_BAD_ATTR_VALUE`; junction-missing-two-references / sourceRefField-not-matching / M:N-attr-on-1:N / **junction-unpairable** → `ERR_INVALID_RELATIONSHIP`. **Unpairable means the junction declares its two references but neither resolves to the navigating entity, or neither to the `@objectRef` target** — declaring two references is NOT enough, and the loader now checks WHAT they point at (owner ruling 2026-09-20). It does so by running the real FK derivation and converting its failure, never a parallel re-implementation, so the loader and the derivation cannot drift; scope mirrors codegen's own iteration exactly — every CONCRETE, non-projection object crossed with its EFFECTIVE relationships, NOT deduped by declaration, because pairing is a property of the navigating entity and an inherited M:N can pair from one subtype and not another. Before the ruling this loaded clean and then diverged: TS and C# warned and emitted no traversal route (a silent 404), while Java, Kotlin and Python failed the build. Gated by `fixtures/conformance/error-relationship-m2m-junction-unpairable/`. - Index subtypes: `index.lookup` (non-unique retrieval index; uniqueness is encoded in the **type**: `identity.secondary` = unique alternate key, `index.lookup` = non-unique; `@unique` is REMOVED from `identity.secondary` — `ERR_UNKNOWN_ATTR` on any legacy `@unique`). RDB-physical escapes `@using`/`@expr`/`@where`/`@orders` are registered by the db provider on **both** `identity.secondary` and `index.lookup`. `index.fulltext` / `index.vector` / `index.spatial` are reserved on the subtype axis — documented, NOT registered (YAGNI + 1.0 vocab freeze). See [ADR-0040](spec/decisions/ADR-0040-index-type-and-secondary-key-purity.md). - Layout subtypes: `dataGrid` -- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service` and `service-routes` for derived CRUD, transitions, declared operations and the rules' checks). +- API subtypes: `api.base` / `api.operational` (request/response surface, a root child; subtype axis = interaction model, NEVER protocol — protocol lives in `binding.*` per operation: `binding.rest` (`@method`, `@path`) now, `messaging`/`grpc` reserved; the event/streaming sibling of `api.operational` is reserved). Children: `operation.query` (`@outputRef`, `@many`) / `operation.command` (`@inputRef` → `object.value`, `@transitions`, `@errors`); both take `@inputRef`, `@outputRef`, `@objectRef` (only when the target cannot be derived), `@permission`, `@public`. Derived CRUD (FR-008/009) stays the zero-config default; declared `api` extends it. Org-tier modeling (application/service/network/deployment) stays OUT of core — provider SPI, FQN references. See [ADR-0030](spec/decisions/ADR-0030-declared-api-surface-and-org-tier-boundary.md). **Registered in all five ports since 1.3.0, experimental** (may change in a MINOR) ([ADR-0066](spec/decisions/ADR-0066-business-rules-operations-and-lifecycles.md)), with the loader rules (`error-rules-*` fixtures) and the `verify` rules gate (`fixtures/rules-check-conformance/`); the flat generators generate nothing from it (`fixtures/codegen-noop/rules/`); the ADR-0067 layer generators do (`rules-names` and `contract-types` in TypeScript and C#; the TypeScript `service`, `service-routes` and `service-routes-hono` for derived CRUD, transitions, declared operations and the rules' checks). - Transition subtypes: `transition.action` (a child of `field.enum` on an `object.entity`: `@from`, `@to`, `@condition` in the validators' grammar, `@permission`, `@public`); `transition.base` is the abstract root and `transition.timed` is reserved, not registered. An enum with a transition IS a lifecycle — states, initial state (`@default`), terminal states and each unclaimed transition's command are derived, never declared (ADR-0066). A transition's `@from` lists enum members, not object references: every port's ref-bearing-attr check excludes `transition.*` nodes. A lifecycle belongs to the declaring entity and its `extends` descendants, NEVER to an entity whose field merely `extends` the lifecycle field (filter by the declaring field's owner); a command claims a transition NODE for its target and every entity extending it. Transition and operation names compare case-insensitively; operation names are unique per PACKAGE across its APIs, except one operation declared identically in two APIs (a versioned API). A lifecycle on an entity with no source loads and is inert (no derived command, no permission checks); the writable-source check applies once a source exists. A `@permission` is a dotted identifier path (a package prefix may use `::`); an absent one derives `.` for an operation and `..` for a transition's command. - Currency attrs: `@currency` (ISO 4217), `@locale` (BCP 47) - Schema attrs: `@schema` on `source.rdb` (DB schema name; Postgres default `public`, SQLite rejects non-default values) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index e1acbb9b2..78aa6d0e2 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | From 299c45f38a2d26d222b2a2f2f6b3ece1c99fddc9 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 07:06:17 -0500 Subject: [PATCH 08/17] wip(runtime-ts): extract framework-neutral read-only and M:N reads from the Fastify mounts --- .../src/drizzle-fastify/mount-m2m.ts | 100 +------- .../src/drizzle-fastify/mount-read-only.ts | 223 +++--------------- .../packages/runtime-ts/src/m2m-read.ts | 107 +++++++++ .../packages/runtime-ts/src/read-only-read.ts | 197 ++++++++++++++++ 4 files changed, 342 insertions(+), 285 deletions(-) create mode 100644 server/typescript/packages/runtime-ts/src/m2m-read.ts create mode 100644 server/typescript/packages/runtime-ts/src/read-only-read.ts diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts index ffb804776..0529ac7c3 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts index cec28d7fa..44a142366 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/server/typescript/packages/runtime-ts/src/m2m-read.ts b/server/typescript/packages/runtime-ts/src/m2m-read.ts new file mode 100644 index 000000000..57bd984c0 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/server/typescript/packages/runtime-ts/src/read-only-read.ts b/server/typescript/packages/runtime-ts/src/read-only-read.ts new file mode 100644 index 000000000..ee49798d3 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage { + readonly rows: Record[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} From 57b7446746eac059a2e9b418ef91e455e8eabfac Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 07:11:29 -0500 Subject: [PATCH 09/17] wip(codegen-ts,runtime-ts): service coverage walk, read-only transport helpers, registry README counts --- fixtures/codegen-noop/rules/README.md | 7 +- .../generator-registry-conformance/README.md | 10 +- .../packages/codegen-ts/src/service-walk.ts | 130 ++++++++++++++++-- .../runtime-ts/src/service/fastify.ts | 34 ++++- .../packages/runtime-ts/src/service/hono.ts | 32 ++++- .../packages/runtime-ts/src/service/index.ts | 33 ++++- 6 files changed, 222 insertions(+), 24 deletions(-) diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index f5ee25f27..153887902 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -9,9 +9,10 @@ Two models that differ ONLY by the business-rules vocabulary: (one carrying a `binding.rest`) take those objects as input and output. It is derived from the positive conformance fixture `fixtures/conformance/rules-purchase-request/`. -1.3.0 registers the vocabulary, validates it at load and checks it in `verify`. The -generated services and enforcing shells that act on it are later work, so until they land -the two models produce the same output everywhere: +1.3.0 registers the vocabulary, validates it at load and checks it in `verify`. Apart from the +generators named below that read it (the rules names, the contract types and the TypeScript +service generators `service`, `service-routes` and `service-routes-hono`), the two models +produce the same output everywhere: - Every code generator in every port writes the same files, byte for byte. - TypeScript `meta migrate` proposes the same schema. diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index 6d9b2ae2c..e3d41c817 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -135,11 +135,11 @@ shapes, the operations' inputs and outputs, and the wire error bodies, with no p mapping; C# so far writes the create and update records). Each other port adds itself to their `ports` with its own rules-layer work. -Two names are **TypeScript only for now**: `service`, layer 4 (one module per package, a -function per operation, each write in one transaction with the declared write rules), and -`service-routes`, its thin Fastify transport (layer 5). Each other port adds itself with its own -service-layer work. `service-routes-hono`, its Hono transport, is **TypeScript only by design**, -as `routes-hono` is: Hono is a TypeScript framework. +Three names are **TypeScript only**. Two are TypeScript only for now: `service`, layer 4 (one +module per package, a function per operation, each write in one transaction with the declared +write rules), and `service-routes`, its thin Fastify transport (layer 5); each other port adds +itself with its own service-layer work. The third, `service-routes-hono`, its Hono transport, is +TypeScript only by design, as `routes-hono` is: Hono is a TypeScript framework. ## Changing the surface diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 827495a83..472e6df91 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -5,12 +5,16 @@ // operations are named and where their files go stays packaged while the files' shape is the // adopter's. // -// Covered: every concrete `object.entity` whose primary source is a writable `source.rdb`, keyed -// by a single-field primary identity. It gets the five derived operations (list, get, create, -// update and delete), a command per transition that derives one (ADR-0066 §2, under -// `rules.lifecycle.commands`), and the package's declared operations that act on a covered entity -// or on none. Not covered yet: a write-through entity (reads through a replica view), a -// single-table (TPH) hierarchy, many-to-many traversal, projections and reports. +// Covered: every object the flat routes serve, keyed by a single-field primary identity where it +// has a key. A concrete `object.entity` whose primary source is a writable `source.rdb` gets the +// five derived operations (list, get, create, update and delete); a write-through entity reads +// through its replica view and writes its table. A single-table (TPH) hierarchy's discriminator +// base gets a polymorphic list and get, and each concrete subtype the five operations, scoped to its +// discriminator value. A projection gets a list, and a get when it has a key; a served report a +// list (with its row cap, and its export when `report-export` is wired). Every many-to-many +// relationship of a covered entity gets a traversal query. An entity also gets a command per +// transition that derives one (ADR-0066 §2, under `rules.lifecycle.commands`), and the package's +// declared operations that act on a covered entity or on none. import { BINDING_ATTR_METHOD, @@ -57,8 +61,12 @@ import type { GenContext } from "./generator.js"; import { effectivePackage } from "./docs-paths.js"; import { hasWritableRdbSource } from "./source-detect.js"; import { isAbstract } from "./instance-artifacts.js"; -import { isWriteThrough } from "./projection/projection-detector.js"; -import { declaresTphDiscriminator, isTphSubtype } from "./tph.js"; +import { isProjection, isWriteThrough } from "./projection/projection-detector.js"; +import { declaresTphDiscriminator, isTphSubtype, tphDiscriminatorBase, tphDiscriminatorPin, tphStorageObject } from "./tph.js"; +import { isReport } from "./source-detect.js"; +import { itemRouteField, servesReadApi } from "./api-surface.js"; +import { tphPlan } from "./templates/tph-discriminator.js"; +import { buildRelationMap, type RelationMap } from "./relation-resolver.js"; import { pkInfoOf } from "./pk-resolver.js"; import { listFnName, toCamelCase, toPascalCase } from "./naming.js"; @@ -98,6 +106,35 @@ export interface ServiceTransitionCommand { readonly permission: string | undefined; } +/** What kind of object a service entity is: a writable entity, or a read-only projection or report. */ +export type ServiceObjectKind = "entity" | "projection" | "report"; + +/** A single-table subtype's scope: its rows are the base table's rows whose `field` holds `value`. */ +export interface ServiceDiscriminator { + readonly field: string; + readonly value: string; +} + +/** A many-to-many traversal of a covered entity (FR-018): `GET /:id/`. */ +export interface ServiceRelation { + /** The service function: `Of` (`tagsOfPost`). */ + readonly fn: string; + /** The relationship's name: the path segment. */ + readonly name: string; + readonly junction: MetaObject; + /** The junction's field holding the source key, and the one holding the target key. */ + readonly sourceJoinField: string; + readonly targetJoinField: string; + /** The object whose table holds the target rows (a single-table subtype's base). */ + readonly target: MetaObject; + /** The objects whose fields the target rows carry: the target, and a TPH base's subtypes. */ + readonly targetObjects: readonly MetaObject[]; + /** The target is a single-table subtype: only rows of its discriminator value. */ + readonly targetDiscriminator: ServiceDiscriminator | undefined; + /** Undirected self-join: both junction columns are read. */ + readonly symmetric: boolean; +} + /** One entity's service operations. */ export interface ServiceEntity { readonly obj: MetaObject; @@ -105,6 +142,24 @@ export interface ServiceEntity { readonly keyField: string; /** The function name of each derived operation (`listAuthors`, `getAuthor`, ...). */ readonly operations: Readonly>; + /** The derived operations it has, in `DERIVED_OPERATIONS` order. */ + readonly verbs: readonly DerivedOperation[]; + readonly kind: ServiceObjectKind; + /** + * The object whose entity module exports the table the operations read and write: the object + * itself, or a single-table subtype's discriminator base. A projection or report reads its view. + */ + readonly storage: MetaObject; + /** A write-through entity: reads go through its replica view, and a write is read back through it. */ + readonly readView: boolean; + /** The REST path, before the API prefix (`/auths/bridge` for a single-table subtype). */ + readonly path: string; + /** A single-table subtype's scope. */ + readonly discriminator: ServiceDiscriminator | undefined; + /** The objects of its single-table hierarchy (the base and every concrete subtype), else just itself. */ + readonly hierarchy: readonly MetaObject[]; + /** Its many-to-many traversals. */ + readonly relations: readonly ServiceRelation[]; /** The entity's lifecycles: the generic write path may not move them (409 `state_managed`). */ readonly lifecycles: readonly ServiceLifecycle[]; /** The commands its transitions derive, in lifecycle order. */ @@ -161,14 +216,59 @@ export interface ServiceWalkOpts { matches?: (obj: MetaObject) => boolean; } -/** Whether `obj` gets the derived service operations. */ +/** Whether `obj` gets service operations: every object the flat routes serve, with a single key where it has one. */ export function hasServiceOperations(obj: MetaObject): boolean { - if (obj.subType !== OBJECT_SUBTYPE_ENTITY || isAbstract(obj)) return false; - if (!hasWritableRdbSource(obj) || isWriteThrough(obj)) return false; - if (declaresTphDiscriminator(obj) || isTphSubtype(obj)) return false; + if (!servesReadApi(obj)) return false; + if (isProjection(obj)) return true; + if (obj.subType !== OBJECT_SUBTYPE_ENTITY || !hasWritableRdbSource(obj)) return false; return serviceKeyField(obj) !== undefined; } +/** The verbs, storage, path and scope of a covered object. */ +function shapeOf(obj: MetaObject, root: MetaData): Pick { + const path = restPath(obj); + if (isProjection(obj)) { + const keyed = itemRouteField(obj) !== undefined; + return { kind: isReport(obj) ? "report" : "projection", verbs: keyed ? ["list", "get"] : ["list"], storage: obj, readView: false, path, discriminator: undefined, hierarchy: [obj] }; + } + const pin = tphDiscriminatorPin(obj); + const base = tphDiscriminatorBase(obj); + if (pin !== undefined && base !== undefined) { + const plan = tphPlan(base, root as never); + const hierarchy = plan === null ? [base, obj] : [base, ...plan.subtypes.map((st) => st.entity)]; + return { kind: "entity", verbs: DERIVED_OPERATIONS, storage: base, readView: false, path, discriminator: { field: pin.fieldName, value: pin.value }, hierarchy }; + } + const plan = declaresTphDiscriminator(obj) ? tphPlan(obj, root as never) : null; + if (plan !== null) { + // The polymorphic base is read-only by construction: the union has no single writable shape. + return { kind: "entity", verbs: ["list", "get"], storage: obj, readView: false, path, discriminator: undefined, hierarchy: [obj, ...plan.subtypes.map((st) => st.entity)] }; + } + return { kind: "entity", verbs: DERIVED_OPERATIONS, storage: obj, readView: isWriteThrough(obj), path, discriminator: undefined, hierarchy: [obj] }; +} + +/** The many-to-many traversals `obj` resolves (the relation map's rule, the flat routes' too). */ +function relationsOf(obj: MetaObject, relationMap: RelationMap, root: MetaData): ServiceRelation[] { + const out: ServiceRelation[] = []; + for (const e of relationMap.get(obj.name) ?? []) { + if (e.junction === undefined || e.sourceJoinField === undefined || e.targetJoinField === undefined) continue; + const target = tphStorageObject(e.target); + const plan = declaresTphDiscriminator(target) ? tphPlan(target, root as never) : null; + const pin = tphDiscriminatorPin(e.target); + out.push({ + fn: `${toCamelCase(e.name)}Of${obj.name}`, + name: e.name, + junction: e.junction, + sourceJoinField: e.sourceJoinField, + targetJoinField: e.targetJoinField, + target, + targetObjects: plan === null ? [target] : [target, ...plan.subtypes.map((st) => st.entity)], + targetDiscriminator: pin === undefined ? undefined : { field: pin.fieldName, value: pin.value }, + symmetric: e.symmetric === true, + }); + } + return out; +} + /** The single field a service operation addresses a row by, or undefined for a composite or absent key. */ export function serviceKeyField(obj: MetaObject): string | undefined { const pk = pkInfoOf(obj); @@ -285,9 +385,13 @@ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): Serv return b; }; const covered = new Map(); + const relationMap = buildRelationMap(root as never); for (const obj of root.children().filter(isMetaObject)) { if (!hasServiceOperations(obj) || !matches(obj)) continue; - const e: ServiceEntity = { obj, keyField: serviceKeyField(obj)!, operations: serviceOperationNames(obj), ...entityRules(obj, claimed, settings) }; + const shape = shapeOf(obj, root); + const rules = shape.kind === "entity" ? entityRules(obj, claimed, settings) : { lifecycles: [], commands: [] }; + const keyField = shape.kind === "entity" ? serviceKeyField(obj)! : (itemRouteField(obj) ?? "id"); + const e: ServiceEntity = { obj, keyField, operations: serviceOperationNames(obj), ...shape, relations: relationsOf(obj, relationMap, root), ...rules }; covered.set(obj, e); bucket(effectivePackage(obj) ?? "").entities.push(e); } diff --git a/server/typescript/packages/runtime-ts/src/service/fastify.ts b/server/typescript/packages/runtime-ts/src/service/fastify.ts index efad5f595..adc1ecd3f 100644 --- a/server/typescript/packages/runtime-ts/src/service/fastify.ts +++ b/server/typescript/packages/runtime-ts/src/service/fastify.ts @@ -4,7 +4,8 @@ // adapter (`../drizzle-fastify`) and what `meta eject routes` copies of it stay as they were. import type { FastifyReply } from "fastify"; -import type { OpResult } from "./index.js"; +import type { OpResult, ReadOnlyPage } from "./index.js"; +import { EXPORT_CONTENT_TYPES, exportContentDisposition, renderExport, type ReportExportSpec } from "../drizzle-fastify/report-export.js"; export { withContractErrorHandler } from "../drizzle-fastify/route-error-handler.js"; export { parseListQueryString, rawQueryOf } from "../drizzle-fastify/list-query.js"; @@ -24,3 +25,34 @@ export function sendOpResult( if (okStatus === 204) return reply.code(204).send(); return reply.code(okStatus).send(toWire === undefined ? result.value : toWire(result.value)); } + +/** The body a read-only object answers a write with: `405 { "error": "method_not_allowed" }`. */ +export function methodNotAllowed(method: string, resource: "projection" | "report"): { error: string; message: string } { + return { error: "method_not_allowed", message: `${method} is not supported on a ${resource} (read-only).` }; +} + +/** + * Send a read-only list page: the rows mapped to the wire, as a `{ rows, total }` envelope when + * the count was asked for; with an export spec and an export format asked (`?format=`), the rows + * rendered in that format as a download named after `path`'s last segment. + */ +export function sendListPage( + reply: FastifyReply, + result: OpResult, + toWire: (row: Record) => unknown, + exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, +): FastifyReply { + if (!result.ok) return reply.code(result.status).send(result.error); + const page = result.value; + const rows = page.rows.map(toWire); + if (exportOf !== undefined && page.format !== undefined) { + // Rendered before any header is set, so a writer that throws leaves no download headers on + // the 500. A Buffer, so Fastify sends the contract's content type exactly. + const body = Buffer.from(renderExport(exportOf.spec, page.format, rows as Record[], page.total), "utf8"); + return reply + .header("content-disposition", exportContentDisposition(exportOf.path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]) + .send(body); + } + return reply.send(page.total === undefined ? rows : { rows, total: page.total }); +} diff --git a/server/typescript/packages/runtime-ts/src/service/hono.ts b/server/typescript/packages/runtime-ts/src/service/hono.ts index 63ba45640..50cd5f585 100644 --- a/server/typescript/packages/runtime-ts/src/service/hono.ts +++ b/server/typescript/packages/runtime-ts/src/service/hono.ts @@ -5,7 +5,8 @@ import type { Context } from "hono"; import type { ContentfulStatusCode } from "hono/utils/http-status"; -import type { OpResult } from "./index.js"; +import type { OpResult, ReadOnlyPage } from "./index.js"; +import { EXPORT_CONTENT_TYPES, exportContentDisposition, renderExport, type ReportExportSpec } from "../drizzle-fastify/report-export.js"; import { HTTP_STATUS_BAD_REQUEST, INVALID_JSON_BODY } from "../route-errors.js"; export { guardRoute } from "../hono/route-guard.js"; @@ -40,3 +41,32 @@ export function sendOpResult(c: Context, result: OpResult, okStatus = 200, if (okStatus === 204) return c.body(null, 204); return c.json(toWire === undefined ? result.value : toWire(result.value), okStatus as ContentfulStatusCode); } + +/** Answer a write to a read-only object: `405 { "error": "method_not_allowed" }`. */ +export function methodNotAllowed(c: Context, resource: "projection" | "report"): Response { + return c.json({ error: "method_not_allowed", message: `${c.req.method} is not supported on a ${resource} (read-only).` }, 405); +} + +/** + * Answer a read-only list page: the rows mapped to the wire, as a `{ rows, total }` envelope when + * the count was asked for; with an export spec and an export format asked (`?format=`), the rows + * rendered in that format as a download named after `path`'s last segment. + */ +export function sendListPage( + c: Context, + result: OpResult, + toWire: (row: Record) => unknown, + exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, +): Response { + if (!result.ok) return c.json(result.error, result.status as ContentfulStatusCode); + const page = result.value; + const rows = page.rows.map(toWire); + if (exportOf !== undefined && page.format !== undefined) { + const body = renderExport(exportOf.spec, page.format, rows as Record[], page.total); + return c.body(body, 200, { + "content-disposition": exportContentDisposition(exportOf.path, page.format), + "content-type": EXPORT_CONTENT_TYPES[page.format], + }); + } + return c.json(page.total === undefined ? rows : { rows, total: page.total }); +} diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts index bf93722bf..cad712fb5 100644 --- a/server/typescript/packages/runtime-ts/src/service/index.ts +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -20,6 +20,9 @@ import { coerceIdForColumn, contractErrorCode, extractRowCount, firstRow, isTrut import { parseFilterParams } from "../drizzle-fastify/filter-parser.js"; import { FilterParseError, pageLimit, type PageSize } from "../drizzle-fastify/list-params.js"; import type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; +import { ReportTooLargeError } from "../drizzle-fastify/list-params.js"; +import { ReportExportError } from "../drizzle-fastify/report-export.js"; +import { InvalidIdError } from "../read-only-read.js"; export type { SqlDialect } from "../sql-dialect.js"; export type { PageSize } from "../drizzle-fastify/list-params.js"; @@ -215,6 +218,9 @@ async function syncSqliteTransaction(handle: Drizzle, nested: boolean, fn: (t function failure(e: unknown): OpResult { if (e instanceof Refusal) return { ok: false, status: e.status, error: e.body }; + if (e instanceof InvalidIdError) return { ok: false, status: 400, error: { error: "invalid_id" } }; + if (e instanceof ReportTooLargeError) return { ok: false, status: 400, error: { error: "report_too_large", maxRows: e.maxRows } }; + if (e instanceof ReportExportError) return { ok: false, status: e.status, error: e.body }; if (e instanceof FilterParseError) { return { ok: false, status: 400, error: { error: contractErrorCode(e.code), ...(e.details ?? {}) } }; } @@ -326,6 +332,11 @@ export interface ListSpec { readonly pagination?: PageSize; /** The key field a list with no `sort` is ordered by, so a page is stable. Default `id`. */ readonly keyField?: string; + /** + * A condition every row of the list meets besides the query's filter: a single-table subtype's + * discriminator (`scopeCondition`), so its list answers its own rows only. + */ + readonly scope?: SQL; } /** A page of a list, and the count of every row the filter matches when the query asked for it (`withCount`). */ @@ -354,7 +365,7 @@ export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect, }); - const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + const where = and(...[parsed.where, parsed.searchWhere, spec.scope].filter((c): c is SQL => c !== undefined)); let q = db.select().from(src).$dynamic(); if (where) q = q.where(where); if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); @@ -368,3 +379,23 @@ export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, const countRow = (await cq)[0] as { c: number } | undefined; return { rows, total: countRow?.c ?? 0 }; } + +/** The condition a single-table subtype's rows meet: its discriminator `field` holds `value`. */ +export function scopeCondition(table: Drizzle, field: string, value: string): SQL { + return eq(table[field], value); +} + +/** + * The row a write to a write-through entity's table just wrote, read back through its replica + * view by key, so the answer carries the view's derived columns. Answers the written row when the + * view has none (it never 500s a write that succeeded). + */ +export async function readThroughView(db: Drizzle, view: Drizzle, keyField: string, written: Record): Promise> { + return (await readOne(db, view, eq(view[keyField], written[keyField]))) ?? written; +} + +// How a read-only object (a projection, a served report) and a many-to-many traversal are read: the +// same functions the flat routes call, so the service answers what they answer. +export { readOnlyGet, readOnlyList, type ReadOnlyPage, type ReadOnlySpec } from "../read-only-read.js"; +export { m2mRelated, type M2mSpec } from "../m2m-read.js"; +export type { ReportExportSpec } from "../drizzle-fastify/report-export.js"; From ab5d255e36c4662ad9e57523f3514968bd4af959 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 07:21:19 -0500 Subject: [PATCH 10/17] wip(codegen-ts): service operations for read-only, write-through, TPH and M:N; write-through on every lane --- .../codegen-ts/src/generators/service-file.ts | 5 +- .../codegen-ts/src/reference/service.ts | 5 +- .../packages/codegen-ts/src/service-walk.ts | 6 +- .../codegen-ts/src/templates/service-file.ts | 443 +++++++++++++++--- .../codegen-ts/test/service-file.test.ts | 26 +- ...contract-write-through-generated-server.ts | 30 +- .../test/api-contract-write-through.test.ts | 5 +- .../packages/runtime-ts/src/read-only-read.ts | 4 +- .../runtime-ts/src/service/fastify.ts | 6 +- .../packages/runtime-ts/src/service/hono.ts | 6 +- .../packages/runtime-ts/src/service/index.ts | 5 + 11 files changed, 436 insertions(+), 105 deletions(-) diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index b11cd9a25..65c13430b 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -37,6 +37,8 @@ export interface ServiceFileOpts { * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. */ interactiveTransactions?: boolean; + /** The most rows a served report answers with no `limit` (the routes generator's option of the same name). Default 10000. */ + reportMaxRows?: number; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -48,7 +50,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service", opts?.runtimeImport); const interactiveTransactions = opts?.interactiveTransactions !== false; - return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); + const reportMaxRows = opts?.reportMaxRows; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions, ...(reportMaxRows === undefined ? {} : { reportMaxRows }) }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/reference/service.ts b/server/typescript/packages/codegen-ts/src/reference/service.ts index 0169ac798..e896df46a 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service.ts @@ -55,6 +55,8 @@ export interface ServiceFileOpts { * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. */ interactiveTransactions?: boolean; + /** The most rows a served report answers with no `limit` (the routes generator's option of the same name). Default 10000. */ + reportMaxRows?: number; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -68,7 +70,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); const rc = serviceRenderContext(ctx, "service", runtimeImport); const interactiveTransactions = opts?.interactiveTransactions !== false; - return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); + const reportMaxRows = opts?.reportMaxRows; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions, ...(reportMaxRows === undefined ? {} : { reportMaxRows }) }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 472e6df91..9e55884ad 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -209,6 +209,8 @@ export interface ServicePackage { * service generator's `interactiveTransactions` option, not the model's. Absent: true. */ readonly interactiveTransactions?: boolean; + /** A served report's row cap: the service generator's `reportMaxRows` option. Absent: 10000, the same in every port. */ + readonly reportMaxRows?: number; } export interface ServiceWalkOpts { @@ -252,7 +254,7 @@ function relationsOf(obj: MetaObject, relationMap: RelationMap, root: MetaData): for (const e of relationMap.get(obj.name) ?? []) { if (e.junction === undefined || e.sourceJoinField === undefined || e.targetJoinField === undefined) continue; const target = tphStorageObject(e.target); - const plan = declaresTphDiscriminator(target) ? tphPlan(target, root as never) : null; + const plan = declaresTphDiscriminator(e.target) ? tphPlan(e.target, root as never) : null; const pin = tphDiscriminatorPin(e.target); out.push({ fn: `${toCamelCase(e.name)}Of${obj.name}`, @@ -261,7 +263,7 @@ function relationsOf(obj: MetaObject, relationMap: RelationMap, root: MetaData): sourceJoinField: e.sourceJoinField, targetJoinField: e.targetJoinField, target, - targetObjects: plan === null ? [target] : [target, ...plan.subtypes.map((st) => st.entity)], + targetObjects: plan === null ? [e.target] : [e.target, ...plan.subtypes.map((st) => st.entity)], targetDiscriminator: pin === undefined ? undefined : { field: pin.fieldName, value: pin.value }, symmetric: e.symmetric === true, }); diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index 9eba35c74..7480366a0 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -17,7 +17,9 @@ // back. Reads open no write transaction and call no hooks. The mechanics are // `@metaobjectsdev/runtime-ts/service`; what runs, against which schema and table, is written here. -import type { MetaObject } from "@metaobjectsdev/metadata"; +import { TYPE_FIELD, resolveColumnName, type MetaObject } from "@metaobjectsdev/metadata"; +import { pkInfoOf } from "../pk-resolver.js"; +import { hasInsertRefinements } from "./zod-validators.js"; import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; import { withExtIfRelative, type RenderContext } from "../render-context.js"; import { decimalColumnsLine, knownFieldsLine, paginationLine, restPath, writeDeniedColumnsLine } from "../api-surface.js"; @@ -38,6 +40,7 @@ import { SERVICE_INDEX_FILE, type ServiceEntity, type ServiceOperation, + type ServiceRelation, type ServicePackage, type ServiceTransition, type ServiceTransitionCommand, @@ -92,6 +95,11 @@ export function wireMapperName(entityName: string): string { return `${lowerFirst(entityName)}ToWire`; } +/** The wire mapper of a write-through entity's write answers, as the service index exports it. */ +export function writeWireMapperName(entityName: string): string { + return `${lowerFirst(entityName)}WriteToWire`; +} + /** Does the store hold a transaction across application code? (`interactiveTransactions`, default true) */ function interactive(pkg: ServicePackage): boolean { return pkg.interactiveTransactions !== false; @@ -118,10 +126,14 @@ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): Ser } const files: ServiceFile[] = []; for (const e of pkg.entities) { - for (const op of ["list", "get", "create", "update", "delete"] as const) { + for (const op of e.verbs) { const path = servicePath(pkg.package, `${e.operations[op]}.ts`); files.push({ path, content: renderOperation(op, e, path, ctx, pkg) }); } + for (const r of e.relations) { + const path = servicePath(pkg.package, `${r.fn}.ts`); + files.push({ path, content: renderRelation(r, e, path, ctx) }); + } for (const c of e.commands) { const path = servicePath(pkg.package, `${c.fn}.ts`); files.push({ path, content: renderTransitionCommand(c, e, path, ctx, pkg) }); @@ -136,6 +148,46 @@ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): Ser return files; } +/** Where an entity's operations read and write, as the operation file imports them. */ +interface Sources { + /** The table writes go to (a single-table subtype's base table). */ + readonly table: string; + /** What reads select from: the table, a write-through entity's replica view, or a read-only object's view. */ + readonly read: string; + /** The replica view a write is read back through (write-through), else undefined. */ + readonly view: string | undefined; +} + +function sourcesOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): Sources { + const own = modulesOf(path, e.obj, ctx).entity; + if (e.kind !== "entity") { + const view = w.use(`${lowerFirst(e.obj.name)}View`, own); + return { table: view, read: view, view: undefined }; + } + const table = w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity); + if (!e.readView) return { table, read: table, view: undefined }; + const view = w.use(`${lowerFirst(e.obj.name)}View`, own); + return { table, read: view, view }; +} + +/** The row type of an entity's operations: its contract type, or a report's row type from its entity module. */ +function rowTypeOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): string { + const mods = modulesOf(path, e.obj, ctx); + return w.useType(e.obj.name, e.kind === "report" ? mods.entity : mods.contract); +} + +/** A single-table subtype's create input: its create shape without the discriminator, which the path names. */ +function createInputType(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): string { + const create = w.useType(`${e.obj.name}Create`, modulesOf(path, e.obj, ctx).contract); + return e.discriminator === undefined ? create : `Omit<${create}, ${str(e.discriminator.field)}>`; +} + +/** The scope expression of a single-table subtype's operations, or undefined. */ +function scopeExpr(w: TsWriter, e: ServiceEntity, table: string, runtime: string): string | undefined { + if (e.discriminator === undefined) return undefined; + return `${w.use("scopeCondition", runtime)}(${table}, ${str(e.discriminator.field)}, ${str(e.discriminator.value)})`; +} + function renderOperation( op: "list" | "get" | "create" | "update" | "delete", e: ServiceEntity, @@ -150,8 +202,9 @@ function renderOperation( header(w, `${name} (${obj.fqn()}) — service operation ${fn} (ADR-0067 layer 4)`); const runtime = runtimeSpecifierFrom(path, "service", ctx); const mods = modulesOf(path, obj, ctx); - const table = w.use(ctx.collectionName(name), mods.entity); - const row = w.useType(name, mods.contract); + const src = sourcesOf(w, e, path, ctx); + const table = src.table; + const row = rowTypeOf(w, e, path, ctx); const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); @@ -159,6 +212,74 @@ function renderOperation( const lifecycleFields = e.lifecycles.map((l) => l.field); const keyField = str(e.keyField); const id = "id: number | string"; + const scope = scopeExpr(w, e, table, runtime); + const addressed = (on: string) => { + const cond = `${w.use("keyCondition", runtime)}(${on}, ${keyField}, id)`; + return scope === undefined ? cond : `${w.use("scoped", runtime)}(${cond}, ${scope})`; + }; + const readOnly = e.kind !== "entity"; + + if (op === "list" && readOnly) { + const readOnlyList = w.use("readOnlyList", runtime); + const page = w.useType("ReadOnlyPage", runtime); + const query = w.useType("ListQueryInput", runtime); + const inReadScope = w.use("inReadScope", runtime); + const filter = w.use(`${name}FilterAllowlist`, mods.entity); + const sort = w.use(`${name}SortAllowlist`, mods.entity); + const report = e.kind === "report"; + const exported = report && ctx.includeReportExport; + const keyed = e.verbs.includes("get"); + w.doc( + ...(report + ? [ + `The ${name} report's rows: the filter, search and sort of \`query\`, checked against the allowlists.`, + "It answers every row up to its cap and refuses above it (`report_too_large`); a `limit` pages it.", + ...(exported ? ["`?format=` asks for an export (`format` on the page), capped by the export's own row cap."] : []), + ] + : [ + `A page of ${name} rows: the filter, search, sort and page of \`query\` (the bracketed tree a`, + "query string parses to), checked against the allowlists.", + ]), + ); + w.block( + `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${page}<${row}>>> {`, + () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + objectLiteral( + w, + `const spec: ${w.useType("ReadOnlySpec", runtime)} = `, + [ + `filterAllowlist: ${filter},`, + `sortAllowlist: ${sort},`, + `dialect: ${dialect},`, + ...(keyed && e.keyField !== "id" ? [`idColumn: ${keyField},`] : []), + ...(report ? ["report: true,"] : []), + ...(report && pkg.reportMaxRows !== undefined ? [`reportMaxRows: ${pkg.reportMaxRows},`] : []), + ...(exported ? [`export: ${w.use(`${name}Export`, exportSpecifier(path, obj, ctx))},`] : []), + report ? "" : paginationLine(obj, "", ctx.loadedRoot), + ], + ";", + ); + w.line(`return (await ${readOnlyList}(db, ${table}, query, spec)) as ${page}<${row}>;`); + }, "});"); + }, + ); + return w.toString(); + } + + if (op === "get" && readOnly) { + const inReadScope = w.use("inReadScope", runtime); + const notFound = w.use("notFound", runtime); + w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + w.line(`const row = await ${w.use("readOnlyGet", runtime)}(db, ${table}, id, { dialect: ${dialect}${e.keyField !== "id" ? `, idColumn: ${keyField}` : ""} });`); + w.line(`if (row === undefined) ${notFound}();`); + w.line(`return row as ${row};`); + }, "});"); + }); + return w.toString(); + } if (op === "list") { const listRows = w.use("listRows", runtime); @@ -170,6 +291,8 @@ function renderOperation( w.doc( `A page of ${name} rows: the filter, search, sort and page of \`query\` (the bracketed tree a`, "query string parses to), checked against the allowlists; ordered by the key when it names no sort.", + ...(e.discriminator !== undefined ? [`Only the rows of discriminator value ${e.discriminator.value}.`] : []), + ...(e.readView ? ["Read through the replica view, so a row carries its derived fields."] : []), ); w.block( `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${listPage}<${row}>>> {`, @@ -178,10 +301,17 @@ function renderOperation( objectLiteral( w, `const spec: ${w.useType("ListSpec", runtime)} = `, - [`filterAllowlist: ${filter},`, `sortAllowlist: ${sort},`, `dialect: ${dialect},`, `keyField: ${keyField},`, paginationLine(obj, "", ctx.loadedRoot)], + [ + `filterAllowlist: ${filter},`, + `sortAllowlist: ${sort},`, + `dialect: ${dialect},`, + `keyField: ${keyField},`, + paginationLine(obj, "", ctx.loadedRoot), + ...(scope === undefined ? [] : [`scope: ${scope},`]), + ], ";", ); - w.line(`return (await ${listRows}(db, ${table}, query, spec)) as ${listPage}<${row}>;`); + w.line(`return (await ${listRows}(db, ${src.read}, query, spec)) as ${listPage}<${row}>;`); }, "});"); }, ); @@ -191,12 +321,11 @@ function renderOperation( if (op === "get") { const inReadScope = w.use("inReadScope", runtime); const readOne = w.use("readOne", runtime); - const keyCondition = w.use("keyCondition", runtime); const notFound = w.use("notFound", runtime); w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { - w.line(`const row = await ${readOne}(db, ${table}, ${keyCondition}(${table}, ${keyField}, id));`); + w.line(`const row = await ${readOne}(db, ${src.read}, ${addressed(src.read)});`); w.line(`if (row === undefined) ${notFound}();`); w.line(`return row as ${row};`); }, "});"); @@ -204,21 +333,40 @@ function renderOperation( return w.toString(); } + // A write to a write-through entity is read back through its replica view, so the answer + // carries the view's derived fields. + const readBack = (expr: string) => + src.view === undefined ? expr : `(await ${w.use("readThroughView", runtime)}(tx, ${src.view}, ${keyField}, ${expr})) as ${row}`; + // Under `interactiveTransactions: false` a write opens no transaction and has no hooks or event // hook to run inside one (ADR-0067 §4): it is its one statement, after the load and the checks. const tx = interactive(pkg); const inWriteTransaction = tx ? w.use("inWriteTransaction", runtime) : w.use("withoutTransaction", runtime); const inOne = tx ? "In one transaction:" : "With no transaction (`interactiveTransactions: false`):"; + const disc = e.discriminator; if (op === "create" || op === "update") { const writeRules = w.useType("WriteBodyRules", runtime); const validateBody = w.use("validateBody", runtime); w.doc("What a write body may name: every other key is refused, a server-owned one dropped."); - objectLiteral(w, `const writeRules: ${writeRules} = `, [knownFieldsLine(obj, "", ctx.loadedRoot), writeDeniedColumnsLine(obj, "")], ";"); + objectLiteral( + w, + `const writeRules: ${writeRules} = `, + [knownFieldsLine(obj, "", ctx.loadedRoot, e.hierarchy), writeDeniedColumnsLine(obj, "", e.hierarchy)], + ";", + ); w.blank(); if (op === "create") { const insertRow = w.use("insertRow", runtime); - const schema = w.use(`${name}InsertSchema`, mods.contract); - const input = w.useType(`${name}Create`, mods.contract); + // A single-table subtype's body omits the discriminator: the path names the subtype. One with + // cross-field rules has a refined schema, which Zod will not `.omit()`: its entity module + // exports the discriminator-less body schema instead. + const schema = + disc === undefined + ? w.use(`${name}InsertSchema`, mods.contract) + : hasInsertRefinements(obj) + ? w.use(`${name}InsertBodySchema`, mods.entity) + : `${w.use(`${name}InsertSchema`, mods.contract)}.omit({ ${disc.field}: true })`; + const input = createInputType(w, e, path, ctx); w.doc( ...(tx ? [ @@ -227,6 +375,7 @@ function renderOperation( "and the event hook; answer the written row.", ] : [`Create a ${name}. ${inOne} validate the input and stamp what the model declares`, "(ADR-0045), insert it; answer the written row."]), + ...(disc !== undefined ? [`The row is stamped with discriminator value ${disc.value}.`] : []), ); w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { @@ -235,6 +384,7 @@ function renderOperation( w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(input, ctx)) ?? input;`); } else w.line("const given = input;"); w.line(`const values: Record = ${validateBody}(${schema}, given, writeRules);`); + if (disc !== undefined) w.line(`values[${str(disc.field)}] = ${str(disc.value)};`); if (e.lifecycles.length > 0) { if (pkg.settings.lifecycleCreate === "initial") { const initials = e.lifecycles.map((l) => `${l.field}: ${str(l.initial ?? "")}`).join(", "); @@ -244,7 +394,7 @@ function renderOperation( w.line(`// rules.lifecycle.create: "any" — a create may start a lifecycle in any of its states.`); } } - w.line(`const row = (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); + w.line(`const row = ${readBack(`(await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField}))`)} as ${row};`); if (tx) { w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, ctx);`); w.line( @@ -256,7 +406,6 @@ function renderOperation( }); return w.toString(); } - const keyCondition = w.use("keyCondition", runtime); const loadForWrite = w.use("loadForWrite", runtime); const updateRow = w.use("updateRow", runtime); const notFound = w.use("notFound", runtime); @@ -275,12 +424,13 @@ function renderOperation( "(`not_found` when there is none), validate the patch and stamp what the model declares", "(ADR-0045), write it; answer the written row. A patch with nothing to write answers the row.", ]), + ...(disc !== undefined ? [`A row's subtype never changes: the discriminator is dropped from the patch.`] : []), ); w.block( `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`const cond = ${addressed(table)};`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); if (tx) { @@ -288,13 +438,15 @@ function renderOperation( w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(patch, current, ctx)) ?? patch;`); } else w.line("const given = patch;"); w.line(`const data: Record = ${validateBody}(${schema}, given, writeRules);`); + if (disc !== undefined) w.line(`delete data[${str(disc.field)}];`); if (lifecycleFields.length > 0) { w.line("// A lifecycle moves only through its transitions (ADR-0066 §6 step 7)."); w.line(`${w.use("checkStateManaged", runtime)}(data, current, ${JSON.stringify(lifecycleFields)});`); } - w.line("if (Object.keys(data).length === 0) return current;"); - w.line(`const row = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); - w.line(`if (row === undefined) ${notFound}();`); + w.line(`if (Object.keys(data).length === 0) return ${readBack("current")};`); + w.line(`const written = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); + w.line(`if (written === undefined) ${notFound}();`); + w.line(`const row = ${readBack("written")};`); if (tx) { w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, current, ctx);`); w.line( @@ -308,7 +460,6 @@ function renderOperation( return w.toString(); } - const keyCondition = w.use("keyCondition", runtime); const loadForWrite = w.use("loadForWrite", runtime); const deleteRows = w.use("deleteRows", runtime); const notFound = w.use("notFound", runtime); @@ -322,7 +473,7 @@ function renderOperation( ); w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`const cond = ${addressed(table)};`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); if (!tx) { @@ -341,6 +492,64 @@ function renderOperation( return w.toString(); } +/** Where a report's export spec module (`report-export`, `.export`) is, from the file at `from`. */ +function exportSpecifier(from: string, obj: MetaObject, ctx: RenderContext): string { + const layout = ctx.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; + return contractSpecifier(from, entityOutputPath(layout, effectivePackage(obj), `${obj.name}.export.ts`), ctx.extStyle); +} + +/** The physical column of `obj`'s field `fieldName` (the field name when it declares none). */ +function physicalColumn(obj: MetaObject, fieldName: string, ctx: RenderContext): string { + // ADR-0039: resolving — a junction's key field may be inherited through extends. + const field = obj.children().find((c) => c.type === TYPE_FIELD && c.name === fieldName); + return field === undefined ? fieldName : resolveColumnName(field, ctx.columnNamingStrategy); +} + +/** A many-to-many traversal of `e`: the target rows the junction links a source row to. */ +function renderRelation(r: ServiceRelation, e: ServiceEntity, path: string, ctx: RenderContext): string { + const w = new TsWriter(); + header(w, `${e.obj.name} (${e.obj.fqn()}) — service query ${r.fn}, the ${r.name} relationship (ADR-0067 layer 4)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; + const opOptions = `${w.useType("OpOptions", runtime)}`; + const opResult = w.useType("OpResult", runtime); + const junction = w.use(ctx.collectionName(r.junction.name), modulesOf(path, r.junction, ctx).entity); + const target = w.use(ctx.collectionName(r.target.name), modulesOf(path, r.target, ctx).entity); + const targetRow = w.useType(r.target.name, modulesOf(path, r.target, ctx).contract); + w.doc( + `The ${r.name} of the ${e.obj.name} row \`id\` names: the target rows its junction links it to.`, + ...(e.discriminator !== undefined ? [`An id that is no ${e.obj.name} (another subtype's row) has none.`] : []), + ); + objectLiteral( + w, + `const spec: ${w.useType("M2mSpec", runtime)} = `, + [ + `junctionTable: ${junction},`, + `targetTable: ${target},`, + `sourceColumn: ${str(physicalColumn(r.junction, r.sourceJoinField, ctx))},`, + `targetColumn: ${str(physicalColumn(r.junction, r.targetJoinField, ctx))},`, + `targetPkColumn: ${str(physicalColumn(r.target, pkInfoOf(r.target)?.fieldName ?? "id", ctx))},`, + `symmetric: ${r.symmetric},`, + ...(r.targetDiscriminator === undefined + ? [] + : [`targetDiscriminator: { column: ${str(physicalColumn(r.target, r.targetDiscriminator.field, ctx))}, value: ${str(r.targetDiscriminator.value)} },`]), + ...(e.discriminator === undefined + ? [] + : [ + `sourceDiscriminator: { table: ${w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity)}, pkColumn: ${str( + physicalColumn(e.storage, e.keyField, ctx), + )}, column: ${str(physicalColumn(e.storage, e.discriminator.field, ctx))}, value: ${str(e.discriminator.value)} },`, + ]), + ], + ";", + ); + w.blank(); + w.block(`export async function ${r.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${targetRow}[]>> {`, () => { + w.line(`return ${w.use("inReadScope", runtime)}(deps.db, opts.tx, async (db) => (await ${w.use("m2mRelated", runtime)}(db, spec, id)) as ${targetRow}[]);`); + }); + return w.toString(); +} + /** The specifier of the package's service index, from a file in the same folder. */ function indexSpecifier(ctx: RenderContext): string { return withExtIfRelative(`./${SERVICE_INDEX_FILE.replace(/\.ts$/, "")}`, ctx.extStyle); @@ -610,9 +819,10 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex ); w.block(`export interface ${stem}Hooks {`, () => { for (const e of pkg.entities) { + if (!e.verbs.includes("create")) continue; const mods = modulesOf(path, e.obj, ctx); const row = w.useType(e.obj.name, mods.contract); - const create = w.useType(`${e.obj.name}Create`, mods.contract); + const create = createInputType(w, e, path, ctx); const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const o = e.operations; const P = (f: string) => toPascalCase(f); @@ -680,24 +890,34 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex ); w.block(`export interface ${type} {`, () => { for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const row = w.useType(e.obj.name, mods.contract); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const row = rowTypeOf(w, e, path, ctx); const o = e.operations; - for (const f of Object.values(o)) w.use(f, withExtIfRelative(`./${f}`, ctx.extStyle)); - w.line(`${o.list}(query?: ${query}, opts?: ${opOptions}): Promise<${opResult}<${listPage}<${row}>>>;`); - w.line(`${o.get}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.create}(input: ${create}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.update}(id: number | string, patch: ${patch}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.delete}(id: number | string, opts?: ${opOptions}): Promise<${opResult}>;`); - calls.push( - `${o.list}: (query, opts) => ${o.list}(deps, query, opts),`, - `${o.get}: (id, opts) => ${o.get}(deps, id, opts),`, - `${o.create}: (input, opts) => ${o.create}(deps, input, opts),`, - `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, - `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, - ); + for (const v of e.verbs) w.use(o[v], withExtIfRelative(`./${o[v]}`, ctx.extStyle)); + const page = e.kind === "entity" ? listPage : w.useType("ReadOnlyPage", runtime); + w.line(`${o.list}(query?: ${query}, opts?: ${opOptions}): Promise<${opResult}<${page}<${row}>>>;`); + calls.push(`${o.list}: (query, opts) => ${o.list}(deps, query, opts),`); + if (e.verbs.includes("get")) { + w.line(`${o.get}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + calls.push(`${o.get}: (id, opts) => ${o.get}(deps, id, opts),`); + } + if (e.verbs.includes("create")) { + const create = createInputType(w, e, path, ctx); + const patch = w.useType(`${e.obj.name}Patch`, modulesOf(path, e.obj, ctx).contract); + w.line(`${o.create}(input: ${create}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.update}(id: number | string, patch: ${patch}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.delete}(id: number | string, opts?: ${opOptions}): Promise<${opResult}>;`); + calls.push( + `${o.create}: (input, opts) => ${o.create}(deps, input, opts),`, + `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, + `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, + ); + } + for (const r of e.relations) { + w.use(r.fn, withExtIfRelative(`./${r.fn}`, ctx.extStyle)); + const targetRow = w.useType(r.target.name, modulesOf(path, r.target, ctx).contract); + w.line(`${r.fn}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${targetRow}[]>>;`); + calls.push(`${r.fn}: (id, opts) => ${r.fn}(deps, id, opts),`); + } for (const c of e.commands) { w.use(c.fn, withExtIfRelative(`./${c.fn}`, ctx.extStyle)); w.line(`${c.fn}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); @@ -721,12 +941,31 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex }, "};"); }); + const withWire = () => w.use("withWire", runtime); + const timestampWire = () => w.use("timestampWire", runtime); for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const table = w.use(ctx.collectionName(e.obj.name), mods.entity); + const src = sourcesOf(w, e, path, ctx); + const decimals = + e.discriminator !== undefined + ? decimalColumnsLine(e.obj, "", ctx.loadedRoot, e.hierarchy) + : decimalColumnsLine(e.hierarchy.length > 1 ? e.hierarchy : e.obj, "", ctx.loadedRoot); w.blank(); w.doc(`The wire form (ADR-0019) of a ${e.obj.name} row: what a transport sends.`); - objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${w.use("withWire", runtime)}(${w.use("timestampWire", runtime)}(${table}), `, [decimalColumnsLine(e.obj, "", ctx.loadedRoot)], ");"); + objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${withWire()}(${timestampWire()}(${src.read}), `, [decimals], ");"); + if (src.view !== undefined) { + w.blank(); + w.doc( + `The wire form of a ${e.obj.name} row a write answers: read back through the replica view, or the`, + "table's row when the view has none, so it is mapped against both.", + ); + objectLiteral(w, `export const ${writeWireMapperName(e.obj.name)} = ${withWire()}(${timestampWire()}(${src.table}, ${src.view}), `, [decimals], ");"); + } + for (const r of e.relations) { + w.blank(); + w.doc(`The wire form of a row of ${e.obj.name}'s ${r.name}.`); + const target = w.use(ctx.collectionName(r.target.name), modulesOf(path, r.target, ctx).entity); + objectLiteral(w, `export const ${wireMapperName(r.fn)} = ${withWire()}(${timestampWire()}(${target}), `, [decimalColumnsLine(r.targetObjects, "", ctx.loadedRoot)], ");"); + } } return w.toString(); } @@ -757,16 +996,24 @@ function refuseRouteCollisions(routes: readonly MountedRoute[]): void { function transportRoutes(pkg: ServicePackage): MountedRoute[] { const mounted: MountedRoute[] = []; for (const e of pkg.entities) { - const base = restPath(e.obj); + const base = e.path; const item = `${base}/:id`; - mounted.push( - { method: "GET", path: base, what: `${e.obj.name} list` }, - { method: "GET", path: item, what: `${e.obj.name} get` }, - { method: "POST", path: base, what: `${e.obj.name} create` }, - { method: "PATCH", path: item, what: `${e.obj.name} update` }, - { method: "PUT", path: item, what: `${e.obj.name} update` }, - { method: "DELETE", path: item, what: `${e.obj.name} delete` }, - ); + const keyed = e.verbs.includes("get"); + mounted.push({ method: "GET", path: base, what: `${e.obj.name} list` }); + if (keyed) mounted.push({ method: "GET", path: item, what: `${e.obj.name} get` }); + // A read-only object answers its writes 405; a single-table base serves no writes at all. + if (e.verbs.includes("create") || e.kind !== "entity") { + const what = (verb: string) => `${e.obj.name} ${e.kind === "entity" ? verb : "405"}`; + mounted.push({ method: "POST", path: base, what: what("create") }); + if (keyed) { + mounted.push( + { method: "PATCH", path: item, what: what("update") }, + { method: "PUT", path: item, what: what("update") }, + { method: "DELETE", path: item, what: what("delete") }, + ); + } + } + for (const r of e.relations) mounted.push({ method: "GET", path: `${item}/${r.name}`, what: `${e.obj.name}.${r.name} traversal` }); for (const c of e.commands) mounted.push({ method: "POST", path: `${item}/${c.transition.name}`, what: `transition ${e.obj.name}.${c.transition.name}` }); } for (const op of pkg.operations) mounted.push({ method: op.method, path: op.path, what: `operation ${op.name}` }); @@ -815,14 +1062,27 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): w.line(`const ro = ${handler}(undefined);`); const mount = (app: string) => { for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); const o = e.operations; - const base = str(restPath(e.obj)); - const item = str(`${restPath(e.obj)}/:id`); + const base = str(e.path); + const item = str(`${e.path}/:id`); const params = "{ Params: { id: string } }"; + const keyed = e.verbs.includes("get"); + if (e.kind !== "entity") { + const listPage = w.use("sendListPage", runtime); + const exported = e.kind === "report" && ctx.includeReportExport; + const exportOf = exported ? `, { spec: ${w.use(`${e.obj.name}Export`, exportSpecifier(path, e.obj, ctx))}, path: ${base} }` : ""; + w.line( + `${app}.get(${base}, ro, async (req, reply) => ${listPage}(reply, await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)), await actorOf(req)), ${toWire}${exportOf}));`, + ); + if (keyed) w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id, await actorOf(req)), 200, ${toWire}));`); + const notAllowed = w.use("methodNotAllowed", runtime); + w.line(`// A ${e.kind} is read-only: every write answers 405.`); + w.line(`const ${lowerFirst(e.obj.name)}ReadOnly = async (req: ${fastifyRequest}, reply: ${w.useType("FastifyReply", "fastify")}) => reply.code(405).send(${notAllowed}(req.method, ${str(e.kind)}));`); + w.line(`${app}.post(${base}, ro, ${lowerFirst(e.obj.name)}ReadOnly);`); + if (keyed) for (const verb of ["patch", "put", "delete"]) w.line(`${app}.${verb}(${item}, ro, ${lowerFirst(e.obj.name)}ReadOnly);`); + continue; + } w.block(`${app}.get(${base}, ro, async (req, reply) => {`, () => { w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)), await actorOf(req));`); w.line( @@ -830,17 +1090,29 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): ); }, "});"); w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id, await actorOf(req)), 200, ${toWire}));`); - w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}, await actorOf(req)), 201, ${toWire}));`); - w.line("// The update is reachable by PATCH and by PUT, as in every port."); - for (const verb of ["patch", "put"]) { + if (e.verbs.includes("create")) { + const mods = modulesOf(path, e.obj, ctx); + const create = createInputType(w, e, path, ctx); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const writeWire = e.readView ? w.use(writeWireMapperName(e.obj.name), serviceIndex) : toWire; + w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}, await actorOf(req)), 201, ${writeWire}));`); + w.line("// The update is reachable by PATCH and by PUT, as in every port."); + for (const verb of ["patch", "put"]) { + w.line( + `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}, await actorOf(req)), 200, ${writeWire}));`, + ); + } + w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id, await actorOf(req)), 204));`); + } + for (const c of e.commands) { w.line( - `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}, await actorOf(req)), 200, ${toWire}));`, + `${app}.post<${params}>(${str(`${e.path}/:id/${c.transition.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${c.fn}(req.params.id, await actorOf(req)), 200, ${toWire}));`, ); } - w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id, await actorOf(req)), 204));`); - for (const c of e.commands) { + for (const r of e.relations) { + const relWire = w.use(wireMapperName(r.fn), serviceIndex); w.line( - `${app}.post<${params}>(${str(`${restPath(e.obj)}/:id/${c.transition.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${c.fn}(req.params.id, await actorOf(req)), 200, ${toWire}));`, + `${app}.get<${params}>(${str(`${e.path}/:id/${r.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${r.fn}(req.params.id, await actorOf(req)), 200, (rows) => rows.map(${relWire})));`, ); } } @@ -917,16 +1189,38 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se const routes: Array<{ path: string; emit: () => void }> = []; const route = (path: string, emit: () => void) => routes.push({ path, emit }); for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); const o = e.operations; - const base = at(restPath(e.obj)); - const item = at(`${restPath(e.obj)}/:id`); - const id = `c.req.param("id") ?? ""`; - const basePath = restPath(e.obj); + const basePath = e.path; const itemPath = `${basePath}/:id`; + const base = at(basePath); + const item = at(itemPath); + const id = `c.req.param("id") ?? ""`; + const keyed = e.verbs.includes("get"); + if (e.kind !== "entity") { + const listPage = w.use("sendListPage", runtime); + const notAllowed = w.use("methodNotAllowed", runtime); + const exported = e.kind === "report" && ctx.includeReportExport; + const exportOf = exported ? `, { spec: ${w.use(`${e.obj.name}Export`, exportSpecifier(path, e.obj, ctx))}, path: ${str(basePath)} }` : ""; + const kind = str(e.kind); + route(basePath, () => { + w.line(`app.get(${base}, ${guard}(async (c) => ${listPage}(c, await service.${o.list}(${parseQuery}(${rawQuery}(c.req.url)), await actorOf(c)), ${toWire}${exportOf})));`); + w.line(`// A ${e.kind} is read-only: every write answers 405.`); + w.line(`app.post(${base}, (c) => ${notAllowed}(c, ${kind}));`); + }); + if (keyed) { + route(itemPath, () => { + w.line(`app.get(${item}, ${guard}(async (c) => ${send}(c, await service.${o.get}(${id}, await actorOf(c)), 200, ${toWire})));`); + for (const verb of ["patch", "put", "delete"]) w.line(`app.${verb}(${item}, (c) => ${notAllowed}(c, ${kind}));`); + }); + } + continue; + } + const writable = e.verbs.includes("create"); + const mods = modulesOf(path, e.obj, ctx); + const create = writable ? createInputType(w, e, path, ctx) : ""; + const patch = writable ? w.useType(`${e.obj.name}Patch`, mods.contract) : ""; + const writeWire = e.readView ? w.use(writeWireMapperName(e.obj.name), serviceIndex) : toWire; route(basePath, () => { w.block(`app.get(${base}, ${guard}(async (c) => {`, () => { w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(c.req.url)), await actorOf(c));`); @@ -934,20 +1228,22 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se `return ${send}(c, result, 200, (page) => (page.total === undefined ? page.rows.map(${toWire}) : { rows: page.rows.map(${toWire}), total: page.total }));`, ); }, "}));"); + if (!writable) return; w.block(`app.post(${base}, ${guard}(async (c) => {`, () => { w.line(`const read = await ${readBody}(c);`); w.line("if (!read.ok) return read.response;"); - w.line(`return ${send}(c, await service.${o.create}(read.body as ${create}, await actorOf(c)), 201, ${toWire});`); + w.line(`return ${send}(c, await service.${o.create}(read.body as ${create}, await actorOf(c)), 201, ${writeWire});`); }, "}));"); }); route(itemPath, () => { w.line(`app.get(${item}, ${guard}(async (c) => ${send}(c, await service.${o.get}(${id}, await actorOf(c)), 200, ${toWire})));`); + if (!writable) return; w.line("// The update is reachable by PATCH and by PUT, as in every port."); for (const verb of ["patch", "put"]) { w.block(`app.${verb}(${item}, ${guard}(async (c) => {`, () => { w.line(`const read = await ${readBody}(c);`); w.line("if (!read.ok) return read.response;"); - w.line(`return ${send}(c, await service.${o.update}(${id}, read.body as ${patch}, await actorOf(c)), 200, ${toWire});`); + w.line(`return ${send}(c, await service.${o.update}(${id}, read.body as ${patch}, await actorOf(c)), 200, ${writeWire});`); }, "}));"); } w.line(`app.delete(${item}, ${guard}(async (c) => ${send}(c, await service.${o.delete}(${id}, await actorOf(c)), 204)));`); @@ -958,6 +1254,13 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se w.line(`app.post(${at(path)}, ${guard}(async (c) => ${send}(c, await service.${c.fn}(${id}, await actorOf(c)), 200, ${toWire})));`), ); } + for (const r of e.relations) { + const path = `${itemPath}/${r.name}`; + const relWire = w.use(wireMapperName(r.fn), serviceIndex); + route(path, () => + w.line(`app.get(${at(path)}, ${guard}(async (c) => ${send}(c, await service.${r.fn}(${id}, await actorOf(c)), 200, (rows) => rows.map(${relWire}))));`), + ); + } } for (const op of pkg.operations) { const key = op.keyed ? op.target!.keyField : undefined; diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index 763698359..ada0d8a02 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -164,17 +164,29 @@ describe("service-routes-hono — the service's Hono transport", () => { }); describe("service walk — which entities get the derived operations", () => { - test("over the fitness corpus: concrete, store-backed, single-key entities only", async () => { + test("over the fitness corpus: every object the flat routes serve, single-key where keyed", async () => { const result = await loadUris([pathToFileURL(FITNESS).href]); expect(result.errors).toEqual([]); - const covered = serviceModelOf(result.root).flatMap((p) => p.entities.map((e) => e.obj.name)); - expect(covered).toContain("Program"); + const entities = serviceModelOf(result.root).flatMap((p) => p.entities); + const byName = new Map(entities.map((e) => [e.obj.name, e])); + expect(byName.has("Program")).toBe(true); // A concrete entity that inherits its fields from an abstract one. - expect(covered).toContain("Gadget"); + expect(byName.has("Gadget")).toBe(true); // The abstract level has no table of its own. - expect(covered).not.toContain("Labeled"); - // A single-table hierarchy, its base and its subtypes, is later service work. - for (const tph of ["Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth"]) expect(covered).not.toContain(tph); + expect(byName.has("Labeled")).toBe(false); + // A single-table hierarchy: the base is polymorphic and read-only (the union has no single + // writable shape), each concrete subtype has the five operations on the base table, scoped to + // its discriminator value, at the base path plus its segment (FR-017). + expect(byName.get("Auth")?.verbs).toEqual(["list", "get"]); + const bridge = byName.get("BridgeAuth")!; + expect(bridge.verbs).toEqual(["list", "get", "create", "update", "delete"]); + expect(bridge.storage.name).toBe("Auth"); + expect(bridge.path).toBe("/auths/bridge"); + expect(bridge.discriminator).toEqual({ field: "type", value: "Bridge" }); + // A served report has a list and no key. + const report = byName.get("FitnessTotals")!; + expect(report.kind).toBe("report"); + expect(report.verbs).toEqual(["list"]); }); }); diff --git a/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts index 7d479cbd5..275436891 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts @@ -16,7 +16,7 @@ // This proves the GENERATED write-through routes — the deployed artifact, not a // re-implementation — return the derived field on read-your-writes over HTTP. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -27,6 +27,7 @@ import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { loadMetadataFile } from "./load-metadata.ts"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; export interface WriteThroughSeed { customers: Array<{ id: number; name: string }>; @@ -43,6 +44,7 @@ export async function startGeneratedWriteThroughServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -56,14 +58,14 @@ export async function startGeneratedWriteThroughServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -95,16 +97,16 @@ export const db = drizzle(pool); FROM "orders" o JOIN "customers" c ON o."customer_id" = c."id"; `); - // 4. Import the EMITTED Order route file unmodified and mount it. - const orderRoutes = (await import(pathToFileURL(emitted.locate("Order.routes.ts")).href)) as { - orderRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(orderRoutes.orderRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: the Order routes, or the service behind + // its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const orderRoutes = (await import(pathToFileURL(emitted.locate("Order.routes.ts")).href)) as { + orderRoutes: (f: FastifyInstance) => Promise; + }; + await fastify.register(orderRoutes.orderRoutes); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -112,7 +114,7 @@ export const db = drizzle(pool); await seedWriteThrough(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts b/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts index 6128fd6c3..387df0d0e 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts @@ -21,6 +21,7 @@ import { import { openApiCheck, type ContractCheck } from "../src/api-contract-openapi-check.ts"; import { loadScenarios, assertResponse, type ApiScenario, parseBodyExact } from "../src/api-contract-scenario.ts"; import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { startGeneratedWriteThroughServer, type GeneratedWriteThroughServerHandle, @@ -34,14 +35,14 @@ const META_PATH = join(API_CONTRACT_WRITE_THROUGH_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("write-through"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract write-through (#214) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract write-through (#214) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_WRITE_THROUGH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedWriteThroughServerHandle | null = null; try { - server = await startGeneratedWriteThroughServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedWriteThroughServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/runtime-ts/src/read-only-read.ts b/server/typescript/packages/runtime-ts/src/read-only-read.ts index ee49798d3..1ae074d3c 100644 --- a/server/typescript/packages/runtime-ts/src/read-only-read.ts +++ b/server/typescript/packages/runtime-ts/src/read-only-read.ts @@ -52,8 +52,8 @@ export interface ReadOnlySpec { } /** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ -export interface ReadOnlyPage { - readonly rows: Record[]; +export interface ReadOnlyPage> { + readonly rows: T[]; readonly total?: number; /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ readonly format?: ExportFormat; diff --git a/server/typescript/packages/runtime-ts/src/service/fastify.ts b/server/typescript/packages/runtime-ts/src/service/fastify.ts index adc1ecd3f..0d7ce3972 100644 --- a/server/typescript/packages/runtime-ts/src/service/fastify.ts +++ b/server/typescript/packages/runtime-ts/src/service/fastify.ts @@ -36,10 +36,10 @@ export function methodNotAllowed(method: string, resource: "projection" | "repor * the count was asked for; with an export spec and an export format asked (`?format=`), the rows * rendered in that format as a download named after `path`'s last segment. */ -export function sendListPage( +export function sendListPage( reply: FastifyReply, - result: OpResult, - toWire: (row: Record) => unknown, + result: OpResult>, + toWire: (row: T) => unknown, exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, ): FastifyReply { if (!result.ok) return reply.code(result.status).send(result.error); diff --git a/server/typescript/packages/runtime-ts/src/service/hono.ts b/server/typescript/packages/runtime-ts/src/service/hono.ts index 50cd5f585..a1de23d34 100644 --- a/server/typescript/packages/runtime-ts/src/service/hono.ts +++ b/server/typescript/packages/runtime-ts/src/service/hono.ts @@ -52,10 +52,10 @@ export function methodNotAllowed(c: Context, resource: "projection" | "report"): * the count was asked for; with an export spec and an export format asked (`?format=`), the rows * rendered in that format as a download named after `path`'s last segment. */ -export function sendListPage( +export function sendListPage( c: Context, - result: OpResult, - toWire: (row: Record) => unknown, + result: OpResult>, + toWire: (row: T) => unknown, exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, ): Response { if (!result.ok) return c.json(result.error, result.status as ContentfulStatusCode); diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts index cad712fb5..d2e47647b 100644 --- a/server/typescript/packages/runtime-ts/src/service/index.ts +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -380,6 +380,11 @@ export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, return { rows, total: countRow?.c ?? 0 }; } +/** `cond`, and `scope` when there is one: a single-table subtype's row is addressed within its own rows. */ +export function scoped(cond: SQL, scope: SQL | undefined): SQL { + return scope === undefined ? cond : and(cond, scope)!; +} + /** The condition a single-table subtype's rows meet: its discriminator `field` holds `value`. */ export function scopeCondition(table: Drizzle, field: string, value: string): SQL { return eq(table[field], value); From 5fe60d9766f2dda6fa85674ec0a9534a76131bff Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 07:56:01 -0500 Subject: [PATCH 11/17] wip: service lane on report/tph/m2m/decimal/secret-fields; served reports read through their read model; runGen removes its no-project gen-state at exit --- CHANGELOG.md | 15 ++++++ docs/features/business-rules.md | 18 ++++++- docs/ports/typescript.md | 7 ++- .../cli/test/unit/reporting-inert.test.ts | 34 ++++++++++++- .../packages/codegen-ts/src/runner.ts | 4 +- .../packages/codegen-ts/src/scratch-dir.ts | 23 +++++++++ .../packages/codegen-ts/src/service-walk.ts | 10 ++-- .../codegen-ts/test/scratch-dir.test.ts | 31 +++++++++++- .../src/api-contract-decimal-server.ts | 3 +- .../src/api-contract-m2m-generated-server.ts | 49 +++++++----------- ...pi-contract-projection-generated-server.ts | 42 ++++++---------- .../api-contract-report-generated-server.ts | 50 ++++++++++--------- .../src/api-contract-report-mysql-server.ts | 49 ++++++++++-------- .../src/api-contract-report-sqlite-server.ts | 48 ++++++++++-------- ...contract-secret-fields-generated-server.ts | 30 ++++++----- .../src/api-contract-tph-generated-server.ts | 30 +++++------ .../integration-tests/src/api-lane.ts | 11 ++-- .../test/api-contract-decimal.test.ts | 11 ++-- .../test/api-contract-m2m.test.ts | 5 +- .../test/api-contract-projection.test.ts | 5 +- .../test/api-contract-report-mysql.test.ts | 15 +++--- .../test/api-contract-report-sqlite.test.ts | 18 ++++--- .../test/api-contract-report.test.ts | 7 +-- .../test/api-contract-secret-fields.test.ts | 11 ++-- .../test/api-contract-tph.test.ts | 5 +- .../ADR-0067-layering-and-the-service-seam.md | 5 +- 26 files changed, 332 insertions(+), 204 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7c02fa87..bc1aad9cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,21 @@ here.** run the `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` and `duration/` corpora beside the root and `rules/` corpora, on every engine the routes lane runs, D1 included through `interactiveTransactions: false`. The service compile gate compiles both transports. +- **The service covers every object the flat routes serve.** Projections and served reports get + their reads, and their transports answer writes `405`. A report keeps its row cap, through the + new `serviceFile({ reportMaxRows })` option, and its `?format=` export. Write-through entities + read through their view and read a write back through it. A single-table hierarchy gets the + polymorphic base reads and per-subtype operations scoped to the discriminator. Each + many-to-many relationship gets a query and a `GET /{id}/` route. The + `projection/`, `report/` (Postgres, MySQL, SQLite and D1), `write-through/`, `tph/`, `m2m/`, + `decimal/` and `secret-fields/` corpora now run on both service lanes. runtime-ts: the read-only + and many-to-many reads (`readOnlyList`, `readOnlyGet`, `m2mRelated`) are framework-neutral + functions, which the flat Fastify mounts and the service both call. +- **codegen-ts: a `runGen` with no project no longer leaves its gen-state in the scratch root.** + The state of such a run is kept for that process's later runs only, and is removed when the + process exits. Before this fix, each such process left `meta-gen-state-` behind + permanently. The test harnesses that generate with no project had left hundreds of those + directories, about 3 GB, in a RAM-backed `$DEV_SCRATCH`. - **runtime-ts: the generated service keeps its rollback guarantee on a sync SQLite driver.** On bun:sqlite and better-sqlite3, Drizzle's `transaction()` commits when its callback returns, so a diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 5d19aa142..d4c511964 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -471,8 +471,22 @@ generated service, under the default settings and under `rules.lifecycle.create: `rules.lifecycle.commands: all` and `none`. Its README specifies the hand-written pieces, so every port's lane implements the same ones. -Not covered yet, and still served by the flat generators: write-through entities, single-table (TPH) -hierarchies, many-to-many traversal, projections and reports. +The service covers every object the flat routes serve, with the same answers: + +- A projection and a served report get a list (and a get, when the projection is keyed). Their + transports answer every write `405 method_not_allowed`. A report keeps its row cap + (`serviceFile({ reportMaxRows })`, as `routesFile` takes it) and, with `report-export` wired, + its `?format=` export. +- A write-through entity reads through its replica view and answers a write by reading the row + back through that view. +- A single-table (TPH) hierarchy's base gets the polymorphic list and get. Each concrete subtype + gets the five operations at its own path, on the base table, scoped to its discriminator value. +- A many-to-many relationship gets a query, `Of(id)`, served at + `GET /{id}/`. + +The `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` +corpora run on the service lanes as well as the routes lane. An entity with a composite key has no +derived operations. ## Requirements can claim operations and transitions diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 7213596c8..9fdd4483c 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -754,7 +754,9 @@ and give it its own `target` to put the layer in a package the transport and cli `serviceFile()` (stable name `service`, layer `service`) is layer 4 of ADR-0067. It writes one module per metadata package, under the package's directory in either layout: a file per operation in `/service/` (each entity's derived list, get, create, update and delete, every write in -one transaction by default, with the declared write rules) and `service/index.ts` with the `Service` +one transaction by default, with the declared write rules; the reads of a projection or a served +report; a single-table subtype's operations, scoped to its discriminator; a query per many-to-many +relationship) and `service/index.ts` with the `Service` interface and `createService(deps)`. A model with ADR-0066 rules also gets a file per derived transition command and per declared command and query, each running the rules' checks around a hand-written body; the policy, bodies, hooks and event hook are passed in `deps`. @@ -764,7 +766,8 @@ routes that call it, with a `getActor(request)` option for the app's actor. `/transport/hono.ts`, with `getActor(c)`. Each needs `entity` and `contract-types` in the same target. None is scaffolded; add them to `generators` or `meta eject` them. On SQLite the service takes a sync or an async Drizzle driver. A store that holds no transaction across -application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. +application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`, and a +report's row cap is `serviceFile({ reportMaxRows })`, as `routesFile` takes it. See [Business rules](../features/business-rules.md#the-service-layer-typescript). ### Prove it works diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index 96564c569..1edcc90ea 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -149,6 +149,18 @@ const SERVED_REPORT_FILES: Readonly> = { // The export spec for the report's list route, and the project's one shared writer module. "report-export": [`${OUT}/StoreTotals.export.ts`, `${OUT}/report-export-writers.ts`], "contract-schema": [`${OUT}/schemas/acme/shop/StoreTotals.schema.json`], + // The report's list operation (ADR-0067 layer 4); the package index and the transports grow + // by it (SERVICE_GROWS below). + service: [`${OUT}/acme/shop/service/listStoreTotals.ts`], +}; +/** + * The package-wide service files a served report changes: the service index gains its list + * operation and wire mapper, and each transport its list route and its `405` write routes. + */ +const SERVICE_GROWS: Readonly> = { + service: [`${OUT}/acme/shop/service/index.ts`], + "service-routes": [`${OUT}/acme/shop/transport/fastify.ts`], + "service-routes-hono": [`${OUT}/acme/shop/transport/hono.ts`], }; /** * FR-044 Plan 4: the files `cube-model` writes for `with/`, and none for `without/`. It writes @@ -206,6 +218,14 @@ function expectOnlyAdds( } } +/** A module's lines after its import block (the last line ending an import, `... from "x";`). */ +function bodyOf(source: string): string[] { + const lines = source.split("\n"); + let last = -1; + lines.forEach((l, i) => { if (/^(import .*|\} )from "[^"]+";$/.test(l)) last = i; }); + return lines.slice(last + 1); +} + interface OpenApiDoc { paths: Record; components: { schemas: Record }; @@ -257,7 +277,17 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(actual).toEqual(expected); return; } - expectOnlyAdds(expected, actual, ADDED_FOR_WITH[name] ?? [], [OPENAPI_DOC]); + expectOnlyAdds(expected, actual, ADDED_FOR_WITH[name] ?? [], [OPENAPI_DOC, ...(SERVICE_GROWS[name] ?? [])]); + for (const path of SERVICE_GROWS[name] ?? []) { + // A served report's service code names it, and it moves nothing it had: past the + // imports (which gain the report's names and helpers), every line of the file is still + // there, in order. + expect(actual[path]).toContain("StoreTotals"); + const before = bodyOf(expected[path]!); + let kept = 0; + for (const line of bodyOf(actual[path]!)) if (line === before[kept]) kept++; + expect(kept).toBe(before.length); + } if (name === "openapi") expectOpenApiAddsOnlyTheServedReport(expected[OPENAPI_DOC]!, actual[OPENAPI_DOC]!); if (name === "barrel") { // The barrel is the one shared file that moves, and it moves by the report's @@ -378,7 +408,7 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(expected[""]).toBeUndefined(); expect(actual[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); - expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC]); + expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); // The agent UI page moves by the served report's section alone: every line it had is // still there, in order, and the section names the report. const before = expected[AGENT_UI_PAGE]!.split("\n"); diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index adbdb6f1a..30c7172a8 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -3,7 +3,7 @@ import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path"; import { warnMissingPromptGenerators } from "./prompt-generator-gate.js"; import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose, warnUnmarkedRoutesGenerators, warnUnmarkedUiGenerators } from "./ui-tier-gate.js"; import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; -import { removeTree, scratchRoot } from "./scratch-dir.js"; +import { removeTree, removeTreeAtExit, scratchRoot } from "./scratch-dir.js"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import { existsSync, readFileSync } from "node:fs"; @@ -383,6 +383,8 @@ export async function runGen(opts: RunGenOpts): Promise { : (projectRoot !== undefined ? join(projectRoot, ".metaobjects", ".gen-state") : join(scratchRoot(), `meta-gen-state-${process.pid}`)); + // A run with no project keeps its state for this process's later runs only. + if (opts.genStateDir === undefined && projectRoot === undefined) removeTreeAtExit(genStateDir); // A file written OUTSIDE the project has no place in the project's gen-state: its // manifest key would be `../..`-relative, committed into the hash manifest, and its snapshot // body — stored at `/` — would walk out of `.gen-state/` and land a second diff --git a/server/typescript/packages/codegen-ts/src/scratch-dir.ts b/server/typescript/packages/codegen-ts/src/scratch-dir.ts index b3402c0c5..9e199f3c2 100644 --- a/server/typescript/packages/codegen-ts/src/scratch-dir.ts +++ b/server/typescript/packages/codegen-ts/src/scratch-dir.ts @@ -47,3 +47,26 @@ function walkRemove(path: string): void { export function removeTree(path: string): void { walkRemove(path); } + +const removedAtExit = new Set(); + +/** + * Remove `path` when this process exits. For state a process shares across its own runs and no + * later process reads (runGen's gen-state for a run with no project): without it, every process + * that ever ran one left a directory in the scratch root. + */ +export function removeTreeAtExit(path: string): void { + if (removedAtExit.has(path)) return; + if (removedAtExit.size === 0) { + process.once("exit", () => { + for (const p of removedAtExit) { + try { + removeTree(p); + } catch { + // An exit handler must not throw: a directory it cannot remove is left behind. + } + } + }); + } + removedAtExit.add(path); +} diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 9e55884ad..f390ef1a5 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -48,6 +48,7 @@ import { transitionFrom, transitionTo, type MetaData, + type MetaRoot, type MetaObject, type RulesSettings, } from "@metaobjectsdev/metadata"; @@ -59,7 +60,7 @@ import { HTTP_RUNTIME_MODULES, HTTP_RUNTIME_PACKAGE, type HttpRuntimeModule } fr import type { ExtStyle, RenderContext } from "./render-context.js"; import type { GenContext } from "./generator.js"; import { effectivePackage } from "./docs-paths.js"; -import { hasWritableRdbSource } from "./source-detect.js"; +import { generatableObjects, hasWritableRdbSource } from "./source-detect.js"; import { isAbstract } from "./instance-artifacts.js"; import { isProjection, isWriteThrough } from "./projection/projection-detector.js"; import { declaresTphDiscriminator, isTphSubtype, tphDiscriminatorBase, tphDiscriminatorPin, tphStorageObject } from "./tph.js"; @@ -388,7 +389,9 @@ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): Serv }; const covered = new Map(); const relationMap = buildRelationMap(root as never); - for (const obj of root.children().filter(isMetaObject)) { + // A served report is read through its read model (its derived fields as real fields), the + // object every other generator is handed; a report that is not served has no API. + for (const obj of generatableObjects(root.children().filter(isMetaObject), root as MetaRoot)) { if (!hasServiceOperations(obj) || !matches(obj)) continue; const shape = shapeOf(obj, root); const rules = shape.kind === "entity" ? entityRules(obj, claimed, settings) : { lifecycles: [], commands: [] }; @@ -398,8 +401,7 @@ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): Serv bucket(effectivePackage(obj) ?? "").entities.push(e); } // One operation declared identically by two APIs (a versioned API) is one operation (O6). An - // operation whose target the service does not cover (a single-table hierarchy, say) is left to - // later service work, as its entity is. + // operation whose target has no derived operations (a composite key) has none either. const seen = new Set(); for (const op of modelOperations(root)) { const targetNode = operationTarget(op); diff --git a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts index 875ed7d8f..b8c2972a5 100644 --- a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts +++ b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from "bun:test"; -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; import { makeScratchDir, removeTree, scratchRoot } from "../src/scratch-dir.js"; describe("scratch-dir", () => { @@ -22,4 +22,31 @@ describe("scratch-dir", () => { removeTree(a); expect(() => removeTree(a)).not.toThrow(); }); + + // A run with no project keeps its gen-state in the scratch root for the process's later runs. + // Before this, every such process left `meta-gen-state-` behind for good, and the test + // harnesses that generate with no project filled a RAM-backed scratch root with them. + test("a run with no project leaves no gen-state behind once its process exits", () => { + const root = makeScratchDir("scratch-dir-exit-"); + try { + const runner = resolve(import.meta.dir, "../src/runner.ts"); + writeFileSync(join(root, "meta.t.json"), JSON.stringify({ "metadata.root": { package: "t", children: [{ "object.entity": { name: "Thing", children: [{ "field.string": { name: "label" } }] } }] } })); + const script = ` + import { runGen } from ${JSON.stringify(runner)}; + import { loadUris } from "@metaobjectsdev/metadata"; + import { pathToFileURL } from "node:url"; + const { root: metadata } = await loadUris([pathToFileURL(${JSON.stringify(join(root, "meta.t.json"))}).href]); + const out = ${JSON.stringify(join(root, "out"))}; + await runGen({ metadata, config: { outDir: out, generators: [{ name: "one", generate: () => [{ path: "one.txt", content: "1" }] }] } }); + const state = (await import("node:fs")).readdirSync(${JSON.stringify(root)}).filter((n) => n.startsWith("meta-gen-state-")); + if (state.length !== 1) throw new Error("expected the run's gen-state while the process runs, found " + (await import("node:fs")).readdirSync(${JSON.stringify(root)}).join(",")); + `; + const child = Bun.spawnSync(["bun", "-e", script], { env: { ...process.env, DEV_SCRATCH: root }, stderr: "pipe" }); + expect({ exit: child.exitCode, stderr: child.stderr.toString() }).toEqual({ exit: 0, stderr: "" }); + expect(existsSync(join(root, "out", "one.txt"))).toBe(true); + expect(readdirSync(root).filter((n) => n.startsWith("meta-gen-"))).toEqual([]); + } finally { + removeTree(root); + } + }); }); diff --git a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts index bd8b0a604..ec3bdec29 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts @@ -82,8 +82,9 @@ export function startDecimalServer( /** The Postgres or MySQL connection URL; unused by SQLite and D1. */ connectionUrl?: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { - return startGeneratedCorpusServer(DECIMAL, engine, metaPath, connectionUrl, outputLayout); + return startGeneratedCorpusServer(DECIMAL, engine, metaPath, connectionUrl, outputLayout, lane); } /** Generate, provision and mount one generated-lane sub-corpus on `engine`. */ diff --git a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts index 5a9af4aaa..42ddba4e0 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts @@ -22,13 +22,14 @@ // This proves the GENERATED M:N traversal route — not a stand-in — implements // the cross-port contract over HTTP, including the TPH source/target narrowing. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -61,6 +62,7 @@ export async function startGeneratedM2mServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -74,14 +76,14 @@ export async function startGeneratedM2mServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -120,32 +122,19 @@ export const db = drizzle(pool); CREATE TABLE IF NOT EXISTS "blog_categories" ("id" bigserial PRIMARY KEY, "name" varchar(80) NOT NULL); `); - // 4. Import the EMITTED route files unmodified and mount them. - const postRoutes = (await import(pathToFileURL(emitted.locate("Post.routes.ts")).href)) as { - postRoutes: (f: FastifyInstance) => Promise; - }; - const personRoutes = (await import(pathToFileURL(emitted.locate("Person.routes.ts")).href)) as { - personRoutes: (f: FastifyInstance) => Promise; - }; - // FW-8: the TPH discriminator base's routes file carries the polymorphic base - // path AND every per-subtype path (incl. subtype-scoped M:N mounts) in one module. - const accountRoutes = (await import(pathToFileURL(emitted.locate("Account.routes.ts")).href)) as { - accountRoutes: (f: FastifyInstance) => Promise; - }; - // PostCategory takes part in no relationship; it is mounted so the corpus can - // gate the COLLECTION-URL spelling of a multi-word, y-ending entity name. - const postCategoryRoutes = (await import(pathToFileURL(emitted.locate("PostCategory.routes.ts")).href)) as { - postCategoryRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(postRoutes.postRoutes); - await fastify.register(personRoutes.personRoutes); - await fastify.register(accountRoutes.accountRoutes); - await fastify.register(postCategoryRoutes.postCategoryRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it, or the service behind its transport. + // FW-8: the TPH discriminator base's routes file carries the polymorphic base path AND every + // per-subtype path (incl. subtype-scoped M:N mounts) in one module. PostCategory takes part + // in no relationship; it is mounted so the corpus can gate the COLLECTION-URL spelling of a + // multi-word, y-ending entity name. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Post", "Person", "Account", "PostCategory"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -153,7 +142,7 @@ export const db = drizzle(pool); await seedM2m(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts index f43b643f3..f152bdd7e 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts @@ -18,7 +18,7 @@ // projection at all; a hand-rolled reference server would answer every scenario // by construction and prove nothing about the emitted artifact. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -29,6 +29,7 @@ import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { loadMetadataFile } from "./load-metadata.ts"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; export interface ProjectionSeed { invoices: Array<{ @@ -51,6 +52,7 @@ export async function startGeneratedProjectionServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -64,14 +66,14 @@ export async function startGeneratedProjectionServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -117,28 +119,16 @@ export const db = drizzle(pool); SELECT "id", "reference" FROM "invoices"; `); - // 4. Import the EMITTED InvoiceSummary route file unmodified and mount it. - const routes = (await import( - pathToFileURL(emitted.locate("InvoiceSummary.routes.ts")).href - )) as { invoiceSummaryRoutes: (f: FastifyInstance) => Promise }; - const ledgerRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceLedger.routes.ts")).href - )) as { invoiceLedgerRoutes: (f: FastifyInstance) => Promise }; - const registerRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceRegister.routes.ts")).href - )) as { invoiceRegisterRoutes: (f: FastifyInstance) => Promise }; - const stubRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceStub.routes.ts")).href - )) as { invoiceStubRoutes: (f: FastifyInstance) => Promise }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(routes.invoiceSummaryRoutes); - await fastify.register(ledgerRoutes.invoiceLedgerRoutes); - await fastify.register(registerRoutes.invoiceRegisterRoutes); - await fastify.register(stubRoutes.invoiceStubRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: the four projections' routes, or the + // service behind its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["InvoiceSummary", "InvoiceLedger", "InvoiceRegister", "InvoiceStub"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -146,7 +136,7 @@ export const db = drizzle(pool); await seedProjection(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts index 52f385d79..fdbab52d9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts @@ -14,7 +14,7 @@ // // Generated lane only, and on every port — see the corpus README. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -24,6 +24,7 @@ import { DEFAULT_PHYSICAL_NAMING, resolveColumnName, resolveTableName, type MetaRoot, } from "@metaobjectsdev/metadata"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { loadMetadataFile } from "./load-metadata.ts"; @@ -198,6 +199,7 @@ export async function startGeneratedReportServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -211,19 +213,23 @@ export async function startGeneratedReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - // The export cap equals the list cap so the 61-row ReadingLog trips export_too_large; xsi:nil pins the nil spelling. - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + // The export cap equals the list cap so the 61-row ReadingLog trips export_too_large; xsi:nil pins the nil spelling. + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + { reportMaxRows: REPORT_CORPUS_MAX_ROWS }, + ), }), metadata: root, }); @@ -262,21 +268,19 @@ export const db = drizzle(pool); `); // 4. Import the EMITTED route files unmodified and mount every served report. - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) { - throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); } - await fastify.register(registrar); - } - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -284,7 +288,7 @@ export const db = drizzle(pool); await seedReport(connectionUri, root, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts index 2461ba83c..738fd4959 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts @@ -7,13 +7,14 @@ // ADR-0015), create each view from buildReportViews (the real lowering, `dialect: "mysql"`), // import the EMITTED .routes.ts files unmodified and mount them. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig, buildReportViews } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import mysql from "mysql2/promise"; import { REPORT_CORPUS_MAX_ROWS, seedInserts, SERVED_REPORTS, type ReportSeed } from "./api-contract-report-generated-server.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -90,7 +91,7 @@ const BASE_TABLES: ReadonlyArray<{ name: string; ddl: string }> = [ }, ]; -export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, outputLayout: OutputLayout = "flat"): Promise { +export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, outputLayout: OutputLayout = "flat", lane: ApiLane = "routes"): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); mkdirSync(genTmpRoot, { recursive: true }); @@ -102,18 +103,22 @@ export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "mysql", apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + { reportMaxRows: REPORT_CORPUS_MAX_ROWS }, + ), }), metadata: root, }); @@ -136,7 +141,7 @@ export const pool = createPool({ uri: ${JSON.stringify(mysqlUrl)}, timezone: "Z" export const db = drizzle(pool); `; writeFileSync(join(tmp, "db.ts"), dbModule, "utf8"); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: { end(cb: () => void): void } }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: { end(cb: () => void): void }; db: unknown }; const admin = await mysql.createConnection({ uri: mysqlUrl, timezone: "Z" }); const views = buildReportViews(root, { dialect: "mysql" }); @@ -148,18 +153,18 @@ export const db = drizzle(pool); await admin.query(`CREATE VIEW \`${v.name}\` AS ${v.sql}`); } - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); - await fastify.register(registrar); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -175,7 +180,7 @@ export const db = drizzle(pool); } }, close: async () => { - await fastify.close(); + await served.close(); await new Promise((done) => dbMod.pool.end(done)); for (const v of views) await admin.query(`DROP VIEW IF EXISTS \`${v.name}\``); for (const t of [...BASE_TABLES].reverse()) await admin.query(`DROP TABLE IF EXISTS \`${t.name}\``); diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts index f992eba6b..44686ebb4 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts @@ -11,7 +11,7 @@ // spelling, create each view from buildReportViews (the real lowering), import the // EMITTED .routes.ts files unmodified and mount them. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; @@ -20,6 +20,7 @@ import { runGen, defineConfig, buildReportViews } from "@metaobjectsdev/codegen- import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import { loadMetadataFile } from "./load-metadata.ts"; import { REPORT_CORPUS_MAX_ROWS, seedInserts, SERVED_REPORTS, type ReportSeed } from "./api-contract-report-generated-server.ts"; import { startLocalD1 } from "./query-scenario-d1.ts"; @@ -113,6 +114,7 @@ export async function startSqliteReportServer( metaPath: string, engine: SqliteReportEngine = "sqlite", outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -125,18 +127,23 @@ export async function startSqliteReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "sqlite", // codegen has no d1 dialect: D1 is SQLite to Drizzle (only the db module differs) apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + // D1 holds no transaction across application code (ADR-0067 §4). + { reportMaxRows: REPORT_CORPUS_MAX_ROWS, ...(engine === "d1" ? { interactiveTransactions: false } : {}) }, + ), }), metadata: root, }); @@ -159,18 +166,19 @@ export async function startSqliteReportServer( await client.run(`CREATE VIEW "${v.name}" AS ${v.sql}`); } - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); - await fastify.register(registrar); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -186,7 +194,7 @@ export async function startSqliteReportServer( } }, close: async () => { - await fastify.close(); + await served.close(); await client.close(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts index 533134cf4..f949a9d3d 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts @@ -12,13 +12,14 @@ // declares a credential. Their emitted routes are mounted too, so the credential redaction of // the projection and the M:N traversal is driven over HTTP as well. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -81,6 +82,7 @@ export async function startGeneratedSecretFieldsServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -93,14 +95,14 @@ export async function startGeneratedSecretFieldsServer( // The lane provisions its table below in the generated Drizzle table's default spelling. root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -149,19 +151,15 @@ export const db = drizzle(pool); INSERT INTO "payer_auths" ("payer_id", "auth_id") VALUES (1, 1), (1, 2);`, ); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - for (const [file, plugin] of [ - ["Account.routes.ts", "accountRoutes"], - ["AccountView.routes.ts", "accountViewRoutes"], - ["Payer.routes.ts", "payerRoutes"], - ] as const) { - const mod = (await import(pathToFileURL(emitted.locate(file)).href)) as Record Promise>; - await fastify.register(mod[plugin]!); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Account", "AccountView", "Payer"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -182,7 +180,7 @@ export const db = drizzle(pool); return res.rows.map((r) => ({ id: Number(r.id), tokenHash: r.token_hash, pinHash: r.pin_hash })); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts index e9826ad2e..31261d1ce 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts @@ -15,13 +15,14 @@ // This proves the GENERATED TPH routes — not a stand-in — implement the // cross-port contract over HTTP. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -57,6 +58,7 @@ export async function startGeneratedTphServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -70,14 +72,14 @@ export async function startGeneratedTphServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -118,16 +120,16 @@ export const db = drizzle(pool); ); `); - // 4. Import the EMITTED Auth.routes.ts unmodified and mount it. - const authRoutesMod = (await import(pathToFileURL(emitted.locate("Auth.routes.ts")).href)) as { - authRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(authRoutesMod.authRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: Auth.routes.ts (the base path and every + // subtype's), or the service behind its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Auth"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -135,7 +137,7 @@ export const db = drizzle(pool); await seedTph(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-lane.ts b/server/typescript/packages/integration-tests/src/api-lane.ts index a873dc84f..f4aed3d18 100644 --- a/server/typescript/packages/integration-tests/src/api-lane.ts +++ b/server/typescript/packages/integration-tests/src/api-lane.ts @@ -29,12 +29,15 @@ export function apiGenerators( lane: ApiLane, model: Generator[], routes: () => Generator[], - /** The store: Cloudflare D1 holds no transaction across application code (ADR-0067 §4). */ - store: { interactiveTransactions?: boolean } = {}, + /** + * The service generator's options: the store (Cloudflare D1 holds no transaction across + * application code, ADR-0067 §4), and a served report's row cap, which the routes lane gives + * `routesFile` the same way. + */ + service: { interactiveTransactions?: boolean; reportMaxRows?: number } = {}, ): Generator[] { if (lane === "routes") return [...model, ...routes()]; - const service = store.interactiveTransactions === false ? serviceFile({ interactiveTransactions: false }) : serviceFile(); - return [...model, contractTypes(), service, lane === "service" ? serviceRoutesFile() : serviceRoutesHonoFile()]; + return [...model, contractTypes(), serviceFile(service), lane === "service" ? serviceRoutesFile() : serviceRoutesHonoFile()]; } type Factory = (deps: Record) => unknown; diff --git a/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts b/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts index 4bb555b59..8f9c36164 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts @@ -15,11 +15,12 @@ import { loadScenarios, runScenario } from "../src/api-contract-scenario.ts"; import { startDecimalServer, type DecimalEngine } from "../src/api-contract-decimal-server.ts"; import type { ReportSeed } from "../src/api-contract-report-generated-server.ts"; import { startMysql, type MysqlContainerHandle } from "../src/mysql-container.ts"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { OUTPUT_LAYOUTS, postgresFor, type OutputLayout } from "../src/output-layout.ts"; import type { RunningPg } from "../src/postgres-container.ts"; /** Which output layout a lane generates in, and where its Postgres databases come from. */ -interface Lane { layout: OutputLayout; startPg: (() => Promise) | undefined } +interface Lane { api: ApiLane; layout: OutputLayout; startPg: (() => Promise) | undefined } const SEED = JSON.parse(readFileSync(join(API_CONTRACT_DECIMAL_DIR, "seed.json"), "utf8")) as ReportSeed; const META_PATH = join(API_CONTRACT_DECIMAL_DIR, "meta.json"); @@ -38,14 +39,14 @@ async function withServer( if (engine === "postgres") { const pg = await lane.startPg!(); try { - const server = await startDecimalServer(engine, META_PATH, pg.connectionUri, lane.layout); + const server = await startDecimalServer(engine, META_PATH, pg.connectionUri, lane.layout, lane.api); try { await server.applySeed(seed); await fn(server.baseUrl); } finally { await server.close(); } } finally { await pg.stop(); } return; } - const server = await startDecimalServer(engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout); + const server = await startDecimalServer(engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout, lane.api); try { await server.applySeed(seed); await fn(server.baseUrl); } finally { await server.close(); } } @@ -53,8 +54,8 @@ const scenarios = loadScenarios(API_CONTRACT_DECIMAL_SCENARIOS_DIR); // The package layout skips D1 (a Miniflare process per test, the same routes as SQLite) and, on // MySQL, the scenario loop (Postgres and SQLite run every scenario in both layouts). -for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract decimal (ADR-0019 Amendment 1) — GENERATED routes on ${engine} [${layout}]`, () => { - const lane: Lane = { layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined }; +for (const api of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract decimal (ADR-0019 Amendment 1) — ${laneLabel(api)} on ${engine} [${layout}]`, () => { + const lane: Lane = { api, layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined }; for (const scenario of layout === "package" && engine === "mysql" ? [] : scenarios) { if (scenario.engines !== undefined && !scenario.engines.includes(engine)) continue; test(scenario.name, async () => { diff --git a/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts b/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts index 51bce8cd6..82f0247bd 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts @@ -11,6 +11,7 @@ // assertion runner, so a contract drift in either surfaces here. import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_M2M_DIR, API_CONTRACT_M2M_SCENARIOS_DIR } from "../src/paths.ts"; @@ -47,14 +48,14 @@ describe("api contract M:N — hand-rolled reference lane", () => { } }); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract M:N — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract M:N — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_M2M_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedM2mServerHandle | null = null; try { - server = await startGeneratedM2mServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedM2mServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server, openApiCheck("m2m")); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts b/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts index 629d6f9e4..67eede576 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts @@ -11,6 +11,7 @@ // scenario (full isolation). import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { @@ -33,14 +34,14 @@ const META_PATH = join(API_CONTRACT_PROJECTION_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("projection"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract projection (F22) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract projection (F22) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_PROJECTION_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedProjectionServerHandle | null = null; try { - server = await startGeneratedProjectionServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedProjectionServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts index 506aa2c5f..9ca8564cc 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts @@ -9,6 +9,7 @@ // METAOBJECTS_TEST_MYSQL_URL). import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -33,8 +34,8 @@ let container: MysqlContainerHandle; beforeAll(async () => { container = await startMysql(); }, 240_000); afterAll(() => { container?.stop(); }, 60_000); -async function withServer(layout: OutputLayout, fn: (server: MysqlReportServerHandle) => Promise, seed: ReportSeed = SEED): Promise { - const server = await startMysqlReportServer(container.url, META_PATH, layout); +async function withServer(layout: OutputLayout, lane: ApiLane, fn: (server: MysqlReportServerHandle) => Promise, seed: ReportSeed = SEED): Promise { + const server = await startMysqlReportServer(container.url, META_PATH, layout, lane); try { await server.applySeed(seed); await fn(server); @@ -43,9 +44,9 @@ async function withServer(layout: OutputLayout, fn: (server: MysqlReportServerHa } } -for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — GENERATED routes on MySQL [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — ${laneLabel(lane)} on MySQL [${layout}]`, () => { test("a ratio is a decimal string (MySQL keeps its scale), and the integers around it stay numbers", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { const res = await fetch(server.baseUrl + "/api/invoice_totals"); expect(res.status).toBe(200); const rows = (await res.json()) as Array>; @@ -58,14 +59,14 @@ for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — }, { timeout: 120_000 }); test("a ratio over zero rows is null", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { const res = await fetch(server.baseUrl + "/api/invoice_totals"); expect(await res.json()).toEqual([{ invoices: 0, totalCents: null, paidShare: null }]); }, { invoices: [] }); }, { timeout: 120_000 }); test("the seeded report rows are what the views return", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { for (const [name, path] of SERVED_PATHS) { const res = await fetch(server.baseUrl + path); expect(res.status).toBe(200); @@ -87,7 +88,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — // Postgres report lane runs every scenario in both layouts. for (const scenario of layout === "flat" ? loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR) : []) { test(`shared scenario: ${scenario.name}`, async () => { - await withServer(layout, (server) => runScenario(scenario, server.baseUrl)); + await withServer(layout, lane, (server) => runScenario(scenario, server.baseUrl)); }, { timeout: 120_000 }); } }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts index 26b6a3d2e..d18fba2dd 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts @@ -15,6 +15,7 @@ // filtering, sorting and paging a decimal measure behave the same on both engines. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -36,10 +37,11 @@ const ENGINES: readonly SqliteReportEngine[] = ["sqlite", "d1"]; async function withServer( engine: SqliteReportEngine, layout: OutputLayout, + lane: ApiLane, fn: (server: SqliteReportServerHandle) => Promise, seed: ReportSeed = SEED, ): Promise { - const server = await startSqliteReportServer(META_PATH, engine, layout); + const server = await startSqliteReportServer(META_PATH, engine, layout, lane); try { await server.applySeed(seed); await fn(server); @@ -56,9 +58,9 @@ async function getJson(server: SqliteReportServerHandle, path: string): Promise< // D1 starts a Miniflare (workerd) process per test and emits the same routes as SQLite (only the // db module differs), so the package layout runs on SQLite alone. -for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract report (FR-044) — GENERATED routes on ${engine === "d1" ? "Cloudflare D1 (local)" : "SQLite"} [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract report (FR-044) — ${laneLabel(lane)} on ${engine === "d1" ? "Cloudflare D1 (local)" : "SQLite"} [${layout}]`, () => { test("a ratio is a JSON string, as it is on Postgres, and the integers around it stay numbers", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows.length).toBe(1); const row = rows[0]!; @@ -70,7 +72,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio is a string in the withCount envelope too", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const body = (await getJson(server, "/api/invoice_totals?withCount=1")) as { rows: Array>; total: number; }; @@ -80,14 +82,14 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio over zero rows is null, not the string 'null' or 0", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows).toEqual([{ invoices: 0, totalCents: null, paidShare: null }]); }, { invoices: [] }); }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a report with no decimal field is untouched: every value keeps its type", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { expect(await getJson(server, "/api/invoice_status_totals?sort=status:asc")).toEqual( SEED.reports!["InvoiceStatusTotals"], ); @@ -101,7 +103,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("the filter and the sort on a ratio still compare numerically after the wire change", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const hit = async (path: string): Promise => ((await getJson(server, path)) as unknown[]).length; expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.3")).toBe(1); expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.5")).toBe(0); @@ -114,7 +116,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN for (const scenario of loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR)) { test(`shared scenario: ${scenario.name}`, async () => { - await withServer(engine, layout, (server) => runScenario(scenario, server.baseUrl)); + await withServer(engine, layout, lane, (server) => runScenario(scenario, server.baseUrl)); }, { timeout: SERVER_TEST_TIMEOUT_MS }); } }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-report.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report.test.ts index eab0e41c4..5235cf0b1 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report.test.ts @@ -6,6 +6,7 @@ // lane only — see the corpus README. One Postgres testcontainer per scenario. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -37,14 +38,14 @@ const SERVED_PATHS: Array<[string, string]> = [ const contractCheck: ContractCheck = openApiCheck("report"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedReportServerHandle | null = null; try { - server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { @@ -58,7 +59,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — const pg = await startDb(); let server: GeneratedReportServerHandle | null = null; try { - server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); for (const [name, path] of SERVED_PATHS) { const res = await fetch(server.baseUrl + path); diff --git a/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts b/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts index e23d1c66b..6faafe1bd 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts @@ -7,6 +7,7 @@ // per scenario. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { @@ -36,14 +37,14 @@ const META_PATH = join(API_CONTRACT_SECRET_FIELDS_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("secret-fields"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_SECRET_FIELDS_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedSecretFieldsServerHandle | null = null; try { - server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); if (scenario.name === "write-ignores-excluded") await expectDeniedColumnsUntouched(server); @@ -61,7 +62,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) const pg = await startDb(); let server: GeneratedSecretFieldsServerHandle | null = null; try { - server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); const list = await getJson(server, "/api/account_views"); @@ -86,14 +87,14 @@ const TPH_META_PATH = join(API_CONTRACT_SECRET_FIELDS_TPH_DIR, "meta.json"); // A TPH hierarchy shares one table, so a column any subtype marks as a credential is one for the // whole table: the base and both subtypes refuse a filter or sort on it. -for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields — TPH sibling credential — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields — TPH sibling credential — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_SECRET_FIELDS_TPH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedTphServerHandle | null = null; try { - server = await startGeneratedTphServer(pg.connectionUri, TPH_META_PATH, layout); + server = await startGeneratedTphServer(pg.connectionUri, TPH_META_PATH, layout, lane); await server.applySeed(TPH_SEED); for (const req of scenario.requests) { const res = await fetch(server.baseUrl + req.path, { method: req.method }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts b/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts index ba0510bf9..ffd598c5f 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts @@ -12,6 +12,7 @@ // + assertion runner, so a contract drift in either surfaces here. import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_TPH_DIR, API_CONTRACT_TPH_SCENARIOS_DIR } from "../src/paths.ts"; @@ -54,14 +55,14 @@ describe("api contract TPH — hand-rolled reference lane", () => { } }); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract TPH — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract TPH — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_TPH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedTphServerHandle | null = null; try { - server = await startGeneratedTphServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedTphServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server, openApiCheck("tph")); } finally { diff --git a/spec/decisions/ADR-0067-layering-and-the-service-seam.md b/spec/decisions/ADR-0067-layering-and-the-service-seam.md index 2c41674db..b435e1f4d 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -18,7 +18,10 @@ and every generator below is a helper. Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in TypeScript, and C# writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: `service` writes each package's derived list, get, create, update and delete in one transaction with -the declared write rules, and `service-routes` the thin Fastify transport over it, with +the declared write rules, for every object the flat routes serve: a projection's and a served +report's reads (their writes answer 405), a write-through entity's writes read back through its +view, a single-table hierarchy's polymorphic base reads and per-subtype operations, and each +many-to-many traversal, and `service-routes` the thin Fastify transport over it, with `service-routes-hono` its Hono twin (the `service` layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, with the policy, bodies, hooks and events interfaces, and enforce the rules at run time. The other From 4d59b3606ddf063673e686348a833f140fba13b7 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 12:43:36 -0500 Subject: [PATCH 12/17] fix: examples own the read-only and M:N read modules; the eject contract ignores import wrapping --- .../runtime/drizzle-fastify/mount-m2m.ts | 100 +------- .../drizzle-fastify/mount-read-only.ts | 223 +++--------------- .../codegen/runtime/m2m-read.ts | 107 +++++++++ .../codegen/runtime/read-only-read.ts | 197 ++++++++++++++++ .../runtime/drizzle-fastify/mount-m2m.ts | 100 +------- .../drizzle-fastify/mount-read-only.ts | 223 +++--------------- examples/showcase/codegen/runtime/m2m-read.ts | 107 +++++++++ .../codegen/runtime/read-only-read.ts | 197 ++++++++++++++++ .../packages/cli/test/eject-contract.test.ts | 9 +- 9 files changed, 690 insertions(+), 573 deletions(-) create mode 100644 examples/advanced-modeling/codegen/runtime/m2m-read.ts create mode 100644 examples/advanced-modeling/codegen/runtime/read-only-read.ts create mode 100644 examples/showcase/codegen/runtime/m2m-read.ts create mode 100644 examples/showcase/codegen/runtime/read-only-read.ts diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts index ffb804776..0529ac7c3 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts index cec28d7fa..44a142366 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/examples/advanced-modeling/codegen/runtime/m2m-read.ts b/examples/advanced-modeling/codegen/runtime/m2m-read.ts new file mode 100644 index 000000000..57bd984c0 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/examples/advanced-modeling/codegen/runtime/read-only-read.ts b/examples/advanced-modeling/codegen/runtime/read-only-read.ts new file mode 100644 index 000000000..1ae074d3c --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage> { + readonly rows: T[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts index ffb804776..0529ac7c3 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts index cec28d7fa..44a142366 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/examples/showcase/codegen/runtime/m2m-read.ts b/examples/showcase/codegen/runtime/m2m-read.ts new file mode 100644 index 000000000..57bd984c0 --- /dev/null +++ b/examples/showcase/codegen/runtime/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/examples/showcase/codegen/runtime/read-only-read.ts b/examples/showcase/codegen/runtime/read-only-read.ts new file mode 100644 index 000000000..1ae074d3c --- /dev/null +++ b/examples/showcase/codegen/runtime/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage> { + readonly rows: T[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index 69950237c..e42a7392f 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -394,8 +394,9 @@ async function emit( /** * The one difference an owned copy's output is allowed: it imports the HTTP adapter the * adopter owns in `codegen/runtime/`, where packaged output imports the package. The - * formatter orders a package import and a relative one differently, so the import block - * is compared as a set of statements and everything after it exactly. + * formatter orders a package import and a relative one differently, and the longer relative + * path can wrap a named-import list across lines, so the import block is compared as a set of + * statements with their whitespace collapsed, and everything after it exactly. */ function adapterNeutral(source: string): string { const adapter = "@@ADAPTER@@"; @@ -404,7 +405,9 @@ function adapterNeutral(source: string): string { .replace(new RegExp(`${HTTP_RUNTIME_PACKAGE}(?:/[\\w-]+)+`, "g"), adapter) .replace(new RegExp(`(?:\\.\\./)+${OWNED_RUNTIME_DIR}/[\\w-]+/[\\w-]+`, "g"), adapter); const IMPORT = /^import [^;]*;\n/gm; - return [...(moved.match(IMPORT) ?? [])].sort().join("") + moved.replace(IMPORT, ""); + const oneLine = (stmt: string): string => + `${stmt.replace(/\s+/g, " ").replace(/\{ /g, "{ ").replace(/,? \}/g, " }").trim()}\n`; + return [...(moved.match(IMPORT) ?? [])].map(oneLine).sort().join("") + moved.replace(IMPORT, ""); } describe("eject contract — depth", () => { From 3adb794a4e8b81308683d21f2084efe6355e5633 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 12:55:09 -0500 Subject: [PATCH 13/17] fix(codegen-ts): a single-table subtype's transition commands and keyed operations address its base's table, scoped to its discriminator --- CHANGELOG.md | 2 +- .../packages/cli/test/eject-contract.test.ts | 2 +- .../packages/codegen-ts/src/scratch-dir.ts | 3 +- .../packages/codegen-ts/src/service-walk.ts | 16 +++---- .../codegen-ts/src/templates/service-file.ts | 32 +++++++++---- .../codegen-ts/test/service-file.test.ts | 48 +++++++++++++++++++ .../test/fixtures/service-tph-lifecycle.json | 44 +++++++++++++++++ .../test/service-compile.test.ts | 10 ++++ 8 files changed, 137 insertions(+), 20 deletions(-) create mode 100644 server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json diff --git a/CHANGELOG.md b/CHANGELOG.md index bc1aad9cb..3b6443189 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,7 +33,7 @@ here.** functions, which the flat Fastify mounts and the service both call. - **codegen-ts: a `runGen` with no project no longer leaves its gen-state in the scratch root.** The state of such a run is kept for that process's later runs only, and is removed when the - process exits. Before this fix, each such process left `meta-gen-state-` behind + process exits normally (a process killed by a signal still leaves it). Before this fix, each such process left `meta-gen-state-` behind permanently. The test harnesses that generate with no project had left hundreds of those directories, about 3 GB, in a RAM-backed `$DEV_SCRATCH`. diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index e42a7392f..62054d79c 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -406,7 +406,7 @@ function adapterNeutral(source: string): string { .replace(new RegExp(`(?:\\.\\./)+${OWNED_RUNTIME_DIR}/[\\w-]+/[\\w-]+`, "g"), adapter); const IMPORT = /^import [^;]*;\n/gm; const oneLine = (stmt: string): string => - `${stmt.replace(/\s+/g, " ").replace(/\{ /g, "{ ").replace(/,? \}/g, " }").trim()}\n`; + `${stmt.replace(/\s+/g, " ").replace(/\{ ?/g, "{ ").replace(/,? ?\}/g, " }").trim()}\n`; return [...(moved.match(IMPORT) ?? [])].map(oneLine).sort().join("") + moved.replace(IMPORT, ""); } diff --git a/server/typescript/packages/codegen-ts/src/scratch-dir.ts b/server/typescript/packages/codegen-ts/src/scratch-dir.ts index 9e199f3c2..9f313028e 100644 --- a/server/typescript/packages/codegen-ts/src/scratch-dir.ts +++ b/server/typescript/packages/codegen-ts/src/scratch-dir.ts @@ -51,7 +51,8 @@ export function removeTree(path: string): void { const removedAtExit = new Set(); /** - * Remove `path` when this process exits. For state a process shares across its own runs and no + * Remove `path` when this process exits normally (the `exit` event; a process killed by a signal + * leaves it behind). For state a process shares across its own runs and no * later process reads (runGen's gen-state for a run with no project): without it, every process * that ever ran one left a directory in the scratch root. */ diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index f390ef1a5..20fc35c4d 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -228,7 +228,7 @@ export function hasServiceOperations(obj: MetaObject): boolean { } /** The verbs, storage, path and scope of a covered object. */ -function shapeOf(obj: MetaObject, root: MetaData): Pick { +function shapeOf(obj: MetaObject, root: MetaRoot): Pick { const path = restPath(obj); if (isProjection(obj)) { const keyed = itemRouteField(obj) !== undefined; @@ -237,11 +237,11 @@ function shapeOf(obj: MetaObject, root: MetaData): Pick st.entity)]; return { kind: "entity", verbs: DERIVED_OPERATIONS, storage: base, readView: false, path, discriminator: { field: pin.fieldName, value: pin.value }, hierarchy }; } - const plan = declaresTphDiscriminator(obj) ? tphPlan(obj, root as never) : null; + const plan = declaresTphDiscriminator(obj) ? tphPlan(obj, root) : null; if (plan !== null) { // The polymorphic base is read-only by construction: the union has no single writable shape. return { kind: "entity", verbs: ["list", "get"], storage: obj, readView: false, path, discriminator: undefined, hierarchy: [obj, ...plan.subtypes.map((st) => st.entity)] }; @@ -250,12 +250,12 @@ function shapeOf(obj: MetaObject, root: MetaData): Pick true); const settings = rulesSettingsOfModel(root); const claimed = claimedTransitions(root); @@ -388,10 +388,10 @@ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): Serv return b; }; const covered = new Map(); - const relationMap = buildRelationMap(root as never); + const relationMap = buildRelationMap(root); // A served report is read through its read model (its derived fields as real fields), the // object every other generator is handed; a report that is not served has no API. - for (const obj of generatableObjects(root.children().filter(isMetaObject), root as MetaRoot)) { + for (const obj of generatableObjects(root.children().filter(isMetaObject), root)) { if (!hasServiceOperations(obj) || !matches(obj)) continue; const shape = shapeOf(obj, root); const rules = shape.kind === "entity" ? entityRules(obj, claimed, settings) : { lifecycles: [], commands: [] }; diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index 7480366a0..e570036d7 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -170,6 +170,21 @@ function sourcesOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderConte return { table, read: view, view }; } +/** + * The table a transition command or a keyed declared operation addresses, and its key condition: + * the storage table, which for a single-table subtype is its base's, scoped to its discriminator + * value. The loader admits only an `object.entity` as an operation's target (ADR-0066). + */ +function addressedOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext, runtime: string): { table: string; cond: () => string } { + const table = w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity); + const cond = (): string => { + const key = `${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id)`; + const scope = scopeExpr(w, e, table, runtime); + return scope === undefined ? key : `${w.use("scoped", runtime)}(${key}, ${scope})`; + }; + return { table, cond }; +} + /** The row type of an entity's operations: its contract type, or a report's row type from its entity module. */ function rowTypeOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): string { const mods = modulesOf(path, e.obj, ctx); @@ -616,9 +631,8 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, const w = new TsWriter(); header(w, `${name} (${obj.fqn()}) — transition ${t.field}.${t.name}, service operation ${c.fn} (ADR-0066 §2)`); const runtime = runtimeSpecifierFrom(path, "service", ctx); - const mods = modulesOf(path, obj, ctx); - const table = w.use(ctx.collectionName(name), mods.entity); - const row = w.useType(name, mods.contract); + const { table, cond } = addressedOf(w, e, path, ctx, runtime); + const row = w.useType(name, modulesOf(path, obj, ctx).contract); const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); @@ -645,7 +659,7 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, ); w.block(`export async function ${c.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${w.use(inTx ? "inWriteTransaction" : "withoutTransaction", runtime)}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id);`); + w.line(`const cond = ${cond()};`); w.line(`const current = (await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${w.use("notFound", runtime)}();`); if (c.permission === undefined) w.line("// @public: the policy is not asked."); @@ -678,12 +692,12 @@ function renderDeclaredOperation(op: ServiceOperation, path: string, ctx: Render const target = op.target; // The target's table and row type, imported only by an operation that reads or answers its row. const usesRow = op.keyed || outputIsTargetRow(op); - const mods = target === undefined || !usesRow ? undefined : modulesOf(path, target.obj, ctx); - const table = mods === undefined ? undefined : w.use(ctx.collectionName(target!.obj.name), mods.entity); - const row = mods === undefined ? undefined : w.useType(target!.obj.name, mods.contract); + const command = op.kind === "command"; + const addressed = target === undefined || !usesRow ? undefined : addressedOf(w, target, path, ctx, runtime); + const table = addressed?.table; + const row = addressed === undefined ? undefined : w.useType(target!.obj.name, modulesOf(path, target!.obj, ctx).contract); const output = outputType(w, op, path, pkg, ctx); const params = [...operationParams(w, op, path, pkg, ctx), `opts: ${opOptions} = {}`]; - const command = op.kind === "command"; if (op.input !== undefined) { w.doc("What the input may name: every other key is refused."); @@ -717,7 +731,7 @@ function renderDeclaredOperation(op: ServiceOperation, path: string, ctx: Render const scope = command ? w.use("inWriteTransaction", runtime) : w.use("inReadScope", runtime); w.block(`return ${scope}(deps.db, opts.tx, async (tx) => {`, () => { if (op.keyed) { - w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(target!.keyField)}, id);`); + w.line(`const cond = ${addressed!.cond()};`); const load = command ? `await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})` : `await ${w.use("readOne", runtime)}(tx, ${table}, cond)`; diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index ada0d8a02..6ab1b6e5c 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -288,6 +288,54 @@ describe("service generators — lifecycles and declared operations (ADR-0066)", }); }); +describe("service generators — commands and keyed operations address the object's own storage", () => { + const ticket = { + "object.entity": { + name: "Ticket", + "@discriminator": "type", + children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "type", "@values": ["Bug", "Task"] } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, + }; + const bug = { + "object.entity": { + name: "BugTicket", + extends: "Ticket", + "@discriminatorValue": "Bug", + children: [ + { + "field.enum": { + name: "status", + "@values": ["open", "closed"], + "@default": "open", + children: [{ "transition.action": { name: "close", "@from": ["open"], "@to": "closed", "@public": true } }], + }, + }, + ], + }, + }; + test("a single-table subtype's transition command writes the base's table, scoped to its discriminator value", async () => { + const files = await gen(await load("acme::desk", [ticket, bug]), tier()); + const close = files["acme/desk/service/closeBugTicket.ts"]!; + expect(close).toBeDefined(); + // The subtype's module exports no table: the rows live in the base's. + expect(close).toMatch(/import \{ tickets \} from "\.\.\/Ticket(\.js)?";/); + expect(close).toContain('const cond = scoped(keyCondition(tickets, "id", id), scopeCondition(tickets, "type", "Bug"));'); + }); + + test("a keyed declared operation on a single-table subtype reads only rows of its discriminator value", async () => { + const peek = { "operation.query": { name: "peek", "@objectRef": "BugTicket", "@outputRef": "BugTicket", "@public": true } }; + const files = await gen(await load("acme::desk", [ticket, bug, api(peek)]), tier()); + const op = files["acme/desk/service/peek.ts"]!; + expect(op).toMatch(/import \{ tickets \} from "\.\.\/Ticket(\.js)?";/); + expect(op).toContain('const cond = scoped(keyCondition(tickets, "id", id), scopeCondition(tickets, "type", "Bug"));'); + }); +}); + describe("service generator — a store without interactive transactions (ADR-0067 §4)", () => { const noTx = (): Generator[] => [entityFile(), contractTypes(), serviceFile({ interactiveTransactions: false }), serviceRoutesFile()]; const peek = { "operation.query": { name: "peek", "@objectRef": "Order", "@outputRef": "Order", "@public": true } }; diff --git a/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json b/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json new file mode 100644 index 000000000..2a9c66d64 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json @@ -0,0 +1,44 @@ +{ + "metadata.root": { + "package": "acme::desk", + "children": [ + { "object.entity": { + "name": "Ticket", + "@discriminator": "type", + "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bug", "Task"] } }, + { "field.string": { "name": "title", "@maxLength": 80 } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + }}, + { "object.entity": { + "name": "BugTicket", + "extends": "Ticket", + "@discriminatorValue": "Bug", + "children": [ + { "field.enum": { + "name": "status", + "@values": ["open", "closed"], + "@default": "open", + "children": [ + { "transition.action": { "name": "close", "@from": ["open"], "@to": "closed", "@public": true } } + ] + }} + ] + }}, + { "object.entity": { + "name": "TaskTicket", + "extends": "Ticket", + "@discriminatorValue": "Task" + }}, + { "api.operational": { + "name": "Desk", + "children": [ + { "operation.query": { "name": "peek", "@objectRef": "BugTicket", "@outputRef": "BugTicket", "@public": true } } + ] + }} + ] + } +} diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts index 410be3ad0..dd4a7e40e 100644 --- a/server/typescript/packages/integration-tests/test/service-compile.test.ts +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -74,6 +74,10 @@ function emittedTs(dir: string): string[] { return out.sort(); } +// A single-table (TPH) subtype that carries a lifecycle and is a keyed operation's target: its +// command and operation address the base's table, scoped to the subtype's discriminator value. +const TPH_LIFECYCLE = resolve(dirname(fileURLToPath(import.meta.url)), "fixtures", "service-tph-lifecycle.json"); + const CORPORA = [ { label: "the shared fitness corpus", path: CORPUS, pkg: "fitness", present: ["fitness/service/createProgram.ts"] }, { @@ -82,6 +86,12 @@ const CORPORA = [ pkg: "acme/purchasing", present: ["acme/purchasing/service/submitPurchaseRequest.ts", "acme/purchasing/service/decide.ts", "acme/purchasing/service/requestTotals.ts"], }, + { + label: "a single-table subtype with a lifecycle", + path: TPH_LIFECYCLE, + pkg: "acme/desk", + present: ["acme/desk/service/closeBugTicket.ts", "acme/desk/service/peek.ts"], + }, // A store without interactive transactions (Cloudflare D1, which generates as `sqlite`): the // service with no transaction, no hooks and no event hook (ADR-0067 §4). { From b2de19f5192a7d363355332881aabe19db2c7243 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 12:58:30 -0500 Subject: [PATCH 14/17] refactor(codegen-ts): one key-and-scope condition builder for the service's keyed reads and writes --- .../codegen-ts/src/templates/service-file.ts | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index e570036d7..e5d9db322 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -177,12 +177,17 @@ function sourcesOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderConte */ function addressedOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext, runtime: string): { table: string; cond: () => string } { const table = w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity); - const cond = (): string => { - const key = `${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id)`; - const scope = scopeExpr(w, e, table, runtime); - return scope === undefined ? key : `${w.use("scoped", runtime)}(${key}, ${scope})`; - }; - return { table, cond }; + return { table, cond: () => addressedCond(w, e, table, table, runtime) }; +} + +/** + * The key condition of a keyed operation on `on` (a table or a read view), scoped to the single-table + * subtype's discriminator on `scopeTable` (the storage table). + */ +function addressedCond(w: TsWriter, e: ServiceEntity, on: string, scopeTable: string, runtime: string): string { + const key = `${w.use("keyCondition", runtime)}(${on}, ${str(e.keyField)}, id)`; + const scope = scopeExpr(w, e, scopeTable, runtime); + return scope === undefined ? key : `${w.use("scoped", runtime)}(${key}, ${scope})`; } /** The row type of an entity's operations: its contract type, or a report's row type from its entity module. */ @@ -228,10 +233,7 @@ function renderOperation( const keyField = str(e.keyField); const id = "id: number | string"; const scope = scopeExpr(w, e, table, runtime); - const addressed = (on: string) => { - const cond = `${w.use("keyCondition", runtime)}(${on}, ${keyField}, id)`; - return scope === undefined ? cond : `${w.use("scoped", runtime)}(${cond}, ${scope})`; - }; + const addressed = (on: string) => addressedCond(w, e, on, table, runtime); const readOnly = e.kind !== "entity"; if (op === "list" && readOnly) { From 3fcb389f8f76bd59126e27aca5e9541c7c3763e0 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 18:18:33 -0500 Subject: [PATCH 15/17] no-mistakes(test): Move typed-create compile test temp dirs to scratch --- .../test/typed-create-compile.test.ts | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts index a638328b9..a35b0694a 100644 --- a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts @@ -12,7 +12,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -23,7 +23,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; -import { removeTree } from "../src/scratch-dir.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -53,6 +53,18 @@ const MODEL = { }, }; +/** + * A throwaway directory under the scratch root, never under `test/`: the package typecheck + * compiles `test/**`, so a half-written caller there (or one a killed run left behind, holding + * a deliberately misspelt call) fails it. Its `node_modules` links to this package's, so the + * generated tree resolves drizzle-orm / zod to the REAL types. + */ +function makeCompileDir(prefix: string): string { + const dir = makeScratchDir(prefix); + symlinkSync(join(import.meta.dir, "..", "node_modules"), join(dir, "node_modules"), "dir"); + return dir; +} + async function loadModel(): Promise { const result = await new MetaDataLoader({ strict: true }).load([ new InMemoryStringSource(JSON.stringify(MODEL), { id: "typed-create.json" }), @@ -107,7 +119,7 @@ function compile(dir: string, paths: string[]): string[] { /** Generate the tree, add `caller.ts` with `body`, compile everything; the caller's diagnostics. */ async function compileCaller(dialect: Dialect, body: string): Promise<{ all: string[]; caller: string[] }> { const root = await loadModel(); - const dir = mkdtempSync(join(import.meta.dir, `tmp-typed-create-${dialect}-`)); + const dir = makeCompileDir(`typed-create-${dialect}-`); try { const files = await generate(root, dialect, dir); for (const f of files) writeFileSync(join(dir, f.path), f.content); @@ -133,7 +145,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { describe(`generated create calls are typed with the insert input (${dialect})`, () => { test("the signatures name the typed input, not unknown", async () => { const root = await loadModel(); - const dir = mkdtempSync(join(import.meta.dir, `tmp-typed-create-src-${dialect}-`)); + const dir = makeScratchDir(`typed-create-src-${dialect}-`); try { const files = await generate(root, dialect, dir); const brewer = files.find((f) => f.path === "Brewer.ts")!.content.replace(/\s+/g, " "); From ae4f2dcd03369107454628bb4a01640a62006228 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 18:29:11 -0500 Subject: [PATCH 16/17] no-mistakes(document): docs: service lane coverage in api-contract docs --- docs/CONFORMANCE.md | 2 +- fixtures/api-contract-conformance/README.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 03e2c5e7d..e0f346a4e 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 5de4f7064..9ab04340d 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -270,8 +270,9 @@ against a Postgres testcontainer over HTTP, and by service lanes beside the seco Hono transport (layer 5). The `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` and `duration/` corpora, the root corpus and `rules/` run on them, in both output layouts, on every engine the generated-routes lane runs for the corpus. D1 generates its service - with `interactiveTransactions: false`. The `projection/`, `report/`, `tph/`, `m2m/`, - `write-through/`, `secret-fields/` and `decimal/` corpora stay on the generated-routes lane. + with `interactiveTransactions: false`. The `projection/`, `report/` (Postgres, MySQL, SQLite + and D1), `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` corpora run on + both service lanes too. Both lanes live in `server/typescript/packages/integration-tests/test/` and are run by the same `cd server/typescript/packages/integration-tests && bun test` From dfe371fb5d2110cd43c9f04ed4338abb1f5249e9 Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 18:32:40 -0500 Subject: [PATCH 17/17] no-mistakes(lint): Report site transcript capture failures distinctly --- scripts/site/payload.ts | 16 +++++++++++--- scripts/site/transcript.test.ts | 29 +++++++++++++++++++++++++- scripts/site/transcript.ts | 37 ++++++++++++++++++++++++++++++--- 3 files changed, 75 insertions(+), 7 deletions(-) diff --git a/scripts/site/payload.ts b/scripts/site/payload.ts index a211549f0..ce5fd795d 100644 --- a/scripts/site/payload.ts +++ b/scripts/site/payload.ts @@ -29,7 +29,7 @@ import { extractMarkedRegion } from "./markers.js"; import { splitLines, matchSubsequence, renderWithElisions } from "./subsequence.js"; import { loadVocabulary, highlightMetadata, type Vocabulary } from "./highlight-metadata.js"; import { highlightCode } from "./highlight-code.js"; -import { captureTranscript, normalizeTranscript, HOME_PATH } from "./transcript.js"; +import { captureTranscript, captureFailure, normalizeTranscript, HOME_PATH } from "./transcript.js"; import { deriveCounts, type Counts } from "./counts.js"; export interface Snippet { @@ -206,7 +206,12 @@ function wholeSnippet(repoRoot: string, src: Extract): Snippet { - const { text, exitCode } = captureTranscript(src.argv, resolve(repoRoot, src.cwd)); + const capture = captureTranscript(src.argv, resolve(repoRoot, src.cwd)); + const failure = captureFailure(capture); + if (failure) { + throw new Error(`site payload: the "${id}" transcript was not captured: ${failure}.`); + } + const { text, exitCode } = capture; if (exitCode === 0) { throw new Error( `site payload: the "${id}" fixture now PASSES (exit 0).\n` + @@ -240,7 +245,12 @@ function transcriptSnippet(repoRoot: string, id: string, */ function assertRequirementsResolve(repoRoot: string): void { const showcase = resolve(repoRoot, "examples/showcase"); - const { text, exitCode } = captureTranscript(["verify", ...PROMPTS_ARGS], showcase); + const capture = captureTranscript(["verify", ...PROMPTS_ARGS], showcase); + const failure = captureFailure(capture); + if (failure) { + throw new Error(`site payload: \`meta verify\` on examples/showcase was not captured: ${failure}.`); + } + const { text, exitCode } = capture; if (exitCode !== 0) { throw new Error( `site payload: \`meta verify\` fails on examples/showcase (exit ${exitCode}).\n` + diff --git a/scripts/site/transcript.test.ts b/scripts/site/transcript.test.ts index f74fc2856..ea1272edd 100644 --- a/scripts/site/transcript.test.ts +++ b/scripts/site/transcript.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from "bun:test"; import { resolve } from "node:path"; -import { captureTranscript, normalizeTranscript, HOME_PATH } from "./transcript.js"; +import { captureTranscript, captureFailure, normalizeTranscript, HOME_PATH, type Capture } from "./transcript.js"; const REPO = resolve(import.meta.dirname, "../.."); @@ -67,3 +67,30 @@ describe("captureTranscript", () => { expect(() => normalizeTranscript(r.text, REPO)).not.toThrow(); }); }); + +// A CLI that never ran must not be reported as "the diagnostic changed". Injected +// spawn results, so the cases do not depend on actually starving the machine. +describe("captureFailure", () => { + const ran: Capture = { text: "ERR_X", exitCode: 1, signal: null, error: undefined }; + + test("a capture that ran and failed with output is not a capture failure", () => { + expect(captureFailure(ran)).toBeNull(); + expect(captureFailure({ ...ran, exitCode: 0, text: "" })).toBeNull(); + }); + + test("names the signal when the CLI was killed", () => { + expect(captureFailure({ ...ran, text: "", signal: "SIGTRAP" })) + .toBe("the CLI was killed by SIGTRAP; the capture did not run"); + }); + + test("names the errno when the CLI failed to spawn", () => { + const error = Object.assign(new Error("spawn bun EAGAIN"), { code: "EAGAIN" }); + expect(captureFailure({ ...ran, text: "", error })) + .toBe("the CLI failed to spawn (EAGAIN); the capture did not run"); + }); + + test("names the exit status when the CLI exited non-zero with no output", () => { + expect(captureFailure({ ...ran, text: "", exitCode: 132 })) + .toBe("the CLI exited 132 with no output; the capture did not run"); + }); +}); diff --git a/scripts/site/transcript.ts b/scripts/site/transcript.ts index 051594d9d..5f500a628 100644 --- a/scripts/site/transcript.ts +++ b/scripts/site/transcript.ts @@ -6,10 +6,41 @@ const REPO_ROOT = resolve(import.meta.dirname, "../.."); // scope, so running it exits 0 having written nothing, which reads like success. const CLI = resolve(REPO_ROOT, "server/typescript/packages/cli/bin/meta.ts"); -export function captureTranscript(argv: string[], cwd: string): - { text: string; exitCode: number } { +export interface Capture { + text: string; + exitCode: number; + /** The signal that killed the CLI, if one did. */ + signal: NodeJS.Signals | null; + /** Set when the CLI could not be spawned at all. */ + error: Error | undefined; +} + +export function captureTranscript(argv: string[], cwd: string): Capture { const r = spawnSync("bun", [CLI, ...argv], { cwd, encoding: "utf8" }); - return { text: `${r.stdout ?? ""}${r.stderr ?? ""}`.trimEnd(), exitCode: r.status ?? 1 }; + return { + text: `${r.stdout ?? ""}${r.stderr ?? ""}`.trimEnd(), + exitCode: r.status ?? 1, + signal: r.signal, + error: r.error, + }; +} + +/** + * Why a capture did not RUN, or null when it did. A CLI that was killed, failed to + * spawn, or exited non-zero having written nothing produced no transcript at all; + * reading that as "the diagnostic changed" (or as a real verify failure) blames the + * fixture for what the machine did. + */ +export function captureFailure(r: Capture): string | null { + if (r.error) { + const errno = (r.error as NodeJS.ErrnoException).code ?? r.error.message; + return `the CLI failed to spawn (${errno}); the capture did not run`; + } + if (r.signal) return `the CLI was killed by ${r.signal}; the capture did not run`; + if (r.exitCode !== 0 && r.text === "") { + return `the CLI exited ${r.exitCode} with no output; the capture did not run`; + } + return null; } /**