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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<collection>/{id}/<transition>`) and a shell per declared command and query, at its binding or
Expand Down
46 changes: 31 additions & 15 deletions docs/features/business-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,17 +355,32 @@ directory in either layout.
the `<Pkg>Service` interface, `create<Pkg>Service(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
`<Pkg>Hooks` and no `<Pkg>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, `<pkg path>/transport/fastify.ts`: one plugin per package,
Expand All @@ -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 });
});
Expand All @@ -403,7 +419,7 @@ The service also writes what the rules on this page declare:
addresses a row, `<collection>/<operation>` 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.
Expand All @@ -421,7 +437,7 @@ What you write is passed to `create<Pkg>Service(deps)`; there is no base class t
| `hooks` | `<Pkg>Hooks<A>` | Optional `before`/`after` hooks on each derived create, update and delete. A before hook may return a replacement input. |
| `events` | `<Pkg>Events<A>` | 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.

Expand Down
7 changes: 4 additions & 3 deletions docs/ports/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<pkg path>/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 `<Pkg>Service`
one transaction by default, with the declared write rules) and `service/index.ts` with the `<Pkg>Service`
interface and `create<Pkg>Service(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 `<pkg path>/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

Expand Down
8 changes: 4 additions & 4 deletions server/typescript/packages/codegen-ts/src/dialect-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<string, unknown>>;`,
alias: `type Db = BaseSQLiteDatabase<"sync" | "async", unknown, Record<string, unknown>>;`,
};
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ export const generatorRegistry: Record<string, GeneratorRegistryEntry> = {
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"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand All @@ -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 {
Expand All @@ -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;
Expand Down
11 changes: 10 additions & 1 deletion server/typescript/packages/codegen-ts/src/reference/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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;
Expand Down
5 changes: 5 additions & 0 deletions server/typescript/packages/codegen-ts/src/service-walk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading