Skip to content
16 changes: 16 additions & 0 deletions .changeset/37709-form-reads-once.md
Original file line number Diff line number Diff line change
@@ -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.
113 changes: 111 additions & 2 deletions packages/metadata-protocol/src/protocol-form-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -71,6 +72,109 @@ export type FormReadHost = Pick<ProtocolHost,

const keyOf = (pkg: unknown, name: unknown): string => `${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<object>();

/**
* 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<object, object>;
}

const FORM_REQUEST = new AsyncLocalStorage<FormRequestReading>();

/** The two host members a {@link formRequestScope} replaces. */
type ScopableHost = Pick<FormReadHost, 'readActiveOverlayRows' | 'readFlattenedMetaItems'>;

/**
* [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<T>(read: () => Promise<T>): Promise<T> {
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<H extends ScopableHost>(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<string, Promise<any[]>>();
const lists = new Map<string, ReturnType<FormReadHost['readFlattenedMetaItems']>>();
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<H extends ScopableHost>(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;
Expand Down Expand Up @@ -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
Expand All @@ -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<string, unknown>> {
// 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<string, unknown>;
Expand Down Expand Up @@ -401,7 +510,7 @@ export async function readUnreadableFormBodies(
report: (line: string) => void = (line) => console.error(line),
): Promise<UnreadableFormBody[]> {
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 = {
Expand Down
5 changes: 4 additions & 1 deletion packages/metadata-protocol/src/protocol-meta-item-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 16 additions & 9 deletions packages/metadata-protocol/src/protocol-meta-list-reads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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. */
Expand All @@ -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. */
Expand All @@ -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<ProtocolHost, 'readFlattenedMetaItems'>, request: { type: string; packageId?: string; previewDrafts?: boolean }) {
export async function getMetaItemsPerPackage(host: Pick<ProtocolHost, 'readActiveOverlayRows' | 'readFlattenedMetaItems'>, 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');
}

/**
Expand Down Expand Up @@ -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<ProtocolHost, 'artifactLockLayerAt' | 'baseServesBundleMember' | 'convertStoredItem' | 'declinesStoredRow' | 'disabledActionsOf' | 'engine' | 'environmentId' | 'expandStoredViewContainers' | 'findEnvironmentRows' | 'flowRegistrationsOf' | 'foldObjectExtendersFromRegistry' | 'getServicesRegistry' | 'governServedObject' | 'hydrateOverlayIntoRegistry' | 'isStoredEntryOfDeclinedName' | 'isUnservedSealedOverlay' | 'isWritablePackage' | 'lookupArtifactItem' | 'namesWithOwnStoredRow' | 'readActiveOverlayRows' | 'readItemActiveRows' | 'rethrowUnlessMetadataStoreUnprovisioned' | 'shippedArtifactsOf' | 'shippingPackagesOf' | 'shipsBundleName' | 'storedOverlayEntries'>, 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<any[]>,) {
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`).
Expand Down Expand Up @@ -299,8 +306,8 @@ export async function readFlattenedMetaItems(host: Pick<ProtocolHost, 'artifactL
// the view containers it expands through the same two calls, so
// the two doors cannot disagree about which containers are in
// scope for one caller.
const records = await host.readActiveOverlayRows(request);
lockRows = packageId ? await host.readActiveOverlayRows({ type: request.type }) : records;
const records = await readRows(request);
lockRows = packageId ? await readRows({ type: request.type }) : records;
const standInRows = packageId ? lockRows.filter((row) => (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
Expand Down
34 changes: 17 additions & 17 deletions packages/metadata-protocol/src/protocol.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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<T>(read: () => Promise<T>): Promise<T> {
return readInFormRequest(read);
}

/**
* [#28411, ADR-0146 D8 item 4] The served overrides of a base package's
* items: each ACTIVE row of its paired `<base>.custom` package that
Expand Down Expand Up @@ -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<any[]>,
) {
// [#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);
}

/**
Expand Down
Loading
Loading