diff --git a/.changeset/37709-form-reads-once.md b/.changeset/37709-form-reads-once.md new file mode 100644 index 00000000000..c9a706ddffd --- /dev/null +++ b/.changeset/37709-form-reads-once.md @@ -0,0 +1,16 @@ +--- +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +--- + +perf(metadata-protocol): a by-name `form` read and an anonymous form-door request read the `view` list once and each type's stored rows once + +Clause-②: yes (widening) — ObjectStackProtocolImplementation.readFormRequest +Metadata-protocol: none + +The effective `form` read resolves over both types (ADR-0159 D5): the generic `form` list, the projection of the `view` list, and the cross-type resolution over the stored rows of both types. Those readings asked for the same stored rows separately, and an anonymous form door made five protocol calls (the `view` list, the `form` list, the unreadable bodies and both per-package layers), each reading the rows again. With the overlay row cache off, a by-name `form` read read the `form` and `view` rows twice each, and a form-door GET read the `view` list twice, the `view` rows five times and the `form` rows three times. + +- **`@objectstack/metadata-protocol`.** The effective `form` read now reads through one request scope: each stored row set (per type and package binding) and each flattened list is read once per request, and nothing is kept past the request. A new server-only extension, `readFormRequest(read)`, runs `read` as one request's reading: the `getMetaItems`, `getMetaItemsPerPackage` and `getUnreadableFormBodies` calls inside it share that one scope, each answering what it answers on its own. +- **`@objectstack/rest`.** The form doors (`GET /forms/:slug`, `POST /forms/:slug/submit`) make their five reads inside `readFormRequest` when the protocol serves it, and as before otherwise. + +Every answer is unchanged: the same items, in the same order, from the same served-row order. Nothing to migrate. diff --git a/packages/metadata-protocol/src/protocol-form-reads.ts b/packages/metadata-protocol/src/protocol-form-reads.ts index 18c5cf91b01..31e49d8fbe2 100644 --- a/packages/metadata-protocol/src/protocol-form-reads.ts +++ b/packages/metadata-protocol/src/protocol-form-reads.ts @@ -42,6 +42,7 @@ * Pure over what the host reads: no write, no registry mutation. */ +import { AsyncLocalStorage } from 'node:async_hooks'; import { pairsOf, type InstalledManifestLookup } from '@objectstack/metadata-core'; import { PROJECTED_FORM_SOURCE_KEY, isAggregatedViewContainer, projectViewForms, type UnreadableFormBody } from '@objectstack/spec/ui'; import { installedManifestsOfEngine } from './installed-manifests.js'; @@ -71,6 +72,109 @@ export type FormReadHost = Pick `${typeof pkg === 'string' ? pkg : ''}\u0000${String(name)}`; +/** The hosts {@link formRequestScope} built, so a scope handed on is never scoped twice. */ +const REQUEST_SCOPES = new WeakSet(); + +/** + * One request's reading ({@link readInFormRequest}): the scope it built over + * each host, and whether the request is still reading. Once the request has + * answered, a scope it built memoizes nothing: a continuation that outlives + * the request reads the store as any read does. + */ +interface FormRequestReading { + open: boolean; + readonly scopes: WeakMap; +} + +const FORM_REQUEST = new AsyncLocalStorage(); + +/** The two host members a {@link formRequestScope} replaces. */ +type ScopableHost = Pick; + +/** + * [ADR-0159 D5, D6] Run `read` as ONE request's reading of the two types: + * every list read and stored-row read inside it, through any of the protocol + * reads below, shares one {@link formRequestScope} per host. The anonymous + * form doors read the `view` list, the `form` list, the unreadable bodies and + * both per-package layers as five protocol calls; inside one reading they read + * the `view` list once and each type's stored rows once, and each call answers + * what it answers on its own. The reading ends when `read` settles. + */ +export async function readInFormRequest(read: () => Promise): Promise { + const reading: FormRequestReading = { open: true, scopes: new WeakMap() }; + try { + return await FORM_REQUEST.run(reading, read); + } finally { + reading.open = false; + } +} + +/** + * [ADR-0159 D5] ONE request's reading of the two types: the host the `form` + * read reads through, over which each stored row set (`sys_metadata`, per type + * and package binding) and each flattened list (per request, audience and + * layer) is read once, however many of the readings below ask for it. + * + * The effective `form` read asks for the same rows more than once by + * construction: the generic `form` list and step 3 both read the stored `form` + * rows, and the `view` list and step 3 both read the stored `view` rows. A + * form door asks the `view` list, the `form` list (which reads the `view` list + * again), both per-package layers and the unreadable bodies, each over the + * same stored rows. Read through one scope, the request reads each row set and + * each list once (measured and pinned in `public-form-reads-once-37709.test.ts`, + * `@objectstack/rest`). A list read in the scope reads its stored rows through + * the scope too (`readFlattenedMetaItems`' row reader), so the generic lists + * and step 3 share one reading of each type's rows. + * + * Inside {@link readInFormRequest} the scope is the request's own, shared by + * every read of that request over the same host; outside one, it is the scope + * of the one call that built it. ⛔ Never kept across requests (the + * cross-request row cache is `meta-overlay-cache.ts`, under its own + * invalidation). Every member the scope does not replace is the host's own, + * read at call time. + */ +export function formRequestScope(host: H): H { + if (REQUEST_SCOPES.has(host)) return host; + const reading = FORM_REQUEST.getStore(); + const shared = reading?.scopes.get(host) as H | undefined; + if (shared !== undefined) return shared; + const live = (): boolean => reading === undefined || reading.open; + const rows = new Map>(); + const lists = new Map>(); + const readActiveOverlayRows: FormReadHost['readActiveOverlayRows'] = (request) => { + if (!live()) return host.readActiveOverlayRows(request); + const key = `${request.type}\u0000${request.packageId ?? ''}`; + let read = rows.get(key); + if (read === undefined) { + read = host.readActiveOverlayRows(request); + rows.set(key, read); + } + return read; + }; + const readFlattenedMetaItems: FormReadHost['readFlattenedMetaItems'] = (request, audience, layer = 'effective') => { + if (!live()) return host.readFlattenedMetaItems(request, audience, layer); + const key = JSON.stringify([request.type, request.packageId ?? null, request.names ?? null, request.previewDrafts === true, audience, layer]); + let read = lists.get(key); + if (read === undefined) { + read = host.readFlattenedMetaItems(request, audience, layer, readActiveOverlayRows); + lists.set(key, read); + } + return read; + }; + const scope = Object.create(host, { + readActiveOverlayRows: { value: readActiveOverlayRows }, + readFlattenedMetaItems: { value: readFlattenedMetaItems }, + }) as H; + REQUEST_SCOPES.add(scope); + reading?.scopes.set(host, scope); + return scope; +} + +/** The scope of the request reading in progress ({@link readInFormRequest}) over `host`, or `host` outside one. */ +export function inFormRequestScope(host: H): H { + return FORM_REQUEST.getStore()?.open === true ? formRequestScope(host) : host; +} + /** A listed item's package, as its envelope states it. */ function packageOf(item: unknown): string | undefined { const pkg = (item as { _packageId?: unknown } | null)?._packageId; @@ -226,7 +330,10 @@ export async function readEffectiveForms( * is read from, so the named items resolve exactly as the whole list would. * The stored rows of step 3 are read whole: a container row's `name` is not * the name its expansion writes, so no row predicate can select them by the - * form's name. + * form's name. They are read ONCE per request ({@link formRequestScope}): + * step 3 reads the same stored rows of each type the two generic reads read, + * so a by-name read reads each type's stored rows once, as a form door does + * (measured on the pin, `public-form-reads-once-37709.test.ts`). * - **`packageId` is NOT pushed down**, and is applied to the resolved list: * the effective `form` read is resolved per address over both types, and a * list scoped to a package reads another address than its own. Step 1 @@ -242,6 +349,8 @@ export async function readEffectiveFormList( request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', ): Promise<{ type: string; items: unknown[] } & Record> { + // Every reading below reads through one request scope: each stored row set once. + host = formRequestScope(host); const { packageId: scope, names, ...rest } = request; const unscoped = { ...rest, type: 'form', ...(names !== undefined ? { names } : {}) }; const genericList = await host.readFlattenedMetaItems(unscoped, audience) as { items: unknown[] } & Record; @@ -401,7 +510,7 @@ export async function readUnreadableFormBodies( report: (line: string) => void = (line) => console.error(line), ): Promise { const out: UnreadableFormBody[] = []; - for (const entry of await storedEntries(host as FormReadHost, 'view')) { + for (const entry of await storedEntries(inFormRequestScope(host as FormReadHost), 'view')) { const projection = projectViewForms(entry.data); if (projection.unreadable === undefined) continue; const body: UnreadableFormBody = { diff --git a/packages/metadata-protocol/src/protocol-meta-item-reads.ts b/packages/metadata-protocol/src/protocol-meta-item-reads.ts index e409d542465..57545d42fb8 100644 --- a/packages/metadata-protocol/src/protocol-meta-item-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-item-reads.ts @@ -695,7 +695,10 @@ async function readEffectiveFormItem( const generic: any = await host.readMetaItemFace(request, 'served'); // ONE effective read of the name, unscoped: the list scoped to a package // is the same resolution filtered to that address (`readEffectiveFormList`), - // so the address's answer and every address's are both read off it. + // so the address's answer and every address's are both read off it. It + // reads the `view` list once and each type's stored rows once (its request + // scope, `formRequestScope`); the generic read above reads only the rows + // of the name. const everywhere = await readEffectiveForms(host, { type: 'form', names: [request.name] }, 'served'); const pkgOf = (item: unknown): unknown => (item as { _packageId?: unknown } | null)?._packageId; const listed = request.packageId === undefined diff --git a/packages/metadata-protocol/src/protocol-meta-list-reads.ts b/packages/metadata-protocol/src/protocol-meta-list-reads.ts index 22b8789c59d..1a2d65733d9 100644 --- a/packages/metadata-protocol/src/protocol-meta-list-reads.ts +++ b/packages/metadata-protocol/src/protocol-meta-list-reads.ts @@ -34,7 +34,7 @@ import { } from './protocol-authoring-refusals.js'; import { shippingPackageIds } from './protocol-environment-rows.js'; import type { ProtocolHost } from './protocol-host.js'; -import { readEffectiveFormList, type FormReadHost } from './protocol-form-reads.js'; +import { formRequestScope, inFormRequestScope, readEffectiveFormList, type FormReadHost } from './protocol-form-reads.js'; import { canonicalizeMetaRequestType } from './protocol-meta-type-schema.js'; import { mergePackageAwareOverlay, servedViewExpansion, withoutServedRowName } from './protocol-overlay-merge.js'; import { @@ -71,9 +71,11 @@ async function effectiveFormList( request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', ) { - const resolved = await readEffectiveFormList(host, request, audience); + // One request scope: the scoped list's envelope reads the stored rows the resolution read. + const scoped = formRequestScope(host); + const resolved = await readEffectiveFormList(scoped, request, audience); if (request.packageId === undefined) return resolved; - return { ...(await host.readFlattenedMetaItems(request, audience)), items: resolved.items }; + return { ...(await scoped.readFlattenedMetaItems(request, audience)), items: resolved.items }; } /** The body of `ObjectStackProtocolImplementation#getMetaItems`; the method's docblock there is its contract. */ @@ -92,7 +94,8 @@ export async function getMetaItems(host: FormReadHost, request: { type: string; // [ADR-0159 D5] The `form` list is resolved over both types, in one // generic read where the list names no package (`readEffectiveFormList`). if (canonical.type === 'form') return effectiveFormList(host, canonical, 'served'); - return host.readFlattenedMetaItems(canonical, 'served'); + // Inside a form request's reading (`readInFormRequest`), through its scope. + return inFormRequestScope(host).readFlattenedMetaItems(canonical, 'served'); } /** The body of `ObjectStackProtocolImplementation#getMetaItemsForExecution`; the method's docblock there is its contract. */ @@ -104,9 +107,10 @@ export async function getMetaItemsForExecution(host: FormReadHost, request: { ty } /** The body of `ObjectStackProtocolImplementation#getMetaItemsPerPackage`; the method's docblock there is its contract. */ -export async function getMetaItemsPerPackage(host: Pick, request: { type: string; packageId?: string; previewDrafts?: boolean }) { +export async function getMetaItemsPerPackage(host: Pick, request: { type: string; packageId?: string; previewDrafts?: boolean }) { // The same #4432 fold {@link getMetaItems} applies, for the same reason. - return host.readFlattenedMetaItems(canonicalizeMetaRequestType(request), 'served', 'per-package'); + // Inside a form request's reading (`readInFormRequest`), through its scope. + return inFormRequestScope(host).readFlattenedMetaItems(canonicalizeMetaRequestType(request), 'served', 'per-package'); } /** @@ -188,8 +192,11 @@ function disabledHolderListing( /** The body of `ObjectStackProtocolImplementation#readFlattenedMetaItems`; the method's docblock there is its contract. */ export async function readFlattenedMetaItems(host: Pick, request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', - layer: 'effective' | 'per-package' = 'effective',) { + layer: 'effective' | 'per-package' = 'effective', + /** [ADR-0159 D5] One request's stored-row reader (`formRequestScope`); omitted, the host's. */ + rows?: (request: { type: string; packageId?: string }) => Promise,) { const { packageId } = request; + const readRows = rows ?? ((r: { type: string; packageId?: string }) => host.readActiveOverlayRows(r)); const servedOverride = layer === 'effective'; // The registry's installed manifests: a package's declared override is // its App's pair's (`pairOf`, `isServedOverrideRowOf`). @@ -299,8 +306,8 @@ export async function readFlattenedMetaItems(host: Pick (row?.package_id ?? null) === null) : []; // [#28409, ADR-0146 D8 item 2] …and a list scoped to a package // serves, in each slot the package seats, the package's declared diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index cbd8f442c8d..b896d378c57 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -1,7 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { formTypeWriteRefusal } from './protocol-form-writes.js'; -import { readUnreadableFormBodies } from './protocol-form-reads.js'; +import { readInFormRequest, readUnreadableFormBodies } from './protocol-form-reads.js'; import type { DataProtocol, FlowRegistration, @@ -3540,6 +3540,11 @@ export class ObjectStackProtocolImplementation implements return readUnreadableFormBodies(protocolHost(this)); } + /** Contract: {@link readInFormRequest} [ADR-0159 D5, D6]; the doors' five reads as one request reading, feature-detected likewise. */ + async readFormRequest(read: () => Promise): Promise { + return readInFormRequest(read); + } + /** * [#28411, ADR-0146 D8 item 4] The served overrides of a base package's * items: each ACTIVE row of its paired `.custom` package that @@ -3628,30 +3633,25 @@ export class ObjectStackProtocolImplementation implements } /** - * The one body behind {@link getMetaItems}, - * {@link getMetaItemsForExecution} and {@link getMetaItemsPerPackage}. - * `audience` decides ONLY whether the serving decorations are applied at - * the very end; every source, merge and filter above that line is shared, - * so the list the engine executes and the list a caller is served cannot + * The one body behind {@link getMetaItems}, {@link getMetaItemsForExecution} and {@link getMetaItemsPerPackage}. + * `audience` decides ONLY whether the serving decorations are applied at the very end; every source, merge and + * filter above that line is shared, so the list the engine executes and the list a caller is served cannot * disagree about which items exist. * - * [#28409] `layer` decides ONLY whether the two steps of the one - * effective read are taken (ADR-0146 D8): a package's declared override - * served over its slot ({@link servedOverlayRowCandidates}' - * `servedOverride`), and, naming no package, a name exactly one code - * package ships listed once, under that package - * ({@link soleShippingPackageOf}). `'effective'` takes both; the - * per-package layer takes neither. - * - * `request` arrives already folded by the calling face (#4432). + * [#28409] `layer` decides ONLY whether the two steps of the one effective read are taken (ADR-0146 D8): a + * package's declared override served over its slot ({@link servedOverlayRowCandidates}' `servedOverride`), and, + * naming no package, a name exactly one code package ships listed once, under that package + * ({@link soleShippingPackageOf}). `'effective'` takes both; the per-package layer takes neither. + * `request` arrives already folded by the calling face (#4432). [ADR-0159 D5] `rows`, when given, is one + * request's stored-row reader (`formRequestScope`); omitted, {@link readActiveOverlayRows}. */ private async readFlattenedMetaItems( request: { type: string; packageId?: string; names?: readonly string[]; previewDrafts?: boolean }, audience: 'served' | 'execution', - layer: 'effective' | 'per-package' = 'effective', + layer: 'effective' | 'per-package' = 'effective', rows?: (request: { type: string; packageId?: string }) => Promise, ) { // [#25467 E1] The body moved to `protocol-meta-list-reads.ts`; it reaches this class through `protocol-host.ts`. - return readFlattenedMetaItems(protocolHost(this), request, audience, layer); + return readFlattenedMetaItems(protocolHost(this), request, audience, layer, rows); } /** diff --git a/packages/rest/src/form-routes.ts b/packages/rest/src/form-routes.ts index 4f64d109447..ca470f73809 100644 --- a/packages/rest/src/form-routes.ts +++ b/packages/rest/src/form-routes.ts @@ -306,28 +306,39 @@ export function registerFormEndpoints(this: FormRouteHost, basePath: string): vo ? result : []); const formsRequest: TransportScopedMetaRequest = { ...viewsRequest, type: 'form' }; - const views = listOf(await p.getMetaItems(viewsRequest)); - // [ADR-0159 D5, D6 rules 1 and 3] The candidates are the effective - // `form` read, which projects the old shapes itself: ONE read, and no - // second candidate source inside the door. A protocol that serves no - // `form` item serves no candidate. - const forms = listOf(await p.getMetaItems(formsRequest)); - // [#28409] The per-package layers, where the protocol serves them: a - // server-only extension, feature-detected like the other extensions - // the doors read. A protocol without it serves no narrower list than - // the one it lists, which is then the whole layer. - const perPackage = async (request: TransportScopedMetaRequest): Promise => - (typeof (p as any).getMetaItemsPerPackage === 'function' - ? listOf(await (p as any).getMetaItemsPerPackage(request)) - : []); - // [ADR-0159 D6 rule 7] …and the stored bodies the projection cannot read. - const unreadable: UnreadableFormBody[] = typeof (p as any).getUnreadableFormBodies === 'function' - ? await (p as any).getUnreadableFormBodies() - : []; - const layer = formIntakeLayer({ - forms: [...forms, ...(await perPackage(formsRequest))], - views: [...views, ...(await perPackage(viewsRequest))], - unreadable, + // [ADR-0159 D5, D6] The five readings below are ONE request's reading + // where the protocol serves one (`readFormRequest`, a server-only + // extension, feature-detected): the request reads the `view` list + // once and each type's stored rows once, and each call answers what it + // answers on its own. Without it, the five calls read as they always did. + const inOneReading = (read: () => Promise): Promise => (typeof (p as any).readFormRequest === 'function' + ? (p as any).readFormRequest(read) + : read()); + const { forms, views, layer } = await inOneReading(async () => { + const views = listOf(await p.getMetaItems(viewsRequest)); + // [ADR-0159 D5, D6 rules 1 and 3] The candidates are the effective + // `form` read, which projects the old shapes itself: ONE read, and no + // second candidate source inside the door. A protocol that serves no + // `form` item serves no candidate. + const forms = listOf(await p.getMetaItems(formsRequest)); + // [#28409] The per-package layers, where the protocol serves them: a + // server-only extension, feature-detected like the other extensions + // the doors read. A protocol without it serves no narrower list than + // the one it lists, which is then the whole layer. + const perPackage = async (request: TransportScopedMetaRequest): Promise => + (typeof (p as any).getMetaItemsPerPackage === 'function' + ? listOf(await (p as any).getMetaItemsPerPackage(request)) + : []); + // [ADR-0159 D6 rule 7] …and the stored bodies the projection cannot read. + const unreadable: UnreadableFormBody[] = typeof (p as any).getUnreadableFormBodies === 'function' + ? await (p as any).getUnreadableFormBodies() + : []; + const layer = formIntakeLayer({ + forms: [...forms, ...(await perPackage(formsRequest))], + views: [...views, ...(await perPackage(viewsRequest))], + unreadable, + }); + return { forms, views, layer }; }); const match = findPublicForm(forms, views, layer, slug); if (!match) return null; diff --git a/packages/rest/src/public-form-reads-once-37709.test.ts b/packages/rest/src/public-form-reads-once-37709.test.ts new file mode 100644 index 00000000000..19f0fcd8c40 --- /dev/null +++ b/packages/rest/src/public-form-reads-once-37709.test.ts @@ -0,0 +1,210 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0159 D5, D6] One form request reads the `view` list at most once and + * each type's stored rows (`sys_metadata`) at most once. + * + * The effective `form` read resolves over both types: the generic `form` list, + * the projection of the `view` list, and the cross-type resolution over the + * stored rows of both types (`readEffectiveFormList`, `@objectstack/metadata-protocol`). + * Each of those readings, and each of the five an anonymous form door makes + * (the `view` list, the `form` list, the unreadable bodies, both per-package + * layers), asks for the same stored rows. The effective `form` read reads + * through one request scope (`formRequestScope`), and the doors make their + * five calls inside one request reading (`readFormRequest`), so the request + * reads each row set once. + * + * Measured on the merged tree before the scope (`OS_METADATA_OVERLAY_CACHE_TTL_MS=0`, + * an authored `form` item): a by-name `form` read read the `form` rows twice + * and the `view` rows twice; a form-door GET read the `view` list twice, the + * `view` rows five times and the `form` rows three times. An old-shape form + * (no address left the `view` type, so no cross-type resolution) read the + * `view` rows four times and the `form` rows twice on the door. + * + * Every pin runs the REAL protocol over a real `ObjectQL` engine and a real + * SQL store, with the cross-request row cache off (`TTL=0`), so every row-set + * read is a SQL statement the engine sees. A row-set read of a type issues one + * statement under the singular spelling and, when that answers no row, one + * under the plural (`readActiveOverlayRows`); each spelling is counted. + * + * CONTROL: two requests read twice (the scope never spans requests), and the + * five door calls outside one reading (a protocol without `readFormRequest`) + * still read the rows once per call, so the counter sees a repeated read when + * there is one. Ablation (recorded on the PR): drop the scope from the + * effective `form` read, from the door's reading, or the scope's row reader + * from its list reads, and the counts go red. + */ +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { + SysMetadataAuditObject, + SysMetadataCommitObject, + SysMetadataHistoryObject, + SysMetadataObject, +} from '@objectstack/metadata-core'; +import { RestServer } from './rest-server'; + +const BASE = 'com.example.forms37709'; +const OBJECT = 'fro_inquiry'; +const NAME = `${OBJECT}.contact`; +const SLUG = 'contact-37709'; + +const body = { type: 'simple', sections: [{ fields: ['name'] }], sharing: { enabled: true, allowAnonymous: true, publicLink: `/forms/${SLUG}` } }; +const INQUIRY = { name: OBJECT, label: 'Inquiry', fields: { name: { name: 'name', type: 'text' as const, label: 'Name' } } }; + +/** The two shapes a first-party form takes: an authored `form` item, an old-shape container's `formViews` entry. */ +const SHAPES = { + 'an authored `form` item': { forms: [{ name: NAME, object: OBJECT, label: 'Contact us', ...body }] }, + 'an old-shape `formViews` entry': { views: [{ object: OBJECT, formViews: { contact: { ...body, data: { provider: 'object', object: OBJECT } } } }] }, +} as const; + +function mockServer() { + const noop = () => {}; + return { get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, listen: async () => {}, close: async () => {} }; +} + +function makeRes() { + const res: any = { + header: () => res, + setHeader: () => res, + send: (b: unknown) => { res._json = b; return res; }, + write: () => true, + end: () => res, + status: (code: number) => { res._status = code; return res; }, + json: (b: unknown) => { res._json = b; return res; }, + }; + return res; +} + +/** The reads one request issues: row-set statements per type spelling, name-predicated row reads, flattened lists. */ +interface Reads { + rows: Record; + named: number; + lists: Record; +} + +const FAMILIES = new Set(['form', 'forms', 'view', 'views']); + +async function boot(ships: Record) { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as any); + const engine = new ObjectQL(); + engine.registerDriver(driver, true); + await engine.init(); + for (const o of [SysMetadataObject, SysMetadataHistoryObject, SysMetadataAuditObject, SysMetadataCommitObject]) { + engine.registry.registerObject(o as any, 'test-package'); + } + engine.registerApp({ id: BASE, name: 'forms37709', version: '1.0.0', namespace: 'fro', objects: [INQUIRY], ...ships } as any); + await engine.syncSchemas(); + const protocol: any = new ObjectStackProtocolImplementation(engine as any, () => new Map()); + const rest = new RestServer(mockServer() as any, protocol, { api: { requireAuth: false } } as any); + rest.registerRoutes(); + const resolve = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/forms/:slug'); + expect(resolve, 'GET /api/v1/forms/:slug is registered').toBeDefined(); + + let reads: Reads | undefined; + const find = engine.find.bind(engine); + vi.spyOn(engine, 'find').mockImplementation(async (object: string, query?: any) => { + if (reads !== undefined && object === 'sys_metadata' && query?.where?.state === 'active') { + const type = query.where.type; + if (typeof type === 'string' && FAMILIES.has(type) && query.where.name === undefined) reads.rows[type] = (reads.rows[type] ?? 0) + 1; + else if (query.where.name !== undefined) reads.named += 1; + } + return find(object, query); + }); + const flattened = protocol.readFlattenedMetaItems.bind(protocol); + protocol.readFlattenedMetaItems = (request: any, audience: any, layer: any, rows: any) => { + if (reads !== undefined && FAMILIES.has(request.type)) { + const key = `${request.type}:${layer ?? 'effective'}`; + reads.lists[key] = (reads.lists[key] ?? 0) + 1; + } + return flattened(request, audience, layer, rows); + }; + /** The reads `run` issued. */ + const counted = async (run: () => Promise): Promise => { + reads = { rows: {}, named: 0, lists: {} }; + try { + await run(); + return reads; + } finally { + reads = undefined; + } + }; + const door = async () => { + const res = makeRes(); + await resolve!.handler({ params: { slug: SLUG }, query: {}, headers: {} } as any, res); + return { status: res._status ?? 200, body: res._json }; + }; + const byName = () => protocol.getMetaItem({ type: 'form', name: NAME }); + return { engine, protocol, door, byName, counted }; +} + +/** Each type's stored rows read once: one statement per spelling. */ +const ONCE = { form: 1, forms: 1, view: 1, views: 1 }; + +describe('[ADR-0159 D5, D6] one form request reads the `view` list once and each type\'s stored rows once', () => { + const engines: ObjectQL[] = []; + beforeAll(() => { + // The cross-request row cache off: every row-set read reaches the store. + vi.stubEnv('OS_METADATA_OVERLAY_CACHE_TTL_MS', '0'); + }); + afterAll(async () => { + vi.unstubAllEnvs(); + vi.restoreAllMocks(); + for (const engine of engines) await engine.destroy().catch(() => {}); + }); + const booted = async (ships: Record) => { + const b = await boot(ships); + engines.push(b.engine); + // The first request of a process pays its one-time reads (the catalog probe); measure the next. + await b.byName(); + await b.door(); + return b; + }; + + describe.each(Object.entries(SHAPES))('the form is %s', (_shape, ships) => { + it('a by-name `form` read: the `view` list once, each type\'s stored rows once, and the rows of the name once', async () => { + const b = await booted(ships); + let answer: any; + const reads = await b.counted(async () => { answer = await b.byName(); }); + expect(answer?.item?.name).toBe(NAME); + expect(answer?.item?._packageId).toBe(BASE); + expect(reads.lists).toEqual({ 'form:effective': 1, 'view:effective': 1 }); + expect(reads.rows).toEqual(ONCE); + // The generic by-name read: its own row read, predicated on the name. + expect(reads.named).toBe(1); + }); + + it('an anonymous form-door GET: the `view` list once, each type\'s stored rows once', async () => { + const b = await booted(ships); + let answer: any; + const reads = await b.counted(async () => { answer = await b.door(); }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(reads.lists).toEqual({ + 'view:effective': 1, 'form:effective': 1, 'form:per-package': 1, 'view:per-package': 1, + }); + expect(reads.rows).toEqual(ONCE); + expect(reads.named).toBe(0); + }); + + it('CONTROL: two requests read twice: the scope never outlives its request', async () => { + const b = await booted(ships); + const reads = await b.counted(async () => { await b.door(); await b.byName(); }); + expect(reads.rows).toEqual({ form: 2, forms: 2, view: 2, views: 2 }); + expect(reads.lists['view:effective']).toBe(2); + }); + + it('CONTROL: the five door calls outside one reading (a protocol without `readFormRequest`) read the rows once per call', async () => { + const b = await booted(ships); + b.protocol.readFormRequest = undefined; + let answer: any; + const reads = await b.counted(async () => { answer = await b.door(); }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + // The `view` list twice: the door's own read, and the `form` list's step 2. + expect(reads.lists['view:effective']).toBe(2); + // The `view` rows: the `view` list, the `form` list's scope, the unreadable bodies, the per-package layer. + expect(reads.rows.view).toBe(4); + }); + }); +}); diff --git a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts index a0a75e2fddb..b9319542b8d 100644 --- a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts +++ b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts @@ -136,6 +136,8 @@ const READS: Record = { getMetaItemsPerPackage: async (req: { type?: string }) => (req?.type === 'view' ? [FORM_VIEW] : []), // [ADR-0159 D6 rule 7] No stored body the projection cannot read. getUnreadableFormBodies: async () => [], + // [ADR-0159 D5, D6] The form doors' five reads run as one request reading. + readFormRequest: async (read: () => Promise) => read(), getMetaItem: async () => SCHEMA, findData: async () => ({ records: [] }), getData: async () => ({ record: { id: 'r1' } }),