diff --git a/CHANGELOG.md b/CHANGELOG.md index ba8122c7f3..440cceef29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,21 @@ here.** run the `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` and `duration/` corpora beside the root and `rules/` corpora, on every engine the routes lane runs, D1 included through `interactiveTransactions: false`. The service compile gate compiles both transports. +- **The service covers every object the flat routes serve.** Projections and served reports get + their reads, and their transports answer writes `405`. A report keeps its row cap, through the + new `serviceFile({ reportMaxRows })` option, and its `?format=` export. Write-through entities + read through their view and read a write back through it. A single-table hierarchy gets the + polymorphic base reads and per-subtype operations scoped to the discriminator. Each + many-to-many relationship gets a query and a `GET /{id}/` route. The + `projection/`, `report/` (Postgres, MySQL, SQLite and D1), `write-through/`, `tph/`, `m2m/`, + `decimal/` and `secret-fields/` corpora now run on both service lanes. runtime-ts: the read-only + and many-to-many reads (`readOnlyList`, `readOnlyGet`, `m2mRelated`) are framework-neutral + functions, which the flat Fastify mounts and the service both call. +- **codegen-ts: a `runGen` with no project no longer leaves its gen-state in the scratch root.** + The state of such a run is kept for that process's later runs only, and is removed when the + process exits normally (a process killed by a signal still leaves it). Before this fix, each such process left `meta-gen-state-` behind + permanently. The test harnesses that generate with no project had left hundreds of those + directories, about 3 GB, in a RAM-backed `$DEV_SCRATCH`. - **runtime-ts: the generated service keeps its rollback guarantee on a sync SQLite driver.** On bun:sqlite and better-sqlite3, Drizzle's `transaction()` commits when its callback returns, so a diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 03e2c5e7d9..e0f346a4e4 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -36,7 +36,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor | [`fixtures/extract-conformance/`](../fixtures/extract-conformance/) | 58 | ✓ | ✓ | inherits the shared JVM engine | ✓ | ✓ | | [`fixtures/output-prompt-conformance/`](../fixtures/output-prompt-conformance/) | 17 | ✓ | ✓ | ✓ | ✓ | ✓ | | [`fixtures/persistence-conformance/`](../fixtures/persistence-conformance/) | 68 (56 query + 12 migration) | all 68; the 24 `report-*` and the `-15` decimal scenarios also on SQLite, MySQL and D1, `decimal-exact` and `guarded-update` also on MySQL (a scenario's `engines:` key is exact) | 55 query (migrations TS-only, ADR-0015; `guarded-update` deferred to L-JV-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (via Exposed; `guarded-update` deferred to L-KT-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (`guarded-update` deferred to L-CS-2); the `report-*` and `engines:` scenarios also on SQLite and MySQL | 55 query (pg8000; `guarded-update` deferred to L-PY-2); the `report-*` and `engines:` scenarios also on SQLite (`sqlite3`) and MySQL (PyMySQL) | -| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | +| [`fixtures/api-contract-conformance/`](../fixtures/api-contract-conformance/) | 179 (34 core + 14 tph + 9 m2m + 6 jsonb + 2 write-through + 4 secret-fields + 2 enum-default + 12 projection + 37 report + 11 decimal + 2 duration + 8 api-settings + 21 list-query + 17 rules) | ✓ (Fastify reference + generated lane; service lanes on Fastify and Hono for the entity, `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` sub-corpora, see the [api-contract README](../fixtures/api-contract-conformance/README.md#ts-lanes-illustrative-detail)); `report/`, `decimal/` and `duration/` also on SQLite, MySQL and D1; `list-query/` is TypeScript-only until each port's 1.3.0 REST-standard work, and `rules/` until each port's 1.3.0 service work | ✓ (embedded HTTP + JDBC); `report/`, `decimal/` and `duration/` generated controllers over OMDB on Postgres, SQLite and MySQL | ✓ (embedded HTTP + Exposed); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (Kestrel + Npgsql); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | ✓ (FastAPI + pg8000); `report/`, `decimal/` and `duration/` also on SQLite and MySQL | | [`fixtures/decimal-wire/`](../fixtures/decimal-wire/) | 1 vector file (format, parse, filter operand, 15-digit read) | ✓ (`runtime-ts` and the generated helper) | ✓ (`CanonicalDecimal`) | ✓ (the generated wire file) | ✓ (`DecimalWire`) | ✓ (`decimal_wire`) | | [`fixtures/duration-wire/`](../fixtures/duration-wire/) | 1 vector file: the `wire` vectors (parse, precision, refused) every port passes, and the `codecs` groups (Postgres text read and write, stored microseconds) each port passes only for the codecs it has | ✓ (`metadata` / `runtime-ts` and the generated helper) | ✓ | ✓ | ✓ | ✓ | | [`fixtures/validation-conformance/`](../fixtures/validation-conformance/) | 42 cases + 43 cross-field cases (`cross-field-cases.json`, generated record model only) | ✓ (generated Zod + run-time `runValidators`) | ✓ | ✓ | ✓ | ✓ (generated Pydantic + run-time `run_validators`) | diff --git a/docs/features/business-rules.md b/docs/features/business-rules.md index 5d19aa142b..d4c5119641 100644 --- a/docs/features/business-rules.md +++ b/docs/features/business-rules.md @@ -471,8 +471,22 @@ generated service, under the default settings and under `rules.lifecycle.create: `rules.lifecycle.commands: all` and `none`. Its README specifies the hand-written pieces, so every port's lane implements the same ones. -Not covered yet, and still served by the flat generators: write-through entities, single-table (TPH) -hierarchies, many-to-many traversal, projections and reports. +The service covers every object the flat routes serve, with the same answers: + +- A projection and a served report get a list (and a get, when the projection is keyed). Their + transports answer every write `405 method_not_allowed`. A report keeps its row cap + (`serviceFile({ reportMaxRows })`, as `routesFile` takes it) and, with `report-export` wired, + its `?format=` export. +- A write-through entity reads through its replica view and answers a write by reading the row + back through that view. +- A single-table (TPH) hierarchy's base gets the polymorphic list and get. Each concrete subtype + gets the five operations at its own path, on the base table, scoped to its discriminator value. +- A many-to-many relationship gets a query, `Of(id)`, served at + `GET /{id}/`. + +The `projection/`, `report/`, `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` +corpora run on the service lanes as well as the routes lane. An entity with a composite key has no +derived operations. ## Requirements can claim operations and transitions diff --git a/docs/ports/typescript.md b/docs/ports/typescript.md index 7213596c88..9fdd4483c9 100644 --- a/docs/ports/typescript.md +++ b/docs/ports/typescript.md @@ -754,7 +754,9 @@ and give it its own `target` to put the layer in a package the transport and cli `serviceFile()` (stable name `service`, layer `service`) is layer 4 of ADR-0067. It writes one module per metadata package, under the package's directory in either layout: a file per operation in `/service/` (each entity's derived list, get, create, update and delete, every write in -one transaction by default, with the declared write rules) and `service/index.ts` with the `Service` +one transaction by default, with the declared write rules; the reads of a projection or a served +report; a single-table subtype's operations, scoped to its discriminator; a query per many-to-many +relationship) and `service/index.ts` with the `Service` interface and `createService(deps)`. A model with ADR-0066 rules also gets a file per derived transition command and per declared command and query, each running the rules' checks around a hand-written body; the policy, bodies, hooks and event hook are passed in `deps`. @@ -764,7 +766,8 @@ routes that call it, with a `getActor(request)` option for the app's actor. `/transport/hono.ts`, with `getActor(c)`. Each needs `entity` and `contract-types` in the same target. None is scaffolded; add them to `generators` or `meta eject` them. On SQLite the service takes a sync or an async Drizzle driver. A store that holds no transaction across -application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`. +application code (Cloudflare D1) takes `serviceFile({ interactiveTransactions: false })`, and a +report's row cap is `serviceFile({ reportMaxRows })`, as `routesFile` takes it. See [Business rules](../features/business-rules.md#the-service-layer-typescript). ### Prove it works diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts index ffb804776e..0529ac7c3c 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts index cec28d7fa5..44a1423660 100644 --- a/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/advanced-modeling/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/examples/advanced-modeling/codegen/runtime/m2m-read.ts b/examples/advanced-modeling/codegen/runtime/m2m-read.ts new file mode 100644 index 0000000000..57bd984c01 --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/examples/advanced-modeling/codegen/runtime/read-only-read.ts b/examples/advanced-modeling/codegen/runtime/read-only-read.ts new file mode 100644 index 0000000000..1ae074d3ce --- /dev/null +++ b/examples/advanced-modeling/codegen/runtime/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage> { + readonly rows: T[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts index ffb804776e..0529ac7c3c 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts index cec28d7fa5..44a1423660 100644 --- a/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts +++ b/examples/showcase/codegen/runtime/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/examples/showcase/codegen/runtime/m2m-read.ts b/examples/showcase/codegen/runtime/m2m-read.ts new file mode 100644 index 0000000000..57bd984c01 --- /dev/null +++ b/examples/showcase/codegen/runtime/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/examples/showcase/codegen/runtime/read-only-read.ts b/examples/showcase/codegen/runtime/read-only-read.ts new file mode 100644 index 0000000000..1ae074d3ce --- /dev/null +++ b/examples/showcase/codegen/runtime/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage> { + readonly rows: T[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} diff --git a/fixtures/api-contract-conformance/README.md b/fixtures/api-contract-conformance/README.md index 5de4f7064d..9ab04340d2 100644 --- a/fixtures/api-contract-conformance/README.md +++ b/fixtures/api-contract-conformance/README.md @@ -270,8 +270,9 @@ against a Postgres testcontainer over HTTP, and by service lanes beside the seco Hono transport (layer 5). The `list-query/`, `api-settings/`, `enum-default/`, `jsonb/` and `duration/` corpora, the root corpus and `rules/` run on them, in both output layouts, on every engine the generated-routes lane runs for the corpus. D1 generates its service - with `interactiveTransactions: false`. The `projection/`, `report/`, `tph/`, `m2m/`, - `write-through/`, `secret-fields/` and `decimal/` corpora stay on the generated-routes lane. + with `interactiveTransactions: false`. The `projection/`, `report/` (Postgres, MySQL, SQLite + and D1), `write-through/`, `tph/`, `m2m/`, `decimal/` and `secret-fields/` corpora run on + both service lanes too. Both lanes live in `server/typescript/packages/integration-tests/test/` and are run by the same `cd server/typescript/packages/integration-tests && bun test` diff --git a/fixtures/codegen-noop/rules/README.md b/fixtures/codegen-noop/rules/README.md index f5ee25f277..153887902a 100644 --- a/fixtures/codegen-noop/rules/README.md +++ b/fixtures/codegen-noop/rules/README.md @@ -9,9 +9,10 @@ Two models that differ ONLY by the business-rules vocabulary: (one carrying a `binding.rest`) take those objects as input and output. It is derived from the positive conformance fixture `fixtures/conformance/rules-purchase-request/`. -1.3.0 registers the vocabulary, validates it at load and checks it in `verify`. The -generated services and enforcing shells that act on it are later work, so until they land -the two models produce the same output everywhere: +1.3.0 registers the vocabulary, validates it at load and checks it in `verify`. Apart from the +generators named below that read it (the rules names, the contract types and the TypeScript +service generators `service`, `service-routes` and `service-routes-hono`), the two models +produce the same output everywhere: - Every code generator in every port writes the same files, byte for byte. - TypeScript `meta migrate` proposes the same schema. diff --git a/fixtures/generator-registry-conformance/README.md b/fixtures/generator-registry-conformance/README.md index 6d9b2ae2c1..e3d41c817e 100644 --- a/fixtures/generator-registry-conformance/README.md +++ b/fixtures/generator-registry-conformance/README.md @@ -135,11 +135,11 @@ shapes, the operations' inputs and outputs, and the wire error bodies, with no p mapping; C# so far writes the create and update records). Each other port adds itself to their `ports` with its own rules-layer work. -Two names are **TypeScript only for now**: `service`, layer 4 (one module per package, a -function per operation, each write in one transaction with the declared write rules), and -`service-routes`, its thin Fastify transport (layer 5). Each other port adds itself with its own -service-layer work. `service-routes-hono`, its Hono transport, is **TypeScript only by design**, -as `routes-hono` is: Hono is a TypeScript framework. +Three names are **TypeScript only**. Two are TypeScript only for now: `service`, layer 4 (one +module per package, a function per operation, each write in one transaction with the declared +write rules), and `service-routes`, its thin Fastify transport (layer 5); each other port adds +itself with its own service-layer work. The third, `service-routes-hono`, its Hono transport, is +TypeScript only by design, as `routes-hono` is: Hono is a TypeScript framework. ## Changing the surface diff --git a/scripts/site/payload.ts b/scripts/site/payload.ts index a211549f00..ce5fd795db 100644 --- a/scripts/site/payload.ts +++ b/scripts/site/payload.ts @@ -29,7 +29,7 @@ import { extractMarkedRegion } from "./markers.js"; import { splitLines, matchSubsequence, renderWithElisions } from "./subsequence.js"; import { loadVocabulary, highlightMetadata, type Vocabulary } from "./highlight-metadata.js"; import { highlightCode } from "./highlight-code.js"; -import { captureTranscript, normalizeTranscript, HOME_PATH } from "./transcript.js"; +import { captureTranscript, captureFailure, normalizeTranscript, HOME_PATH } from "./transcript.js"; import { deriveCounts, type Counts } from "./counts.js"; export interface Snippet { @@ -206,7 +206,12 @@ function wholeSnippet(repoRoot: string, src: Extract): Snippet { - const { text, exitCode } = captureTranscript(src.argv, resolve(repoRoot, src.cwd)); + const capture = captureTranscript(src.argv, resolve(repoRoot, src.cwd)); + const failure = captureFailure(capture); + if (failure) { + throw new Error(`site payload: the "${id}" transcript was not captured: ${failure}.`); + } + const { text, exitCode } = capture; if (exitCode === 0) { throw new Error( `site payload: the "${id}" fixture now PASSES (exit 0).\n` + @@ -240,7 +245,12 @@ function transcriptSnippet(repoRoot: string, id: string, */ function assertRequirementsResolve(repoRoot: string): void { const showcase = resolve(repoRoot, "examples/showcase"); - const { text, exitCode } = captureTranscript(["verify", ...PROMPTS_ARGS], showcase); + const capture = captureTranscript(["verify", ...PROMPTS_ARGS], showcase); + const failure = captureFailure(capture); + if (failure) { + throw new Error(`site payload: \`meta verify\` on examples/showcase was not captured: ${failure}.`); + } + const { text, exitCode } = capture; if (exitCode !== 0) { throw new Error( `site payload: \`meta verify\` fails on examples/showcase (exit ${exitCode}).\n` + diff --git a/scripts/site/transcript.test.ts b/scripts/site/transcript.test.ts index f74fc28566..ea1272edd5 100644 --- a/scripts/site/transcript.test.ts +++ b/scripts/site/transcript.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from "bun:test"; import { resolve } from "node:path"; -import { captureTranscript, normalizeTranscript, HOME_PATH } from "./transcript.js"; +import { captureTranscript, captureFailure, normalizeTranscript, HOME_PATH, type Capture } from "./transcript.js"; const REPO = resolve(import.meta.dirname, "../.."); @@ -67,3 +67,30 @@ describe("captureTranscript", () => { expect(() => normalizeTranscript(r.text, REPO)).not.toThrow(); }); }); + +// A CLI that never ran must not be reported as "the diagnostic changed". Injected +// spawn results, so the cases do not depend on actually starving the machine. +describe("captureFailure", () => { + const ran: Capture = { text: "ERR_X", exitCode: 1, signal: null, error: undefined }; + + test("a capture that ran and failed with output is not a capture failure", () => { + expect(captureFailure(ran)).toBeNull(); + expect(captureFailure({ ...ran, exitCode: 0, text: "" })).toBeNull(); + }); + + test("names the signal when the CLI was killed", () => { + expect(captureFailure({ ...ran, text: "", signal: "SIGTRAP" })) + .toBe("the CLI was killed by SIGTRAP; the capture did not run"); + }); + + test("names the errno when the CLI failed to spawn", () => { + const error = Object.assign(new Error("spawn bun EAGAIN"), { code: "EAGAIN" }); + expect(captureFailure({ ...ran, text: "", error })) + .toBe("the CLI failed to spawn (EAGAIN); the capture did not run"); + }); + + test("names the exit status when the CLI exited non-zero with no output", () => { + expect(captureFailure({ ...ran, text: "", exitCode: 132 })) + .toBe("the CLI exited 132 with no output; the capture did not run"); + }); +}); diff --git a/scripts/site/transcript.ts b/scripts/site/transcript.ts index 051594d9d0..5f500a6283 100644 --- a/scripts/site/transcript.ts +++ b/scripts/site/transcript.ts @@ -6,10 +6,41 @@ const REPO_ROOT = resolve(import.meta.dirname, "../.."); // scope, so running it exits 0 having written nothing, which reads like success. const CLI = resolve(REPO_ROOT, "server/typescript/packages/cli/bin/meta.ts"); -export function captureTranscript(argv: string[], cwd: string): - { text: string; exitCode: number } { +export interface Capture { + text: string; + exitCode: number; + /** The signal that killed the CLI, if one did. */ + signal: NodeJS.Signals | null; + /** Set when the CLI could not be spawned at all. */ + error: Error | undefined; +} + +export function captureTranscript(argv: string[], cwd: string): Capture { const r = spawnSync("bun", [CLI, ...argv], { cwd, encoding: "utf8" }); - return { text: `${r.stdout ?? ""}${r.stderr ?? ""}`.trimEnd(), exitCode: r.status ?? 1 }; + return { + text: `${r.stdout ?? ""}${r.stderr ?? ""}`.trimEnd(), + exitCode: r.status ?? 1, + signal: r.signal, + error: r.error, + }; +} + +/** + * Why a capture did not RUN, or null when it did. A CLI that was killed, failed to + * spawn, or exited non-zero having written nothing produced no transcript at all; + * reading that as "the diagnostic changed" (or as a real verify failure) blames the + * fixture for what the machine did. + */ +export function captureFailure(r: Capture): string | null { + if (r.error) { + const errno = (r.error as NodeJS.ErrnoException).code ?? r.error.message; + return `the CLI failed to spawn (${errno}); the capture did not run`; + } + if (r.signal) return `the CLI was killed by ${r.signal}; the capture did not run`; + if (r.exitCode !== 0 && r.text === "") { + return `the CLI exited ${r.exitCode} with no output; the capture did not run`; + } + return null; } /** diff --git a/server/typescript/packages/cli/test/eject-contract.test.ts b/server/typescript/packages/cli/test/eject-contract.test.ts index 69950237c3..62054d79c7 100644 --- a/server/typescript/packages/cli/test/eject-contract.test.ts +++ b/server/typescript/packages/cli/test/eject-contract.test.ts @@ -394,8 +394,9 @@ async function emit( /** * The one difference an owned copy's output is allowed: it imports the HTTP adapter the * adopter owns in `codegen/runtime/`, where packaged output imports the package. The - * formatter orders a package import and a relative one differently, so the import block - * is compared as a set of statements and everything after it exactly. + * formatter orders a package import and a relative one differently, and the longer relative + * path can wrap a named-import list across lines, so the import block is compared as a set of + * statements with their whitespace collapsed, and everything after it exactly. */ function adapterNeutral(source: string): string { const adapter = "@@ADAPTER@@"; @@ -404,7 +405,9 @@ function adapterNeutral(source: string): string { .replace(new RegExp(`${HTTP_RUNTIME_PACKAGE}(?:/[\\w-]+)+`, "g"), adapter) .replace(new RegExp(`(?:\\.\\./)+${OWNED_RUNTIME_DIR}/[\\w-]+/[\\w-]+`, "g"), adapter); const IMPORT = /^import [^;]*;\n/gm; - return [...(moved.match(IMPORT) ?? [])].sort().join("") + moved.replace(IMPORT, ""); + const oneLine = (stmt: string): string => + `${stmt.replace(/\s+/g, " ").replace(/\{ ?/g, "{ ").replace(/,? ?\}/g, " }").trim()}\n`; + return [...(moved.match(IMPORT) ?? [])].map(oneLine).sort().join("") + moved.replace(IMPORT, ""); } describe("eject contract — depth", () => { diff --git a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts index 96564c569b..1edcc90eae 100644 --- a/server/typescript/packages/cli/test/unit/reporting-inert.test.ts +++ b/server/typescript/packages/cli/test/unit/reporting-inert.test.ts @@ -149,6 +149,18 @@ const SERVED_REPORT_FILES: Readonly> = { // The export spec for the report's list route, and the project's one shared writer module. "report-export": [`${OUT}/StoreTotals.export.ts`, `${OUT}/report-export-writers.ts`], "contract-schema": [`${OUT}/schemas/acme/shop/StoreTotals.schema.json`], + // The report's list operation (ADR-0067 layer 4); the package index and the transports grow + // by it (SERVICE_GROWS below). + service: [`${OUT}/acme/shop/service/listStoreTotals.ts`], +}; +/** + * The package-wide service files a served report changes: the service index gains its list + * operation and wire mapper, and each transport its list route and its `405` write routes. + */ +const SERVICE_GROWS: Readonly> = { + service: [`${OUT}/acme/shop/service/index.ts`], + "service-routes": [`${OUT}/acme/shop/transport/fastify.ts`], + "service-routes-hono": [`${OUT}/acme/shop/transport/hono.ts`], }; /** * FR-044 Plan 4: the files `cube-model` writes for `with/`, and none for `without/`. It writes @@ -206,6 +218,14 @@ function expectOnlyAdds( } } +/** A module's lines after its import block (the last line ending an import, `... from "x";`). */ +function bodyOf(source: string): string[] { + const lines = source.split("\n"); + let last = -1; + lines.forEach((l, i) => { if (/^(import .*|\} )from "[^"]+";$/.test(l)) last = i; }); + return lines.slice(last + 1); +} + interface OpenApiDoc { paths: Record; components: { schemas: Record }; @@ -257,7 +277,17 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(actual).toEqual(expected); return; } - expectOnlyAdds(expected, actual, ADDED_FOR_WITH[name] ?? [], [OPENAPI_DOC]); + expectOnlyAdds(expected, actual, ADDED_FOR_WITH[name] ?? [], [OPENAPI_DOC, ...(SERVICE_GROWS[name] ?? [])]); + for (const path of SERVICE_GROWS[name] ?? []) { + // A served report's service code names it, and it moves nothing it had: past the + // imports (which gain the report's names and helpers), every line of the file is still + // there, in order. + expect(actual[path]).toContain("StoreTotals"); + const before = bodyOf(expected[path]!); + let kept = 0; + for (const line of bodyOf(actual[path]!)) if (line === before[kept]) kept++; + expect(kept).toBe(before.length); + } if (name === "openapi") expectOpenApiAddsOnlyTheServedReport(expected[OPENAPI_DOC]!, actual[OPENAPI_DOC]!); if (name === "barrel") { // The barrel is the one shared file that moves, and it moves by the report's @@ -378,7 +408,7 @@ describe("FR-044 a sourceless report is inert; a served report emits exactly its expect(expected[""]).toBeUndefined(); expect(actual[""]).toBeUndefined(); expect(Object.keys(expected).length).toBeGreaterThan(10); - expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC]); + expectOnlyAdds(expected, actual, Object.values(ADDED_FOR_WITH).flat(), [AGENT_UI_PAGE, OPENAPI_DOC, ...Object.values(SERVICE_GROWS).flat()]); // The agent UI page moves by the served report's section alone: every line it had is // still there, in order, and the section names the report. const before = expected[AGENT_UI_PAGE]!.split("\n"); diff --git a/server/typescript/packages/codegen-ts/src/generators/service-file.ts b/server/typescript/packages/codegen-ts/src/generators/service-file.ts index b11cd9a253..65c13430b0 100644 --- a/server/typescript/packages/codegen-ts/src/generators/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/generators/service-file.ts @@ -37,6 +37,8 @@ export interface ServiceFileOpts { * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. */ interactiveTransactions?: boolean; + /** The most rows a served report answers with no `limit` (the routes generator's option of the same name). Default 10000. */ + reportMaxRows?: number; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -48,7 +50,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { if (model.length === 0) return []; const rc = serviceRenderContext(ctx, "service", opts?.runtimeImport); const interactiveTransactions = opts?.interactiveTransactions !== false; - return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); + const reportMaxRows = opts?.reportMaxRows; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions, ...(reportMaxRows === undefined ? {} : { reportMaxRows }) }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/reference/service.ts b/server/typescript/packages/codegen-ts/src/reference/service.ts index 0169ac7981..e896df46a5 100644 --- a/server/typescript/packages/codegen-ts/src/reference/service.ts +++ b/server/typescript/packages/codegen-ts/src/reference/service.ts @@ -55,6 +55,8 @@ export interface ServiceFileOpts { * refused with `ERR_STORE_NO_INTERACTIVE_TX` (ADR-0067 §4). Default true. */ interactiveTransactions?: boolean; + /** The most rows a served report answers with no `limit` (the routes generator's option of the same name). Default 10000. */ + reportMaxRows?: number; } export function serviceFile(opts?: ServiceFileOpts): Generator { @@ -68,7 +70,8 @@ export function serviceFile(opts?: ServiceFileOpts): Generator { opts?.runtimeImport ?? (ctx.renderContext && ownedRuntimeImport(ctx.projectRoot ?? ".", ctx.renderContext.selfTarget.outDir)); const rc = serviceRenderContext(ctx, "service", runtimeImport); const interactiveTransactions = opts?.interactiveTransactions !== false; - return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions }, rc)); + const reportMaxRows = opts?.reportMaxRows; + return model.flatMap((pkg) => renderServiceFiles({ ...pkg, interactiveTransactions, ...(reportMaxRows === undefined ? {} : { reportMaxRows }) }, rc)); }, }; if (opts?.filter) generator.filter = opts.filter; diff --git a/server/typescript/packages/codegen-ts/src/runner.ts b/server/typescript/packages/codegen-ts/src/runner.ts index adbdb6f1af..30c7172a89 100644 --- a/server/typescript/packages/codegen-ts/src/runner.ts +++ b/server/typescript/packages/codegen-ts/src/runner.ts @@ -3,7 +3,7 @@ import { join, relative, resolve, isAbsolute, dirname, sep } from "node:path"; import { warnMissingPromptGenerators } from "./prompt-generator-gate.js"; import { runEmitsEntityModule, runEmitsHonoRoutes, runEmitsQueries, runEmitsRestRoutes, runEmitsUiTier, runRoutesExpose, warnUnmarkedRoutesGenerators, warnUnmarkedUiGenerators } from "./ui-tier-gate.js"; import { warnRetiredCodegenAttrs } from "./retired-codegen-attrs.js"; -import { removeTree, scratchRoot } from "./scratch-dir.js"; +import { removeTree, removeTreeAtExit, scratchRoot } from "./scratch-dir.js"; import { randomUUID } from "node:crypto"; import { fileURLToPath } from "node:url"; import { existsSync, readFileSync } from "node:fs"; @@ -383,6 +383,8 @@ export async function runGen(opts: RunGenOpts): Promise { : (projectRoot !== undefined ? join(projectRoot, ".metaobjects", ".gen-state") : join(scratchRoot(), `meta-gen-state-${process.pid}`)); + // A run with no project keeps its state for this process's later runs only. + if (opts.genStateDir === undefined && projectRoot === undefined) removeTreeAtExit(genStateDir); // A file written OUTSIDE the project has no place in the project's gen-state: its // manifest key would be `../..`-relative, committed into the hash manifest, and its snapshot // body — stored at `/` — would walk out of `.gen-state/` and land a second diff --git a/server/typescript/packages/codegen-ts/src/scratch-dir.ts b/server/typescript/packages/codegen-ts/src/scratch-dir.ts index b3402c0c56..9f313028e0 100644 --- a/server/typescript/packages/codegen-ts/src/scratch-dir.ts +++ b/server/typescript/packages/codegen-ts/src/scratch-dir.ts @@ -47,3 +47,27 @@ function walkRemove(path: string): void { export function removeTree(path: string): void { walkRemove(path); } + +const removedAtExit = new Set(); + +/** + * Remove `path` when this process exits normally (the `exit` event; a process killed by a signal + * leaves it behind). For state a process shares across its own runs and no + * later process reads (runGen's gen-state for a run with no project): without it, every process + * that ever ran one left a directory in the scratch root. + */ +export function removeTreeAtExit(path: string): void { + if (removedAtExit.has(path)) return; + if (removedAtExit.size === 0) { + process.once("exit", () => { + for (const p of removedAtExit) { + try { + removeTree(p); + } catch { + // An exit handler must not throw: a directory it cannot remove is left behind. + } + } + }); + } + removedAtExit.add(path); +} diff --git a/server/typescript/packages/codegen-ts/src/service-walk.ts b/server/typescript/packages/codegen-ts/src/service-walk.ts index 827495a832..20fc35c4d2 100644 --- a/server/typescript/packages/codegen-ts/src/service-walk.ts +++ b/server/typescript/packages/codegen-ts/src/service-walk.ts @@ -5,12 +5,16 @@ // operations are named and where their files go stays packaged while the files' shape is the // adopter's. // -// Covered: every concrete `object.entity` whose primary source is a writable `source.rdb`, keyed -// by a single-field primary identity. It gets the five derived operations (list, get, create, -// update and delete), a command per transition that derives one (ADR-0066 §2, under -// `rules.lifecycle.commands`), and the package's declared operations that act on a covered entity -// or on none. Not covered yet: a write-through entity (reads through a replica view), a -// single-table (TPH) hierarchy, many-to-many traversal, projections and reports. +// Covered: every object the flat routes serve, keyed by a single-field primary identity where it +// has a key. A concrete `object.entity` whose primary source is a writable `source.rdb` gets the +// five derived operations (list, get, create, update and delete); a write-through entity reads +// through its replica view and writes its table. A single-table (TPH) hierarchy's discriminator +// base gets a polymorphic list and get, and each concrete subtype the five operations, scoped to its +// discriminator value. A projection gets a list, and a get when it has a key; a served report a +// list (with its row cap, and its export when `report-export` is wired). Every many-to-many +// relationship of a covered entity gets a traversal query. An entity also gets a command per +// transition that derives one (ADR-0066 §2, under `rules.lifecycle.commands`), and the package's +// declared operations that act on a covered entity or on none. import { BINDING_ATTR_METHOD, @@ -44,6 +48,7 @@ import { transitionFrom, transitionTo, type MetaData, + type MetaRoot, type MetaObject, type RulesSettings, } from "@metaobjectsdev/metadata"; @@ -55,10 +60,14 @@ import { HTTP_RUNTIME_MODULES, HTTP_RUNTIME_PACKAGE, type HttpRuntimeModule } fr import type { ExtStyle, RenderContext } from "./render-context.js"; import type { GenContext } from "./generator.js"; import { effectivePackage } from "./docs-paths.js"; -import { hasWritableRdbSource } from "./source-detect.js"; +import { generatableObjects, hasWritableRdbSource } from "./source-detect.js"; import { isAbstract } from "./instance-artifacts.js"; -import { isWriteThrough } from "./projection/projection-detector.js"; -import { declaresTphDiscriminator, isTphSubtype } from "./tph.js"; +import { isProjection, isWriteThrough } from "./projection/projection-detector.js"; +import { declaresTphDiscriminator, isTphSubtype, tphDiscriminatorBase, tphDiscriminatorPin, tphStorageObject } from "./tph.js"; +import { isReport } from "./source-detect.js"; +import { itemRouteField, servesReadApi } from "./api-surface.js"; +import { tphPlan } from "./templates/tph-discriminator.js"; +import { buildRelationMap, type RelationMap } from "./relation-resolver.js"; import { pkInfoOf } from "./pk-resolver.js"; import { listFnName, toCamelCase, toPascalCase } from "./naming.js"; @@ -98,6 +107,35 @@ export interface ServiceTransitionCommand { readonly permission: string | undefined; } +/** What kind of object a service entity is: a writable entity, or a read-only projection or report. */ +export type ServiceObjectKind = "entity" | "projection" | "report"; + +/** A single-table subtype's scope: its rows are the base table's rows whose `field` holds `value`. */ +export interface ServiceDiscriminator { + readonly field: string; + readonly value: string; +} + +/** A many-to-many traversal of a covered entity (FR-018): `GET /:id/`. */ +export interface ServiceRelation { + /** The service function: `Of` (`tagsOfPost`). */ + readonly fn: string; + /** The relationship's name: the path segment. */ + readonly name: string; + readonly junction: MetaObject; + /** The junction's field holding the source key, and the one holding the target key. */ + readonly sourceJoinField: string; + readonly targetJoinField: string; + /** The object whose table holds the target rows (a single-table subtype's base). */ + readonly target: MetaObject; + /** The objects whose fields the target rows carry: the target, and a TPH base's subtypes. */ + readonly targetObjects: readonly MetaObject[]; + /** The target is a single-table subtype: only rows of its discriminator value. */ + readonly targetDiscriminator: ServiceDiscriminator | undefined; + /** Undirected self-join: both junction columns are read. */ + readonly symmetric: boolean; +} + /** One entity's service operations. */ export interface ServiceEntity { readonly obj: MetaObject; @@ -105,6 +143,24 @@ export interface ServiceEntity { readonly keyField: string; /** The function name of each derived operation (`listAuthors`, `getAuthor`, ...). */ readonly operations: Readonly>; + /** The derived operations it has, in `DERIVED_OPERATIONS` order. */ + readonly verbs: readonly DerivedOperation[]; + readonly kind: ServiceObjectKind; + /** + * The object whose entity module exports the table the operations read and write: the object + * itself, or a single-table subtype's discriminator base. A projection or report reads its view. + */ + readonly storage: MetaObject; + /** A write-through entity: reads go through its replica view, and a write is read back through it. */ + readonly readView: boolean; + /** The REST path, before the API prefix (`/auths/bridge` for a single-table subtype). */ + readonly path: string; + /** A single-table subtype's scope. */ + readonly discriminator: ServiceDiscriminator | undefined; + /** The objects of its single-table hierarchy (the base and every concrete subtype), else just itself. */ + readonly hierarchy: readonly MetaObject[]; + /** Its many-to-many traversals. */ + readonly relations: readonly ServiceRelation[]; /** The entity's lifecycles: the generic write path may not move them (409 `state_managed`). */ readonly lifecycles: readonly ServiceLifecycle[]; /** The commands its transitions derive, in lifecycle order. */ @@ -154,6 +210,8 @@ export interface ServicePackage { * service generator's `interactiveTransactions` option, not the model's. Absent: true. */ readonly interactiveTransactions?: boolean; + /** A served report's row cap: the service generator's `reportMaxRows` option. Absent: 10000, the same in every port. */ + readonly reportMaxRows?: number; } export interface ServiceWalkOpts { @@ -161,14 +219,59 @@ export interface ServiceWalkOpts { matches?: (obj: MetaObject) => boolean; } -/** Whether `obj` gets the derived service operations. */ +/** Whether `obj` gets service operations: every object the flat routes serve, with a single key where it has one. */ export function hasServiceOperations(obj: MetaObject): boolean { - if (obj.subType !== OBJECT_SUBTYPE_ENTITY || isAbstract(obj)) return false; - if (!hasWritableRdbSource(obj) || isWriteThrough(obj)) return false; - if (declaresTphDiscriminator(obj) || isTphSubtype(obj)) return false; + if (!servesReadApi(obj)) return false; + if (isProjection(obj)) return true; + if (obj.subType !== OBJECT_SUBTYPE_ENTITY || !hasWritableRdbSource(obj)) return false; return serviceKeyField(obj) !== undefined; } +/** The verbs, storage, path and scope of a covered object. */ +function shapeOf(obj: MetaObject, root: MetaRoot): Pick { + const path = restPath(obj); + if (isProjection(obj)) { + const keyed = itemRouteField(obj) !== undefined; + return { kind: isReport(obj) ? "report" : "projection", verbs: keyed ? ["list", "get"] : ["list"], storage: obj, readView: false, path, discriminator: undefined, hierarchy: [obj] }; + } + const pin = tphDiscriminatorPin(obj); + const base = tphDiscriminatorBase(obj); + if (pin !== undefined && base !== undefined) { + const plan = tphPlan(base, root); + const hierarchy = plan === null ? [base, obj] : [base, ...plan.subtypes.map((st) => st.entity)]; + return { kind: "entity", verbs: DERIVED_OPERATIONS, storage: base, readView: false, path, discriminator: { field: pin.fieldName, value: pin.value }, hierarchy }; + } + const plan = declaresTphDiscriminator(obj) ? tphPlan(obj, root) : null; + if (plan !== null) { + // The polymorphic base is read-only by construction: the union has no single writable shape. + return { kind: "entity", verbs: ["list", "get"], storage: obj, readView: false, path, discriminator: undefined, hierarchy: [obj, ...plan.subtypes.map((st) => st.entity)] }; + } + return { kind: "entity", verbs: DERIVED_OPERATIONS, storage: obj, readView: isWriteThrough(obj), path, discriminator: undefined, hierarchy: [obj] }; +} + +/** The many-to-many traversals `obj` resolves (the relation map's rule, the flat routes' too). */ +function relationsOf(obj: MetaObject, relationMap: RelationMap, root: MetaRoot): ServiceRelation[] { + const out: ServiceRelation[] = []; + for (const e of relationMap.get(obj.name) ?? []) { + if (e.junction === undefined || e.sourceJoinField === undefined || e.targetJoinField === undefined) continue; + const target = tphStorageObject(e.target); + const plan = declaresTphDiscriminator(e.target) ? tphPlan(e.target, root) : null; + const pin = tphDiscriminatorPin(e.target); + out.push({ + fn: `${toCamelCase(e.name)}Of${obj.name}`, + name: e.name, + junction: e.junction, + sourceJoinField: e.sourceJoinField, + targetJoinField: e.targetJoinField, + target, + targetObjects: plan === null ? [e.target] : [e.target, ...plan.subtypes.map((st) => st.entity)], + targetDiscriminator: pin === undefined ? undefined : { field: pin.fieldName, value: pin.value }, + symmetric: e.symmetric === true, + }); + } + return out; +} + /** The single field a service operation addresses a row by, or undefined for a composite or absent key. */ export function serviceKeyField(obj: MetaObject): string | undefined { const pk = pkInfoOf(obj); @@ -274,7 +377,7 @@ function operationOf(op: MetaData, target: ServiceEntity | undefined, settings: * The service modules of `root`, one per package that has a covered entity or a declared * operation the service covers, sorted by package. */ -export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): ServicePackage[] { +export function serviceModelOf(root: MetaRoot, opts: ServiceWalkOpts = {}): ServicePackage[] { const matches = opts.matches ?? (() => true); const settings = rulesSettingsOfModel(root); const claimed = claimedTransitions(root); @@ -285,15 +388,20 @@ export function serviceModelOf(root: MetaData, opts: ServiceWalkOpts = {}): Serv return b; }; const covered = new Map(); - for (const obj of root.children().filter(isMetaObject)) { + const relationMap = buildRelationMap(root); + // A served report is read through its read model (its derived fields as real fields), the + // object every other generator is handed; a report that is not served has no API. + for (const obj of generatableObjects(root.children().filter(isMetaObject), root)) { if (!hasServiceOperations(obj) || !matches(obj)) continue; - const e: ServiceEntity = { obj, keyField: serviceKeyField(obj)!, operations: serviceOperationNames(obj), ...entityRules(obj, claimed, settings) }; + const shape = shapeOf(obj, root); + const rules = shape.kind === "entity" ? entityRules(obj, claimed, settings) : { lifecycles: [], commands: [] }; + const keyField = shape.kind === "entity" ? serviceKeyField(obj)! : (itemRouteField(obj) ?? "id"); + const e: ServiceEntity = { obj, keyField, operations: serviceOperationNames(obj), ...shape, relations: relationsOf(obj, relationMap, root), ...rules }; covered.set(obj, e); bucket(effectivePackage(obj) ?? "").entities.push(e); } // One operation declared identically by two APIs (a versioned API) is one operation (O6). An - // operation whose target the service does not cover (a single-table hierarchy, say) is left to - // later service work, as its entity is. + // operation whose target has no derived operations (a composite key) has none either. const seen = new Set(); for (const op of modelOperations(root)) { const targetNode = operationTarget(op); diff --git a/server/typescript/packages/codegen-ts/src/templates/service-file.ts b/server/typescript/packages/codegen-ts/src/templates/service-file.ts index 9eba35c744..e5d9db322c 100644 --- a/server/typescript/packages/codegen-ts/src/templates/service-file.ts +++ b/server/typescript/packages/codegen-ts/src/templates/service-file.ts @@ -17,7 +17,9 @@ // back. Reads open no write transaction and call no hooks. The mechanics are // `@metaobjectsdev/runtime-ts/service`; what runs, against which schema and table, is written here. -import type { MetaObject } from "@metaobjectsdev/metadata"; +import { TYPE_FIELD, resolveColumnName, type MetaObject } from "@metaobjectsdev/metadata"; +import { pkInfoOf } from "../pk-resolver.js"; +import { hasInsertRefinements } from "./zod-validators.js"; import { GENERATED_EDIT_NOTE, GENERATED_HEADER } from "../constants.js"; import { withExtIfRelative, type RenderContext } from "../render-context.js"; import { decimalColumnsLine, knownFieldsLine, paginationLine, restPath, writeDeniedColumnsLine } from "../api-surface.js"; @@ -38,6 +40,7 @@ import { SERVICE_INDEX_FILE, type ServiceEntity, type ServiceOperation, + type ServiceRelation, type ServicePackage, type ServiceTransition, type ServiceTransitionCommand, @@ -92,6 +95,11 @@ export function wireMapperName(entityName: string): string { return `${lowerFirst(entityName)}ToWire`; } +/** The wire mapper of a write-through entity's write answers, as the service index exports it. */ +export function writeWireMapperName(entityName: string): string { + return `${lowerFirst(entityName)}WriteToWire`; +} + /** Does the store hold a transaction across application code? (`interactiveTransactions`, default true) */ function interactive(pkg: ServicePackage): boolean { return pkg.interactiveTransactions !== false; @@ -118,10 +126,14 @@ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): Ser } const files: ServiceFile[] = []; for (const e of pkg.entities) { - for (const op of ["list", "get", "create", "update", "delete"] as const) { + for (const op of e.verbs) { const path = servicePath(pkg.package, `${e.operations[op]}.ts`); files.push({ path, content: renderOperation(op, e, path, ctx, pkg) }); } + for (const r of e.relations) { + const path = servicePath(pkg.package, `${r.fn}.ts`); + files.push({ path, content: renderRelation(r, e, path, ctx) }); + } for (const c of e.commands) { const path = servicePath(pkg.package, `${c.fn}.ts`); files.push({ path, content: renderTransitionCommand(c, e, path, ctx, pkg) }); @@ -136,6 +148,66 @@ export function renderServiceFiles(pkg: ServicePackage, ctx: RenderContext): Ser return files; } +/** Where an entity's operations read and write, as the operation file imports them. */ +interface Sources { + /** The table writes go to (a single-table subtype's base table). */ + readonly table: string; + /** What reads select from: the table, a write-through entity's replica view, or a read-only object's view. */ + readonly read: string; + /** The replica view a write is read back through (write-through), else undefined. */ + readonly view: string | undefined; +} + +function sourcesOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): Sources { + const own = modulesOf(path, e.obj, ctx).entity; + if (e.kind !== "entity") { + const view = w.use(`${lowerFirst(e.obj.name)}View`, own); + return { table: view, read: view, view: undefined }; + } + const table = w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity); + if (!e.readView) return { table, read: table, view: undefined }; + const view = w.use(`${lowerFirst(e.obj.name)}View`, own); + return { table, read: view, view }; +} + +/** + * The table a transition command or a keyed declared operation addresses, and its key condition: + * the storage table, which for a single-table subtype is its base's, scoped to its discriminator + * value. The loader admits only an `object.entity` as an operation's target (ADR-0066). + */ +function addressedOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext, runtime: string): { table: string; cond: () => string } { + const table = w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity); + return { table, cond: () => addressedCond(w, e, table, table, runtime) }; +} + +/** + * The key condition of a keyed operation on `on` (a table or a read view), scoped to the single-table + * subtype's discriminator on `scopeTable` (the storage table). + */ +function addressedCond(w: TsWriter, e: ServiceEntity, on: string, scopeTable: string, runtime: string): string { + const key = `${w.use("keyCondition", runtime)}(${on}, ${str(e.keyField)}, id)`; + const scope = scopeExpr(w, e, scopeTable, runtime); + return scope === undefined ? key : `${w.use("scoped", runtime)}(${key}, ${scope})`; +} + +/** The row type of an entity's operations: its contract type, or a report's row type from its entity module. */ +function rowTypeOf(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): string { + const mods = modulesOf(path, e.obj, ctx); + return w.useType(e.obj.name, e.kind === "report" ? mods.entity : mods.contract); +} + +/** A single-table subtype's create input: its create shape without the discriminator, which the path names. */ +function createInputType(w: TsWriter, e: ServiceEntity, path: string, ctx: RenderContext): string { + const create = w.useType(`${e.obj.name}Create`, modulesOf(path, e.obj, ctx).contract); + return e.discriminator === undefined ? create : `Omit<${create}, ${str(e.discriminator.field)}>`; +} + +/** The scope expression of a single-table subtype's operations, or undefined. */ +function scopeExpr(w: TsWriter, e: ServiceEntity, table: string, runtime: string): string | undefined { + if (e.discriminator === undefined) return undefined; + return `${w.use("scopeCondition", runtime)}(${table}, ${str(e.discriminator.field)}, ${str(e.discriminator.value)})`; +} + function renderOperation( op: "list" | "get" | "create" | "update" | "delete", e: ServiceEntity, @@ -150,8 +222,9 @@ function renderOperation( header(w, `${name} (${obj.fqn()}) — service operation ${fn} (ADR-0067 layer 4)`); const runtime = runtimeSpecifierFrom(path, "service", ctx); const mods = modulesOf(path, obj, ctx); - const table = w.use(ctx.collectionName(name), mods.entity); - const row = w.useType(name, mods.contract); + const src = sourcesOf(w, e, path, ctx); + const table = src.table; + const row = rowTypeOf(w, e, path, ctx); const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); @@ -159,6 +232,71 @@ function renderOperation( const lifecycleFields = e.lifecycles.map((l) => l.field); const keyField = str(e.keyField); const id = "id: number | string"; + const scope = scopeExpr(w, e, table, runtime); + const addressed = (on: string) => addressedCond(w, e, on, table, runtime); + const readOnly = e.kind !== "entity"; + + if (op === "list" && readOnly) { + const readOnlyList = w.use("readOnlyList", runtime); + const page = w.useType("ReadOnlyPage", runtime); + const query = w.useType("ListQueryInput", runtime); + const inReadScope = w.use("inReadScope", runtime); + const filter = w.use(`${name}FilterAllowlist`, mods.entity); + const sort = w.use(`${name}SortAllowlist`, mods.entity); + const report = e.kind === "report"; + const exported = report && ctx.includeReportExport; + const keyed = e.verbs.includes("get"); + w.doc( + ...(report + ? [ + `The ${name} report's rows: the filter, search and sort of \`query\`, checked against the allowlists.`, + "It answers every row up to its cap and refuses above it (`report_too_large`); a `limit` pages it.", + ...(exported ? ["`?format=` asks for an export (`format` on the page), capped by the export's own row cap."] : []), + ] + : [ + `A page of ${name} rows: the filter, search, sort and page of \`query\` (the bracketed tree a`, + "query string parses to), checked against the allowlists.", + ]), + ); + w.block( + `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${page}<${row}>>> {`, + () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + objectLiteral( + w, + `const spec: ${w.useType("ReadOnlySpec", runtime)} = `, + [ + `filterAllowlist: ${filter},`, + `sortAllowlist: ${sort},`, + `dialect: ${dialect},`, + ...(keyed && e.keyField !== "id" ? [`idColumn: ${keyField},`] : []), + ...(report ? ["report: true,"] : []), + ...(report && pkg.reportMaxRows !== undefined ? [`reportMaxRows: ${pkg.reportMaxRows},`] : []), + ...(exported ? [`export: ${w.use(`${name}Export`, exportSpecifier(path, obj, ctx))},`] : []), + report ? "" : paginationLine(obj, "", ctx.loadedRoot), + ], + ";", + ); + w.line(`return (await ${readOnlyList}(db, ${table}, query, spec)) as ${page}<${row}>;`); + }, "});"); + }, + ); + return w.toString(); + } + + if (op === "get" && readOnly) { + const inReadScope = w.use("inReadScope", runtime); + const notFound = w.use("notFound", runtime); + w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); + w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { + w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { + w.line(`const row = await ${w.use("readOnlyGet", runtime)}(db, ${table}, id, { dialect: ${dialect}${e.keyField !== "id" ? `, idColumn: ${keyField}` : ""} });`); + w.line(`if (row === undefined) ${notFound}();`); + w.line(`return row as ${row};`); + }, "});"); + }); + return w.toString(); + } if (op === "list") { const listRows = w.use("listRows", runtime); @@ -170,6 +308,8 @@ function renderOperation( w.doc( `A page of ${name} rows: the filter, search, sort and page of \`query\` (the bracketed tree a`, "query string parses to), checked against the allowlists; ordered by the key when it names no sort.", + ...(e.discriminator !== undefined ? [`Only the rows of discriminator value ${e.discriminator.value}.`] : []), + ...(e.readView ? ["Read through the replica view, so a row carries its derived fields."] : []), ); w.block( `export async function ${fn}(deps: ${deps}, query: ${query} = {}, opts: ${opOptions} = {}): Promise<${opResult}<${listPage}<${row}>>> {`, @@ -178,10 +318,17 @@ function renderOperation( objectLiteral( w, `const spec: ${w.useType("ListSpec", runtime)} = `, - [`filterAllowlist: ${filter},`, `sortAllowlist: ${sort},`, `dialect: ${dialect},`, `keyField: ${keyField},`, paginationLine(obj, "", ctx.loadedRoot)], + [ + `filterAllowlist: ${filter},`, + `sortAllowlist: ${sort},`, + `dialect: ${dialect},`, + `keyField: ${keyField},`, + paginationLine(obj, "", ctx.loadedRoot), + ...(scope === undefined ? [] : [`scope: ${scope},`]), + ], ";", ); - w.line(`return (await ${listRows}(db, ${table}, query, spec)) as ${listPage}<${row}>;`); + w.line(`return (await ${listRows}(db, ${src.read}, query, spec)) as ${listPage}<${row}>;`); }, "});"); }, ); @@ -191,12 +338,11 @@ function renderOperation( if (op === "get") { const inReadScope = w.use("inReadScope", runtime); const readOne = w.use("readOne", runtime); - const keyCondition = w.use("keyCondition", runtime); const notFound = w.use("notFound", runtime); w.doc(`The ${name} row \`id\` names: \`not_found\` when there is none, \`invalid_id\` when \`id\` is no key.`); w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inReadScope}(deps.db, opts.tx, async (db) => {`, () => { - w.line(`const row = await ${readOne}(db, ${table}, ${keyCondition}(${table}, ${keyField}, id));`); + w.line(`const row = await ${readOne}(db, ${src.read}, ${addressed(src.read)});`); w.line(`if (row === undefined) ${notFound}();`); w.line(`return row as ${row};`); }, "});"); @@ -204,21 +350,40 @@ function renderOperation( return w.toString(); } + // A write to a write-through entity is read back through its replica view, so the answer + // carries the view's derived fields. + const readBack = (expr: string) => + src.view === undefined ? expr : `(await ${w.use("readThroughView", runtime)}(tx, ${src.view}, ${keyField}, ${expr})) as ${row}`; + // Under `interactiveTransactions: false` a write opens no transaction and has no hooks or event // hook to run inside one (ADR-0067 §4): it is its one statement, after the load and the checks. const tx = interactive(pkg); const inWriteTransaction = tx ? w.use("inWriteTransaction", runtime) : w.use("withoutTransaction", runtime); const inOne = tx ? "In one transaction:" : "With no transaction (`interactiveTransactions: false`):"; + const disc = e.discriminator; if (op === "create" || op === "update") { const writeRules = w.useType("WriteBodyRules", runtime); const validateBody = w.use("validateBody", runtime); w.doc("What a write body may name: every other key is refused, a server-owned one dropped."); - objectLiteral(w, `const writeRules: ${writeRules} = `, [knownFieldsLine(obj, "", ctx.loadedRoot), writeDeniedColumnsLine(obj, "")], ";"); + objectLiteral( + w, + `const writeRules: ${writeRules} = `, + [knownFieldsLine(obj, "", ctx.loadedRoot, e.hierarchy), writeDeniedColumnsLine(obj, "", e.hierarchy)], + ";", + ); w.blank(); if (op === "create") { const insertRow = w.use("insertRow", runtime); - const schema = w.use(`${name}InsertSchema`, mods.contract); - const input = w.useType(`${name}Create`, mods.contract); + // A single-table subtype's body omits the discriminator: the path names the subtype. One with + // cross-field rules has a refined schema, which Zod will not `.omit()`: its entity module + // exports the discriminator-less body schema instead. + const schema = + disc === undefined + ? w.use(`${name}InsertSchema`, mods.contract) + : hasInsertRefinements(obj) + ? w.use(`${name}InsertBodySchema`, mods.entity) + : `${w.use(`${name}InsertSchema`, mods.contract)}.omit({ ${disc.field}: true })`; + const input = createInputType(w, e, path, ctx); w.doc( ...(tx ? [ @@ -227,6 +392,7 @@ function renderOperation( "and the event hook; answer the written row.", ] : [`Create a ${name}. ${inOne} validate the input and stamp what the model declares`, "(ADR-0045), insert it; answer the written row."]), + ...(disc !== undefined ? [`The row is stamped with discriminator value ${disc.value}.`] : []), ); w.block(`export async function ${fn}(deps: ${deps}, input: ${input}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { @@ -235,6 +401,7 @@ function renderOperation( w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(input, ctx)) ?? input;`); } else w.line("const given = input;"); w.line(`const values: Record = ${validateBody}(${schema}, given, writeRules);`); + if (disc !== undefined) w.line(`values[${str(disc.field)}] = ${str(disc.value)};`); if (e.lifecycles.length > 0) { if (pkg.settings.lifecycleCreate === "initial") { const initials = e.lifecycles.map((l) => `${l.field}: ${str(l.initial ?? "")}`).join(", "); @@ -244,7 +411,7 @@ function renderOperation( w.line(`// rules.lifecycle.create: "any" — a create may start a lifecycle in any of its states.`); } } - w.line(`const row = (await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField})) as ${row};`); + w.line(`const row = ${readBack(`(await ${insertRow}(tx, ${table}, values, ${dialect}, ${keyField}))`)} as ${row};`); if (tx) { w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, ctx);`); w.line( @@ -256,7 +423,6 @@ function renderOperation( }); return w.toString(); } - const keyCondition = w.use("keyCondition", runtime); const loadForWrite = w.use("loadForWrite", runtime); const updateRow = w.use("updateRow", runtime); const notFound = w.use("notFound", runtime); @@ -275,12 +441,13 @@ function renderOperation( "(`not_found` when there is none), validate the patch and stamp what the model declares", "(ADR-0045), write it; answer the written row. A patch with nothing to write answers the row.", ]), + ...(disc !== undefined ? [`A row's subtype never changes: the discriminator is dropped from the patch.`] : []), ); w.block( `export async function ${fn}(deps: ${deps}, ${id}, patch: ${patch}, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`const cond = ${addressed(table)};`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); if (tx) { @@ -288,13 +455,15 @@ function renderOperation( w.line(`const given = (await deps.hooks?.before${toPascalCase(fn)}?.(patch, current, ctx)) ?? patch;`); } else w.line("const given = patch;"); w.line(`const data: Record = ${validateBody}(${schema}, given, writeRules);`); + if (disc !== undefined) w.line(`delete data[${str(disc.field)}];`); if (lifecycleFields.length > 0) { w.line("// A lifecycle moves only through its transitions (ADR-0066 §6 step 7)."); w.line(`${w.use("checkStateManaged", runtime)}(data, current, ${JSON.stringify(lifecycleFields)});`); } - w.line("if (Object.keys(data).length === 0) return current;"); - w.line(`const row = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); - w.line(`if (row === undefined) ${notFound}();`); + w.line(`if (Object.keys(data).length === 0) return ${readBack("current")};`); + w.line(`const written = (await ${updateRow}(tx, ${table}, data, cond, ${dialect})) as ${row} | undefined;`); + w.line(`if (written === undefined) ${notFound}();`); + w.line(`const row = ${readBack("written")};`); if (tx) { w.line(`await deps.hooks?.after${toPascalCase(fn)}?.(row, current, ctx);`); w.line( @@ -308,7 +477,6 @@ function renderOperation( return w.toString(); } - const keyCondition = w.use("keyCondition", runtime); const loadForWrite = w.use("loadForWrite", runtime); const deleteRows = w.use("deleteRows", runtime); const notFound = w.use("notFound", runtime); @@ -322,7 +490,7 @@ function renderOperation( ); w.block(`export async function ${fn}(deps: ${deps}, ${id}, opts: ${opOptions} = {}): Promise<${opResult}> {`, () => { w.block(`return ${inWriteTransaction}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${keyCondition}(${table}, ${keyField}, id);`); + w.line(`const cond = ${addressed(table)};`); w.line(`const current = (await ${loadForWrite}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${notFound}();`); if (!tx) { @@ -341,6 +509,64 @@ function renderOperation( return w.toString(); } +/** Where a report's export spec module (`report-export`, `.export`) is, from the file at `from`. */ +function exportSpecifier(from: string, obj: MetaObject, ctx: RenderContext): string { + const layout = ctx.outputLayout ?? DEFAULT_OUTPUT_LAYOUT; + return contractSpecifier(from, entityOutputPath(layout, effectivePackage(obj), `${obj.name}.export.ts`), ctx.extStyle); +} + +/** The physical column of `obj`'s field `fieldName` (the field name when it declares none). */ +function physicalColumn(obj: MetaObject, fieldName: string, ctx: RenderContext): string { + // ADR-0039: resolving — a junction's key field may be inherited through extends. + const field = obj.children().find((c) => c.type === TYPE_FIELD && c.name === fieldName); + return field === undefined ? fieldName : resolveColumnName(field, ctx.columnNamingStrategy); +} + +/** A many-to-many traversal of `e`: the target rows the junction links a source row to. */ +function renderRelation(r: ServiceRelation, e: ServiceEntity, path: string, ctx: RenderContext): string { + const w = new TsWriter(); + header(w, `${e.obj.name} (${e.obj.fqn()}) — service query ${r.fn}, the ${r.name} relationship (ADR-0067 layer 4)`); + const runtime = runtimeSpecifierFrom(path, "service", ctx); + const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; + const opOptions = `${w.useType("OpOptions", runtime)}`; + const opResult = w.useType("OpResult", runtime); + const junction = w.use(ctx.collectionName(r.junction.name), modulesOf(path, r.junction, ctx).entity); + const target = w.use(ctx.collectionName(r.target.name), modulesOf(path, r.target, ctx).entity); + const targetRow = w.useType(r.target.name, modulesOf(path, r.target, ctx).contract); + w.doc( + `The ${r.name} of the ${e.obj.name} row \`id\` names: the target rows its junction links it to.`, + ...(e.discriminator !== undefined ? [`An id that is no ${e.obj.name} (another subtype's row) has none.`] : []), + ); + objectLiteral( + w, + `const spec: ${w.useType("M2mSpec", runtime)} = `, + [ + `junctionTable: ${junction},`, + `targetTable: ${target},`, + `sourceColumn: ${str(physicalColumn(r.junction, r.sourceJoinField, ctx))},`, + `targetColumn: ${str(physicalColumn(r.junction, r.targetJoinField, ctx))},`, + `targetPkColumn: ${str(physicalColumn(r.target, pkInfoOf(r.target)?.fieldName ?? "id", ctx))},`, + `symmetric: ${r.symmetric},`, + ...(r.targetDiscriminator === undefined + ? [] + : [`targetDiscriminator: { column: ${str(physicalColumn(r.target, r.targetDiscriminator.field, ctx))}, value: ${str(r.targetDiscriminator.value)} },`]), + ...(e.discriminator === undefined + ? [] + : [ + `sourceDiscriminator: { table: ${w.use(ctx.collectionName(e.storage.name), modulesOf(path, e.storage, ctx).entity)}, pkColumn: ${str( + physicalColumn(e.storage, e.keyField, ctx), + )}, column: ${str(physicalColumn(e.storage, e.discriminator.field, ctx))}, value: ${str(e.discriminator.value)} },`, + ]), + ], + ";", + ); + w.blank(); + w.block(`export async function ${r.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${targetRow}[]>> {`, () => { + w.line(`return ${w.use("inReadScope", runtime)}(deps.db, opts.tx, async (db) => (await ${w.use("m2mRelated", runtime)}(db, spec, id)) as ${targetRow}[]);`); + }); + return w.toString(); +} + /** The specifier of the package's service index, from a file in the same folder. */ function indexSpecifier(ctx: RenderContext): string { return withExtIfRelative(`./${SERVICE_INDEX_FILE.replace(/\.ts$/, "")}`, ctx.extStyle); @@ -407,9 +633,8 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, const w = new TsWriter(); header(w, `${name} (${obj.fqn()}) — transition ${t.field}.${t.name}, service operation ${c.fn} (ADR-0066 §2)`); const runtime = runtimeSpecifierFrom(path, "service", ctx); - const mods = modulesOf(path, obj, ctx); - const table = w.use(ctx.collectionName(name), mods.entity); - const row = w.useType(name, mods.contract); + const { table, cond } = addressedOf(w, e, path, ctx, runtime); + const row = w.useType(name, modulesOf(path, obj, ctx).contract); const deps = `${w.useType("ServiceDeps", indexSpecifier(ctx))}`; const opOptions = `${w.useType("OpOptions", runtime)}`; const opResult = w.useType("OpResult", runtime); @@ -436,7 +661,7 @@ function renderTransitionCommand(c: ServiceTransitionCommand, e: ServiceEntity, ); w.block(`export async function ${c.fn}(deps: ${deps}, id: number | string, opts: ${opOptions} = {}): Promise<${opResult}<${row}>> {`, () => { w.block(`return ${w.use(inTx ? "inWriteTransaction" : "withoutTransaction", runtime)}(deps.db, opts.tx, async (tx) => {`, () => { - w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(e.keyField)}, id);`); + w.line(`const cond = ${cond()};`); w.line(`const current = (await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})) as ${row} | undefined;`); w.line(`if (current === undefined) ${w.use("notFound", runtime)}();`); if (c.permission === undefined) w.line("// @public: the policy is not asked."); @@ -469,12 +694,12 @@ function renderDeclaredOperation(op: ServiceOperation, path: string, ctx: Render const target = op.target; // The target's table and row type, imported only by an operation that reads or answers its row. const usesRow = op.keyed || outputIsTargetRow(op); - const mods = target === undefined || !usesRow ? undefined : modulesOf(path, target.obj, ctx); - const table = mods === undefined ? undefined : w.use(ctx.collectionName(target!.obj.name), mods.entity); - const row = mods === undefined ? undefined : w.useType(target!.obj.name, mods.contract); + const command = op.kind === "command"; + const addressed = target === undefined || !usesRow ? undefined : addressedOf(w, target, path, ctx, runtime); + const table = addressed?.table; + const row = addressed === undefined ? undefined : w.useType(target!.obj.name, modulesOf(path, target!.obj, ctx).contract); const output = outputType(w, op, path, pkg, ctx); const params = [...operationParams(w, op, path, pkg, ctx), `opts: ${opOptions} = {}`]; - const command = op.kind === "command"; if (op.input !== undefined) { w.doc("What the input may name: every other key is refused."); @@ -508,7 +733,7 @@ function renderDeclaredOperation(op: ServiceOperation, path: string, ctx: Render const scope = command ? w.use("inWriteTransaction", runtime) : w.use("inReadScope", runtime); w.block(`return ${scope}(deps.db, opts.tx, async (tx) => {`, () => { if (op.keyed) { - w.line(`const cond = ${w.use("keyCondition", runtime)}(${table}, ${str(target!.keyField)}, id);`); + w.line(`const cond = ${addressed!.cond()};`); const load = command ? `await ${w.use("loadForWrite", runtime)}(tx, ${table}, cond, ${dialect})` : `await ${w.use("readOne", runtime)}(tx, ${table}, cond)`; @@ -610,9 +835,10 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex ); w.block(`export interface ${stem}Hooks {`, () => { for (const e of pkg.entities) { + if (!e.verbs.includes("create")) continue; const mods = modulesOf(path, e.obj, ctx); const row = w.useType(e.obj.name, mods.contract); - const create = w.useType(`${e.obj.name}Create`, mods.contract); + const create = createInputType(w, e, path, ctx); const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const o = e.operations; const P = (f: string) => toPascalCase(f); @@ -680,24 +906,34 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex ); w.block(`export interface ${type} {`, () => { for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const row = w.useType(e.obj.name, mods.contract); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const row = rowTypeOf(w, e, path, ctx); const o = e.operations; - for (const f of Object.values(o)) w.use(f, withExtIfRelative(`./${f}`, ctx.extStyle)); - w.line(`${o.list}(query?: ${query}, opts?: ${opOptions}): Promise<${opResult}<${listPage}<${row}>>>;`); - w.line(`${o.get}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.create}(input: ${create}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.update}(id: number | string, patch: ${patch}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); - w.line(`${o.delete}(id: number | string, opts?: ${opOptions}): Promise<${opResult}>;`); - calls.push( - `${o.list}: (query, opts) => ${o.list}(deps, query, opts),`, - `${o.get}: (id, opts) => ${o.get}(deps, id, opts),`, - `${o.create}: (input, opts) => ${o.create}(deps, input, opts),`, - `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, - `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, - ); + for (const v of e.verbs) w.use(o[v], withExtIfRelative(`./${o[v]}`, ctx.extStyle)); + const page = e.kind === "entity" ? listPage : w.useType("ReadOnlyPage", runtime); + w.line(`${o.list}(query?: ${query}, opts?: ${opOptions}): Promise<${opResult}<${page}<${row}>>>;`); + calls.push(`${o.list}: (query, opts) => ${o.list}(deps, query, opts),`); + if (e.verbs.includes("get")) { + w.line(`${o.get}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + calls.push(`${o.get}: (id, opts) => ${o.get}(deps, id, opts),`); + } + if (e.verbs.includes("create")) { + const create = createInputType(w, e, path, ctx); + const patch = w.useType(`${e.obj.name}Patch`, modulesOf(path, e.obj, ctx).contract); + w.line(`${o.create}(input: ${create}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.update}(id: number | string, patch: ${patch}, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); + w.line(`${o.delete}(id: number | string, opts?: ${opOptions}): Promise<${opResult}>;`); + calls.push( + `${o.create}: (input, opts) => ${o.create}(deps, input, opts),`, + `${o.update}: (id, patch, opts) => ${o.update}(deps, id, patch, opts),`, + `${o.delete}: (id, opts) => ${o.delete}(deps, id, opts),`, + ); + } + for (const r of e.relations) { + w.use(r.fn, withExtIfRelative(`./${r.fn}`, ctx.extStyle)); + const targetRow = w.useType(r.target.name, modulesOf(path, r.target, ctx).contract); + w.line(`${r.fn}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${targetRow}[]>>;`); + calls.push(`${r.fn}: (id, opts) => ${r.fn}(deps, id, opts),`); + } for (const c of e.commands) { w.use(c.fn, withExtIfRelative(`./${c.fn}`, ctx.extStyle)); w.line(`${c.fn}(id: number | string, opts?: ${opOptions}): Promise<${opResult}<${row}>>;`); @@ -721,12 +957,31 @@ function renderServiceIndex(pkg: ServicePackage, path: string, ctx: RenderContex }, "};"); }); + const withWire = () => w.use("withWire", runtime); + const timestampWire = () => w.use("timestampWire", runtime); for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const table = w.use(ctx.collectionName(e.obj.name), mods.entity); + const src = sourcesOf(w, e, path, ctx); + const decimals = + e.discriminator !== undefined + ? decimalColumnsLine(e.obj, "", ctx.loadedRoot, e.hierarchy) + : decimalColumnsLine(e.hierarchy.length > 1 ? e.hierarchy : e.obj, "", ctx.loadedRoot); w.blank(); w.doc(`The wire form (ADR-0019) of a ${e.obj.name} row: what a transport sends.`); - objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${w.use("withWire", runtime)}(${w.use("timestampWire", runtime)}(${table}), `, [decimalColumnsLine(e.obj, "", ctx.loadedRoot)], ");"); + objectLiteral(w, `export const ${wireMapperName(e.obj.name)} = ${withWire()}(${timestampWire()}(${src.read}), `, [decimals], ");"); + if (src.view !== undefined) { + w.blank(); + w.doc( + `The wire form of a ${e.obj.name} row a write answers: read back through the replica view, or the`, + "table's row when the view has none, so it is mapped against both.", + ); + objectLiteral(w, `export const ${writeWireMapperName(e.obj.name)} = ${withWire()}(${timestampWire()}(${src.table}, ${src.view}), `, [decimals], ");"); + } + for (const r of e.relations) { + w.blank(); + w.doc(`The wire form of a row of ${e.obj.name}'s ${r.name}.`); + const target = w.use(ctx.collectionName(r.target.name), modulesOf(path, r.target, ctx).entity); + objectLiteral(w, `export const ${wireMapperName(r.fn)} = ${withWire()}(${timestampWire()}(${target}), `, [decimalColumnsLine(r.targetObjects, "", ctx.loadedRoot)], ");"); + } } return w.toString(); } @@ -757,16 +1012,24 @@ function refuseRouteCollisions(routes: readonly MountedRoute[]): void { function transportRoutes(pkg: ServicePackage): MountedRoute[] { const mounted: MountedRoute[] = []; for (const e of pkg.entities) { - const base = restPath(e.obj); + const base = e.path; const item = `${base}/:id`; - mounted.push( - { method: "GET", path: base, what: `${e.obj.name} list` }, - { method: "GET", path: item, what: `${e.obj.name} get` }, - { method: "POST", path: base, what: `${e.obj.name} create` }, - { method: "PATCH", path: item, what: `${e.obj.name} update` }, - { method: "PUT", path: item, what: `${e.obj.name} update` }, - { method: "DELETE", path: item, what: `${e.obj.name} delete` }, - ); + const keyed = e.verbs.includes("get"); + mounted.push({ method: "GET", path: base, what: `${e.obj.name} list` }); + if (keyed) mounted.push({ method: "GET", path: item, what: `${e.obj.name} get` }); + // A read-only object answers its writes 405; a single-table base serves no writes at all. + if (e.verbs.includes("create") || e.kind !== "entity") { + const what = (verb: string) => `${e.obj.name} ${e.kind === "entity" ? verb : "405"}`; + mounted.push({ method: "POST", path: base, what: what("create") }); + if (keyed) { + mounted.push( + { method: "PATCH", path: item, what: what("update") }, + { method: "PUT", path: item, what: what("update") }, + { method: "DELETE", path: item, what: what("delete") }, + ); + } + } + for (const r of e.relations) mounted.push({ method: "GET", path: `${item}/${r.name}`, what: `${e.obj.name}.${r.name} traversal` }); for (const c of e.commands) mounted.push({ method: "POST", path: `${item}/${c.transition.name}`, what: `transition ${e.obj.name}.${c.transition.name}` }); } for (const op of pkg.operations) mounted.push({ method: op.method, path: op.path, what: `operation ${op.name}` }); @@ -815,14 +1078,27 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): w.line(`const ro = ${handler}(undefined);`); const mount = (app: string) => { for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); const o = e.operations; - const base = str(restPath(e.obj)); - const item = str(`${restPath(e.obj)}/:id`); + const base = str(e.path); + const item = str(`${e.path}/:id`); const params = "{ Params: { id: string } }"; + const keyed = e.verbs.includes("get"); + if (e.kind !== "entity") { + const listPage = w.use("sendListPage", runtime); + const exported = e.kind === "report" && ctx.includeReportExport; + const exportOf = exported ? `, { spec: ${w.use(`${e.obj.name}Export`, exportSpecifier(path, e.obj, ctx))}, path: ${base} }` : ""; + w.line( + `${app}.get(${base}, ro, async (req, reply) => ${listPage}(reply, await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)), await actorOf(req)), ${toWire}${exportOf}));`, + ); + if (keyed) w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id, await actorOf(req)), 200, ${toWire}));`); + const notAllowed = w.use("methodNotAllowed", runtime); + w.line(`// A ${e.kind} is read-only: every write answers 405.`); + w.line(`const ${lowerFirst(e.obj.name)}ReadOnly = async (req: ${fastifyRequest}, reply: ${w.useType("FastifyReply", "fastify")}) => reply.code(405).send(${notAllowed}(req.method, ${str(e.kind)}));`); + w.line(`${app}.post(${base}, ro, ${lowerFirst(e.obj.name)}ReadOnly);`); + if (keyed) for (const verb of ["patch", "put", "delete"]) w.line(`${app}.${verb}(${item}, ro, ${lowerFirst(e.obj.name)}ReadOnly);`); + continue; + } w.block(`${app}.get(${base}, ro, async (req, reply) => {`, () => { w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(req.raw.url)), await actorOf(req));`); w.line( @@ -830,17 +1106,29 @@ export function renderFastifyTransport(pkg: ServicePackage, ctx: RenderContext): ); }, "});"); w.line(`${app}.get<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.get}(req.params.id, await actorOf(req)), 200, ${toWire}));`); - w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}, await actorOf(req)), 201, ${toWire}));`); - w.line("// The update is reachable by PATCH and by PUT, as in every port."); - for (const verb of ["patch", "put"]) { + if (e.verbs.includes("create")) { + const mods = modulesOf(path, e.obj, ctx); + const create = createInputType(w, e, path, ctx); + const patch = w.useType(`${e.obj.name}Patch`, mods.contract); + const writeWire = e.readView ? w.use(writeWireMapperName(e.obj.name), serviceIndex) : toWire; + w.line(`${app}.post(${base}, ro, async (req, reply) => ${send}(reply, await service.${o.create}(req.body as ${create}, await actorOf(req)), 201, ${writeWire}));`); + w.line("// The update is reachable by PATCH and by PUT, as in every port."); + for (const verb of ["patch", "put"]) { + w.line( + `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}, await actorOf(req)), 200, ${writeWire}));`, + ); + } + w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id, await actorOf(req)), 204));`); + } + for (const c of e.commands) { w.line( - `${app}.${verb}<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.update}(req.params.id, req.body as ${patch}, await actorOf(req)), 200, ${toWire}));`, + `${app}.post<${params}>(${str(`${e.path}/:id/${c.transition.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${c.fn}(req.params.id, await actorOf(req)), 200, ${toWire}));`, ); } - w.line(`${app}.delete<${params}>(${item}, ro, async (req, reply) => ${send}(reply, await service.${o.delete}(req.params.id, await actorOf(req)), 204));`); - for (const c of e.commands) { + for (const r of e.relations) { + const relWire = w.use(wireMapperName(r.fn), serviceIndex); w.line( - `${app}.post<${params}>(${str(`${restPath(e.obj)}/:id/${c.transition.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${c.fn}(req.params.id, await actorOf(req)), 200, ${toWire}));`, + `${app}.get<${params}>(${str(`${e.path}/:id/${r.name}`)}, ro, async (req, reply) => ${send}(reply, await service.${r.fn}(req.params.id, await actorOf(req)), 200, (rows) => rows.map(${relWire})));`, ); } } @@ -917,16 +1205,38 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se const routes: Array<{ path: string; emit: () => void }> = []; const route = (path: string, emit: () => void) => routes.push({ path, emit }); for (const e of pkg.entities) { - const mods = modulesOf(path, e.obj, ctx); - const create = w.useType(`${e.obj.name}Create`, mods.contract); - const patch = w.useType(`${e.obj.name}Patch`, mods.contract); const toWire = w.use(wireMapperName(e.obj.name), serviceIndex); const o = e.operations; - const base = at(restPath(e.obj)); - const item = at(`${restPath(e.obj)}/:id`); - const id = `c.req.param("id") ?? ""`; - const basePath = restPath(e.obj); + const basePath = e.path; const itemPath = `${basePath}/:id`; + const base = at(basePath); + const item = at(itemPath); + const id = `c.req.param("id") ?? ""`; + const keyed = e.verbs.includes("get"); + if (e.kind !== "entity") { + const listPage = w.use("sendListPage", runtime); + const notAllowed = w.use("methodNotAllowed", runtime); + const exported = e.kind === "report" && ctx.includeReportExport; + const exportOf = exported ? `, { spec: ${w.use(`${e.obj.name}Export`, exportSpecifier(path, e.obj, ctx))}, path: ${str(basePath)} }` : ""; + const kind = str(e.kind); + route(basePath, () => { + w.line(`app.get(${base}, ${guard}(async (c) => ${listPage}(c, await service.${o.list}(${parseQuery}(${rawQuery}(c.req.url)), await actorOf(c)), ${toWire}${exportOf})));`); + w.line(`// A ${e.kind} is read-only: every write answers 405.`); + w.line(`app.post(${base}, (c) => ${notAllowed}(c, ${kind}));`); + }); + if (keyed) { + route(itemPath, () => { + w.line(`app.get(${item}, ${guard}(async (c) => ${send}(c, await service.${o.get}(${id}, await actorOf(c)), 200, ${toWire})));`); + for (const verb of ["patch", "put", "delete"]) w.line(`app.${verb}(${item}, (c) => ${notAllowed}(c, ${kind}));`); + }); + } + continue; + } + const writable = e.verbs.includes("create"); + const mods = modulesOf(path, e.obj, ctx); + const create = writable ? createInputType(w, e, path, ctx) : ""; + const patch = writable ? w.useType(`${e.obj.name}Patch`, mods.contract) : ""; + const writeWire = e.readView ? w.use(writeWireMapperName(e.obj.name), serviceIndex) : toWire; route(basePath, () => { w.block(`app.get(${base}, ${guard}(async (c) => {`, () => { w.line(`const result = await service.${o.list}(${parseQuery}(${rawQuery}(c.req.url)), await actorOf(c));`); @@ -934,20 +1244,22 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se `return ${send}(c, result, 200, (page) => (page.total === undefined ? page.rows.map(${toWire}) : { rows: page.rows.map(${toWire}), total: page.total }));`, ); }, "}));"); + if (!writable) return; w.block(`app.post(${base}, ${guard}(async (c) => {`, () => { w.line(`const read = await ${readBody}(c);`); w.line("if (!read.ok) return read.response;"); - w.line(`return ${send}(c, await service.${o.create}(read.body as ${create}, await actorOf(c)), 201, ${toWire});`); + w.line(`return ${send}(c, await service.${o.create}(read.body as ${create}, await actorOf(c)), 201, ${writeWire});`); }, "}));"); }); route(itemPath, () => { w.line(`app.get(${item}, ${guard}(async (c) => ${send}(c, await service.${o.get}(${id}, await actorOf(c)), 200, ${toWire})));`); + if (!writable) return; w.line("// The update is reachable by PATCH and by PUT, as in every port."); for (const verb of ["patch", "put"]) { w.block(`app.${verb}(${item}, ${guard}(async (c) => {`, () => { w.line(`const read = await ${readBody}(c);`); w.line("if (!read.ok) return read.response;"); - w.line(`return ${send}(c, await service.${o.update}(${id}, read.body as ${patch}, await actorOf(c)), 200, ${toWire});`); + w.line(`return ${send}(c, await service.${o.update}(${id}, read.body as ${patch}, await actorOf(c)), 200, ${writeWire});`); }, "}));"); } w.line(`app.delete(${item}, ${guard}(async (c) => ${send}(c, await service.${o.delete}(${id}, await actorOf(c)), 204)));`); @@ -958,6 +1270,13 @@ export function renderHonoTransport(pkg: ServicePackage, ctx: RenderContext): Se w.line(`app.post(${at(path)}, ${guard}(async (c) => ${send}(c, await service.${c.fn}(${id}, await actorOf(c)), 200, ${toWire})));`), ); } + for (const r of e.relations) { + const path = `${itemPath}/${r.name}`; + const relWire = w.use(wireMapperName(r.fn), serviceIndex); + route(path, () => + w.line(`app.get(${at(path)}, ${guard}(async (c) => ${send}(c, await service.${r.fn}(${id}, await actorOf(c)), 200, (rows) => rows.map(${relWire}))));`), + ); + } } for (const op of pkg.operations) { const key = op.keyed ? op.target!.keyField : undefined; diff --git a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts index 875ed7d8f8..b8c2972a54 100644 --- a/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts +++ b/server/typescript/packages/codegen-ts/test/scratch-dir.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect } from "bun:test"; -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; import { makeScratchDir, removeTree, scratchRoot } from "../src/scratch-dir.js"; describe("scratch-dir", () => { @@ -22,4 +22,31 @@ describe("scratch-dir", () => { removeTree(a); expect(() => removeTree(a)).not.toThrow(); }); + + // A run with no project keeps its gen-state in the scratch root for the process's later runs. + // Before this, every such process left `meta-gen-state-` behind for good, and the test + // harnesses that generate with no project filled a RAM-backed scratch root with them. + test("a run with no project leaves no gen-state behind once its process exits", () => { + const root = makeScratchDir("scratch-dir-exit-"); + try { + const runner = resolve(import.meta.dir, "../src/runner.ts"); + writeFileSync(join(root, "meta.t.json"), JSON.stringify({ "metadata.root": { package: "t", children: [{ "object.entity": { name: "Thing", children: [{ "field.string": { name: "label" } }] } }] } })); + const script = ` + import { runGen } from ${JSON.stringify(runner)}; + import { loadUris } from "@metaobjectsdev/metadata"; + import { pathToFileURL } from "node:url"; + const { root: metadata } = await loadUris([pathToFileURL(${JSON.stringify(join(root, "meta.t.json"))}).href]); + const out = ${JSON.stringify(join(root, "out"))}; + await runGen({ metadata, config: { outDir: out, generators: [{ name: "one", generate: () => [{ path: "one.txt", content: "1" }] }] } }); + const state = (await import("node:fs")).readdirSync(${JSON.stringify(root)}).filter((n) => n.startsWith("meta-gen-state-")); + if (state.length !== 1) throw new Error("expected the run's gen-state while the process runs, found " + (await import("node:fs")).readdirSync(${JSON.stringify(root)}).join(",")); + `; + const child = Bun.spawnSync(["bun", "-e", script], { env: { ...process.env, DEV_SCRATCH: root }, stderr: "pipe" }); + expect({ exit: child.exitCode, stderr: child.stderr.toString() }).toEqual({ exit: 0, stderr: "" }); + expect(existsSync(join(root, "out", "one.txt"))).toBe(true); + expect(readdirSync(root).filter((n) => n.startsWith("meta-gen-"))).toEqual([]); + } finally { + removeTree(root); + } + }); }); diff --git a/server/typescript/packages/codegen-ts/test/service-file.test.ts b/server/typescript/packages/codegen-ts/test/service-file.test.ts index 763698359b..6ab1b6e5ce 100644 --- a/server/typescript/packages/codegen-ts/test/service-file.test.ts +++ b/server/typescript/packages/codegen-ts/test/service-file.test.ts @@ -164,17 +164,29 @@ describe("service-routes-hono — the service's Hono transport", () => { }); describe("service walk — which entities get the derived operations", () => { - test("over the fitness corpus: concrete, store-backed, single-key entities only", async () => { + test("over the fitness corpus: every object the flat routes serve, single-key where keyed", async () => { const result = await loadUris([pathToFileURL(FITNESS).href]); expect(result.errors).toEqual([]); - const covered = serviceModelOf(result.root).flatMap((p) => p.entities.map((e) => e.obj.name)); - expect(covered).toContain("Program"); + const entities = serviceModelOf(result.root).flatMap((p) => p.entities); + const byName = new Map(entities.map((e) => [e.obj.name, e])); + expect(byName.has("Program")).toBe(true); // A concrete entity that inherits its fields from an abstract one. - expect(covered).toContain("Gadget"); + expect(byName.has("Gadget")).toBe(true); // The abstract level has no table of its own. - expect(covered).not.toContain("Labeled"); - // A single-table hierarchy, its base and its subtypes, is later service work. - for (const tph of ["Auth", "BridgeAuth", "CouponAuth", "PermitAuth", "ReferralAuth"]) expect(covered).not.toContain(tph); + expect(byName.has("Labeled")).toBe(false); + // A single-table hierarchy: the base is polymorphic and read-only (the union has no single + // writable shape), each concrete subtype has the five operations on the base table, scoped to + // its discriminator value, at the base path plus its segment (FR-017). + expect(byName.get("Auth")?.verbs).toEqual(["list", "get"]); + const bridge = byName.get("BridgeAuth")!; + expect(bridge.verbs).toEqual(["list", "get", "create", "update", "delete"]); + expect(bridge.storage.name).toBe("Auth"); + expect(bridge.path).toBe("/auths/bridge"); + expect(bridge.discriminator).toEqual({ field: "type", value: "Bridge" }); + // A served report has a list and no key. + const report = byName.get("FitnessTotals")!; + expect(report.kind).toBe("report"); + expect(report.verbs).toEqual(["list"]); }); }); @@ -276,6 +288,54 @@ describe("service generators — lifecycles and declared operations (ADR-0066)", }); }); +describe("service generators — commands and keyed operations address the object's own storage", () => { + const ticket = { + "object.entity": { + name: "Ticket", + "@discriminator": "type", + children: [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { name: "id" } }, + { "field.enum": { name: "type", "@values": ["Bug", "Task"] } }, + { "identity.primary": { name: "pk", "@fields": ["id"] } }, + ], + }, + }; + const bug = { + "object.entity": { + name: "BugTicket", + extends: "Ticket", + "@discriminatorValue": "Bug", + children: [ + { + "field.enum": { + name: "status", + "@values": ["open", "closed"], + "@default": "open", + children: [{ "transition.action": { name: "close", "@from": ["open"], "@to": "closed", "@public": true } }], + }, + }, + ], + }, + }; + test("a single-table subtype's transition command writes the base's table, scoped to its discriminator value", async () => { + const files = await gen(await load("acme::desk", [ticket, bug]), tier()); + const close = files["acme/desk/service/closeBugTicket.ts"]!; + expect(close).toBeDefined(); + // The subtype's module exports no table: the rows live in the base's. + expect(close).toMatch(/import \{ tickets \} from "\.\.\/Ticket(\.js)?";/); + expect(close).toContain('const cond = scoped(keyCondition(tickets, "id", id), scopeCondition(tickets, "type", "Bug"));'); + }); + + test("a keyed declared operation on a single-table subtype reads only rows of its discriminator value", async () => { + const peek = { "operation.query": { name: "peek", "@objectRef": "BugTicket", "@outputRef": "BugTicket", "@public": true } }; + const files = await gen(await load("acme::desk", [ticket, bug, api(peek)]), tier()); + const op = files["acme/desk/service/peek.ts"]!; + expect(op).toMatch(/import \{ tickets \} from "\.\.\/Ticket(\.js)?";/); + expect(op).toContain('const cond = scoped(keyCondition(tickets, "id", id), scopeCondition(tickets, "type", "Bug"));'); + }); +}); + describe("service generator — a store without interactive transactions (ADR-0067 §4)", () => { const noTx = (): Generator[] => [entityFile(), contractTypes(), serviceFile({ interactiveTransactions: false }), serviceRoutesFile()]; const peek = { "operation.query": { name: "peek", "@objectRef": "Order", "@outputRef": "Order", "@public": true } }; diff --git a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts index a638328b9b..a35b0694a8 100644 --- a/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts +++ b/server/typescript/packages/codegen-ts/test/typed-create-compile.test.ts @@ -12,7 +12,7 @@ import { describe, test, expect, setDefaultTimeout } from "bun:test"; import { COMPILE_TEST_TIMEOUT_MS } from "./compile-timeout.js"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { symlinkSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import ts from "typescript"; import { MetaDataLoader, InMemoryStringSource, type MetaObject, type MetaRoot } from "@metaobjectsdev/metadata"; @@ -23,7 +23,7 @@ import { buildPkMap } from "../src/pk-resolver.js"; import { buildRelationMap } from "../src/relation-resolver.js"; import type { EmittedFile, GenContext } from "../src/generator.js"; import type { Dialect } from "../src/metaobjects-config.js"; -import { removeTree } from "../src/scratch-dir.js"; +import { makeScratchDir, removeTree } from "../src/scratch-dir.js"; setDefaultTimeout(COMPILE_TEST_TIMEOUT_MS); @@ -53,6 +53,18 @@ const MODEL = { }, }; +/** + * A throwaway directory under the scratch root, never under `test/`: the package typecheck + * compiles `test/**`, so a half-written caller there (or one a killed run left behind, holding + * a deliberately misspelt call) fails it. Its `node_modules` links to this package's, so the + * generated tree resolves drizzle-orm / zod to the REAL types. + */ +function makeCompileDir(prefix: string): string { + const dir = makeScratchDir(prefix); + symlinkSync(join(import.meta.dir, "..", "node_modules"), join(dir, "node_modules"), "dir"); + return dir; +} + async function loadModel(): Promise { const result = await new MetaDataLoader({ strict: true }).load([ new InMemoryStringSource(JSON.stringify(MODEL), { id: "typed-create.json" }), @@ -107,7 +119,7 @@ function compile(dir: string, paths: string[]): string[] { /** Generate the tree, add `caller.ts` with `body`, compile everything; the caller's diagnostics. */ async function compileCaller(dialect: Dialect, body: string): Promise<{ all: string[]; caller: string[] }> { const root = await loadModel(); - const dir = mkdtempSync(join(import.meta.dir, `tmp-typed-create-${dialect}-`)); + const dir = makeCompileDir(`typed-create-${dialect}-`); try { const files = await generate(root, dialect, dir); for (const f of files) writeFileSync(join(dir, f.path), f.content); @@ -133,7 +145,7 @@ for (const dialect of ["postgres", "sqlite"] as const) { describe(`generated create calls are typed with the insert input (${dialect})`, () => { test("the signatures name the typed input, not unknown", async () => { const root = await loadModel(); - const dir = mkdtempSync(join(import.meta.dir, `tmp-typed-create-src-${dialect}-`)); + const dir = makeScratchDir(`typed-create-src-${dialect}-`); try { const files = await generate(root, dialect, dir); const brewer = files.find((f) => f.path === "Brewer.ts")!.content.replace(/\s+/g, " "); 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 bd8b0a6045..ec3bdec298 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-decimal-server.ts @@ -82,8 +82,9 @@ export function startDecimalServer( /** The Postgres or MySQL connection URL; unused by SQLite and D1. */ connectionUrl?: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { - return startGeneratedCorpusServer(DECIMAL, engine, metaPath, connectionUrl, outputLayout); + return startGeneratedCorpusServer(DECIMAL, engine, metaPath, connectionUrl, outputLayout, lane); } /** Generate, provision and mount one generated-lane sub-corpus on `engine`. */ diff --git a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts index 5a9af4aaa4..42ddba4e08 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-m2m-generated-server.ts @@ -22,13 +22,14 @@ // This proves the GENERATED M:N traversal route — not a stand-in — implements // the cross-port contract over HTTP, including the TPH source/target narrowing. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -61,6 +62,7 @@ export async function startGeneratedM2mServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -74,14 +76,14 @@ export async function startGeneratedM2mServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -120,32 +122,19 @@ export const db = drizzle(pool); CREATE TABLE IF NOT EXISTS "blog_categories" ("id" bigserial PRIMARY KEY, "name" varchar(80) NOT NULL); `); - // 4. Import the EMITTED route files unmodified and mount them. - const postRoutes = (await import(pathToFileURL(emitted.locate("Post.routes.ts")).href)) as { - postRoutes: (f: FastifyInstance) => Promise; - }; - const personRoutes = (await import(pathToFileURL(emitted.locate("Person.routes.ts")).href)) as { - personRoutes: (f: FastifyInstance) => Promise; - }; - // FW-8: the TPH discriminator base's routes file carries the polymorphic base - // path AND every per-subtype path (incl. subtype-scoped M:N mounts) in one module. - const accountRoutes = (await import(pathToFileURL(emitted.locate("Account.routes.ts")).href)) as { - accountRoutes: (f: FastifyInstance) => Promise; - }; - // PostCategory takes part in no relationship; it is mounted so the corpus can - // gate the COLLECTION-URL spelling of a multi-word, y-ending entity name. - const postCategoryRoutes = (await import(pathToFileURL(emitted.locate("PostCategory.routes.ts")).href)) as { - postCategoryRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(postRoutes.postRoutes); - await fastify.register(personRoutes.personRoutes); - await fastify.register(accountRoutes.accountRoutes); - await fastify.register(postCategoryRoutes.postCategoryRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it, or the service behind its transport. + // FW-8: the TPH discriminator base's routes file carries the polymorphic base path AND every + // per-subtype path (incl. subtype-scoped M:N mounts) in one module. PostCategory takes part + // in no relationship; it is mounted so the corpus can gate the COLLECTION-URL spelling of a + // multi-word, y-ending entity name. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Post", "Person", "Account", "PostCategory"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -153,7 +142,7 @@ export const db = drizzle(pool); await seedM2m(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts index f43b643f3c..f152bdd7ee 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-projection-generated-server.ts @@ -18,7 +18,7 @@ // projection at all; a hand-rolled reference server would answer every scenario // by construction and prove nothing about the emitted artifact. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -29,6 +29,7 @@ import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { loadMetadataFile } from "./load-metadata.ts"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; export interface ProjectionSeed { invoices: Array<{ @@ -51,6 +52,7 @@ export async function startGeneratedProjectionServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -64,14 +66,14 @@ export async function startGeneratedProjectionServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -117,28 +119,16 @@ export const db = drizzle(pool); SELECT "id", "reference" FROM "invoices"; `); - // 4. Import the EMITTED InvoiceSummary route file unmodified and mount it. - const routes = (await import( - pathToFileURL(emitted.locate("InvoiceSummary.routes.ts")).href - )) as { invoiceSummaryRoutes: (f: FastifyInstance) => Promise }; - const ledgerRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceLedger.routes.ts")).href - )) as { invoiceLedgerRoutes: (f: FastifyInstance) => Promise }; - const registerRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceRegister.routes.ts")).href - )) as { invoiceRegisterRoutes: (f: FastifyInstance) => Promise }; - const stubRoutes = (await import( - pathToFileURL(emitted.locate("InvoiceStub.routes.ts")).href - )) as { invoiceStubRoutes: (f: FastifyInstance) => Promise }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(routes.invoiceSummaryRoutes); - await fastify.register(ledgerRoutes.invoiceLedgerRoutes); - await fastify.register(registerRoutes.invoiceRegisterRoutes); - await fastify.register(stubRoutes.invoiceStubRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: the four projections' routes, or the + // service behind its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["InvoiceSummary", "InvoiceLedger", "InvoiceRegister", "InvoiceStub"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -146,7 +136,7 @@ export const db = drizzle(pool); await seedProjection(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts index 52f385d79d..fdbab52d9b 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-generated-server.ts @@ -14,7 +14,7 @@ // // Generated lane only, and on every port — see the corpus README. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -24,6 +24,7 @@ import { DEFAULT_PHYSICAL_NAMING, resolveColumnName, resolveTableName, type MetaRoot, } from "@metaobjectsdev/metadata"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { loadMetadataFile } from "./load-metadata.ts"; @@ -198,6 +199,7 @@ export async function startGeneratedReportServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -211,19 +213,23 @@ export async function startGeneratedReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - // The export cap equals the list cap so the 61-row ReadingLog trips export_too_large; xsi:nil pins the nil spelling. - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + // The export cap equals the list cap so the 61-row ReadingLog trips export_too_large; xsi:nil pins the nil spelling. + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + { reportMaxRows: REPORT_CORPUS_MAX_ROWS }, + ), }), metadata: root, }); @@ -262,21 +268,19 @@ export const db = drizzle(pool); `); // 4. Import the EMITTED route files unmodified and mount every served report. - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) { - throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); } - await fastify.register(registrar); - } - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -284,7 +288,7 @@ export const db = drizzle(pool); await seedReport(connectionUri, root, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts index 2461ba83c9..738fd49592 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-mysql-server.ts @@ -7,13 +7,14 @@ // ADR-0015), create each view from buildReportViews (the real lowering, `dialect: "mysql"`), // import the EMITTED .routes.ts files unmodified and mount them. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig, buildReportViews } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import mysql from "mysql2/promise"; import { REPORT_CORPUS_MAX_ROWS, seedInserts, SERVED_REPORTS, type ReportSeed } from "./api-contract-report-generated-server.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -90,7 +91,7 @@ const BASE_TABLES: ReadonlyArray<{ name: string; ddl: string }> = [ }, ]; -export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, outputLayout: OutputLayout = "flat"): Promise { +export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, outputLayout: OutputLayout = "flat", lane: ApiLane = "routes"): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); mkdirSync(genTmpRoot, { recursive: true }); @@ -102,18 +103,22 @@ export async function startMysqlReportServer(mysqlUrl: string, metaPath: string, // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "mysql", apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + { reportMaxRows: REPORT_CORPUS_MAX_ROWS }, + ), }), metadata: root, }); @@ -136,7 +141,7 @@ export const pool = createPool({ uri: ${JSON.stringify(mysqlUrl)}, timezone: "Z" export const db = drizzle(pool); `; writeFileSync(join(tmp, "db.ts"), dbModule, "utf8"); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: { end(cb: () => void): void } }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: { end(cb: () => void): void }; db: unknown }; const admin = await mysql.createConnection({ uri: mysqlUrl, timezone: "Z" }); const views = buildReportViews(root, { dialect: "mysql" }); @@ -148,18 +153,18 @@ export const db = drizzle(pool); await admin.query(`CREATE VIEW \`${v.name}\` AS ${v.sql}`); } - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); - await fastify.register(registrar); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -175,7 +180,7 @@ export const db = drizzle(pool); } }, close: async () => { - await fastify.close(); + await served.close(); await new Promise((done) => dbMod.pool.end(done)); for (const v of views) await admin.query(`DROP VIEW IF EXISTS \`${v.name}\``); for (const t of [...BASE_TABLES].reverse()) await admin.query(`DROP TABLE IF EXISTS \`${t.name}\``); diff --git a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts index f992eba6b6..44686ebb43 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-report-sqlite-server.ts @@ -11,7 +11,7 @@ // spelling, create each view from buildReportViews (the real lowering), import the // EMITTED .routes.ts files unmodified and mount them. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { randomUUID } from "node:crypto"; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; @@ -20,6 +20,7 @@ import { runGen, defineConfig, buildReportViews } from "@metaobjectsdev/codegen- import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { entityFile, reportExport, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import { loadMetadataFile } from "./load-metadata.ts"; import { REPORT_CORPUS_MAX_ROWS, seedInserts, SERVED_REPORTS, type ReportSeed } from "./api-contract-report-generated-server.ts"; import { startLocalD1 } from "./query-scenario-d1.ts"; @@ -113,6 +114,7 @@ export async function startSqliteReportServer( metaPath: string, engine: SqliteReportEngine = "sqlite", outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -125,18 +127,23 @@ export async function startSqliteReportServer( // read, so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "sqlite", // codegen has no d1 dialect: D1 is SQLite to Drizzle (only the db module differs) apiPrefix: "/api", - generators: [ - entityFile(), - routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS }), - reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), - ], + generators: apiGenerators( + lane, + [ + entityFile(), + reportExport({ maxRows: REPORT_CORPUS_MAX_ROWS, xmlNulls: "nil" }), + ], + () => [routesFile({ reportMaxRows: REPORT_CORPUS_MAX_ROWS })], + // D1 holds no transaction across application code (ADR-0067 §4). + { reportMaxRows: REPORT_CORPUS_MAX_ROWS, ...(engine === "d1" ? { interactiveTransactions: false } : {}) }, + ), }), metadata: root, }); @@ -159,18 +166,19 @@ export async function startSqliteReportServer( await client.run(`CREATE VIEW "${v.name}" AS ${v.sql}`); } - const fastify = Fastify(); - for (const r of SERVED_REPORTS) { - const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< - string, - (f: FastifyInstance) => Promise - >; - const registrar = mod[r.registrar]; - if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); - await fastify.register(registrar); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const r of SERVED_REPORTS) { + const mod = (await import(pathToFileURL(emitted.locate(`${r.name}.routes.ts`)).href)) as Record< + string, + (f: FastifyInstance) => Promise + >; + const registrar = mod[r.registrar]; + if (registrar === undefined) throw new Error(`${r.name}.routes.ts does not export ${r.registrar}`); + await fastify.register(registrar); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -186,7 +194,7 @@ export async function startSqliteReportServer( } }, close: async () => { - await fastify.close(); + await served.close(); await client.close(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts index 533134cf44..f949a9d3de 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-secret-fields-generated-server.ts @@ -12,13 +12,14 @@ // declares a credential. Their emitted routes are mounted too, so the credential redaction of // the projection and the M:N traversal is driven over HTTP as well. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -81,6 +82,7 @@ export async function startGeneratedSecretFieldsServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -93,14 +95,14 @@ export async function startGeneratedSecretFieldsServer( // The lane provisions its table below in the generated Drizzle table's default spelling. root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -149,19 +151,15 @@ export const db = drizzle(pool); INSERT INTO "payer_auths" ("payer_id", "auth_id") VALUES (1, 1), (1, 2);`, ); - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; - const fastify = Fastify(); - for (const [file, plugin] of [ - ["Account.routes.ts", "accountRoutes"], - ["AccountView.routes.ts", "accountViewRoutes"], - ["Payer.routes.ts", "payerRoutes"], - ] as const) { - const mod = (await import(pathToFileURL(emitted.locate(file)).href)) as Record Promise>; - await fastify.register(mod[plugin]!); - } - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Account", "AccountView", "Payer"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -182,7 +180,7 @@ export const db = drizzle(pool); return res.rows.map((r) => ({ id: Number(r.id), tokenHash: r.token_hash, pinHash: r.pin_hash })); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts index e9826ad2ed..31261d1ce9 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-tph-generated-server.ts @@ -15,13 +15,14 @@ // This proves the GENERATED TPH routes — not a stand-in — implement the // cross-port contract over HTTP. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { runGen, defineConfig } from "@metaobjectsdev/codegen-ts"; import { indexEmitted, type OutputLayout } from "./output-layout.ts"; import { entityFile, routesFile } from "@metaobjectsdev/test-generators"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; @@ -57,6 +58,7 @@ export async function startGeneratedTphServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -70,14 +72,14 @@ export async function startGeneratedTphServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -118,16 +120,16 @@ export const db = drizzle(pool); ); `); - // 4. Import the EMITTED Auth.routes.ts unmodified and mount it. - const authRoutesMod = (await import(pathToFileURL(emitted.locate("Auth.routes.ts")).href)) as { - authRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(authRoutesMod.authRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: Auth.routes.ts (the base path and every + // subtype's), or the service behind its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + for (const name of ["Auth"]) { + const mod = (await import(pathToFileURL(emitted.locate(`${name}.routes.ts`)).href)) as Record Promise>; + await fastify.register(mod[`${name[0]!.toLowerCase()}${name.slice(1)}Routes`]!); + } + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -135,7 +137,7 @@ export const db = drizzle(pool); await seedTph(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts b/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts index 7d479cbd51..2754368912 100644 --- a/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts +++ b/server/typescript/packages/integration-tests/src/api-contract-write-through-generated-server.ts @@ -16,7 +16,7 @@ // This proves the GENERATED write-through routes — the deployed artifact, not a // re-implementation — return the derived field on read-your-writes over HTTP. -import Fastify, { type FastifyInstance } from "fastify"; +import type { FastifyInstance } from "fastify"; import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -27,6 +27,7 @@ import pg from "pg"; import { executeSql } from "./postgres-sql.ts"; import { DEFAULT_PHYSICAL_NAMING } from "@metaobjectsdev/metadata"; import { loadMetadataFile } from "./load-metadata.ts"; +import { apiGenerators, serveApi, type ApiLane } from "./api-lane.ts"; export interface WriteThroughSeed { customers: Array<{ id: number; name: string }>; @@ -43,6 +44,7 @@ export async function startGeneratedWriteThroughServer( connectionUri: string, metaPath: string, outputLayout: OutputLayout = "flat", + lane: ApiLane = "routes", ): Promise { const here = dirname(fileURLToPath(import.meta.url)); const genTmpRoot = join(here, "..", ".gen-tmp"); @@ -56,14 +58,14 @@ export async function startGeneratedWriteThroughServer( // so it sets the root to the default rules (ADR-0058: every resolver reads the root). root.physicalNaming = DEFAULT_PHYSICAL_NAMING; const lr = await runGen({ - config: defineConfig({ outputLayout: "flat", + config: defineConfig({ outDir: tmp, extStyle: "none", outputLayout, dbImport: "./db", dialect: "postgres", apiPrefix: "/api", - generators: [entityFile(), routesFile()], + generators: apiGenerators(lane, [entityFile()], () => [routesFile()]), }), metadata: root, }); @@ -95,16 +97,16 @@ export const db = drizzle(pool); FROM "orders" o JOIN "customers" c ON o."customer_id" = c."id"; `); - // 4. Import the EMITTED Order route file unmodified and mount it. - const orderRoutes = (await import(pathToFileURL(emitted.locate("Order.routes.ts")).href)) as { - orderRoutes: (f: FastifyInstance) => Promise; - }; - const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool }; - - const fastify = Fastify(); - await fastify.register(orderRoutes.orderRoutes); - await fastify.ready(); - const baseUrl = await fastify.listen({ host: "127.0.0.1", port: 0 }); + // 4. Import the EMITTED API unmodified and mount it: the Order routes, or the service behind + // its transport. + const dbMod = (await import(pathToFileURL(join(tmp, "db.ts")).href)) as { pool: pg.Pool; db: unknown }; + const served = await serveApi(lane, tmp, dbMod.db, async (fastify) => { + const orderRoutes = (await import(pathToFileURL(emitted.locate("Order.routes.ts")).href)) as { + orderRoutes: (f: FastifyInstance) => Promise; + }; + await fastify.register(orderRoutes.orderRoutes); + }); + const baseUrl = served.baseUrl; return { baseUrl, @@ -112,7 +114,7 @@ export const db = drizzle(pool); await seedWriteThrough(connectionUri, seed); }, close: async () => { - await fastify.close(); + await served.close(); await dbMod.pool.end(); rmSync(tmp, { recursive: true, force: true }); }, diff --git a/server/typescript/packages/integration-tests/src/api-lane.ts b/server/typescript/packages/integration-tests/src/api-lane.ts index a873dc84f3..f4aed3d183 100644 --- a/server/typescript/packages/integration-tests/src/api-lane.ts +++ b/server/typescript/packages/integration-tests/src/api-lane.ts @@ -29,12 +29,15 @@ export function apiGenerators( lane: ApiLane, model: Generator[], routes: () => Generator[], - /** The store: Cloudflare D1 holds no transaction across application code (ADR-0067 §4). */ - store: { interactiveTransactions?: boolean } = {}, + /** + * The service generator's options: the store (Cloudflare D1 holds no transaction across + * application code, ADR-0067 §4), and a served report's row cap, which the routes lane gives + * `routesFile` the same way. + */ + service: { interactiveTransactions?: boolean; reportMaxRows?: number } = {}, ): Generator[] { if (lane === "routes") return [...model, ...routes()]; - const service = store.interactiveTransactions === false ? serviceFile({ interactiveTransactions: false }) : serviceFile(); - return [...model, contractTypes(), service, lane === "service" ? serviceRoutesFile() : serviceRoutesHonoFile()]; + return [...model, contractTypes(), serviceFile(service), lane === "service" ? serviceRoutesFile() : serviceRoutesHonoFile()]; } type Factory = (deps: Record) => unknown; diff --git a/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts b/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts index 4bb555b592..8f9c361649 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-decimal.test.ts @@ -15,11 +15,12 @@ import { loadScenarios, runScenario } from "../src/api-contract-scenario.ts"; import { startDecimalServer, type DecimalEngine } from "../src/api-contract-decimal-server.ts"; import type { ReportSeed } from "../src/api-contract-report-generated-server.ts"; import { startMysql, type MysqlContainerHandle } from "../src/mysql-container.ts"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { OUTPUT_LAYOUTS, postgresFor, type OutputLayout } from "../src/output-layout.ts"; import type { RunningPg } from "../src/postgres-container.ts"; /** Which output layout a lane generates in, and where its Postgres databases come from. */ -interface Lane { layout: OutputLayout; startPg: (() => Promise) | undefined } +interface Lane { api: ApiLane; layout: OutputLayout; startPg: (() => Promise) | undefined } const SEED = JSON.parse(readFileSync(join(API_CONTRACT_DECIMAL_DIR, "seed.json"), "utf8")) as ReportSeed; const META_PATH = join(API_CONTRACT_DECIMAL_DIR, "meta.json"); @@ -38,14 +39,14 @@ async function withServer( if (engine === "postgres") { const pg = await lane.startPg!(); try { - const server = await startDecimalServer(engine, META_PATH, pg.connectionUri, lane.layout); + const server = await startDecimalServer(engine, META_PATH, pg.connectionUri, lane.layout, lane.api); try { await server.applySeed(seed); await fn(server.baseUrl); } finally { await server.close(); } } finally { await pg.stop(); } return; } - const server = await startDecimalServer(engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout); + const server = await startDecimalServer(engine, META_PATH, engine === "mysql" ? mysqlContainer!.url : undefined, lane.layout, lane.api); try { await server.applySeed(seed); await fn(server.baseUrl); } finally { await server.close(); } } @@ -53,8 +54,8 @@ const scenarios = loadScenarios(API_CONTRACT_DECIMAL_SCENARIOS_DIR); // The package layout skips D1 (a Miniflare process per test, the same routes as SQLite) and, on // MySQL, the scenario loop (Postgres and SQLite run every scenario in both layouts). -for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract decimal (ADR-0019 Amendment 1) — GENERATED routes on ${engine} [${layout}]`, () => { - const lane: Lane = { layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined }; +for (const api of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract decimal (ADR-0019 Amendment 1) — ${laneLabel(api)} on ${engine} [${layout}]`, () => { + const lane: Lane = { api, layout, startPg: engine === "postgres" ? postgresFor(layout) : undefined }; for (const scenario of layout === "package" && engine === "mysql" ? [] : scenarios) { if (scenario.engines !== undefined && !scenario.engines.includes(engine)) continue; test(scenario.name, async () => { diff --git a/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts b/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts index 51bce8cd64..82f0247bd8 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-m2m.test.ts @@ -11,6 +11,7 @@ // assertion runner, so a contract drift in either surfaces here. import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_M2M_DIR, API_CONTRACT_M2M_SCENARIOS_DIR } from "../src/paths.ts"; @@ -47,14 +48,14 @@ describe("api contract M:N — hand-rolled reference lane", () => { } }); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract M:N — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract M:N — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_M2M_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedM2mServerHandle | null = null; try { - server = await startGeneratedM2mServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedM2mServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server, openApiCheck("m2m")); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts b/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts index 629d6f9e45..67eede5768 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-projection.test.ts @@ -11,6 +11,7 @@ // scenario (full isolation). import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { @@ -33,14 +34,14 @@ const META_PATH = join(API_CONTRACT_PROJECTION_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("projection"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract projection (F22) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract projection (F22) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_PROJECTION_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedProjectionServerHandle | null = null; try { - server = await startGeneratedProjectionServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedProjectionServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts index 506aa2c5f8..9ca8564cce 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report-mysql.test.ts @@ -9,6 +9,7 @@ // METAOBJECTS_TEST_MYSQL_URL). import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -33,8 +34,8 @@ let container: MysqlContainerHandle; beforeAll(async () => { container = await startMysql(); }, 240_000); afterAll(() => { container?.stop(); }, 60_000); -async function withServer(layout: OutputLayout, fn: (server: MysqlReportServerHandle) => Promise, seed: ReportSeed = SEED): Promise { - const server = await startMysqlReportServer(container.url, META_PATH, layout); +async function withServer(layout: OutputLayout, lane: ApiLane, fn: (server: MysqlReportServerHandle) => Promise, seed: ReportSeed = SEED): Promise { + const server = await startMysqlReportServer(container.url, META_PATH, layout, lane); try { await server.applySeed(seed); await fn(server); @@ -43,9 +44,9 @@ async function withServer(layout: OutputLayout, fn: (server: MysqlReportServerHa } } -for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — GENERATED routes on MySQL [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — ${laneLabel(lane)} on MySQL [${layout}]`, () => { test("a ratio is a decimal string (MySQL keeps its scale), and the integers around it stay numbers", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { const res = await fetch(server.baseUrl + "/api/invoice_totals"); expect(res.status).toBe(200); const rows = (await res.json()) as Array>; @@ -58,14 +59,14 @@ for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — }, { timeout: 120_000 }); test("a ratio over zero rows is null", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { const res = await fetch(server.baseUrl + "/api/invoice_totals"); expect(await res.json()).toEqual([{ invoices: 0, totalCents: null, paidShare: null }]); }, { invoices: [] }); }, { timeout: 120_000 }); test("the seeded report rows are what the views return", async () => { - await withServer(layout, async (server) => { + await withServer(layout, lane, async (server) => { for (const [name, path] of SERVED_PATHS) { const res = await fetch(server.baseUrl + path); expect(res.status).toBe(200); @@ -87,7 +88,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`"api contract report (FR-044) — // Postgres report lane runs every scenario in both layouts. for (const scenario of layout === "flat" ? loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR) : []) { test(`shared scenario: ${scenario.name}`, async () => { - await withServer(layout, (server) => runScenario(scenario, server.baseUrl)); + await withServer(layout, lane, (server) => runScenario(scenario, server.baseUrl)); }, { timeout: 120_000 }); } }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts index 26b6a3d2eb..d18fba2dd4 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report-sqlite.test.ts @@ -15,6 +15,7 @@ // filtering, sorting and paging a decimal measure behave the same on both engines. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel, type ApiLane } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -36,10 +37,11 @@ const ENGINES: readonly SqliteReportEngine[] = ["sqlite", "d1"]; async function withServer( engine: SqliteReportEngine, layout: OutputLayout, + lane: ApiLane, fn: (server: SqliteReportServerHandle) => Promise, seed: ReportSeed = SEED, ): Promise { - const server = await startSqliteReportServer(META_PATH, engine, layout); + const server = await startSqliteReportServer(META_PATH, engine, layout, lane); try { await server.applySeed(seed); await fn(server); @@ -56,9 +58,9 @@ async function getJson(server: SqliteReportServerHandle, path: string): Promise< // D1 starts a Miniflare (workerd) process per test and emits the same routes as SQLite (only the // db module differs), so the package layout runs on SQLite alone. -for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract report (FR-044) — GENERATED routes on ${engine === "d1" ? "Cloudflare D1 (local)" : "SQLite"} [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? ENGINES : ENGINES.filter((e) => e !== "d1")) describe(`api contract report (FR-044) — ${laneLabel(lane)} on ${engine === "d1" ? "Cloudflare D1 (local)" : "SQLite"} [${layout}]`, () => { test("a ratio is a JSON string, as it is on Postgres, and the integers around it stay numbers", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows.length).toBe(1); const row = rows[0]!; @@ -70,7 +72,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio is a string in the withCount envelope too", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const body = (await getJson(server, "/api/invoice_totals?withCount=1")) as { rows: Array>; total: number; }; @@ -80,14 +82,14 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a ratio over zero rows is null, not the string 'null' or 0", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const rows = (await getJson(server, "/api/invoice_totals")) as Array>; expect(rows).toEqual([{ invoices: 0, totalCents: null, paidShare: null }]); }, { invoices: [] }); }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("a report with no decimal field is untouched: every value keeps its type", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { expect(await getJson(server, "/api/invoice_status_totals?sort=status:asc")).toEqual( SEED.reports!["InvoiceStatusTotals"], ); @@ -101,7 +103,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN }, { timeout: SERVER_TEST_TIMEOUT_MS }); test("the filter and the sort on a ratio still compare numerically after the wire change", async () => { - await withServer(engine, layout, async (server) => { + await withServer(engine, layout, lane, async (server) => { const hit = async (path: string): Promise => ((await getJson(server, path)) as unknown[]).length; expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.3")).toBe(1); expect(await hit("/api/invoice_totals?filter[paidShare][gt]=0.5")).toBe(0); @@ -114,7 +116,7 @@ for (const layout of OUTPUT_LAYOUTS) for (const engine of layout === "flat" ? EN for (const scenario of loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR)) { test(`shared scenario: ${scenario.name}`, async () => { - await withServer(engine, layout, (server) => runScenario(scenario, server.baseUrl)); + await withServer(engine, layout, lane, (server) => runScenario(scenario, server.baseUrl)); }, { timeout: SERVER_TEST_TIMEOUT_MS }); } }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-report.test.ts b/server/typescript/packages/integration-tests/test/api-contract-report.test.ts index eab0e41c4b..5235cf0b16 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-report.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-report.test.ts @@ -6,6 +6,7 @@ // lane only — see the corpus README. One Postgres testcontainer per scenario. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_REPORT_DIR, API_CONTRACT_REPORT_SCENARIOS_DIR } from "../src/paths.ts"; @@ -37,14 +38,14 @@ const SERVED_PATHS: Array<[string, string]> = [ const contractCheck: ContractCheck = openApiCheck("report"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_REPORT_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedReportServerHandle | null = null; try { - server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { @@ -58,7 +59,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`api contract report (FR-044) — const pg = await startDb(); let server: GeneratedReportServerHandle | null = null; try { - server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedReportServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); for (const [name, path] of SERVED_PATHS) { const res = await fetch(server.baseUrl + path); diff --git a/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts b/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts index e23d1c66bd..6faafe1bd7 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-secret-fields.test.ts @@ -7,6 +7,7 @@ // per scenario. import { describe, expect, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { @@ -36,14 +37,14 @@ const META_PATH = join(API_CONTRACT_SECRET_FIELDS_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("secret-fields"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_SECRET_FIELDS_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedSecretFieldsServerHandle | null = null; try { - server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); if (scenario.name === "write-ignores-excluded") await expectDeniedColumnsUntouched(server); @@ -61,7 +62,7 @@ for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields (#484) const pg = await startDb(); let server: GeneratedSecretFieldsServerHandle | null = null; try { - server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedSecretFieldsServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); const list = await getJson(server, "/api/account_views"); @@ -86,14 +87,14 @@ const TPH_META_PATH = join(API_CONTRACT_SECRET_FIELDS_TPH_DIR, "meta.json"); // A TPH hierarchy shares one table, so a column any subtype marks as a credential is one for the // whole table: the base and both subtypes refuse a filter or sort on it. -for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields — TPH sibling credential — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract secret fields — TPH sibling credential — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_SECRET_FIELDS_TPH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedTphServerHandle | null = null; try { - server = await startGeneratedTphServer(pg.connectionUri, TPH_META_PATH, layout); + server = await startGeneratedTphServer(pg.connectionUri, TPH_META_PATH, layout, lane); await server.applySeed(TPH_SEED); for (const req of scenario.requests) { const res = await fetch(server.baseUrl + req.path, { method: req.method }); diff --git a/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts b/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts index ba0510bf91..ffd598c5f6 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-tph.test.ts @@ -12,6 +12,7 @@ // + assertion runner, so a contract drift in either surfaces here. import { describe, test } from "bun:test"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { API_CONTRACT_TPH_DIR, API_CONTRACT_TPH_SCENARIOS_DIR } from "../src/paths.ts"; @@ -54,14 +55,14 @@ describe("api contract TPH — hand-rolled reference lane", () => { } }); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract TPH — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract TPH — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_TPH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedTphServerHandle | null = null; try { - server = await startGeneratedTphServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedTphServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server, openApiCheck("tph")); } finally { diff --git a/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts b/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts index 6128fd6c3f..387df0d0e2 100644 --- a/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts +++ b/server/typescript/packages/integration-tests/test/api-contract-write-through.test.ts @@ -21,6 +21,7 @@ import { import { openApiCheck, type ContractCheck } from "../src/api-contract-openapi-check.ts"; import { loadScenarios, assertResponse, type ApiScenario, parseBodyExact } from "../src/api-contract-scenario.ts"; import { OUTPUT_LAYOUTS, postgresFor } from "../src/output-layout.ts"; +import { API_LANES, laneLabel } from "../src/api-lane.ts"; import { startGeneratedWriteThroughServer, type GeneratedWriteThroughServerHandle, @@ -34,14 +35,14 @@ const META_PATH = join(API_CONTRACT_WRITE_THROUGH_DIR, "meta.json"); const contractCheck: ContractCheck = openApiCheck("write-through"); -for (const layout of OUTPUT_LAYOUTS) describe(`api contract write-through (#214) — GENERATED routes lane [${layout}]`, () => { +for (const lane of API_LANES) for (const layout of OUTPUT_LAYOUTS) describe(`api contract write-through (#214) — ${laneLabel(lane)} [${layout}]`, () => { const startDb = postgresFor(layout); for (const scenario of loadScenarios(API_CONTRACT_WRITE_THROUGH_SCENARIOS_DIR)) { test(scenario.name, async () => { const pg = await startDb(); let server: GeneratedWriteThroughServerHandle | null = null; try { - server = await startGeneratedWriteThroughServer(pg.connectionUri, META_PATH, layout); + server = await startGeneratedWriteThroughServer(pg.connectionUri, META_PATH, layout, lane); await server.applySeed(SEED); await runScenario(scenario, server); } finally { diff --git a/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json b/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json new file mode 100644 index 0000000000..2a9c66d642 --- /dev/null +++ b/server/typescript/packages/integration-tests/test/fixtures/service-tph-lifecycle.json @@ -0,0 +1,44 @@ +{ + "metadata.root": { + "package": "acme::desk", + "children": [ + { "object.entity": { + "name": "Ticket", + "@discriminator": "type", + "children": [ + { "source.rdb": { "@table": "tickets" } }, + { "field.long": { "name": "id" } }, + { "field.enum": { "name": "type", "@values": ["Bug", "Task"] } }, + { "field.string": { "name": "title", "@maxLength": 80 } }, + { "identity.primary": { "name": "pk", "@fields": ["id"], "@generation": "increment" } } + ] + }}, + { "object.entity": { + "name": "BugTicket", + "extends": "Ticket", + "@discriminatorValue": "Bug", + "children": [ + { "field.enum": { + "name": "status", + "@values": ["open", "closed"], + "@default": "open", + "children": [ + { "transition.action": { "name": "close", "@from": ["open"], "@to": "closed", "@public": true } } + ] + }} + ] + }}, + { "object.entity": { + "name": "TaskTicket", + "extends": "Ticket", + "@discriminatorValue": "Task" + }}, + { "api.operational": { + "name": "Desk", + "children": [ + { "operation.query": { "name": "peek", "@objectRef": "BugTicket", "@outputRef": "BugTicket", "@public": true } } + ] + }} + ] + } +} diff --git a/server/typescript/packages/integration-tests/test/service-compile.test.ts b/server/typescript/packages/integration-tests/test/service-compile.test.ts index 410be3ad0a..dd4a7e40eb 100644 --- a/server/typescript/packages/integration-tests/test/service-compile.test.ts +++ b/server/typescript/packages/integration-tests/test/service-compile.test.ts @@ -74,6 +74,10 @@ function emittedTs(dir: string): string[] { return out.sort(); } +// A single-table (TPH) subtype that carries a lifecycle and is a keyed operation's target: its +// command and operation address the base's table, scoped to the subtype's discriminator value. +const TPH_LIFECYCLE = resolve(dirname(fileURLToPath(import.meta.url)), "fixtures", "service-tph-lifecycle.json"); + const CORPORA = [ { label: "the shared fitness corpus", path: CORPUS, pkg: "fitness", present: ["fitness/service/createProgram.ts"] }, { @@ -82,6 +86,12 @@ const CORPORA = [ pkg: "acme/purchasing", present: ["acme/purchasing/service/submitPurchaseRequest.ts", "acme/purchasing/service/decide.ts", "acme/purchasing/service/requestTotals.ts"], }, + { + label: "a single-table subtype with a lifecycle", + path: TPH_LIFECYCLE, + pkg: "acme/desk", + present: ["acme/desk/service/closeBugTicket.ts", "acme/desk/service/peek.ts"], + }, // A store without interactive transactions (Cloudflare D1, which generates as `sqlite`): the // service with no transaction, no hooks and no event hook (ADR-0067 §4). { diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts index ffb804776e..0529ac7c3c 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-m2m.ts @@ -31,8 +31,8 @@ // that checks the source row's own discriminator first. import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { and, eq, or, inArray } from "drizzle-orm"; -import { coerceIdForColumn } from "./util.js"; +import { m2mRelated } from "../m2m-read.js"; +import { InvalidIdError } from "../read-only-read.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; @@ -92,97 +92,11 @@ export function mountM2mRoute(opts: M2mRouteOptions): void { opts.fastify.get(route, ro, async (req, reply) => { const { id } = req.params as { id: string }; - - const srcCol = columnRef(opts.junctionTable, opts.sourceColumn); - const tgtCol = columnRef(opts.junctionTable, opts.targetColumn); - - // Compare against the junction FK's real type — a numeric-LOOKING id on a - // TEXT fk must stay a string ('0123' ≠ '123'), or affinity traverses the - // WRONG source row's relations. - const sourceId = coerceIdForColumn(srcCol, id); - if (sourceId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - - // Stage 0 — the source id must name a row of THIS subtype. Skipping it would let - // `/auths/bridge/{a Coupon's id}/linkedAuths` return that Coupon's relations, because - // the junction FK cannot tell the subtypes apart: it points at the shared base table. - const srcDisc = opts.sourceDiscriminator; - if (srcDisc !== undefined) { - const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); - const ownId = coerceIdForColumn(srcPk, id); - if (ownId === undefined) { - return reply.code(400).send({ error: "invalid_id" }); - } - const owner = await opts.db - .select({ d: columnRef(srcDisc.table, srcDisc.column) }) - .from(srcDisc.table) - .where(eq(srcPk, ownId)) - .limit(1); - if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; - } - - // Stage 1 — junction rows for this source id. - const joinWhere = opts.symmetric - ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) - : eq(srcCol, sourceId); - const joinRows = (await opts.db - .select({ src: srcCol, tgt: tgtCol }) - .from(opts.junctionTable) - .where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; - - // Collect the related target ids. Symmetric: the related endpoint is the - // column that is NOT the source id (compared by string key to bridge - // number/bigint-as-string driver skew). Otherwise: always the target column. - const sourceKey = String(sourceId); - const relatedIds = new Set(); - for (const r of joinRows) { - if (!opts.symmetric) { - addId(relatedIds, r.tgt); - continue; - } - const srcIsSource = r.src != null && String(r.src) === sourceKey; - // Self-loop (a,a): src matches → relate to a itself (single occurrence). - if (srcIsSource) addId(relatedIds, r.tgt); - else addId(relatedIds, r.src); + try { + return (await m2mRelated(opts.db, opts, id)).map(toWire); + } catch (e) { + if (e instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw e; } - - if (relatedIds.size === 0) return []; - - // Stage 2 — load the target rows. - const pkCol = columnRef(opts.targetTable, targetPk); - const byPk = inArray(pkCol, [...relatedIds]); - const disc = opts.targetDiscriminator; - const rows = await opts.db - .select() - .from(opts.targetTable) - .where(disc ? and(byPk, eq(columnRef(opts.targetTable, disc.column), disc.value)) : byPk); - return (rows as unknown[]).map(toWire); }); } - -function addId(set: Set, v: unknown): void { - if (v === null || v === undefined) return; - // Keep bigint AS bigint — Number(bigint) silently loses precision above - // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle - // binds bigint params natively; the driver never needed the narrowing. - if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); -} - -/** - * Resolve a physical column name to its Drizzle column object. Drizzle exposes - * columns on the table object keyed by the TS property name, but the underlying - * `.name` is the physical column. The descriptor carries physical names (what - * the junction/target SQL uses), so match on `.name` and fall back to the key. - */ -// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder -function columnRef(table: AnyTable, physicalName: string): any { - for (const key of Object.keys(table)) { - const col = table[key]; - if (col && typeof col === "object" && col.name === physicalName) return col; - } - // Fall back to the property-name lookup (covers tables whose TS key == column). - const direct = table[physicalName]; - if (direct !== undefined) return direct; - throw new Error(`mountM2mRoute: column '${physicalName}' not found on table`); -} diff --git a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts index cec28d7fa5..44a1423660 100644 --- a/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts +++ b/server/typescript/packages/runtime-ts/src/drizzle-fastify/mount-read-only.ts @@ -1,17 +1,14 @@ import type { FastifyInstance, RouteShorthandOptions } from "fastify"; -import { quoteIdent, type SqlDialect } from "../sql-dialect.js"; -import { sql, eq, and, count } from "drizzle-orm"; import { parseListQueryString } from "./list-query.js"; -import { parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; -import { - ReportExportError, assertExportWithinCap, exportContentDisposition, exportWithCountError, isExportCountFlag, - parseExportPage, readExportFormat, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec, -} from "./report-export.js"; +import { REPORT_MAX_ROWS, ReportTooLargeError, FilterParseError, type PageSize } from "./filter-parser.js"; +import { ReportExportError, exportContentDisposition, renderExport, EXPORT_CONTENT_TYPES, type ReportExportSpec } from "./report-export.js"; import type { FilterAllowlist, SortAllowlist } from "./filter-allowlist.js"; -import { isTruthyFlag, contractErrorCode, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./util.js"; +import { contractErrorCode } from "./util.js"; +import type { SqlDialect } from "../sql-dialect.js"; import { timestampWire } from "../timestamp-wire.js"; import { withWire, type WireOptions } from "../wire-format.js"; import { withContractErrorHandler } from "./route-error-handler.js"; +import { InvalidIdError, readOnlyGet, readOnlyList, rawViewName, type ReadOnlySpec } from "../read-only-read.js"; // biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views type AnyView = any; @@ -87,84 +84,6 @@ const rejectMutation = (resource: string) => async ( .send({ error: "method_not_allowed", message: `${request.method} is not supported on a ${resource} (read-only).` }); }; -function resolveViewName(view: AnyView): string | undefined { - const cfg = viewBaseConfig(view); - if (cfg) { - if (typeof cfg["name"] === "string") return cfg["name"] as string; - } - // Fallback for non-proxy shapes - const v = view as Record; - return ( - (typeof v["__tableName"] === "string" ? v["__tableName"] as string : undefined) ?? - (typeof v["_name"] === "string" ? v["_name"] as string : undefined) - ); -} - -/** - * Detect whether a Drizzle view was declared with `.existing()` and an empty - * column schema (`{}`). In that case, `db.select().from(view)` generates - * `SELECT FROM ...` (invalid SQL), and we must fall back to raw SQL. - */ -function isEmptyColumnView(view: AnyView): boolean { - const cfg = viewBaseConfig(view); - if (cfg) { - const fields = cfg["selectedFields"] as Record | undefined; - return fields !== undefined && Object.keys(fields).length === 0; - } - return false; -} - -function snakeToCamel(s: string): string { - return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); -} - -/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ -function camelizeRow(row: Record): Record { - const out: Record = {}; - for (const [k, v] of Object.entries(row)) { - out[snakeToCamel(k)] = v; - } - return out; -} - -/** - * Execute a raw SQL read and return its rows, on EITHER dialect. - * - * There is no shared method: drizzle's `BaseSQLiteDatabase` has `.all()` and no - * `.execute()`; `PgDatabase` has `.execute()` and no `.all()` at all (verified - * against drizzle-orm's own `sqlite-core/db.d.ts` and `pg-core/db.d.ts`). So this - * must DISPATCH — unlike the #286 sites, where the query builder is thenable on - * both dialects and simply awaiting it was enough. - * - * That difference is exactly why the #286 sweep missed these. It hunted `.all()` - * on a query BUILDER; these are `.all()` on the top-level `db` HANDLE — the libsql - * raw-exec API, which node-postgres does not implement. BOTH read-only mounts - * carried three each, so the Fastify adapter was broken here too despite being the - * correct reference for the builder shape. Reported by an adopting project's code - * review of the 0.21.4 upgrade. - * - * Reachable whenever `useRawSql` is true — an opaque `@sql` view body (the ADR-0043 - * escape hatch), where the view declares no columns for the query builder to select. - * - * The two Postgres drivers disagree on the result shape (node-postgres returns a - * QueryResult with `.rows`, postgres-js returns the array itself), so both are - * handled rather than betting on one. - */ -// biome-ignore lint/suspicious/noExplicitAny: driver handle is consumer-provided -async function rawRows(db: any, dialect: string | undefined, query: unknown): Promise[]> { - if (dialect === "postgres") { - const res: unknown = await db.execute(query); - if (Array.isArray(res)) return res as Record[]; - return (res as { rows?: Record[] } | null)?.rows ?? []; - } - if (dialect === "mysql") { - // mysql2 answers `[rows, fields]`. - const [rows] = (await db.execute(query)) as [Record[], unknown]; - return rows; - } - return (await db.all(query)) as Record[]; -} - export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const { fastify, path, db, view, filterAllowlist, sortAllowlist, dialect } = opts; const idCol = opts.idColumn ?? "id"; @@ -178,101 +97,38 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { const reportMaxRows = opts.reportMaxRows ?? REPORT_MAX_ROWS; const exportSpec = isReport ? opts.export : undefined; - const viewName = resolveViewName(view); - const useRawSql = isEmptyColumnView(view) && !!viewName; - // The raw-SQL branch has no declared columns, so nothing names a timestamp there. - const timestamps = timestampWire(view); - const toWire = withWire(timestamps, opts); + // The raw-SQL branch (a view with no declared columns) has nothing that names a timestamp. + const raw = rawViewName(view) !== undefined; + const toWire = raw ? (row: unknown) => row : withWire(timestampWire(view), opts); + const spec: ReadOnlySpec = { + filterAllowlist, + sortAllowlist, + dialect, + idColumn: idCol, + report: isReport, + reportMaxRows, + ...(opts.pagination === undefined ? {} : { pagination: opts.pagination }), + ...(exportSpec === undefined ? {} : { export: exportSpec }), + }; // ── List ────────────────────────────────────────────────────────────────── fastify.get(path, ro, async (req, reply) => { try { - if (useRawSql) { - // .existing() view with no column schema — use raw SQL. - // Simple limit/offset only; filter/sort via allowlist is not available - // because column refs don't exist. This is sufficient for projection - // endpoints that return small full-table results. - const url = req.raw.url ?? ""; - const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - // A bound that is not an integer in range is a 400, not silently clamped. - const reportPage = isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const limitVal = reportPage?.limit ?? parsePageBound(parsed, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; - const offsetVal = reportPage?.offset ?? parsePageBound(parsed, "offset") ?? 0; - const withCount = isTruthyFlag(parsed["withCount"]); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} LIMIT ${limitVal} OFFSET ${offsetVal}`)) as any[]; - if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); - const camelRows = rows.map((r: Record) => camelizeRow(r)); - if (!withCount) return camelRows; - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const countRows = await rawRows(db, dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(dialect, viewName)}`)) as any[]; - const total: number = Number(countRows[0]?.c ?? 0); - return { rows: camelRows, total }; - } - const url = req.raw.url ?? ""; const qIdx = url.indexOf("?"); - const queryString = qIdx >= 0 ? url.slice(qIdx + 1) : ""; - const parsed = parseListQueryString(queryString); - const withCount = isTruthyFlag(parsed["withCount"]); - // Export mode: the selector is validated before any query runs, and the export cap governs. - const format = exportSpec ? readExportFormat(parsed, exportSpec) : undefined; - if (format !== undefined && format !== "json" && isExportCountFlag(parsed["withCount"])) throw exportWithCountError(); - const reportPage = exportSpec && format !== undefined - ? parseExportPage(parsed, exportSpec.maxRows) - : isReport ? parseReportPage(parsed, reportMaxRows) : undefined; - const result = parseFilterParams({ - query: parsed, - table: view, - allowlist: filterAllowlist, - sortAllowlist, - dialect, - }); - const combinedWhere = result.where && result.searchWhere - ? and(result.where, result.searchWhere) - : (result.where ?? result.searchWhere); - let q = db.select().from(view); - if (combinedWhere) q = q.where(combinedWhere); - if (result.orderBy) q = q.orderBy(...result.orderBy); - // A report fetches one row past the cap when no limit was sent, to tell exactly the - // cap apart from more than the cap before any body is written. - const limit = reportPage?.limit ?? pageLimit(result.limit, opts.pagination); - const offset = reportPage?.offset ?? result.offset; - if (limit !== undefined) q = q.limit(limit); - if (offset !== undefined) q = q.offset(offset); - // Await directly — `.all()` is libsql/better-sqlite3-only; the - // node-postgres builder is thenable. (The useRawSql branch above keeps - // db.all(sql.raw(...)) because that is the libsql raw-exec API, only - // reachable for `.existing()` empty-column views which are sqlite-only.) - const fetched = await q as unknown[]; - if (exportSpec && format !== undefined && reportPage) { - assertExportWithinCap(fetched.length, reportPage, exportSpec.maxRows); - } else if (reportPage?.unbounded && fetched.length > reportMaxRows) { - throw new ReportTooLargeError(reportMaxRows); - } - const rows = fetched.map(toWire); - - let total: number | undefined; - if (withCount) { - // Count query: same WHERE, no limit/offset/orderBy. - let cq = db.select({ c: count() }).from(view); - if (combinedWhere) cq = cq.where(combinedWhere); - const countRow = (await cq)[0] as { c: number } | undefined; - total = countRow?.c ?? 0; - } - if (exportSpec && format !== undefined) { + const page = await readOnlyList(db, view, parseListQueryString(qIdx >= 0 ? url.slice(qIdx + 1) : ""), spec); + const rows = page.rows.map(toWire); + if (exportSpec && page.format !== undefined) { // Render first: a writer that throws must not leave download headers on the 500. // A Buffer, not a string: Fastify appends "; charset=utf-8" to a string body's // application/json, and the contract pins the content type exactly. - const body = Buffer.from(renderExport(exportSpec, format, rows as Record[], total), "utf8"); + const body = Buffer.from(renderExport(exportSpec, page.format, rows as Record[], page.total), "utf8"); reply - .header("content-disposition", exportContentDisposition(path, format)) - .header("content-type", EXPORT_CONTENT_TYPES[format]); + .header("content-disposition", exportContentDisposition(path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]); return body; } - return total === undefined ? rows : { rows, total }; + return page.total === undefined ? rows : { rows, total: page.total }; } catch (err) { if (err instanceof ReportTooLargeError) { reply.code(400).send({ error: "report_too_large", maxRows: err.maxRows }); @@ -298,30 +154,13 @@ export function mountReadOnlyCrudRoutes(opts: MountReadOnlyOptions): void { // ── Get by ID ───────────────────────────────────────────────────────────── fastify.get(`${path}/:id`, ro, async (req, reply) => { const { id } = req.params as { id: string }; - if (useRawSql) { - const idLiteral = rawIdLiteral(id); - if (idLiteral === undefined) return reply.code(400).send({ error: "invalid_id" }); - // biome-ignore lint/suspicious/noExplicitAny: dynamic raw result - const rows = await rawRows(db, dialect, sql.raw(`SELECT * FROM ${quoteIdent(dialect, viewName)} WHERE ${quoteIdent(dialect, idCol)} = ${idLiteral} LIMIT 1`)) as any[]; - const row = rows[0] ? camelizeRow(rows[0]) : undefined; - return row ?? reply.code(404).send({ error: "not_found" }); - } - // biome-ignore lint/suspicious/noExplicitAny: Drizzle table/view column ref - const colRef = (view as any)[idCol]; - // No column under `idColumn`: there is nothing to compare the id against, and a query - // with no WHERE would answer with the view's first row. No row is addressable. - if (colRef === undefined) { - return reply.code(404).send({ error: "not_found" }); - } - // Compare against the PK's real type — a uuid/text key must NOT go through Number(). - const idValue = coerceIdForColumn(colRef, id); - if (idValue === undefined) { - return reply.code(400).send({ error: "invalid_id" }); + try { + const row = await readOnlyGet(db, view, id, spec); + return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); + } catch (err) { + if (err instanceof InvalidIdError) return reply.code(400).send({ error: "invalid_id" }); + throw err; } - // Await + first row rather than `.get()` (libsql/better-sqlite3-only). - const rows = await db.select().from(view).where(eq(colRef, idValue)).limit(1); - const row = (rows as unknown[])[0]; - return row ? toWire(row) : reply.code(404).send({ error: "not_found" }); }); } diff --git a/server/typescript/packages/runtime-ts/src/m2m-read.ts b/server/typescript/packages/runtime-ts/src/m2m-read.ts new file mode 100644 index 0000000000..57bd984c01 --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/m2m-read.ts @@ -0,0 +1,107 @@ +// m2m-read.ts — how a many-to-many traversal (FR-018) is read: `GET /{id}/` +// answers the target rows the junction links the source row to. Framework-neutral: the Fastify +// mount (`mountM2mRoute`) and the generated service (ADR-0067 layer 4) both call it. + +import { and, eq, or, inArray } from "drizzle-orm"; +import { coerceIdForColumn } from "./drizzle-fastify/util.js"; +import { InvalidIdError } from "./read-only-read.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic Drizzle tables and driver handles +type Any = any; + +/** One traversal: the junction, the target, and how they join. */ +export interface M2mSpec { + /** The junction Drizzle table const. */ + readonly junctionTable: Any; + /** The target Drizzle table const. */ + readonly targetTable: Any; + /** Junction FK column holding the SOURCE key (physical name). */ + readonly sourceColumn: string; + /** Junction FK column holding the TARGET key (physical name). */ + readonly targetColumn: string; + /** Target key column (physical name). Default "id". */ + readonly targetPkColumn?: string; + /** Undirected self-join: union both junction FK columns on read. */ + readonly symmetric: boolean; + /** The target is a TPH subtype: keep only target rows whose discriminator `column` is `value`. */ + readonly targetDiscriminator?: { readonly column: string; readonly value: string }; + /** + * The source is a TPH subtype: an id whose row in `table` is not of discriminator `value` names + * no row of this subtype, so it has no relations (an empty list, not an error). + */ + readonly sourceDiscriminator?: { readonly table: Any; readonly pkColumn: string; readonly column: string; readonly value: string }; +} + +/** + * The target rows the junction links source `id` to: empty when there are none, or when `id` names + * no row of the source subtype. Throws `InvalidIdError` for an id that is no key of the junction's + * source column. + */ +export async function m2mRelated(db: Any, spec: M2mSpec, id: string | number): Promise[]> { + const targetPk = spec.targetPkColumn ?? "id"; + const srcCol = columnRef(spec.junctionTable, spec.sourceColumn); + const tgtCol = columnRef(spec.junctionTable, spec.targetColumn); + + const sourceId = coerceIdForColumn(srcCol, String(id)); + if (sourceId === undefined) throw new InvalidIdError(); + + // Stage 0: a TPH subtype source must be a row of THIS subtype, or it has no relations here. + const srcDisc = spec.sourceDiscriminator; + if (srcDisc !== undefined) { + const srcPk = columnRef(srcDisc.table, srcDisc.pkColumn); + const ownId = coerceIdForColumn(srcPk, String(id)); + if (ownId === undefined) throw new InvalidIdError(); + const owner = await db.select({ d: columnRef(srcDisc.table, srcDisc.column) }).from(srcDisc.table).where(eq(srcPk, ownId)).limit(1); + if (owner.length === 0 || String(owner[0]?.d) !== srcDisc.value) return []; + } + + // Stage 1: the junction rows. A symmetric self-join reads both FK columns. + const joinWhere = spec.symmetric ? or(eq(srcCol, sourceId), eq(tgtCol, sourceId)) : eq(srcCol, sourceId); + const joinRows = (await db.select({ src: srcCol, tgt: tgtCol }).from(spec.junctionTable).where(joinWhere)) as Array<{ src: unknown; tgt: unknown }>; + const sourceKey = String(sourceId); + const relatedIds = new Set(); + for (const r of joinRows) { + if (!spec.symmetric) { + addId(relatedIds, r.tgt); + continue; + } + // The other side of each edge is the related id; a self-loop names the source on both. + if (r.src != null && String(r.src) === sourceKey) addId(relatedIds, r.tgt); + else addId(relatedIds, r.src); + } + if (relatedIds.size === 0) return []; + + // Stage 2: the target rows. + const byPk = inArray(columnRef(spec.targetTable, targetPk), [...relatedIds]); + const disc = spec.targetDiscriminator; + return (await db + .select() + .from(spec.targetTable) + .where(disc ? and(byPk, eq(columnRef(spec.targetTable, disc.column), disc.value)) : byPk)) as Record[]; +} + +function addId(set: Set, v: unknown): void { + if (v === null || v === undefined) return; + // Keep bigint AS bigint — Number(bigint) silently loses precision above + // 2^53, so a field.long id could round to a DIFFERENT row's key. Drizzle + // binds bigint params natively; the driver never needed the narrowing. + if (typeof v === "number" || typeof v === "string" || typeof v === "bigint") set.add(v); +} + +/** + * Resolve a physical column name to its Drizzle column object. Drizzle exposes + * columns on the table object keyed by the TS property name, but the underlying + * `.name` is the physical column. The descriptor carries physical names (what + * the junction/target SQL uses), so match on `.name` and fall back to the key. + */ +// biome-ignore lint/suspicious/noExplicitAny: returns a Drizzle column ref for the loose query builder +function columnRef(table: Any, physicalName: string): Any { + for (const key of Object.keys(table)) { + const col = table[key]; + if (col && typeof col === "object" && col.name === physicalName) return col; + } + // Fall back to the property-name lookup (covers tables whose TS key == column). + const direct = table[physicalName]; + if (direct !== undefined) return direct; + throw new Error(`m2m traversal: column '${physicalName}' not found on table`); +} diff --git a/server/typescript/packages/runtime-ts/src/read-only-read.ts b/server/typescript/packages/runtime-ts/src/read-only-read.ts new file mode 100644 index 0000000000..1ae074d3ce --- /dev/null +++ b/server/typescript/packages/runtime-ts/src/read-only-read.ts @@ -0,0 +1,197 @@ +// read-only-read.ts — how a read-only object (an `object.projection`, a served `object.report`) is +// read: the list page and the row by key, with the filter, sort and page of the REST contract, a +// report's row cap and its export. Framework-neutral: the Fastify mount (`mountReadOnlyCrudRoutes`) +// and the generated service (ADR-0067 layer 4) both call it, so the flat routes and the service +// read a view the same way and answer its refusals with the same codes. +// +// A refusal is thrown: `FilterParseError` (a query the allowlists refuse), `ReportTooLargeError` +// (more rows than a report answers), `ReportExportError` (an export the spec refuses), and +// `InvalidIdError` (an id that is no key of the view's key column). + +import { sql, eq, and, count } from "drizzle-orm"; +import { quoteIdent, type SqlDialect } from "./sql-dialect.js"; +import { + parseFilterParams, parsePageBound, pageLimit, parseReportPage, RAW_VIEW_MAX_LIMIT, REPORT_MAX_ROWS, ReportTooLargeError, type PageSize, +} from "./drizzle-fastify/filter-parser.js"; +import { + assertExportWithinCap, exportWithCountError, isExportCountFlag, parseExportPage, readExportFormat, type ExportFormat, type ReportExportSpec, +} from "./drizzle-fastify/report-export.js"; +import type { FilterAllowlist, SortAllowlist } from "./drizzle-fastify/filter-allowlist.js"; +import { isTruthyFlag, coerceIdForColumn, rawIdLiteral, viewBaseConfig } from "./drizzle-fastify/util.js"; + +// biome-ignore lint/suspicious/noExplicitAny: dynamic dispatch over user-supplied views and driver handles +type Any = any; + +/** An id that is no key of the column it addresses: answered `400 { "error": "invalid_id" }`. */ +export class InvalidIdError extends Error { + constructor() { + super("invalid_id"); + this.name = "InvalidIdError"; + } +} + +/** How a read-only object is read. */ +export interface ReadOnlySpec { + readonly filterAllowlist: FilterAllowlist; + readonly sortAllowlist: SortAllowlist; + readonly dialect: SqlDialect; + /** + * The column a row is addressed by: the KEY of that column in the Drizzle view (the field name). + * Default "id". For a view declared with no columns (the raw-SQL path) it is the physical column + * name instead. A view with no column under this key has no addressable row. + */ + readonly idColumn?: string; + /** A served report: it answers every row up to `reportMaxRows` and refuses above it. */ + readonly report?: boolean; + /** A report's row cap. Default 10000, the same in every port. */ + readonly reportMaxRows?: number; + /** A projection's page size (`api.pagination`); ignored for a report and a raw view. */ + readonly pagination?: PageSize; + /** A report's export (`report-export` wired): `?format=` answers the list in that shape. */ + readonly export?: ReportExportSpec; +} + +/** A page of a read-only object: its rows, the count when asked (`withCount`), and the export format when one was asked. */ +export interface ReadOnlyPage> { + readonly rows: T[]; + readonly total?: number; + /** Set when the query asked for an export (`?format=`): the transport renders the rows in it. */ + readonly format?: ExportFormat; +} + +function resolveViewName(view: Any): string | undefined { + const cfg = viewBaseConfig(view); + if (cfg && typeof cfg["name"] === "string") return cfg["name"] as string; + const v = view as Record; + return ( + (typeof v["__tableName"] === "string" ? (v["__tableName"] as string) : undefined) ?? + (typeof v["_name"] === "string" ? (v["_name"] as string) : undefined) + ); +} + +/** + * Whether a Drizzle view was declared with `.existing()` and an empty column schema (`{}`), for + * which `db.select().from(view)` would write `SELECT FROM ...`: such a view is read with raw SQL. + */ +function isEmptyColumnView(view: Any): boolean { + const cfg = viewBaseConfig(view); + if (cfg) { + const fields = cfg["selectedFields"] as Record | undefined; + return fields !== undefined && Object.keys(fields).length === 0; + } + return false; +} + +/** The view's name when it is read with raw SQL (an empty-column `.existing()` view), else undefined. */ +export function rawViewName(view: Any): string | undefined { + const name = resolveViewName(view); + return isEmptyColumnView(view) && !!name ? name : undefined; +} + +function snakeToCamel(s: string): string { + return s.replace(/_([a-z])/g, (_, c) => c.toUpperCase()); +} + +/** Normalise a raw SQL result row's keys from snake_case to camelCase. */ +function camelizeRow(row: Record): Record { + const out: Record = {}; + for (const [k, v] of Object.entries(row)) out[snakeToCamel(k)] = v; + return out; +} + +/** + * Execute a raw SQL read and return its rows, on every dialect: Drizzle's SQLite database has + * `.all()` and no `.execute()`, Postgres `.execute()` (node-postgres answering `.rows`, postgres-js + * the array), MySQL `.execute()` answering `[rows, fields]`. + */ +async function rawRows(db: Any, dialect: string | undefined, query: unknown): Promise[]> { + if (dialect === "postgres") { + const res: unknown = await db.execute(query); + if (Array.isArray(res)) return res as Record[]; + return (res as { rows?: Record[] } | null)?.rows ?? []; + } + if (dialect === "mysql") { + const [rows] = (await db.execute(query)) as [Record[], unknown]; + return rows; + } + return (await db.all(query)) as Record[]; +} + +/** + * A page of `view`: the filter, search, sort and page of `query` (the bracketed tree a query + * string parses to), checked against the allowlists. A report answers every row up to its cap and + * refuses above it; with an export spec, `?format=` selects an export, capped by `export.maxRows`. + */ +export async function readOnlyList(db: Any, view: Any, query: Record, spec: ReadOnlySpec): Promise { + const isReport = spec.report === true; + const reportMaxRows = spec.reportMaxRows ?? REPORT_MAX_ROWS; + const exportSpec = isReport ? spec.export : undefined; + const withCount = isTruthyFlag(query["withCount"]); + const viewName = rawViewName(view); + + if (viewName !== undefined) { + // No declared columns, so no filter or sort: a page of the whole view. + const reportPage = isReport ? parseReportPage(query, reportMaxRows) : undefined; + const limit = reportPage?.limit ?? parsePageBound(query, "limit", RAW_VIEW_MAX_LIMIT) ?? RAW_VIEW_MAX_LIMIT; + const offset = reportPage?.offset ?? parsePageBound(query, "offset") ?? 0; + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} LIMIT ${limit} OFFSET ${offset}`)); + if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + const camelRows = rows.map(camelizeRow); + if (!withCount) return { rows: camelRows }; + const countRows = await rawRows(db, spec.dialect, sql.raw(`SELECT COUNT(*) AS c FROM ${quoteIdent(spec.dialect, viewName)}`)); + return { rows: camelRows, total: Number(countRows[0]?.["c"] ?? 0) }; + } + + // Export mode: the selector is validated before any query runs, and the export cap governs. + const format = exportSpec ? readExportFormat(query, exportSpec) : undefined; + if (format !== undefined && format !== "json" && isExportCountFlag(query["withCount"])) throw exportWithCountError(); + const reportPage = exportSpec && format !== undefined + ? parseExportPage(query, exportSpec.maxRows) + : isReport ? parseReportPage(query, reportMaxRows) : undefined; + const parsed = parseFilterParams({ query, table: view, allowlist: spec.filterAllowlist, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect }); + const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + let q = db.select().from(view); + if (where) q = q.where(where); + if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); + // A report fetches one row past the cap when no limit was sent, to tell exactly the cap apart + // from more than the cap before any body is written. + const limit = reportPage?.limit ?? pageLimit(parsed.limit, spec.pagination); + const offset = reportPage?.offset ?? parsed.offset; + if (limit !== undefined) q = q.limit(limit); + if (offset !== undefined) q = q.offset(offset); + const rows = (await q) as Record[]; + if (exportSpec && format !== undefined && reportPage) assertExportWithinCap(rows.length, reportPage, exportSpec.maxRows); + else if (reportPage?.unbounded && rows.length > reportMaxRows) throw new ReportTooLargeError(reportMaxRows); + + let total: number | undefined; + if (withCount) { + let cq = db.select({ c: count() }).from(view); + if (where) cq = cq.where(where); + total = ((await cq)[0] as { c: number } | undefined)?.c ?? 0; + } + return { rows, ...(total === undefined ? {} : { total }), ...(format === undefined ? {} : { format }) }; +} + +/** + * The row of `view` that `id` names, or undefined when there is none (or when the view has no + * column under `spec.idColumn`, so no row is addressable). Throws `InvalidIdError` for an id that + * is no key of that column. + */ +export async function readOnlyGet(db: Any, view: Any, id: string | number, spec: Pick): Promise | undefined> { + const idCol = spec.idColumn ?? "id"; + const viewName = rawViewName(view); + if (viewName !== undefined) { + const literal = rawIdLiteral(String(id)); + if (literal === undefined) throw new InvalidIdError(); + const rows = await rawRows(db, spec.dialect, sql.raw(`SELECT * FROM ${quoteIdent(spec.dialect, viewName)} WHERE ${quoteIdent(spec.dialect, idCol)} = ${literal} LIMIT 1`)); + return rows[0] ? camelizeRow(rows[0]) : undefined; + } + const colRef = view[idCol]; + // No column under `idColumn`: a query with no WHERE would answer the view's first row. + if (colRef === undefined) return undefined; + // Compare against the key's real type: a uuid or text key must not go through Number(). + const value = coerceIdForColumn(colRef, String(id)); + if (value === undefined) throw new InvalidIdError(); + const rows = (await db.select().from(view).where(eq(colRef, value)).limit(1)) as Record[]; + return rows[0]; +} diff --git a/server/typescript/packages/runtime-ts/src/service/fastify.ts b/server/typescript/packages/runtime-ts/src/service/fastify.ts index efad5f595a..0d7ce39720 100644 --- a/server/typescript/packages/runtime-ts/src/service/fastify.ts +++ b/server/typescript/packages/runtime-ts/src/service/fastify.ts @@ -4,7 +4,8 @@ // adapter (`../drizzle-fastify`) and what `meta eject routes` copies of it stay as they were. import type { FastifyReply } from "fastify"; -import type { OpResult } from "./index.js"; +import type { OpResult, ReadOnlyPage } from "./index.js"; +import { EXPORT_CONTENT_TYPES, exportContentDisposition, renderExport, type ReportExportSpec } from "../drizzle-fastify/report-export.js"; export { withContractErrorHandler } from "../drizzle-fastify/route-error-handler.js"; export { parseListQueryString, rawQueryOf } from "../drizzle-fastify/list-query.js"; @@ -24,3 +25,34 @@ export function sendOpResult( if (okStatus === 204) return reply.code(204).send(); return reply.code(okStatus).send(toWire === undefined ? result.value : toWire(result.value)); } + +/** The body a read-only object answers a write with: `405 { "error": "method_not_allowed" }`. */ +export function methodNotAllowed(method: string, resource: "projection" | "report"): { error: string; message: string } { + return { error: "method_not_allowed", message: `${method} is not supported on a ${resource} (read-only).` }; +} + +/** + * Send a read-only list page: the rows mapped to the wire, as a `{ rows, total }` envelope when + * the count was asked for; with an export spec and an export format asked (`?format=`), the rows + * rendered in that format as a download named after `path`'s last segment. + */ +export function sendListPage( + reply: FastifyReply, + result: OpResult>, + toWire: (row: T) => unknown, + exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, +): FastifyReply { + if (!result.ok) return reply.code(result.status).send(result.error); + const page = result.value; + const rows = page.rows.map(toWire); + if (exportOf !== undefined && page.format !== undefined) { + // Rendered before any header is set, so a writer that throws leaves no download headers on + // the 500. A Buffer, so Fastify sends the contract's content type exactly. + const body = Buffer.from(renderExport(exportOf.spec, page.format, rows as Record[], page.total), "utf8"); + return reply + .header("content-disposition", exportContentDisposition(exportOf.path, page.format)) + .header("content-type", EXPORT_CONTENT_TYPES[page.format]) + .send(body); + } + return reply.send(page.total === undefined ? rows : { rows, total: page.total }); +} diff --git a/server/typescript/packages/runtime-ts/src/service/hono.ts b/server/typescript/packages/runtime-ts/src/service/hono.ts index 63ba45640b..a1de23d346 100644 --- a/server/typescript/packages/runtime-ts/src/service/hono.ts +++ b/server/typescript/packages/runtime-ts/src/service/hono.ts @@ -5,7 +5,8 @@ import type { Context } from "hono"; import type { ContentfulStatusCode } from "hono/utils/http-status"; -import type { OpResult } from "./index.js"; +import type { OpResult, ReadOnlyPage } from "./index.js"; +import { EXPORT_CONTENT_TYPES, exportContentDisposition, renderExport, type ReportExportSpec } from "../drizzle-fastify/report-export.js"; import { HTTP_STATUS_BAD_REQUEST, INVALID_JSON_BODY } from "../route-errors.js"; export { guardRoute } from "../hono/route-guard.js"; @@ -40,3 +41,32 @@ export function sendOpResult(c: Context, result: OpResult, okStatus = 200, if (okStatus === 204) return c.body(null, 204); return c.json(toWire === undefined ? result.value : toWire(result.value), okStatus as ContentfulStatusCode); } + +/** Answer a write to a read-only object: `405 { "error": "method_not_allowed" }`. */ +export function methodNotAllowed(c: Context, resource: "projection" | "report"): Response { + return c.json({ error: "method_not_allowed", message: `${c.req.method} is not supported on a ${resource} (read-only).` }, 405); +} + +/** + * Answer a read-only list page: the rows mapped to the wire, as a `{ rows, total }` envelope when + * the count was asked for; with an export spec and an export format asked (`?format=`), the rows + * rendered in that format as a download named after `path`'s last segment. + */ +export function sendListPage( + c: Context, + result: OpResult>, + toWire: (row: T) => unknown, + exportOf?: { readonly spec: ReportExportSpec; readonly path: string }, +): Response { + if (!result.ok) return c.json(result.error, result.status as ContentfulStatusCode); + const page = result.value; + const rows = page.rows.map(toWire); + if (exportOf !== undefined && page.format !== undefined) { + const body = renderExport(exportOf.spec, page.format, rows as Record[], page.total); + return c.body(body, 200, { + "content-disposition": exportContentDisposition(exportOf.path, page.format), + "content-type": EXPORT_CONTENT_TYPES[page.format], + }); + } + return c.json(page.total === undefined ? rows : { rows, total: page.total }); +} diff --git a/server/typescript/packages/runtime-ts/src/service/index.ts b/server/typescript/packages/runtime-ts/src/service/index.ts index bf93722bf2..d2e47647b9 100644 --- a/server/typescript/packages/runtime-ts/src/service/index.ts +++ b/server/typescript/packages/runtime-ts/src/service/index.ts @@ -20,6 +20,9 @@ import { coerceIdForColumn, contractErrorCode, extractRowCount, firstRow, isTrut import { parseFilterParams } from "../drizzle-fastify/filter-parser.js"; import { FilterParseError, pageLimit, type PageSize } from "../drizzle-fastify/list-params.js"; import type { FilterAllowlist, SortAllowlist } from "../drizzle-fastify/filter-allowlist.js"; +import { ReportTooLargeError } from "../drizzle-fastify/list-params.js"; +import { ReportExportError } from "../drizzle-fastify/report-export.js"; +import { InvalidIdError } from "../read-only-read.js"; export type { SqlDialect } from "../sql-dialect.js"; export type { PageSize } from "../drizzle-fastify/list-params.js"; @@ -215,6 +218,9 @@ async function syncSqliteTransaction(handle: Drizzle, nested: boolean, fn: (t function failure(e: unknown): OpResult { if (e instanceof Refusal) return { ok: false, status: e.status, error: e.body }; + if (e instanceof InvalidIdError) return { ok: false, status: 400, error: { error: "invalid_id" } }; + if (e instanceof ReportTooLargeError) return { ok: false, status: 400, error: { error: "report_too_large", maxRows: e.maxRows } }; + if (e instanceof ReportExportError) return { ok: false, status: e.status, error: e.body }; if (e instanceof FilterParseError) { return { ok: false, status: 400, error: { error: contractErrorCode(e.code), ...(e.details ?? {}) } }; } @@ -326,6 +332,11 @@ export interface ListSpec { readonly pagination?: PageSize; /** The key field a list with no `sort` is ordered by, so a page is stable. Default `id`. */ readonly keyField?: string; + /** + * A condition every row of the list meets besides the query's filter: a single-table subtype's + * discriminator (`scopeCondition`), so its list answers its own rows only. + */ + readonly scope?: SQL; } /** A page of a list, and the count of every row the filter matches when the query asked for it (`withCount`). */ @@ -354,7 +365,7 @@ export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, sortAllowlist: spec.sortAllowlist, dialect: spec.dialect, }); - const where = parsed.where && parsed.searchWhere ? and(parsed.where, parsed.searchWhere) : (parsed.where ?? parsed.searchWhere); + const where = and(...[parsed.where, parsed.searchWhere, spec.scope].filter((c): c is SQL => c !== undefined)); let q = db.select().from(src).$dynamic(); if (where) q = q.where(where); if (parsed.orderBy) q = q.orderBy(...parsed.orderBy); @@ -368,3 +379,28 @@ export async function listRows(db: Drizzle, src: Drizzle, query: ListQueryInput, const countRow = (await cq)[0] as { c: number } | undefined; return { rows, total: countRow?.c ?? 0 }; } + +/** `cond`, and `scope` when there is one: a single-table subtype's row is addressed within its own rows. */ +export function scoped(cond: SQL, scope: SQL | undefined): SQL { + return scope === undefined ? cond : and(cond, scope)!; +} + +/** The condition a single-table subtype's rows meet: its discriminator `field` holds `value`. */ +export function scopeCondition(table: Drizzle, field: string, value: string): SQL { + return eq(table[field], value); +} + +/** + * The row a write to a write-through entity's table just wrote, read back through its replica + * view by key, so the answer carries the view's derived columns. Answers the written row when the + * view has none (it never 500s a write that succeeded). + */ +export async function readThroughView(db: Drizzle, view: Drizzle, keyField: string, written: Record): Promise> { + return (await readOne(db, view, eq(view[keyField], written[keyField]))) ?? written; +} + +// How a read-only object (a projection, a served report) and a many-to-many traversal are read: the +// same functions the flat routes call, so the service answers what they answer. +export { readOnlyGet, readOnlyList, type ReadOnlyPage, type ReadOnlySpec } from "../read-only-read.js"; +export { m2mRelated, type M2mSpec } from "../m2m-read.js"; +export type { ReportExportSpec } from "../drizzle-fastify/report-export.js"; 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 2c41674dba..b435e1f4d1 100644 --- a/spec/decisions/ADR-0067-layering-and-the-service-seam.md +++ b/spec/decisions/ADR-0067-layering-and-the-service-seam.md @@ -18,7 +18,10 @@ and every generator below is a helper. Layer 0 and layer 1 are generated: `rules-names` and `contract-types` write in TypeScript, and C# writes its own names and create and update records. In TypeScript, layers 4 and 5 have started: `service` writes each package's derived list, get, create, update and delete in one transaction with -the declared write rules, and `service-routes` the thin Fastify transport over it, with +the declared write rules, for every object the flat routes serve: a projection's and a served +report's reads (their writes answer 405), a write-through entity's writes read back through its +view, a single-table hierarchy's polymorphic base reads and per-subtype operations, and each +many-to-many traversal, and `service-routes` the thin Fastify transport over it, with `service-routes-hono` its Hono twin (the `service` layer label of §5.6). The same generators now write ADR-0066's transitions and declared operations, with the policy, bodies, hooks and events interfaces, and enforce the rules at run time. The other