From 64b47cfe615fc77185baba857b94e39731532bfb Mon Sep 17 00:00:00 2001 From: Doug Mealing Date: Sun, 22 Nov 2026 05:36:05 -0500 Subject: [PATCH 1/7] 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 2/7] 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 3/7] 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 4/7] 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 5/7] 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 6/7] 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 7/7] 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`) |