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..ba1943f51 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -355,17 +355,32 @@ 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. - -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. +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 +`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, @@ -375,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 }); }); @@ -403,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. @@ -421,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 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/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"], 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-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 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.