From f2dcd9002ee666ad58dad9953a5f5736f31805e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:37:32 +0000 Subject: [PATCH 01/11] feat(data): one record lock read owned by the data layer (ADR-0162 D9) The engine answers { locked, lockSource?, lockReason? } | null for one record and for a page of up to 200, composing its closed-state judgement with the approvals plugin's, which it reads through an internal engine slot the plugin fills beside its lock hooks. The data protocol, two data routes, two SDK methods and the upload-link door ask it; docs and the changeset come with it. Tests follow. Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- .changeset/37770-one-record-lock-read.md | 26 ++ content/docs/api/client-sdk.mdx | 16 ++ content/docs/api/data-api.mdx | 57 ++++ packages/client/src/index.ts | 40 +++ packages/metadata-protocol/src/host-engine.ts | 11 + .../src/protocol-record-lock.ts | 46 ++++ packages/metadata-protocol/src/protocol.ts | 19 ++ packages/objectql/src/engine.ts | 36 +++ packages/objectql/src/record-lock-read.ts | 259 ++++++++++++++++++ .../plugin-approvals/src/approvals-plugin.ts | 7 + .../plugin-approvals/src/lifecycle-hooks.ts | 8 +- .../src/record-lock-producer.ts | 163 +++++++++++ packages/rest/src/data-action-routes.ts | 6 + packages/rest/src/record-lock-routes.ts | 209 ++++++++++++++ packages/rest/src/rest-route-ledger.ts | 7 + .../service-storage/src/record-file-access.ts | 64 +++-- packages/spec/authorable-surface/api.json | 2 + packages/spec/json-schema.manifest/api.json | 6 + packages/spec/src/api/index.ts | 1 + packages/spec/src/api/record-lock.zod.ts | 111 ++++++++ 20 files changed, 1073 insertions(+), 21 deletions(-) create mode 100644 .changeset/37770-one-record-lock-read.md create mode 100644 packages/metadata-protocol/src/protocol-record-lock.ts create mode 100644 packages/objectql/src/record-lock-read.ts create mode 100644 packages/plugins/plugin-approvals/src/record-lock-producer.ts create mode 100644 packages/rest/src/record-lock-routes.ts create mode 100644 packages/spec/src/api/record-lock.zod.ts diff --git a/.changeset/37770-one-record-lock-read.md b/.changeset/37770-one-record-lock-read.md new file mode 100644 index 00000000000..754b0a6e62c --- /dev/null +++ b/.changeset/37770-one-record-lock-read.md @@ -0,0 +1,26 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@objectstack/metadata-protocol': patch +'@objectstack/rest': patch +'@objectstack/client': patch +'@objectstack/plugin-approvals': patch +'@objectstack/service-storage': patch +--- + +feat(data): one record lock read, for closed states and approvals + +Clause-②: yes (widening) +Metadata-protocol: none + +An app can now ask whether a record is locked, and by which lock, in one read that covers both locks a record can be under: a declared closed state (an object's `closedStates`, or a `master_detail` line of a closed record) and an approval. Before this, a client could only ask the approvals read, which knows nothing of closed states, so a closed invoice looked editable until the save was refused. + +- `GET /api/v1/data/{object}/{id}/lock` answers one record: `{ locked, lockSource?, lockReason? }`. `lockReason` is `closed_state` or `approval`, `lockSource` is `record` or `master`, and both are present exactly when `locked` is true. A record the caller cannot read, or that does not exist, answers 404. +- `POST /api/v1/data/{object}/locks` answers a page of up to 200 records, body `{ "recordIds": [...] }`; a record the caller cannot read answers `locked: null`. A longer list is refused whole with 400. +- `client.data.getRecordLock(object, id)` and `client.data.getRecordLocks(object, recordIds)` call them. The shapes are `RecordLockSchema`, `GetRecordLocksRequestSchema` and `GetRecordLocksResponseSchema` in `@objectstack/spec/api`. + +Every user who can read the record is told, even when field permissions hide the state field. The answer never names the field, the value, the approval request or its participants. The read works without the approvals plugin; then only closed states lock. + +The upload-link door now asks this read before it issues a file-field link: a closed record is refused with "the record is closed, so no file can be added to it", a record an approval holds with the existing approval sentence. + +Nothing existing changes: the approvals read (`/api/v1/approvals/records/...`), its SDK methods and service members answer exactly as before. diff --git a/content/docs/api/client-sdk.mdx b/content/docs/api/client-sdk.mdx index 7614b0d1572..970cadd8b86 100644 --- a/content/docs/api/client-sdk.mdx +++ b/content/docs/api/client-sdk.mdx @@ -328,6 +328,22 @@ const { results } = await client.data.batchTransaction([ See [Batch Operations](/docs/protocol/kernel/http-protocol#batch-operations) for the underlying endpoint contract. +Whether a record is locked, and by which lock — a closed state or an approval +([Record locks](/docs/api/data-api#record-locks)): + +```typescript +// One record: { locked, lockSource?, lockReason? }; rejects with 404 when +// the record is missing or you cannot read it. +const lock = await client.data.getRecordLock('invoice', 'inv_1'); +if (lock.locked && lock.lockReason === 'closed_state') { + // closed: no edit will be taken +} + +// A page of at most 200 records: entry i answers recordIds[i]; +// `locked: null` for a record that is missing or that you cannot read. +const { records } = await client.data.getRecordLocks('invoice', ['inv_1', 'inv_2']); +``` + ### `client.analytics` — BI Queries ```typescript diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index b7ba34789cb..022e0b5ae0f 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -616,6 +616,63 @@ refused `403 CHANGE_OWNER_DISABLED`. ] } } ``` +## Record locks + +Whether a record is locked, and by which lock (ADR-0162 D9). Two locks can hold +a record: a **closed state** (its object declares `closedStates` and the record +is in one of them, or it is a `master_detail` line of such a record) and an +**approval** (a pending request under a node that locks, or, on an object that +declares `closedStates`, an approval in passage). This is the one read for +both, owned by the data layer: it is there whether or not the approvals plugin +is installed, and without it only closed states lock. + +Every caller who can read the record is told, whether or not it may write the +record and whether or not field permissions let it read the state field. The +answer never carries which field or value closed the record, a request id, or +the approval's participants. + +| Field | Present | Meaning | +| :--- | :--- | :--- | +| `locked` | always | `true` when a caller's write of the record is refused by a lock. | +| `lockReason` | exactly when `locked` is `true` | `closed_state` or `approval`. When both hold, `closed_state`. | +| `lockSource` | exactly when `locked` is `true` | `record` (its own state or approval) or `master` (the master of a `master_detail` line). Within a reason, `master` wins. | + +`locked` describes a caller's write. A system context is bound by neither lock, +and the read does not describe it. The approvals-family read +(`GET /approvals/records/:object/:id/lock`) is a different read: it answers for +a pending request only, and stays as published. + +### `GET /data/:object/:id/lock` + +One record's lock (`RecordLockSchema`). A record the caller cannot read, or +that does not exist, answers the by-id read's `404 RECORD_NOT_FOUND`, told +apart by nothing. Takes no query parameter. + +```json +{ "success": true, "data": { "locked": true, "lockSource": "master", "lockReason": "closed_state" } } +``` + +### `POST /data/:object/locks` + +A page of records' locks. The body is `{ "recordIds": [...] }`, at least one +and at most 200 ids (`GetRecordLocksRequestSchema`); a longer list, an empty +one, or any other body key is refused whole with `400 VALIDATION_ERROR`, never +trimmed. Entry `i` answers `recordIds[i]`; a record the caller cannot read, or +that does not exist, answers `locked: null`. A row counts as readable only when +the caller's read hands back the row whose id is the asked id. Takes no query +parameter. + +```json +{ "success": true, "data": { "records": [ + { "recordId": "inv_1", "locked": true, "lockSource": "record", "lockReason": "approval" }, + { "recordId": "inv_2", "locked": false }, + { "recordId": "inv_9", "locked": null } +] } } +``` + +A deployment whose data engine has no lock read answers both doors +`501 NOT_IMPLEMENTED`, never "unlocked". + --- ## Analytics diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 4cfc2730098..72763246491 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -5,6 +5,8 @@ import { BatchUpdateRequest, BatchUpdateResponse, GetRecordFieldAccessResponse, + RecordLock, + GetRecordLocksResponse, RecordPageRequest, RecordPageResponse, // [#32200] The batch dataset-query answer `analytics.queryDatasetBatch` @@ -8662,6 +8664,40 @@ export class ObjectStackClient { return this.unwrapResponse(res); }, + /** + * [ADR-0162 D9] One record's lock — `GET /data/:object/:id/lock`, declared + * by `RecordLockSchema` (`@objectstack/spec/api`): `{ locked, lockSource?, + * lockReason? }`, the data layer's one lock read. `lockReason` is + * `closed_state` (a declared closed state) or `approval` (an approval holds + * it); `lockSource` is `record` or `master` (the master of a + * `master_detail` line). Both are present exactly when `locked` is true. + * Answered to every caller who can read the record; a record that is absent + * or that the caller cannot read rejects with the record read's 404. + */ + getRecordLock: async (object: string, id: string): Promise => { + const route = this.getRoute('data'); + const res = await this.fetch( + `${this.baseUrl}${route}/${encodeURIComponent(object)}/${encodeURIComponent(id)}/lock`, + ); + return this.unwrapResponse(res); + }, + + /** + * [ADR-0162 D9] A page of records' locks — `POST /data/:object/locks`, + * declared by `GetRecordLocksRequestSchema` / `GetRecordLocksResponseSchema`: + * entry `i` answers `recordIds[i]`, `locked: null` for a record the caller + * cannot read or that does not exist. At most `RECORD_LOCKS_MAX_RECORD_IDS` + * (200) ids per call; a longer list is refused whole with a 400. + */ + getRecordLocks: async (object: string, recordIds: string[]): Promise => { + const route = this.getRoute('data'); + const res = await this.fetch( + `${this.baseUrl}${route}/${encodeURIComponent(object)}/locks`, + { method: 'POST', body: JSON.stringify({ recordIds }) }, + ); + return this.unwrapResponse(res); + }, + /** * [#27627] The record page payload — `POST /data/:object/:id/page`, * declared by `RecordPageRequestSchema` / `RecordPageResponseSchema` @@ -9651,6 +9687,10 @@ export type { GetObjectPermissionsResponse, GetEffectivePermissionsResponse, GetRecordFieldAccessResponse, + RecordLock, + GetRecordLocksRequest, + GetRecordLocksResponse, + RecordLockEntry, RecordPageRequest, RecordPageResponse, RealtimeConnectRequest, diff --git a/packages/metadata-protocol/src/host-engine.ts b/packages/metadata-protocol/src/host-engine.ts index d83f631a095..228f319d2d4 100644 --- a/packages/metadata-protocol/src/host-engine.ts +++ b/packages/metadata-protocol/src/host-engine.ts @@ -1,6 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import type { IDataEngine, IObjectQLEngine } from '@objectstack/core'; +import type { RecordLock } from '@objectstack/spec/api'; import type { StoredExpressionFillCapture } from './protocol-stored-expression-fill.js'; import type { PublishedColumnChanges } from './protocol-registry-hydration.js'; @@ -75,5 +76,15 @@ export interface MetadataHostEngine extends IDataEngine { deferSummaryRecompute?: IObjectQLEngine['deferSummaryRecompute']; // Protocol accesses additional engine members structurally; keep it permissive // for this relocation (behavior unchanged — the concrete engine is injected). + /** + * [ADR-0162 D9] The one lock read the data layer owns (`@objectstack/objectql` + * `ObjectQL#getRecordLock`), as the caller in `options.context`. Declared + * explicitly for the reason `transaction` is; optional because a host may be a + * test double or a metadata-only store, and degrading means the data door + * answers `501`, never "unlocked". + */ + getRecordLock?(object: string, recordId: string, options?: { context?: any }): Promise; + /** [ADR-0162 D9] The page form of {@link getRecordLock}: entry `i` answers `recordIds[i]`. */ + getRecordLocks?(object: string, recordIds: readonly string[], options?: { context?: any }): Promise>; [key: string]: any; } diff --git a/packages/metadata-protocol/src/protocol-record-lock.ts b/packages/metadata-protocol/src/protocol-record-lock.ts new file mode 100644 index 00000000000..bb8e13d3931 --- /dev/null +++ b/packages/metadata-protocol/src/protocol-record-lock.ts @@ -0,0 +1,46 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9] The data protocol's two doors onto the one lock read the data + * layer owns (`ObjectQL#getRecordLock` / `ObjectQL#getRecordLocks`, + * `@objectstack/objectql` `record-lock-read.ts`): `getRecordLock` for one + * record, `getRecordLocks` for a page. + * + * Thin by design. The object-existence gate every data entry point asks + * (#3770) runs first, so an unknown object fails here as it fails on a read; + * then the engine answers, as the caller. Readability, the producers and the + * answer's shape are the engine's, not this door's: a door that re-judged any + * of them would be a second read. + * + * An engine without the read (a test double, a metadata-only store) is + * answered `undefined`, which the REST door turns into `501 NOT_IMPLEMENTED`: + * a lock read that cannot be asked must not answer "unlocked". + */ + +import type { RecordLock } from '@objectstack/spec/api'; +import type { ProtocolHost } from './protocol-host.js'; + +/** One record's lock, as the caller; `null` unreadable or missing; `undefined` when the engine has no read. */ +export async function getRecordLock( + host: Pick, + request: { object: string; id: string; context?: any }, +): Promise { + host.assertObjectRegistered(request.object); + const engine = host.engine; + if (typeof engine?.getRecordLock !== 'function') return undefined; + return engine.getRecordLock(request.object, request.id, { context: request.context }); +} + +/** + * A page of records' locks, as the caller: entry `i` answers `recordIds[i]`. + * `undefined` when the engine has no read. The bound is the engine's. + */ +export async function getRecordLocks( + host: Pick, + request: { object: string; recordIds: readonly string[]; context?: any }, +): Promise | undefined> { + host.assertObjectRegistered(request.object); + const engine = host.engine; + if (typeof engine?.getRecordLocks !== 'function') return undefined; + return engine.getRecordLocks(request.object, request.recordIds, { context: request.context }); +} diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 79f0302b0a8..df5e3d589cd 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -624,6 +624,8 @@ import { ProtocolPackageCommitsFacet } from './protocol-package-commits.js'; import { ProtocolPackageMoveInFacet, type MoveIntoPackageRequest } from './protocol-package-move-in.js'; // [#29985 codemod] Diff, deleteMetaItem, loadMetaFromDb, load reports, findReferencesToMeta: the members below delegate to its facet, `ProtocolDiffDeleteLoadFacet`. import { ProtocolDiffDeleteLoadFacet } from './protocol-diff-delete-load.js'; +import { getRecordLock as getRecordLockFacet, getRecordLocks as getRecordLocksFacet } from './protocol-record-lock.js'; +import type { RecordLock } from '@objectstack/spec/api'; /** * [#4435/#5138] The 404 a single-record operation answers when the id names no @@ -5196,6 +5198,23 @@ export class ObjectStackProtocolImplementation implements return ProtocolDataCrudFacet.getData(protocolHost(this), request); } + /** + * [ADR-0162 D9] One record's lock, as the caller: the data layer's one lock + * read (`protocol-record-lock.ts`). `null` when the caller cannot read the + * record or it does not exist; `undefined` when the engine has no read. + */ + async getRecordLock(request: { object: string, id: string, context?: any }): Promise { + return getRecordLockFacet(protocolHost(this), request); + } + + /** + * [ADR-0162 D9] A page of records' locks, as the caller: entry `i` answers + * `recordIds[i]` (`protocol-record-lock.ts`). + */ + async getRecordLocks(request: { object: string, recordIds: readonly string[], context?: any }): Promise | undefined> { + return getRecordLocksFacet(protocolHost(this), request); + } + /** * Validate-only (commit 18189983d — #4633 ruling D): report the write path's verdict * on candidate rows without persisting any of them. diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 772abcaa7a0..0529ba5c20a 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -283,6 +283,9 @@ import { validate } from './engine-validate.js'; // [#32768] The write-free `readonlyWhen` judgement's body; `judgeFieldWriteLock` // below hands it the members it reads (`FieldWriteLockHost`). import { judgeFieldWriteLock, type FieldWriteLock } from './engine-field-write-lock.js'; +// [ADR-0162 D9] The one lock read's body; `getRecordLock` / `getRecordLocks` below hand it a host. +import { getRecordLock as getRecordLockBody, getRecordLocks as getRecordLocksBody, type RecordLockReadHost } from './record-lock-read.js'; +import type { RecordLock } from '@objectstack/spec/api'; // [#25522 cut 20] The `where`-lowering bodies (`QueryLoweringHost`), imported // after every module they import, so module evaluation order is unchanged. import { lowerRelationConditions, resolveSearchQueryableFields, resolveWhereTokens } from './engine-query-lowering.js'; @@ -4719,6 +4722,39 @@ export class ObjectQL implements IObjectQLEngine { return judgeFieldWriteLock.call(host, object, id, field, options); } + /** + * [ADR-0162 D9] The one lock read for one record, as the caller: + * `{ locked, lockSource?, lockReason? }`, both kinds present exactly when + * `locked` is true, composed from the closed-state judgement and the + * approvals producer when one is bound; `null` when the caller cannot read + * the record or it does not exist. See `record-lock-read.ts`. + */ + getRecordLock(object: string, recordId: string, options?: { context?: ExecutionContext }): Promise { + return getRecordLockBody.call(this.recordLockReadHost(), object, recordId, options?.context); + } + + /** + * [ADR-0162 D9] {@link getRecordLock} for a page of records (at most + * `RECORD_LOCKS_MAX_RECORD_IDS`): entry `i` answers `recordIds[i]`. A row + * counts as readable only when the caller's read hands back the row whose + * id IS the asked id. See `record-lock-read.ts`. + */ + getRecordLocks(object: string, recordIds: readonly string[], options?: { context?: ExecutionContext }): Promise> { + return getRecordLocksBody.call(this.recordLockReadHost(), object, recordIds, options?.context); + } + + private recordLockReadHost(): RecordLockReadHost { + const readRegistry = () => this._registry; + return { + get _registry() { return readRegistry(); }, + resolveObjectName: (...a) => this.resolveObjectName(...a), + getDriver: (...a) => this.getDriver(...a), + buildDriverOptions: (...a) => this.buildDriverOptions(...a), + find: (object, query) => this.find(object, query as EngineQueryOptions), + facade: this, + }; + } + private updateByIdExpecting( driver: IDataDriver, object: string, diff --git a/packages/objectql/src/record-lock-read.ts b/packages/objectql/src/record-lock-read.ts new file mode 100644 index 00000000000..148097b93b1 --- /dev/null +++ b/packages/objectql/src/record-lock-read.ts @@ -0,0 +1,259 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9] The one lock read, owned by the data layer: the body of + * `ObjectQL#getRecordLock` and `ObjectQL#getRecordLocks`. + * + * ## The answer + * + * For each record the caller can read, `{ locked, lockSource?, lockReason? }`, + * with `lockSource` and `lockReason` present exactly when `locked` is true + * (`RecordLockSchema`, `@objectstack/spec/api`); `null` for a record the caller + * cannot read or that does not exist, told apart by nothing. + * + * ## Two producers, composed here + * + * - **Closed states** ({@link closedStateLocks}): the engine's own judgement + * (`closed-state-lock.ts`). A record is closed when its stored state is one + * of its object's `closedStates`; a `master_detail` line is held while a + * master it hangs under is closed. Read by the engine itself, straight from + * the store: above the caller's grants (field permissions on the state field + * included, D9) and inside the caller's organization scope. + * - **Approvals**: the approvals plugin's judgement, through the internal seam + * {@link APPROVAL_RECORD_LOCK_PRODUCER}. Absent (no approvals plugin, or one + * that binds no lock), only closed states lock: the read exists without it. + * A third producer is a new decision, not a registration. + * + * One answer when several hold: `closed_state` before `approval`; within a + * reason, `master` before `record`. + * + * ## Who is answered + * + * Readability is read AS THE CALLER, the anchor of each form's approvals-family + * counterpart (D9; seat ruling 7152650156 keeps the two apart): + * - one record: any row the caller's by-id read hands back counts, under + * whatever spelling of the id the engine hands back; the record is judged by + * the id the engine spells; + * - a page: a row counts only when the caller's `$in` read hands back the row + * whose id IS the asked id. + * A refusal of the read itself (no read on the object) is thrown, the same for + * every id. + * + * The read describes the lock as it binds a caller: a system context is bound + * by neither lock (D5), and the read does not answer for one. + * + * ## What it never carries + * + * Which field or value closed the record, a request id, or participants. + * + * ## Reads + * + * The caller's readability read; for an object that declares `closedStates`, + * one store read of the closed rows among the readable ids; for a line of such + * a master, one store read of the lines' foreign keys and one of the closed + * masters, per edge; then the approvals producer, when one is bound. An object + * that neither declares the key nor is a line of one that does reads nothing + * for closed states. A store read that fails is thrown, never read as open. + */ + +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import type { FilterCondition } from '@objectstack/spec/data'; +import { RECORD_LOCKS_MAX_RECORD_IDS, type RecordLock } from '@objectstack/spec/api'; +import { closedPredicate, closedStateUnitOf, type ClosedStateLockHost } from './closed-state-lock.js'; + +/** + * [ADR-0162 D9] The engine slot the approvals plugin fills with its producer + * (`@objectstack/plugin-approvals` `record-lock-producer.ts`), read at use and + * never cached. Internal to the two packages: not exported from this package's + * entry, and spelled there by the same `Symbol.for` key. `Symbol.for` because + * the package ships an ESM and a CJS build and a process may load both. + */ +export const APPROVAL_RECORD_LOCK_PRODUCER: unique symbol = Symbol.for('objectstack.objectql.approvalRecordLockProducer'); + +/** + * The approvals producer's answer for `recordIds` of `object` (each an id the + * engine spells, the caller able to read every one): the ids an approval holds, + * each with whose approval holds it. The source is REQUIRED: an id held with no + * known source is not an answer this seam can carry. An id absent from the map + * is not held by an approval. + */ +export type ApprovalRecordLockProducer = ( + object: string, + recordIds: readonly string[], +) => Promise>; + +/** The engine members the read uses. */ +export interface RecordLockReadHost extends Pick { + find(object: string, query: Record): Promise; + /** The engine itself, whose {@link APPROVAL_RECORD_LOCK_PRODUCER} slot is read at use. */ + readonly facade: object; +} + +/** The refusal of a page over {@link RECORD_LOCKS_MAX_RECORD_IDS}, or of a malformed id list. */ +function recordLocksRefusal(message: string): Error { + return Object.assign(new Error(message), { code: 'VALIDATION_ERROR', status: 400, statusCode: 400, httpStatus: 400 }); +} + +function idIn(ids: readonly string[]): FilterCondition { + return { id: ids.length === 1 ? ids[0] : { $in: [...ids] } } as FilterCondition; +} + +function andWhere(a: FilterCondition, b: FilterCondition): FilterCondition { + return { $and: [a, b] } as FilterCondition; +} + +/** A scalar foreign key, or `null`: an empty or non-scalar value names no one master. */ +function scalarId(value: unknown): string | null { + if (typeof value === 'string') return value === '' ? null : value; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return null; +} + +/** What the closed-state producer found among the readable ids. */ +interface ClosedStateLocks { + readonly own: ReadonlySet; + readonly master: ReadonlySet; +} + +/** + * [D9, D2, D3] The closed-state producer: which of `ids` (readable, as the + * engine spells them) are closed on their own state, and which are lines of a + * closed master. The engine's own reads, straight from the store, inside the + * caller's organization scope. + */ +async function closedStateLocks( + this: RecordLockReadHost, + object: string, + ids: readonly string[], + context: ExecutionContext | undefined, +): Promise { + const own = new Set(); + const master = new Set(); + const unit = closedStateUnitOf.call(this, object); + if (!unit || ids.length === 0) return { own, master }; + const driver = this.getDriver(object); + const opts = this.buildDriverOptions(object, context); + if (unit.own) { + const rows = (await driver.find( + object, + { object, where: andWhere(idIn(ids), closedPredicate(unit.own)), fields: ['id'], limit: ids.length }, + opts, + )) as Array> | null; + for (const row of rows ?? []) if (row && row.id != null) own.add(String(row.id)); + } + if (unit.masters.length > 0) { + const fks = [...new Set(unit.masters.map((e) => e.fk))]; + const lines = ((await driver.find( + object, + { object, where: idIn(ids), fields: ['id', ...fks], limit: ids.length }, + opts, + )) as Array> | null ?? []).filter((r) => r && r.id != null); + for (const edge of unit.masters) { + const masterIds = [...new Set(lines.map((r) => scalarId(r[edge.fk])).filter((v): v is string => v !== null))]; + if (masterIds.length === 0) continue; + const closed = (await this.getDriver(edge.master).find( + edge.master, + { object: edge.master, where: andWhere(idIn(masterIds), closedPredicate(edge.closed)), fields: ['id'], limit: masterIds.length }, + this.buildDriverOptions(edge.master, context), + )) as Array> | null; + const closedIds = new Set((closed ?? []).filter((r) => r && r.id != null).map((r) => String(r.id))); + if (closedIds.size === 0) continue; + for (const line of lines) { + const fk = scalarId(line[edge.fk]); + if (fk !== null && closedIds.has(fk)) master.add(String(line.id)); + } + } + } + return { own, master }; +} + +/** The approvals producer bound on the engine, or `undefined`. */ +function approvalProducerOf(facade: object): ApprovalRecordLockProducer | undefined { + const slot = (facade as Record)[APPROVAL_RECORD_LOCK_PRODUCER]; + return typeof slot === 'function' ? (slot as ApprovalRecordLockProducer) : undefined; +} + +/** [D9] One answer for one readable record, the reasons ordered as D9 orders them. */ +function composeAnswer(id: string, closed: ClosedStateLocks, approval: ReadonlyMap): RecordLock { + if (closed.master.has(id)) return { locked: true, lockSource: 'master', lockReason: 'closed_state' }; + if (closed.own.has(id)) return { locked: true, lockSource: 'record', lockReason: 'closed_state' }; + const held = approval.get(id); + if (held === 'master' || held === 'record') return { locked: true, lockSource: held, lockReason: 'approval' }; + return { locked: false }; +} + +/** Both producers' judgement for `ids` (readable, as the engine spells them). */ +async function judge( + this: RecordLockReadHost, + object: string, + ids: readonly string[], + context: ExecutionContext | undefined, +): Promise> { + const out = new Map(); + if (ids.length === 0) return out; + const closed = await closedStateLocks.call(this, object, ids, context); + const producer = approvalProducerOf(this.facade); + const approval = producer ? await producer(object, ids) : new Map(); + for (const id of ids) out.set(id, composeAnswer(id, closed, approval)); + return out; +} + +function registryName(host: Pick, object: string): string { + try { + return host.resolveObjectName(object); + } catch { + return object; + } +} + +/** + * [D9] The lock of one record, as the caller: `null` when the caller cannot + * read it or it does not exist. + */ +export async function getRecordLock( + this: RecordLockReadHost, + object: string, + recordId: string, + context: ExecutionContext | undefined, +): Promise { + const name = String(object ?? '').trim(); + const id = String(recordId ?? '').trim(); + if (!name || !id) return null; + // The anchor, as the CALLER: any row the by-id read hands back counts. + const rows = await this.find(name, { where: { id }, fields: ['id'], limit: 1, context }); + const found = Array.isArray(rows) ? rows[0] : undefined; + if (!found || found.id == null) return null; + const spelled = String(found.id); + const answers = await judge.call(this, registryName(this, name), [spelled], context); + return answers.get(spelled) ?? { locked: false }; +} + +/** + * [D9] The lock of each of a page of records, as the caller: entry `i` answers + * `recordIds[i]`, `null` for a record the caller cannot read or that does not + * exist. At most {@link RECORD_LOCKS_MAX_RECORD_IDS} ids, else refused whole + * (`400 VALIDATION_ERROR`); a blank id answers `null`. + */ +export async function getRecordLocks( + this: RecordLockReadHost, + object: string, + recordIds: readonly string[], + context: ExecutionContext | undefined, +): Promise> { + if (!Array.isArray(recordIds)) throw recordLocksRefusal('The page lock read takes a list of record ids.'); + if (recordIds.length > RECORD_LOCKS_MAX_RECORD_IDS) { + throw recordLocksRefusal( + `The page lock read carries ${recordIds.length} ids; one read carries at most ${RECORD_LOCKS_MAX_RECORD_IDS}. Nothing was read.`, + ); + } + const name = String(object ?? '').trim(); + const ids = recordIds.map((recordId) => String(recordId ?? '').trim()); + const asked = [...new Set(ids.filter((id) => id !== ''))]; + if (!name || asked.length === 0) return ids.map(() => null); + // The anchor, as the CALLER: a row counts only when its id IS the asked id. + const rows = await this.find(name, { where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context }); + const readable = new Set((Array.isArray(rows) ? rows : []).filter((r) => r && r.id != null).map((r) => String(r.id))); + const readableAsked = asked.filter((id) => readable.has(id)); + const answers = await judge.call(this, registryName(this, name), readableAsked, context); + return ids.map((id) => (readable.has(id) ? answers.get(id) ?? { locked: false } : null)); +} diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 0995a3117aa..a90e100093b 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -35,6 +35,7 @@ import { bindRecordDeleteCancelHook, unbindAllHooks, } from './lifecycle-hooks.js'; +import { bindRecordLockProducer, unbindRecordLockProducer } from './record-lock-producer.js'; import { bindSnapshotRedactionMiddleware } from './payload-redaction-middleware.js'; import { bindSnapshotPredicateGuard } from './payload-predicate-guard.js'; import { bindRequestChildReadGates, bindRequestReadGate } from './request-read-gate.js'; @@ -415,6 +416,7 @@ export class ApprovalsServicePlugin implements Plugin { if (!this.options.disableAutoHooks) { try { unbindAllHooks(engine); + unbindRecordLockProducer(engine); // [#23618] The refusal's title is narrowed by the writer's served fields, // through the same lazily-resolved authority the snapshot redaction reads. // …and it is worded in the writer's locale, with the object's label in @@ -423,6 +425,10 @@ export class ApprovalsServicePlugin implements Plugin { // Ruling A on the record-page edit card: a locked master's detail rows // refuse insert / update / delete as well. bindDetailRowLockHook(engine, ctx.logger, i18nService); + // [ADR-0162 D9] The data layer's one lock read asks this plugin which + // records an approval holds, through the engine's internal producer + // slot: bound beside the two locks it describes, cleared with them. + bindRecordLockProducer(engine); bindRecordDeleteCancelHook(engine, this.service, ctx.logger); bindDelegationWriteGuard(engine, ctx.logger); // [#10749] Generic-door snapshot redaction. Registered here so the @@ -786,6 +792,7 @@ export class ApprovalsServicePlugin implements Plugin { } if (this.engine) { try { unbindAllHooks(this.engine); } catch { /* ignore */ } + try { unbindRecordLockProducer(this.engine); } catch { /* ignore */ } } } diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index 505b352c4af..74d808af27c 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -731,7 +731,7 @@ function declaresClosedStates(engine: Pick, objectNa * for `null`), where the object declares `closedStates`. A read that fails * answers none, like {@link pendingRequestsForRecords}. */ -async function passageRequestsFor( +export async function passageRequestsFor( engine: Pick, objectName: string, recordIds: ReadonlyArray | null, @@ -789,7 +789,7 @@ function writesAsApprovalRun(marked: any, writer: WriterRuns): boolean { * approval was not abandoned. A read that fails holds: a mark is known to * stand. */ -async function approvalInPassage(engine: Pick, marked: any): Promise { +export async function approvalInPassage(engine: Pick, marked: any): Promise { if (!carriesMark(marked) || snapshotAbandoned(marked)) return false; if (!marked?.root_run_id) return true; let rows: any[]; @@ -1096,7 +1096,7 @@ interface MasterEdge { * gives — a raw `registerObject` skips Zod, and an unread spelling here would * be a lock that silently does not apply. */ -function masterEdgesOf(engine: Pick, objectName: string): MasterEdge[] { +export function masterEdgesOf(engine: Pick, objectName: string): MasterEdge[] { let schema: any; try { schema = engine.getSchema?.(objectName); } catch { return []; } const fields = schema?.fields; @@ -1166,7 +1166,7 @@ function inOpenUnit(engine: Pick, handle: u } /** A scalar foreign-key value, or `null` for an empty or non-scalar one. */ -function scalarFk(value: unknown): string | null { +export function scalarFk(value: unknown): string | null { if (typeof value === 'string') return value ? value : null; if (typeof value === 'number' && Number.isFinite(value)) return String(value); return null; diff --git a/packages/plugins/plugin-approvals/src/record-lock-producer.ts b/packages/plugins/plugin-approvals/src/record-lock-producer.ts new file mode 100644 index 00000000000..445c9889238 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/record-lock-producer.ts @@ -0,0 +1,163 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9] The approvals plugin's producer for the one lock read the data + * layer owns (`@objectstack/objectql` `record-lock-read.ts`). + * + * The engine composes two producers: its own closed-state judgement and this + * one. This one answers which records an approval holds, and whose approval + * holds each, through an internal seam: the engine slot named by the + * `Symbol.for` key below, filled when the record lock is bound and cleared with + * it. Nothing here is a contract member, and no other package fills the slot. + * + * ## What it answers + * + * A record is held by an approval, for this read, where a caller's write of it + * is refused by the approvals plugin's lock hooks for a reason that belongs to + * the record and not to the write: + * + * - a pending request on it under a node whose `lockRecord` is not `false` + * (the record lock's judgement, `recordsHeldByLockingApproval`); and + * - on an object that declares `closedStates`, a passage of an approval: a + * decided request carrying the mark, which is still the approval's latest + * on the record and whose approval was not abandoned (the hold of ADR-0162 + * D5, `approvalInPassage`). A passage does not ask the node's `lockRecord`. + * + * Its lines are held with it (`'master'`, which wins when both hold): a + * `master_detail` line whose master is so held, judged by the detail-row lock's + * reads. The hold lets go where D9 says it does: in the revise window of a + * returned request, and while a request is pending under a node that declares + * `lockRecord: false` (neither is pending-locking, and neither is a passage: + * the newer request is not marked). + * + * What belongs to a write is left out: the approval's own runs, a write that + * carries only the mirror field, and a system context are passes of the lock + * hooks, not properties of the record. + * + * The approvals-family read (`IApprovalService.getRecordLock` / + * `getRecordLocks`) is not this one and is not touched: it answers for a + * pending request only, as published. + * + * ⚠️ It answers for the records, not for a caller, and reads the bookkeeping + * as SYSTEM. Whether the asker may learn the answer is the data layer's + * question, settled before the producer is asked: every id it is handed is one + * the caller can read. + */ + +import { + approvalInPassage, + detailRowsHeldByLockingApproval, + masterEdgesOf, + passageRequestsFor, + recordsHeldByLockingApproval, + scalarFk, +} from './lifecycle-hooks.js'; + +/** The approvals plugin's own bookkeeping reads run as SYSTEM, as the lock hooks' do. */ +const SYSTEM_CTX = { isSystem: true, positions: [] as string[], permissions: [] as string[] }; + +/** + * The engine slot the data layer reads its approvals producer from — the key + * `@objectstack/objectql` names `APPROVAL_RECORD_LOCK_PRODUCER`, spelled here + * by the same `Symbol.for` key so neither package imports the other. + */ +export const APPROVAL_RECORD_LOCK_PRODUCER_SLOT: unique symbol = Symbol.for('objectstack.objectql.approvalRecordLockProducer'); + +/** The engine surface the producer reads. */ +type ProducerEngine = Parameters[0]; + +/** The ids among `recordIds` of `objectName` held in a passage of an approval. */ +async function recordsHeldInPassage( + engine: ProducerEngine, + objectName: string, + recordIds: readonly string[], +): Promise> { + const held = new Set(); + if (recordIds.length === 0) return held; + for (const marked of await passageRequestsFor(engine, objectName, recordIds)) { + const recordId = String(marked?.record_id ?? ''); + if (!recordId || held.has(recordId)) continue; + if (await approvalInPassage(engine, marked)) held.add(recordId); + } + return held; +} + +/** + * The ids among `recordIds` that are `master_detail` lines of a master held in + * a passage: one SYSTEM read of the lines' foreign keys, then the passage + * judgement per edge over the masters they name. + */ +async function detailRowsHeldInPassage( + engine: ProducerEngine, + objectName: string, + recordIds: readonly string[], +): Promise> { + const held = new Set(); + if (recordIds.length === 0) return held; + const edges = masterEdgesOf(engine, objectName); + if (edges.length === 0) return held; + const rows = await engine.find(objectName, { + where: recordIds.length === 1 ? { id: recordIds[0] } : { id: { $in: [...recordIds] } }, + fields: ['id', ...edges.map((e) => e.fk)], + limit: recordIds.length, + context: { ...SYSTEM_CTX, positions: [], permissions: [] }, + }); + const found = (Array.isArray(rows) ? rows : []) as Array>; + for (const e of edges) { + const masterIds = [...new Set(found.map((row) => scalarFk(row[e.fk])).filter((id): id is string => id !== null))]; + if (masterIds.length === 0) continue; + const heldMasters = await recordsHeldInPassage(engine, e.master, masterIds); + if (heldMasters.size === 0) continue; + for (const row of found) { + const masterId = scalarFk(row[e.fk]); + if (masterId && heldMasters.has(masterId)) held.add(String(row.id)); + } + } + return held; +} + +/** + * [D9] Which of `recordIds` of `objectName` an approval holds, and whose + * approval holds each: `'master'` for a line of a held master (it wins), else + * `'record'`. An id absent from the answer is not held by an approval. + */ +export async function approvalRecordLocks( + engine: ProducerEngine, + objectName: string, + recordIds: readonly string[], +): Promise> { + const out = new Map(); + const ids = [...new Set(recordIds.map(String).filter((id) => id !== ''))]; + if (ids.length === 0) return out; + const [ownPending, ownPassage, linePending, linePassage] = await Promise.all([ + recordsHeldByLockingApproval(engine, objectName, ids), + recordsHeldInPassage(engine, objectName, ids), + detailRowsHeldByLockingApproval(engine, objectName, ids), + detailRowsHeldInPassage(engine, objectName, ids), + ]); + for (const id of ids) { + if (linePending.has(id) || linePassage.has(id)) out.set(id, 'master'); + else if (ownPending.has(id) || ownPassage.has(id)) out.set(id, 'record'); + } + return out; +} + +/** + * Fill the engine's producer slot. Bound beside the record lock and the + * detail-row lock it mirrors: a composition that binds no lock answers no + * approval lock either. + */ +export function bindRecordLockProducer(engine: ProducerEngine): void { + const producer = (object: string, recordIds: readonly string[]) => approvalRecordLocks(engine, object, recordIds); + Object.defineProperty(engine, APPROVAL_RECORD_LOCK_PRODUCER_SLOT, { + value: producer, configurable: true, enumerable: false, writable: true, + }); +} + +/** Clear the engine's producer slot, beside unbinding the lock hooks. */ +export function unbindRecordLockProducer(engine: object | undefined | null): void { + if (!engine || typeof engine !== 'object') return; + if (Object.prototype.hasOwnProperty.call(engine, APPROVAL_RECORD_LOCK_PRODUCER_SLOT)) { + delete (engine as Record)[APPROVAL_RECORD_LOCK_PRODUCER_SLOT]; + } +} diff --git a/packages/rest/src/data-action-routes.ts b/packages/rest/src/data-action-routes.ts index d68649cbc8c..db5d8781003 100644 --- a/packages/rest/src/data-action-routes.ts +++ b/packages/rest/src/data-action-routes.ts @@ -100,6 +100,8 @@ import { type RestServer, } from './rest-server.js'; import { earnedWriteDespiteStaleSummary } from './stale-summary-answer.js'; +// [ADR-0162 D9] The data family's lock doors live in their own module (this one is over 1,000 lines). +import { registerRecordLockEndpoints } from './record-lock-routes.js'; // [#23050 slice 1] Moved here from `rest-server.ts`, verbatim, because this module is // the first one outside that file to need it: exporting it from there changed the @@ -552,6 +554,10 @@ export function registerDataActionEndpoints(this: DataActionRouteHost, basePath: }, }); + // [ADR-0162 D9] GET /data/:object/:id/lock and POST /data/:object/locks — + // the one lock read the data layer owns (`record-lock-routes.ts`). + registerRecordLockEndpoints.call(this, basePath); + // GET /data/:object/:id/field-access — the field projection of ONE record // (`GetRecordFieldAccessResponseSchema`): the fields the caller may read, // and the fields it may write on this stored row as the write gate judges diff --git a/packages/rest/src/record-lock-routes.ts b/packages/rest/src/record-lock-routes.ts new file mode 100644 index 00000000000..d93ff87f9b1 --- /dev/null +++ b/packages/rest/src/record-lock-routes.ts @@ -0,0 +1,209 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9] The data family's two doors onto the one lock read the data + * layer owns: + * + * - `GET {basePath}/data/:object/:id/lock` — one record's lock + * (`RecordLockSchema`, `@objectstack/spec/api`); + * - `POST {basePath}/data/:object/locks` — a page of records' locks, body + * `{ recordIds }` (`GetRecordLocksRequestSchema` → `GetRecordLocksResponseSchema`). + * + * Each answers `{ locked, lockSource?, lockReason? }` for a record the caller + * can read: the engine's closed-state judgement and, where the approvals plugin + * binds its lock, the approvals judgement, composed by the engine + * (`@objectstack/objectql` `record-lock-read.ts`). Neither door judges anything + * itself: readability, the producers and the order between them are the + * engine's, reached through the data protocol (`getRecordLock` / + * `getRecordLocks`, `@objectstack/metadata-protocol`). + * + * - **No row.** One record the caller cannot read, or that does not exist, + * answers the by-id read's own `404 RECORD_NOT_FOUND` (localized, so the + * answer says it varies by `Accept-Language`); in a page, that entry answers + * `locked: null`, told apart by nothing. + * - **No read.** A protocol or engine without the read answers + * `501 NOT_IMPLEMENTED`, never "unlocked". + * - **Closed query strings.** Neither door reads `req.query`: any name is + * refused with the located 400, never dropped. + * + * The approvals-family doors (`/approvals/records/:object/:id/lock`, + * `/approvals/records/:object/locks`) are a different read and stay as they + * are (`approvals-routes.ts`). + * + * A new module rather than more of `data-action-routes.ts` (over 1,000 lines): + * registered from there, so `rest-server.ts` does not move. + */ + +import { RECORD_LOCKS_MAX_RECORD_IDS, type RecordLock } from '@objectstack/spec/api'; +import { recordNotFoundError } from '@objectstack/core'; +import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; +import { refuseUnknownQueryParams } from './query-allowlist.js'; +import { logUnexpectedRouteError, mapDataError } from './error-response.js'; +import type { DataActionRouteHost } from './data-action-routes.js'; + +/** + * The closed query-parameter set of `GET {basePath}/data/:object/:id/lock`: + * EMPTY. **Measured**: the object and the record are path parameters and the + * caller comes from the session; nothing is read from the query string. + */ +export const RECORD_LOCK_PARAMS: readonly string[] = []; + +/** + * The closed query-parameter set of `POST {basePath}/data/:object/locks`: + * EMPTY. **Measured**: the object is the path, the ids are the body. + */ +export const RECORD_LOCKS_PARAMS: readonly string[] = []; + +/** The body keys `POST {basePath}/data/:object/locks` reads: `recordIds` alone. */ +const RECORD_LOCKS_BODY_KEYS: readonly string[] = ['recordIds']; + +/** The data protocol's lock read, feature-detected: `RestProtocol` does not declare it. */ +interface RecordLockProtocol { + getRecordLock?(request: { object: string; id: string; environmentId?: string; context?: unknown }): Promise; + getRecordLocks?(request: { object: string; recordIds: readonly string[]; environmentId?: string; context?: unknown }): Promise | undefined>; +} + +/** The `RestServer` members these doors read. */ +export type RecordLockRouteHost = Pick< + DataActionRouteHost, + 'config' | 'routeManager' | 'resolveProtocol' | 'resolveExecCtx' | 'enforceAuth' | 'enforceApiAccess' +>; + +/** + * Read the body of `POST {basePath}/data/:object/locks`: the ids, or the + * sentence that refuses the request. Every shape is refused whole, never + * trimmed: a body key the door does not read, a `recordIds` that is not a list + * of non-empty strings, an empty list and one over + * {@link RECORD_LOCKS_MAX_RECORD_IDS}. + */ +export function readDataRecordLocksBody(body: unknown): { recordIds: string[] } | { refusal: string } { + if (body === null || typeof body !== 'object' || Array.isArray(body)) { + return { refusal: 'The request body must be a JSON object of the form {"recordIds": ["", ...]}.' }; + } + const unknown = Object.keys(body).filter((key) => !RECORD_LOCKS_BODY_KEYS.includes(key)); + if (unknown.length > 0) { + return { + refusal: `Unknown body field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `"${key}"`).join(', ')}: ` + + 'this request reads "recordIds" alone. Nothing was read.', + }; + } + const ids = (body as { recordIds?: unknown }).recordIds; + if (!Array.isArray(ids) || ids.some((id) => typeof id !== 'string' || id.trim() === '')) { + return { refusal: '"recordIds" must be a list of record ids, each a non-empty string.' }; + } + if (ids.length === 0) { + return { refusal: '"recordIds" names no record; send at least one id.' }; + } + if (ids.length > RECORD_LOCKS_MAX_RECORD_IDS) { + return { + refusal: `"recordIds" carries ${ids.length} ids; one request carries at most ` + + `${RECORD_LOCKS_MAX_RECORD_IDS}. Send the rest in another request. Nothing was read.`, + }; + } + return { recordIds: (ids as string[]).map((id) => id.trim()) }; +} + +/** + * What the doors serve of one answer: built field by field, so nothing the + * engine might add (a field, a value, a request id) is ever served. + */ +export function recordLockAnswer(lock: RecordLock): RecordLock { + if (lock.locked !== true) return { locked: false }; + return { locked: true, lockSource: lock.lockSource, lockReason: lock.lockReason }; +} + +function notImplemented(res: any): void { + sendEnvelopeError( + res, 501, 'NOT_IMPLEMENTED', + 'The record lock read is not available on this deployment (its data engine has no getRecordLock / getRecordLocks).', + ); +} + +/** Register both doors under `basePath`. Called from `registerDataActionEndpoints`. */ +export function registerRecordLockEndpoints(this: RecordLockRouteHost, basePath: string): void { + const isScoped = basePath.includes('/environments/:environmentId'); + const dataPath = `${basePath}${this.config.crud.dataPrefix}`; + + this.routeManager.register({ + method: 'GET', + path: `${dataPath}/:object/:id/lock`, + handler: async (req: any, res: any) => { + try { + const environmentId = isScoped ? req.params?.environmentId : undefined; + const p = await this.resolveProtocol(environmentId, req); + const context = await this.resolveExecCtx(environmentId, req); + if (this.enforceAuth(req, res, context)) return; + if (await this.enforceApiAccess(req, res, p, environmentId, 'get', context)) return; + if (refuseUnknownQueryParams(req, res, RECORD_LOCK_PARAMS)) return; + const read = (p as RecordLockProtocol).getRecordLock; + if (typeof read !== 'function') return notImplemented(res); + const object = String(req.params.object); + const id = String(req.params.id); + const lock = await read.call(p, { + object, + id, + ...(environmentId ? { environmentId } : {}), + ...(context ? { context } : {}), + }); + if (lock === undefined) return notImplemented(res); + // Unreadable or missing: the by-id read's own no-row answer. + if (lock === null) throw recordNotFoundError(object, id, context); + sendOk(res, recordLockAnswer(lock)); + } catch (error: any) { + const mapped = mapDataError(error, req.params?.object); + logUnexpectedRouteError(error, mapped); + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); + res.status(mapped.status).json(mapped.body); + } + }, + metadata: { + summary: 'Whether a record is locked, and by which lock (closed state or approval)', + tags: ['data', 'lock'], + }, + }); + + this.routeManager.register({ + method: 'POST', + path: `${dataPath}/:object/locks`, + handler: async (req: any, res: any) => { + try { + const environmentId = isScoped ? req.params?.environmentId : undefined; + const p = await this.resolveProtocol(environmentId, req); + const context = await this.resolveExecCtx(environmentId, req); + if (this.enforceAuth(req, res, context)) return; + if (await this.enforceApiAccess(req, res, p, environmentId, 'list', context)) return; + if (refuseUnknownQueryParams(req, res, RECORD_LOCKS_PARAMS)) return; + const body = readDataRecordLocksBody(req.body); + if ('refusal' in body) { + sendEnvelopeError(res, 400, 'VALIDATION_ERROR', body.refusal); + return; + } + const read = (p as RecordLockProtocol).getRecordLocks; + if (typeof read !== 'function') return notImplemented(res); + const object = String(req.params.object); + const answers = await read.call(p, { + object, + recordIds: body.recordIds, + ...(environmentId ? { environmentId } : {}), + ...(context ? { context } : {}), + }); + if (answers === undefined) return notImplemented(res); + sendOk(res, { + records: body.recordIds.map((recordId, index) => { + const answer = answers[index]; + return answer ? { recordId, ...recordLockAnswer(answer) } : { recordId, locked: null }; + }), + }); + } catch (error: any) { + const mapped = mapDataError(error, req.params?.object); + logUnexpectedRouteError(error, mapped); + if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); + res.status(mapped.status).json(mapped.body); + } + }, + metadata: { + summary: 'Whether each of a page of records is locked, and by which lock', + tags: ['data', 'lock'], + }, + }); +} diff --git a/packages/rest/src/rest-route-ledger.ts b/packages/rest/src/rest-route-ledger.ts index 80516219a99..f1329e83fa6 100644 --- a/packages/rest/src/rest-route-ledger.ts +++ b/packages/rest/src/rest-route-ledger.ts @@ -393,6 +393,13 @@ export const REST_ROUTE_LEDGER: readonly RestRouteLedgerEntry[] = [ { route: 'GET /api/v1/data/:object/:id/field-access', family: 'data-actions', source: 'route-manager', disposition: 'sdk', client: 'data.fieldAccess', responseSchema: 'GetRecordFieldAccessResponseSchema', note: 'The field projection of ONE record, for its edit form: `editable` is the write gate\'s own verdict (SecurityPlugin computeForbiddenFieldWrites) on an update of the stored row, so a row-conditioned field permission (`when`) locks only the rows it names; `/auth/me/permissions` stays row-less. Reads the record through getData first, so an absent or unreadable row answers the record read\'s 404. Enveloped ({ success, data }); record-field-access-when.dogfood.test.ts parses `data` against the named schema on the real mount' }, + // [ADR-0162 D9] The one lock read the data layer owns (`record-lock-routes.ts`). + { route: 'GET /api/v1/data/:object/:id/lock', family: 'data-actions', source: 'route-manager', disposition: 'sdk', client: 'data.getRecordLock', + responseSchema: 'RecordLockSchema', + note: 'One record\'s lock: { locked, lockSource?, lockReason? }, the engine\'s closed-state judgement and the approvals plugin\'s (when it binds its lock) composed by ObjectQL#getRecordLock as the caller. Told to every reader, field permissions on the state field notwithstanding; an unreadable or missing record answers the by-id read\'s 404. Enveloped ({ success, data }); record-lock-routes.test.ts parses `data` against the named schema on the mount' }, + { route: 'POST /api/v1/data/:object/locks', family: 'data-actions', source: 'route-manager', disposition: 'sdk', client: 'data.getRecordLocks', + responseSchema: 'GetRecordLocksResponseSchema', + note: 'The page form of the lock read: body { recordIds } (at most 200, refused whole above), entry i answers recordIds[i], `locked: null` for an unreadable or missing record. Enveloped ({ success, data }); record-lock-routes.test.ts parses `data` against the named schema on the mount' }, { route: 'POST /api/v1/data/:object/:id/page', family: 'data-actions', source: 'route-manager', disposition: 'sdk', client: 'data.recordPage', responseSchema: 'RecordPageResponseSchema', note: 'The record page payload: the record, the count and first rows of each related list the body names, the field projection, record-grained explain decisions and the approval state, each part the answer of the read it replaces asked as the same caller (getData, findData with count on the child, getRecordFieldAccess, explain, listRequests + getRecordLock). A refused record read refuses the whole request; a refused part carries its refusal and no answer. Enveloped ({ success, data }); record-page-routes.test.ts parses `data` against the named schema on the mount' }, diff --git a/packages/services/service-storage/src/record-file-access.ts b/packages/services/service-storage/src/record-file-access.ts index caa870bc2af..7657aa0525f 100644 --- a/packages/services/service-storage/src/record-file-access.ts +++ b/packages/services/service-storage/src/record-file-access.ts @@ -88,9 +88,10 @@ import { assertFileConstraints } from './file-reference-lifecycle.js'; * `sys_attachment` insert's own two questions). For a file field, the * parent-EDIT verdict the attach rule asks (`mayEditAttachmentParent`), * the field's writability as the security service answers it, the field's - * own `readonly` declaration, and [#32734] whether a pending approval - * locks the record (`IApprovalService.getRecordLock`, the judgement the - * record-lock hook enforces). A conditional lock (`readonlyWhen`) has no + * own `readonly` declaration, and [#32734, ADR-0162 D9] whether the + * record is locked, by its closed state or by an approval (the data + * layer's one lock read, `getRecordLock` on the engine; the refusal's + * sentence is chosen by the lock's reason). A conditional lock (`readonlyWhen`) has no * judgement a door can ask without writing, so it is judged when the link * is used. * - **Using a link.** The upload acts as the user who minted it: their grants @@ -453,6 +454,18 @@ export interface RecordFileEngine extends IDataEngine { field: string, options?: { context?: ExecutionContext }, ): Promise<{ reason: string; phrase: string } | null>; + /** + * [ADR-0162 D9] The data layer's one lock read (ObjectQL's `getRecordLock`): + * whether the record is locked for a caller, and by which lock. The + * upload-link door asks it before it issues a field link and chooses its + * sentence by `lockReason`. Optional: an engine without it is asked through + * the approvals service instead, as before. + */ + getRecordLock?( + object: string, + recordId: string, + options?: { context?: ExecutionContext }, + ): Promise<{ locked: boolean; lockReason?: 'closed_state' | 'approval' } | null>; } /** What {@link RecordFileAccess} is composed over — each read at call time. */ @@ -499,7 +512,9 @@ export interface RecordFileAccessDeps { getI18n?(): UploadLinkLabelI18n | null | undefined; /** * [#32734] The approvals service, for whether a pending approval locks the - * record a field link would write. Absent (no approvals plugin), or without + * record a field link would write — asked only when the engine has no + * `getRecordLock` (ADR-0162 D9's one lock read, which already composes the + * approvals plugin's judgement). Absent (no approvals plugin), or without * `getRecordLock`: no lock is judged when the link is minted, and the * record-lock hook still refuses the write when it is used. */ @@ -544,6 +559,21 @@ function refuse(code: StandardErrorCode | RegisteredErrorCode, status: number, m throw err; } +/** + * [ADR-0162 D9] The upload-link door's refusal of a locked record, its sentence + * chosen by the lock read's reason: a closed record is closed for good (no + * later link attaches anything), a held one only until the approval is over. + */ +function refuseLockedRecord(object: string, recordId: string, reason: 'closed_state' | 'approval' | undefined): never { + refuse( + 'RECORD_LOCKED', + 409, + reason === 'closed_state' + ? `You cannot attach a file to ${object}/${recordId}: the record is closed, so no file can be added to it.` + : `You cannot attach a file to ${object}/${recordId} now: it is locked while an approval is in progress.`, + ); +} + function refuseUnusableLink(): never { refuse(UPLOAD_LINK_UNUSABLE_CODE, UPLOAD_LINK_UNUSABLE_STATUS, UPLOAD_LINK_UNUSABLE_MESSAGE); } @@ -999,19 +1029,19 @@ export class RecordFileAccess implements ICallerRecordFileService, UploadLinkDoo refuse('FIELD_NOT_ACCESSIBLE', 403, `You cannot attach a file to ${object}.${field}: the field is ${lock.phrase}.`); } } - // [#32734] Nor does a record a pending approval locks: every edit of it - // is refused until the approval is decided, recalled or rejected. The - // approvals service's own answer, judged as the record-lock hook judges - // a write; `null` is a record the caller cannot read, refused above. - const approvals = this.deps.getApprovals?.(); - if (approvals && typeof approvals.getRecordLock === 'function') { - const lock = await approvals.getRecordLock(object, recordId, caller); - if (lock?.locked === true) { - refuse( - 'RECORD_LOCKED', - 409, - `You cannot attach a file to ${object}/${recordId} now: it is locked while an approval is in progress.`, - ); + // [#32734, ADR-0162 D9] Nor does a locked record: every edit of it is + // refused while it is closed or an approval holds it. The data layer's + // one lock read, as the caller, and the sentence chosen by its reason; + // `null` is a record the caller cannot read, refused above. An engine + // without the read is asked through the approvals service, as before. + if (typeof engine.getRecordLock === 'function') { + const lock = await engine.getRecordLock(object, recordId, { context: caller }); + if (lock?.locked === true) refuseLockedRecord(object, recordId, lock.lockReason); + } else { + const approvals = this.deps.getApprovals?.(); + if (approvals && typeof approvals.getRecordLock === 'function') { + const lock = await approvals.getRecordLock(object, recordId, caller); + if (lock?.locked === true) refuseLockedRecord(object, recordId, 'approval'); } } } diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index 0cb48136c0d..a7b02dae6b1 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -972,6 +972,8 @@ "api/GetRecordFieldAccessResponse:readable", "api/GetRecordFieldAccessResponse:recordId", "api/GetRecordFieldAccessResponse:writable", + "api/GetRecordLocksRequest:recordIds", + "api/GetRecordLocksResponse:records", "api/GetRunRequest:name", "api/GetRunRequest:runId", "api/GetRunResponse:data", diff --git a/packages/spec/json-schema.manifest/api.json b/packages/spec/json-schema.manifest/api.json index b381d11e884..a39b5dd4b92 100644 --- a/packages/spec/json-schema.manifest/api.json +++ b/packages/spec/json-schema.manifest/api.json @@ -234,6 +234,8 @@ "api/GetPresignedUrlRequest", "api/GetPublishedMetaItemResponse", "api/GetRecordFieldAccessResponse", + "api/GetRecordLocksRequest", + "api/GetRecordLocksResponse", "api/GetRunRequest", "api/GetRunResponse", "api/GetTranslationsRequest", @@ -400,6 +402,10 @@ "api/RealtimeUnsubscribeRequest", "api/RealtimeUnsubscribeResponse", "api/RecordData", + "api/RecordLock", + "api/RecordLockEntry", + "api/RecordLockReason", + "api/RecordLockSource", "api/RecordPageActivityRequest", "api/RecordPageApprovals", "api/RecordPageAttachmentsRequest", diff --git a/packages/spec/src/api/index.ts b/packages/spec/src/api/index.ts index 98c0bf2d0f7..ff4a5e31bea 100644 --- a/packages/spec/src/api/index.ts +++ b/packages/spec/src/api/index.ts @@ -52,6 +52,7 @@ export * from './router.zod'; export * from './odata.zod'; export * from './batch.zod'; export * from './record-page.zod'; +export * from './record-lock.zod'; export * from './app-bundle.zod'; export * from './http-cache.zod'; export * from './errors.zod'; diff --git a/packages/spec/src/api/record-lock.zod.ts b/packages/spec/src/api/record-lock.zod.ts new file mode 100644 index 00000000000..c9794b431d0 --- /dev/null +++ b/packages/spec/src/api/record-lock.zod.ts @@ -0,0 +1,111 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { lazySchema } from '../shared/lazy-schema'; + +/** + * [ADR-0162 D9] The one lock read, owned by the data layer: + * `GET /api/v1/data/{object}/{id}/lock` for one record and + * `POST /api/v1/data/{object}/locks` for a page of records. + * + * It answers "is this record locked, and by which lock" for both producers the + * record names: the engine's closed-state judgement (an object's + * `closedStates`) and the approvals plugin's judgement of a pending request + * under a node that locks, or of a passage of an approval on an object that + * declares `closedStates`. It is there whether or not the approvals plugin is + * installed; without it, only closed states lock. + * + * - **Who is answered.** Every caller who can read the record, whether or not + * it may write it, and whether or not field permissions let it read the + * state field. A record the caller cannot read answers as one that does not + * exist. + * - **What it never carries.** Which field or value closed the record, a + * request id, or participants. + * - **`locked` means locked for a caller.** A system context is bound by + * neither lock; the read does not describe it. + * + * The approvals-family read (`GET /api/v1/approvals/records/{object}/{id}/lock`, + * `IApprovalService.getRecordLock`) is a different read and stays as + * published: it answers for a pending request only. + */ + +/** + * The most record ids one `POST /api/v1/data/{object}/locks` request carries. + * A longer list is refused whole (`400 VALIDATION_ERROR`), never truncated. The + * same bound as the approvals-family page read. + */ +export const RECORD_LOCKS_MAX_RECORD_IDS = 200; + +/** + * Whose lock holds a locked record: `'record'`, its own state or its own + * approval; `'master'`, the state or the approval of the record a + * `master_detail` line belongs to. + */ +export const RecordLockSourceSchema = z.enum(['record', 'master']).describe( + 'Whose lock holds the record: `record` (its own state or its own approval) or `master` (the master of a ' + + 'master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the ' + + 'request) and a line of a held master may not. Under `closed_state`, a caller\'s delete is refused for either source.', +); + +/** Which producer holds a locked record. */ +export const RecordLockReasonSchema = z.enum(['closed_state', 'approval']).describe( + 'Which lock holds the record: `closed_state` (a declared closed state, ADR-0162) or `approval` (a pending request ' + + 'under a node that locks, or a passage of an approval on an object that declares closedStates). When both ' + + 'hold, `closed_state` is answered.', +); + +/** + * The answer for one readable record (ADR-0162 D9): + * `{ locked, lockSource?, lockReason? }`. `lockSource` and `lockReason` are + * present exactly when `locked` is `true`, on every answer, from either + * producer: the producers' internal seam requires the source. Spelled as two + * strict arms, so the published JSON Schema carries the rule too. + * + * One answer when several hold: the reason first, `closed_state` before + * `approval`; within a reason, `master` before `record`. + */ +export const RecordLockSchema = lazySchema(() => z.union([ + z.object({ + locked: z.literal(true).describe('A caller\'s write of the record is refused by a lock.'), + lockSource: RecordLockSourceSchema, + lockReason: RecordLockReasonSchema, + }).strict(), + z.object({ + locked: z.literal(false).describe('No lock refuses a caller\'s write of the record.'), + }).strict(), +]).describe('One record\'s lock, as `GET /api/v1/data/{object}/{id}/lock` answers it (ADR-0162 D9).')); +export type RecordLock = z.input; + +/** The body of `POST /api/v1/data/{object}/locks`. */ +export const GetRecordLocksRequestSchema = lazySchema(() => z.object({ + recordIds: z.array(z.string().trim().min(1)).min(1).max(RECORD_LOCKS_MAX_RECORD_IDS).describe( + `The records to answer, at least one and at most ${RECORD_LOCKS_MAX_RECORD_IDS}; a repeated id is answered at each of its positions.`, + ), +}).strict().describe('The page lock read\'s body.')); +export type GetRecordLocksRequest = z.input; + +/** + * One entry of the page read: the asked id, and that record's answer — + * `locked: null` for a record the caller cannot read or that does not exist + * (told apart by nothing). A row counts as readable only when the caller's read + * hands back the row whose id IS the asked id. + */ +export const RecordLockEntrySchema = lazySchema(() => z.union([ + z.object({ + recordId: z.string().describe('The id as asked.'), + locked: z.literal(true).describe('A caller\'s write of the record is refused by a lock.'), + lockSource: RecordLockSourceSchema, + lockReason: RecordLockReasonSchema, + }).strict(), + z.object({ + recordId: z.string().describe('The id as asked.'), + locked: z.literal(false).nullable().describe('`false` when no lock holds the record; `null` when the caller cannot read it or it does not exist.'), + }).strict(), +]).describe('One record of the page lock read.')); +export type RecordLockEntry = z.input; + +/** The answer of `POST /api/v1/data/{object}/locks`: entry `i` answers `recordIds[i]`. */ +export const GetRecordLocksResponseSchema = lazySchema(() => z.object({ + records: z.array(RecordLockEntrySchema).describe('One entry per asked id, in order.'), +}).strict().describe('The page lock read\'s answer (ADR-0162 D9).')); +export type GetRecordLocksResponse = z.input; From cb4149c89ca63ad10f86c6cd63114d78650262a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:47:24 +0000 Subject: [PATCH 02/11] test(data): pin the one record lock read, its doors and the upload-link door Every combination on a real engine with the real approvals plugin (and without it), the page bound and entry-by-entry answers, the field-hidden state field, the slot's lifetime; the two REST doors against the ledgered schemas; the upload-link door's two sentences by the lock's reason. Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- ...rd-lock-one-read-37770.integration.test.ts | 354 ++++++++++++++++++ packages/rest/src/record-lock-routes.test.ts | 196 ++++++++++ ...route-hook-refusal-sentence.ledger.test.ts | 3 + .../record-file-access.integration.test.ts | 33 ++ 4 files changed, 586 insertions(+) create mode 100644 packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts create mode 100644 packages/rest/src/record-lock-routes.test.ts diff --git a/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts new file mode 100644 index 00000000000..bfbda9ec1b9 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts @@ -0,0 +1,354 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9, #37770] The one lock read the data layer owns — + * `ObjectQL#getRecordLock` / `ObjectQL#getRecordLocks` — composed from the + * engine's closed-state judgement and this plugin's approvals judgement, which + * the engine reads through the producer slot this plugin fills beside its lock + * hooks (`record-lock-producer.ts`). + * + * ## What each pin holds + * + * - every combination the card names, answered to a caller who can read the + * record: closed by its own state, a line of a closed master, held by an + * approval, a line of a held master, both locks at once (`closed_state` + * wins; within a reason `master` wins), neither, unreadable, missing; + * - the read exists without this plugin: then only closed states lock; + * - a caller whose field permissions hide the state field is told + * `closed_state` all the same; + * - the page form refuses more than 200 ids whole and answers entry by entry, + * a row counting only when its id IS the asked id; + * - a pending request under a `lockRecord: false` node is not a lock, and a + * decided one lets go, as the hooks do; + * - the approvals-family read is untouched: it still answers for a pending + * request only, so it calls a closed record unlocked; + * - the slot is the plugin's for as long as its hooks are bound: `destroy()` + * empties it, and the cross-package key is the one the engine reads. + * + * ## The rig + * + * `record-lock-read.integration.test.ts`'s: a real ObjectQL engine over + * better-sqlite3 and the real `ApprovalsServicePlugin.start()`. Record + * readability is the one stand-in, one middleware per business object; it also + * refuses the reader any query that names the state field, which is what a + * field permission hiding that field does to a read. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { installDefaultOrganization } from './default-organization.testkit.js'; +import { APPROVAL_RECORD_LOCK_PRODUCER_SLOT } from './record-lock-producer.js'; + +/** Declares `closedStates: { stage: ['done'] }`; its approval node locks. */ +const INV = 'lock_invoice'; +/** A master-detail line of the invoice. */ +const LINE = 'lock_invoice_line'; +/** Declares no closed state; its approval node opts out of the lock. */ +const MEMO = 'lock_memo'; +const PKG = 'record-lock-one-read-test'; +const READ_OPS = new Set(['find', 'findOne', 'count', 'aggregate']); + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; + +const SUBMITTER = 'u_submitter'; +const APPROVER = 'u_approver'; +/** Reads every record but `hidden`, and is refused any query that names `stage`. */ +const READER = 'u_reader'; +/** Holds no read on any business object. */ +const OUTSIDER = 'u_outsider'; + +/** Invoice ids: each one combination. */ +const I = { + closed: 'inv_closed', + held: 'inv_held', + both: 'inv_both', + open: 'inv_open', + hidden: 'inv_hidden', +} as const; +/** Line ids, one under each invoice that is not hidden. */ +const L = { + ofClosed: 'line_of_closed', + ofHeld: 'line_of_held', + ofBoth: 'line_of_both', + ofOpen: 'line_of_open', + hidden: 'line_hidden', +} as const; +const MISSING = 'no_such_record'; + +const CLOSED_OWN = { locked: true, lockSource: 'record', lockReason: 'closed_state' }; +const CLOSED_MASTER = { locked: true, lockSource: 'master', lockReason: 'closed_state' }; +const HELD_OWN = { locked: true, lockSource: 'record', lockReason: 'approval' }; +const HELD_MASTER = { locked: true, lockSource: 'master', lockReason: 'approval' }; +const OPEN = { locked: false }; + +const idField = { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }; +const title = { name: 'title', label: 'Title', type: 'text' as const }; + +const invoice = { + name: INV, label: 'Invoice', + fields: { id: idField, title, stage: { name: 'stage', label: 'Stage', type: 'text' as const } }, + closedStates: { stage: ['done'] }, +}; +const invoiceLine = { + name: LINE, label: 'Invoice Line', + fields: { id: idField, title, invoice: { name: 'invoice', label: 'Invoice', type: 'master_detail' as const, reference: INV } }, +}; +const memo = { name: MEMO, label: 'Memo', fields: { id: idField, title } }; + +const nodeConfig = (lockRecord: boolean) => ({ + approvers: [{ type: 'user' as const, value: APPROVER }], + behavior: 'first_response' as const, + lockRecord, +}); + +let current: ObjectQL | undefined; + +afterEach(async () => { + try { await current?.destroy(); } catch { /* noop */ } + current = undefined; +}); + +function mentionsStage(value: unknown): boolean { + return JSON.stringify(value ?? null).includes('"stage"'); +} + +/** Record readability, the stand-in (see the header), on one business object. */ +function guardReads(engine: ObjectQL, object: string, hidden: readonly string[]): void { + engine.registerMiddleware(async (op: any, next: () => Promise) => { + const ctx = op.context; + if (READ_OPS.has(op.operation) && ctx && !ctx.isSystem && op.ast) { + const user = String(ctx.userId ?? ''); + if (user === OUTSIDER || !user) { + throw Object.assign(new Error(`[Security] Access denied: no read on '${object}'`), { + code: 'PERMISSION_DENIED', status: 403, + }); + } + if (user === READER) { + // A field permission hiding `stage` from the reader: any query naming it is refused. + if (mentionsStage(op.ast.fields) || mentionsStage(op.ast.where)) { + throw Object.assign(new Error(`[Security] '${object}.stage' is not readable`), { + code: 'FIELD_NOT_ACCESSIBLE', status: 403, + }); + } + const scope = { id: { $nin: [...hidden] } }; + op.ast.where = op.ast.where ? { $and: [op.ast.where, scope] } : scope; + } + } + return next(); + }, { object }); +} + +interface Rig { + engine: ObjectQL; + svc?: ApprovalService; + plugin?: ApprovalsServicePlugin; + requests: Map; +} + +async function boot(options: { approvals: boolean } = { approvals: true }): Promise { + const engine = new ObjectQL(); + current = engine; + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + for (const def of [invoice, invoiceLine, memo, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation]) { + engine.registry.registerObject(def as any, PKG, PKG); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + guardReads(engine, INV, [I.hidden]); + guardReads(engine, LINE, [L.hidden]); + guardReads(engine, MEMO, []); + + const services: Record = { objectql: engine }; + let plugin: ApprovalsServicePlugin | undefined; + if (options.approvals) { + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: () => {}, + logger: { info: () => {}, debug: () => {}, warn: () => {}, error: () => {} }, + }; + plugin = new ApprovalsServicePlugin(); + await plugin.start(ctx); + } + const svc = services.approvals as ApprovalService | undefined; + + for (const id of Object.values(I)) { + await engine.insert(INV, { id, title: id, stage: 'draft' }, { context: SYSTEM } as any); + } + const lineUnder: Array<[string, string]> = [ + [L.ofClosed, I.closed], [L.ofHeld, I.held], [L.ofBoth, I.both], [L.ofOpen, I.open], [L.hidden, I.open], + ]; + for (const [id, master] of lineUnder) { + await engine.insert(LINE, { id, title: id, invoice: master }, { context: SYSTEM } as any); + } + await engine.insert(MEMO, { id: 'memo_a', title: 'memo_a' }, { context: SYSTEM } as any); + + const requests = new Map(); + if (svc) { + for (const [object, recordId, lockRecord] of [[INV, I.held, true], [INV, I.both, true], [MEMO, 'memo_a', false]] as const) { + const opened = await svc.openNodeRequest({ + object, recordId, runId: `run_${recordId}`, nodeId: 'review', flowName: 'review', + config: nodeConfig(lockRecord) as any, submitterId: SUBMITTER, + record: { id: recordId, title: recordId }, + }, asUser(SUBMITTER)) as any; + requests.set(recordId, String(opened.id)); + } + } + // Closed after the approvals opened: a system write is bound by neither lock. + for (const id of [I.closed, I.both]) { + await engine.update(INV, { id, stage: 'done' }, { context: SYSTEM } as any); + } + return { engine, svc, plugin, requests }; +} + +const lockAs = (rig: Rig, userId: string, object: string, id: string) => + rig.engine.getRecordLock(object, id, { context: asUser(userId) }); +const locksAs = (rig: Rig, userId: string, object: string, ids: string[]) => + rig.engine.getRecordLocks(object, ids, { context: asUser(userId) }); + +describe('[ADR-0162 D9] ObjectQL#getRecordLock — one read for closed states and approvals', () => { + it('answers each combination, with the reasons ordered as D9 orders them', async () => { + const rig = await boot(); + for (const caller of [SUBMITTER, READER]) { + expect(await lockAs(rig, caller, INV, I.closed), `${caller} closed`).toEqual(CLOSED_OWN); + expect(await lockAs(rig, caller, INV, I.held), `${caller} held`).toEqual(HELD_OWN); + // Both at once: closed_state before approval. + expect(await lockAs(rig, caller, INV, I.both), `${caller} both`).toEqual(CLOSED_OWN); + expect(await lockAs(rig, caller, INV, I.open), `${caller} neither`).toEqual(OPEN); + expect(await lockAs(rig, caller, LINE, L.ofClosed), `${caller} line of closed`).toEqual(CLOSED_MASTER); + expect(await lockAs(rig, caller, LINE, L.ofHeld), `${caller} line of held`).toEqual(HELD_MASTER); + expect(await lockAs(rig, caller, LINE, L.ofBoth), `${caller} line of both`).toEqual(CLOSED_MASTER); + expect(await lockAs(rig, caller, LINE, L.ofOpen), `${caller} line of neither`).toEqual(OPEN); + expect(await lockAs(rig, caller, INV, MISSING), `${caller} missing`).toBeNull(); + } + // Unreadable answers as missing does, whatever locks it. + expect(await lockAs(rig, SUBMITTER, INV, I.hidden)).toEqual(OPEN); + expect(await lockAs(rig, READER, INV, I.hidden)).toBeNull(); + expect(await lockAs(rig, READER, LINE, L.hidden)).toBeNull(); + await rig.engine.update(INV, { id: I.hidden, stage: 'done' }, { context: SYSTEM } as any); + expect(await lockAs(rig, SUBMITTER, INV, I.hidden)).toEqual(CLOSED_OWN); + expect(await lockAs(rig, READER, INV, I.hidden)).toBeNull(); + }); + + it('agrees with the write path: what it calls locked, the caller\'s write is refused', async () => { + const rig = await boot(); + const writeAs = async (object: string, id: string) => { + try { + await rig.engine.update(object, { id, title: 'edited' }, { context: asUser(SUBMITTER) } as any); + return 'written'; + } catch (err: any) { + return String(err?.code ?? err?.message); + } + }; + for (const [object, id] of [[INV, I.closed], [INV, I.held], [INV, I.both], [LINE, L.ofClosed], [LINE, L.ofHeld]] as const) { + expect(await writeAs(object, id), `${object}/${id}`).toBe('RECORD_LOCKED'); + } + expect(await writeAs(INV, I.open)).toBe('written'); + expect(await writeAs(LINE, L.ofOpen)).toBe('written'); + }); + + it('tells a reader whose field permissions hide the state field that the record is closed', async () => { + const rig = await boot(); + // The stand-in refuses the reader any query naming `stage`… + const direct = await rig.engine.find(INV, { where: { stage: 'done' }, context: asUser(READER) } as any) + .then(() => 'read', (err: any) => String(err?.code)); + expect(direct).toBe('FIELD_NOT_ACCESSIBLE'); + // …and the lock read tells them all the same, naming neither field nor value. + const lock = await lockAs(rig, READER, INV, I.closed); + expect(lock).toEqual(CLOSED_OWN); + expect(JSON.stringify(lock)).not.toMatch(/stage|done/); + }); + + it('refuses a caller with no read on the object, the same for every id', async () => { + const rig = await boot(); + for (const id of [I.closed, MISSING]) { + const refusal = await lockAs(rig, OUTSIDER, INV, id).then(() => 'answered', (err: any) => `${err?.code} ${err?.status}`); + expect(refusal, id).toBe('PERMISSION_DENIED 403'); + } + }); + + it('lets go where the hooks let go: a lockRecord:false node holds nothing, a decided request releases', async () => { + const rig = await boot(); + expect(await lockAs(rig, SUBMITTER, MEMO, 'memo_a')).toEqual(OPEN); + await rig.svc!.decide(rig.requests.get(I.held)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + expect(await lockAs(rig, READER, INV, I.held)).toEqual(OPEN); + expect(await lockAs(rig, READER, LINE, L.ofHeld)).toEqual(OPEN); + }); + + it('leaves the approvals-family read as published: it answers for a pending request only', async () => { + const rig = await boot(); + expect(await rig.svc!.getRecordLock(INV, I.closed, asUser(READER))).toEqual({ locked: false }); + expect(await rig.svc!.getRecordLock(INV, I.held, asUser(READER))).toEqual({ locked: true, lockSource: 'record' }); + }); +}); + +describe('[ADR-0162 D9] the read without the approvals plugin', () => { + it('answers from closed states alone', async () => { + const rig = await boot({ approvals: false }); + expect((rig.engine as any)[APPROVAL_RECORD_LOCK_PRODUCER_SLOT]).toBeUndefined(); + expect(await lockAs(rig, READER, INV, I.closed)).toEqual(CLOSED_OWN); + expect(await lockAs(rig, READER, INV, I.both)).toEqual(CLOSED_OWN); + expect(await lockAs(rig, READER, LINE, L.ofClosed)).toEqual(CLOSED_MASTER); + expect(await lockAs(rig, READER, INV, I.held)).toEqual(OPEN); + expect(await lockAs(rig, READER, INV, MISSING)).toBeNull(); + }); + + it('empties the slot when the plugin is destroyed, so the approvals half goes with its hooks', async () => { + const rig = await boot(); + // The cross-package key: the engine reads the slot this plugin fills. + expect(typeof (rig.engine as any)[Symbol.for('objectstack.objectql.approvalRecordLockProducer')]).toBe('function'); + expect(await lockAs(rig, READER, INV, I.held)).toEqual(HELD_OWN); + await rig.plugin!.destroy(); + expect((rig.engine as any)[APPROVAL_RECORD_LOCK_PRODUCER_SLOT]).toBeUndefined(); + expect(await lockAs(rig, READER, INV, I.held)).toEqual(OPEN); + expect(await lockAs(rig, READER, INV, I.closed)).toEqual(CLOSED_OWN); + }); +}); + +describe('[ADR-0162 D9] ObjectQL#getRecordLocks — the page form', () => { + it('answers entry by entry, in order, each as the single read answers it', async () => { + const rig = await boot(); + const ids = [I.closed, I.held, I.both, I.open, I.hidden, MISSING, I.closed, '']; + expect(await locksAs(rig, READER, INV, ids)).toEqual([ + CLOSED_OWN, HELD_OWN, CLOSED_OWN, OPEN, null, null, CLOSED_OWN, null, + ]); + const lines = [L.ofClosed, L.ofHeld, L.ofBoth, L.ofOpen, L.hidden]; + expect(await locksAs(rig, READER, LINE, lines)).toEqual([CLOSED_MASTER, HELD_MASTER, CLOSED_MASTER, OPEN, null]); + for (const id of [I.closed, I.held, I.open]) { + const [entry] = await locksAs(rig, SUBMITTER, INV, [id]); + expect(entry, id).toEqual(await lockAs(rig, SUBMITTER, INV, id)); + } + }); + + it('refuses more than 200 ids whole, and takes exactly 200', async () => { + const rig = await boot(); + const over = Array.from({ length: 201 }, (_, i) => (i === 0 ? I.closed : `id_${i}`)); + const refusal = await locksAs(rig, READER, INV, over).then(() => 'answered', (err: any) => `${err?.code} ${err?.status}`); + expect(refusal).toBe('VALIDATION_ERROR 400'); + const page = await locksAs(rig, READER, INV, over.slice(0, 200)); + expect(page).toHaveLength(200); + expect(page[0]).toEqual(CLOSED_OWN); + expect(page.slice(1).every((entry) => entry === null)).toBe(true); + }); + + it('answers without the approvals plugin too', async () => { + const rig = await boot({ approvals: false }); + expect(await locksAs(rig, READER, INV, [I.closed, I.held, MISSING])).toEqual([CLOSED_OWN, OPEN, null]); + }); +}); diff --git a/packages/rest/src/record-lock-routes.test.ts b/packages/rest/src/record-lock-routes.test.ts new file mode 100644 index 00000000000..a296c6a7314 --- /dev/null +++ b/packages/rest/src/record-lock-routes.test.ts @@ -0,0 +1,196 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0162 D9, #37770] The data family's two lock doors — + * `GET /data/:object/:id/lock` and `POST /data/:object/locks`. + * + * What the doors owe, each pinned below: + * + * - the answer is the data protocol's `getRecordLock` / `getRecordLocks`, + * asked with the caller's object, ids and context, relayed in the shared + * envelope and parsed against the ledgered response schema; + * - only `locked`, `lockSource` and `lockReason` are served, whatever else the + * producer hands back; + * - one record the caller cannot read, or that does not exist, answers the + * by-id read's own localized `404 RECORD_NOT_FOUND` (and says it varies by + * language); in a page that entry answers `locked: null`; + * - a page over 200 ids, an empty one, a malformed body or an unknown body key + * is refused whole with a 400, and the protocol is never asked; + * - no protocol method, or an engine without the read → a loud 501, never + * "unlocked"; + * - a CLOSED, empty query-parameter set on both doors. + * + * The engine half (every combination, the readability anchors, the approvals + * producer) is `@objectstack/plugin-approvals` + * `record-lock-one-read-37770.integration.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { RecordLockSchema, GetRecordLocksResponseSchema } from '@objectstack/spec/api'; +import { RestServer } from './rest-server.js'; +import { RECORD_LOCK_PARAMS, RECORD_LOCKS_PARAMS, readDataRecordLocksBody } from './record-lock-routes.js'; +import { unknownQueryParamMessage } from './query-allowlist.js'; +import { objectNotFoundError } from '@objectstack/core'; +// Paid at collection, not inside a case's clock (check:test-source-alias): +// the source under test loads it dynamically. +import '@objectstack/objectql'; + +const TASK = { + name: 'task', + label: 'Task', + fields: { id: { name: 'id', type: 'text', label: 'ID' }, title: { name: 'title', type: 'text', label: 'Title' } }, +}; +const CTX = { userId: 'u1', permissions: ['member_default'] }; +const CLOSED = { locked: true, lockSource: 'master', lockReason: 'closed_state' } as const; +const HELD = { locked: true, lockSource: 'record', lockReason: 'approval' } as const; + +function mockServer() { + const noop = () => { /* routes are driven directly, never through the adapter */ }; + return { + get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop, + listen: async () => { /* never started */ }, + close: async () => { /* never started */ }, + }; +} + +function mockRes() { + const res: any = { + statusCode: 200, + headers: {} as Record, + header: vi.fn(function (this: any, name: string, value: unknown) { this.headers[name] = value; return this; }), + setHeader: vi.fn(function (this: any) { return this; }), + json: vi.fn(function (this: any, body: any) { this._body = body; return this; }), + status: vi.fn(function (this: any, code: number) { this.statusCode = code; return this; }), + }; + return res; +} + +function boot(methods: { getRecordLock?: (...a: any[]) => any; getRecordLocks?: (...a: any[]) => any } = {}) { + const protocol: any = { + getDiscovery: vi.fn().mockResolvedValue({ + version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' }, + }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn().mockResolvedValue({ items: [TASK] }), + getMetaItem: vi.fn().mockResolvedValue({ type: 'object', name: 'task', item: TASK }), + ...(methods.getRecordLock ? { getRecordLock: vi.fn(methods.getRecordLock) } : {}), + ...(methods.getRecordLocks ? { getRecordLocks: vi.fn(methods.getRecordLocks) } : {}), + }; + const rest = new RestServer(mockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => CTX; + rest.registerRoutes(); + const routes = (rest as any).getRoutes(); + const one = routes.find((r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/:id/lock'); + const page = routes.find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/locks'); + const run = async (route: any, req: Record) => { + if (!route) throw new Error('route not registered'); + const res = mockRes(); + await route.handler({ headers: {}, query: {}, body: {}, ...req } as any, res); + return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0], headers: res.headers }; + }; + return { + protocol, + getOne: (query: Record = {}, params = { object: 'task', id: 'r1' }) => + run(one, { method: 'GET', params, query }), + postPage: (body: unknown, query: Record = {}) => + run(page, { method: 'POST', params: { object: 'task' }, query, body }), + }; +} + +describe('[ADR-0162 D9] GET /data/:object/:id/lock', () => { + it("relays the protocol's answer for the caller, parsed against RecordLockSchema", async () => { + for (const lock of [CLOSED, HELD, { locked: false }]) { + const { getOne, protocol } = boot({ getRecordLock: async () => lock }); + const answer = await getOne(); + expect(answer).toEqual({ status: 200, body: { success: true, data: lock }, headers: {} }); + expect(RecordLockSchema.parse(answer.body.data)).toEqual(lock); + expect(protocol.getRecordLock).toHaveBeenCalledWith({ object: 'task', id: 'r1', context: CTX }); + } + }); + + it('serves the three members alone, whatever else the producer hands back', async () => { + const { getOne } = boot({ + getRecordLock: async () => ({ ...HELD, requestId: 'req_1', field: 'stage', value: 'done' }), + }); + expect((await getOne()).body.data).toEqual(HELD); + }); + + it("answers an unreadable or missing record with the by-id read's localized 404", async () => { + const answer = await boot({ getRecordLock: async () => null }).getOne(); + expect(answer.status).toBe(404); + expect(answer.body?.error?.code ?? answer.body?.code).toBe('RECORD_NOT_FOUND'); + expect(answer.headers.Vary).toBeDefined(); + }); + + it('relays the protocol\'s refusals: an unknown object, a caller with no read', async () => { + const unknown = await boot({ getRecordLock: async () => { throw objectNotFoundError('nope'); } }).getOne(); + expect(unknown.status).toBe(404); + const denied = await boot({ + getRecordLock: async () => { throw Object.assign(new Error('[Security] Access denied'), { code: 'PERMISSION_DENIED', status: 403 }); }, + }).getOne(); + expect(denied.status).toBe(403); + }); + + it('answers a loud 501 when the protocol or its engine has no read, never "unlocked"', async () => { + for (const methods of [{}, { getRecordLock: async () => undefined }]) { + const answer = await boot(methods).getOne(); + expect(answer.status).toBe(501); + expect(answer.body?.error?.code).toBe('NOT_IMPLEMENTED'); + } + }); + + it('takes no query parameter: a name is a located 400 and the protocol is never asked', async () => { + expect(RECORD_LOCK_PARAMS).toEqual([]); + const { getOne, protocol } = boot({ getRecordLock: async () => HELD }); + const answer = await getOne({ fields: 'stage' }); + expect(answer.status).toBe(400); + expect(answer.body?.error?.message).toBe(unknownQueryParamMessage(['fields'], [])); + expect(protocol.getRecordLock).not.toHaveBeenCalled(); + }); +}); + +describe('[ADR-0162 D9] POST /data/:object/locks', () => { + it('answers entry by entry in order, null for an unreadable or missing record, parsed against the schema', async () => { + const { postPage, protocol } = boot({ getRecordLocks: async () => [CLOSED, null, { locked: false }, HELD] }); + const answer = await postPage({ recordIds: ['a', 'hidden', 'b', 'c'] }); + const data = { + records: [ + { recordId: 'a', ...CLOSED }, + { recordId: 'hidden', locked: null }, + { recordId: 'b', locked: false }, + { recordId: 'c', ...HELD }, + ], + }; + expect(answer).toEqual({ status: 200, body: { success: true, data }, headers: {} }); + expect(GetRecordLocksResponseSchema.parse(answer.body.data)).toEqual(data); + expect(protocol.getRecordLocks).toHaveBeenCalledWith({ object: 'task', recordIds: ['a', 'hidden', 'b', 'c'], context: CTX }); + }); + + it('refuses a page over 200 ids, an empty one, a malformed body or an unknown key whole, before the protocol', async () => { + const { postPage, protocol } = boot({ getRecordLocks: async () => [] }); + const ids = (n: number) => Array.from({ length: n }, (_, i) => `id_${i}`); + for (const body of [{ recordIds: ids(201) }, { recordIds: [] }, { recordIds: ['a', ''] }, { recordIds: 'a' }, [], null, { recordIds: ['a'], limit: 5 }]) { + const answer = await postPage(body); + expect(answer.status, JSON.stringify(body)?.slice(0, 40)).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + } + expect(protocol.getRecordLocks).not.toHaveBeenCalled(); + expect('recordIds' in readDataRecordLocksBody({ recordIds: ids(200) })).toBe(true); + }); + + it('answers a loud 501 when the protocol or its engine has no read', async () => { + for (const methods of [{}, { getRecordLocks: async () => undefined }]) { + const answer = await boot(methods).postPage({ recordIds: ['a'] }); + expect(answer.status).toBe(501); + expect(answer.body?.error?.code).toBe('NOT_IMPLEMENTED'); + } + }); + + it('takes no query parameter', async () => { + expect(RECORD_LOCKS_PARAMS).toEqual([]); + const { postPage, protocol } = boot({ getRecordLocks: async () => [HELD] }); + const answer = await postPage({ recordIds: ['a'] }, { expand: 'x' }); + expect(answer.status).toBe(400); + expect(protocol.getRecordLocks).not.toHaveBeenCalled(); + }); +}); 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 b9319542b8d..b19e9306827 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 @@ -384,6 +384,9 @@ const ANSWERS_THE_SENTENCE: Record = { called: 'protocol.getData', body: {}, protocol: (error) => ({ getData: async () => { throw error(); } }), }, + // [ADR-0162 D9] A read on a write verb too: the caller's read of the ids, + // inside the engine's lock read, is the one a `beforeFind` hook refuses. + 'POST /api/v1/data/:object/locks': { called: 'protocol.getRecordLocks', body: { recordIds: ['r1'] } }, 'PATCH /api/v1/data/:object/:id': { called: 'protocol.updateData', body: { name: 'x' } }, 'DELETE /api/v1/data/:object/:id': { called: 'protocol.deleteData' }, 'POST /api/v1/data/:object/:id/clone': { called: 'protocol.cloneData', body: {} }, diff --git a/packages/services/service-storage/src/record-file-access.integration.test.ts b/packages/services/service-storage/src/record-file-access.integration.test.ts index 3bf6daf337a..541b0d4ce87 100644 --- a/packages/services/service-storage/src/record-file-access.integration.test.ts +++ b/packages/services/service-storage/src/record-file-access.integration.test.ts @@ -214,6 +214,15 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o return row ? { locked: locked.has(id) } : null; }, }); + // [ADR-0162 D9] …and the same judgement where the data layer's one lock + // read asks it: the engine slot `@objectstack/plugin-approvals` fills + // beside its lock hooks (`record-lock-producer.ts`). The upload-link door + // asks the engine's read, which composes it with the closed-state lock. + Object.defineProperty(engine, Symbol.for('objectstack.objectql.approvalRecordLockProducer'), { + configurable: true, + value: async (_object: string, recordIds: readonly string[]) => + new Map(recordIds.filter((id) => locked.has(id)).map((id) => [id, 'record' as const])), + }); const plugin = new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }); await plugin.init(ctx as any); @@ -228,6 +237,7 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o name: 'claim', label: 'Claim', enable: { files: true }, + closedStates: { stage: ['closed'] }, fields: { name: { name: 'name', type: 'text' }, owner: { name: 'owner', type: 'text' }, @@ -239,6 +249,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o status: { name: 'status', type: 'text' }, invoices: { name: 'invoices', label: 'Invoices', type: 'file', multiple: true, readonlyWhen: "record.status == 'approved'" }, stamp: { name: 'stamp', label: 'Stamp', type: 'file', readonly: true }, + // [ADR-0162 D9] A claim's own lifecycle, which closes it for good. + stage: { name: 'stage', type: 'text' }, // [#32747] A multi-file field that takes only PDFs: invoices for one claim. scans: { name: 'scans', label: 'Scans', type: 'file', multiple: true, accept: ['application/pdf', '.pdf'] }, }, @@ -745,6 +757,8 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o const before = await openLinkRows(); const r = await refusalOf(files.createUploadLinkAs('claim', id, { field: 'invoices' }, OWNER as never)); expect(r).toMatchObject({ code: 'RECORD_LOCKED', status: 409 }); + // [ADR-0162 D9] The approval sentence, chosen by the lock read's reason. + expect(r?.message).toContain('locked while an approval is in progress'); expect(await openLinkRows()).toBe(before); } finally { locked.delete(id); @@ -753,6 +767,25 @@ describe('#30892 — a record\'s files for a resolved caller: read one, attach o expect(grant.path).toBe(`${BASE}/upload-links/${grant.token}`); }); + it('[ADR-0162 D9] minting refuses a closed record 409 RECORD_LOCKED with the closed-state sentence, and writes no link', async () => { + const id = await draftClaim('closed at mint'); + await engine.update('claim', { stage: 'closed' }, { where: { id }, context: SYS } as never); + const before = await openLinkRows(); + const r = await refusalOf(files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never)); + expect(r).toMatchObject({ code: 'RECORD_LOCKED', status: 409 }); + expect(r?.message).toContain('the record is closed, so no file can be added to it'); + expect(r?.message).not.toContain('approval'); + expect(await openLinkRows()).toBe(before); + // Closed and held at once: the closed-state sentence, as the read orders the reasons. + locked.add(id); + try { + const both = await refusalOf(files.createUploadLinkAs('claim', id, { field: 'policy' }, OWNER as never)); + expect(both?.message).toContain('the record is closed'); + } finally { + locked.delete(id); + } + }); + it('a draft takes the upload; once its readonlyWhen holds, an upload through a link minted before is refused 403 with the reason, attaching and keeping nothing', async () => { const id = await draftClaim('approved after mint'); const first = await uploadThroughLink({ field: 'invoices' }, Buffer.from('invoice one'), id); From 341d69f97508179bb01e9ee8f7dcce17ea3fe893 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:54:43 +0000 Subject: [PATCH 03/11] chore(spec): regenerate the strictness ledger counts for the lock read schemas Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md index c78b923b74b..268737d3e5b 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `api/` | 544 | +| `api/` | 550 | From a9876ea5b594ad1c4feae072b6515528e8253a4d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:55:56 +0000 Subject: [PATCH 04/11] docs(approvals): point the approvals lock reads at the data-layer lock read Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- content/docs/automation/approvals.mdx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 30a8dba577a..e6256d8829f 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -520,6 +520,12 @@ member `IApprovalService.getRecordLocks`, and an approvals service without it answers `501`. A list that edits in place reads it when a cell is first selected, and holds an edit asked before the answer arrives until it does. +These two reads answer for approvals alone. Whether a record is locked by +either lock, its closed state (`closedStates`) or an approval, is the data +layer's read, `GET /api/v1/data/:object/:id/lock` and +`POST /api/v1/data/:object/locks` ([Record locks](/docs/api/data-api#record-locks)), +which also says which lock holds it. + Only `approvers` is required on the node; everything else has a default (`behavior: 'first_response'`, `lockRecord: true`, `maxRevisions: 3`). @@ -1836,8 +1842,10 @@ left no marks, and is not held between its steps. The approvals-family lock read (`getRecordLock`, above) answers for a pending request only: in a passage it answers `{ "locked": false }` while an edit is -refused `409 RECORD_LOCKED`. A page that offers an edit in a passage learns of -the hold from the refusal. +refused `409 RECORD_LOCKED`. The data layer's lock read +(`GET /api/v1/data/:object/:id/lock`, [Record locks](/docs/api/data-api#record-locks)) +answers the hold in a passage too, as `lockReason: "approval"`, beside the +closed-state lock, so a page that offers an edit can learn of the hold before the save. ## Why From 817c14bd8f280e9ec26e8dc5670a207e5f368d7d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 12:59:06 +0000 Subject: [PATCH 05/11] chore(spec): record the lock read exports in the api surface snapshot Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- packages/spec/api-surface/api.json | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 8a960d9db4e..91764dfa325 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -582,6 +582,10 @@ "GetRecordFieldAccessResponse (type)", "GetRecordFieldAccessResponseParsed (type)", "GetRecordFieldAccessResponseSchema (const)", + "GetRecordLocksRequest (type)", + "GetRecordLocksRequestSchema (const)", + "GetRecordLocksResponse (type)", + "GetRecordLocksResponseSchema (const)", "GetRunRequest (type)", "GetRunRequestSchema (const)", "GetRunResponse (type)", @@ -960,6 +964,7 @@ "QueryOptimizationConfig (type)", "QueryOptimizationConfigParsed (type)", "QueryOptimizationConfigSchema (const)", + "RECORD_LOCKS_MAX_RECORD_IDS (const)", "RECORD_PAGE_MAX_ACTIVITY_ROWS (const)", "RECORD_PAGE_MAX_ATTACHMENT_ROWS (const)", "RECORD_PAGE_MAX_RELATED (const)", @@ -1003,6 +1008,12 @@ "RealtimeUnsubscribeResponseSchema (const)", "RecordData (type)", "RecordDataSchema (const)", + "RecordLock (type)", + "RecordLockEntry (type)", + "RecordLockEntrySchema (const)", + "RecordLockReasonSchema (const)", + "RecordLockSchema (const)", + "RecordLockSourceSchema (const)", "RecordPageActivityRequest (type)", "RecordPageActivityRequestParsed (type)", "RecordPageActivityRequestSchema (const)", From bd6c6769a02d36fbe20d72263e00b8bb4b8e5438 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 13:01:59 +0000 Subject: [PATCH 06/11] chore(spec): type aliases for the lock source and reason, and the generated reference page Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- content/docs/references/index.mdx | 9 +- packages/spec/api-surface/api.json | 2 + packages/spec/docs/references/README.md | 2 +- packages/spec/docs/references/api/README.md | 1 + .../spec/docs/references/api/record-lock.md | 176 ++++++++++++++++++ packages/spec/src/api/record-lock.zod.ts | 2 + 6 files changed, 187 insertions(+), 5 deletions(-) create mode 100644 packages/spec/docs/references/api/record-lock.md diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index c9e2b5de14e..60b69060fc0 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1750 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1756 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | | [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | -| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 38 | 534 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1750** | 14 protocol modules | +| **Total** | **225** | **1756** | 14 protocol modules | --- @@ -71,7 +71,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. ## API Protocol -**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 528 schemas** +**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **38 pages, 534 schemas** REST contracts, endpoints, routing, realtime, batch, discovery. @@ -107,6 +107,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery. | [`query-adapter.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/query-adapter.md) | `ODataQueryAdapter`, `OperatorMapping`, `QueryAdapterConfig`, `QueryAdapterTarget`, `RestQueryAdapter` | | [`realtime.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/realtime.md) | `RealtimeConfig`, `RealtimeEvent`, `RealtimeEventType`, `RealtimePresence`, `Subscription`, `SubscriptionEvent`, `TransportProtocol` | | [`realtime-shared.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/realtime-shared.md) | `BasePresence`, `PresenceStatus`, `RealtimeRecordAction` | +| [`record-lock.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/record-lock.md) | `GetRecordLocksRequest`, `GetRecordLocksResponse`, `RecordLock`, `RecordLockEntry`, `RecordLockReason`, `RecordLockSource` | | [`record-page.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/record-page.md) | `RecordPageActivityRequest`, `RecordPageApprovals`, `RecordPageAttachmentsRequest`, `RecordPageDiscussion`, `RecordPageDiscussionReactions`, `RecordPageExplainAnswer`, `RecordPageExplainOperation`, `RecordPagePartError`, `RecordPagePartRefusal`, `RecordPageRelatedAnswer`, `RecordPageRelatedRefusal`, `RecordPageRelatedRequest`, `RecordPageRelatedRows`, `RecordPageRequest`, `RecordPageResponse`, `RecordPageStreamRefusal`, `RecordPageStreamRows`, `RecordPageTimelineCount`, `RecordPageTimelineRequest` | | [`rest-server.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/rest-server.md) | `BatchEndpointsConfig`, `CrudEndpointsConfig`, `CrudOperation`, `EndpointRegistry`, `GeneratedEndpoint`, `MetadataEndpointsConfig`, `RestApiConfig`, `RestServerConfig`, `RouteGenerationConfig` | | [`router.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/router.md) | `ConflictResolutionStrategy`, `HttpMethod`, `RouteCategory`, `RouteDefinition`, `RouterConfig` | diff --git a/packages/spec/api-surface/api.json b/packages/spec/api-surface/api.json index 91764dfa325..ea90b9c7a32 100644 --- a/packages/spec/api-surface/api.json +++ b/packages/spec/api-surface/api.json @@ -1011,8 +1011,10 @@ "RecordLock (type)", "RecordLockEntry (type)", "RecordLockEntrySchema (const)", + "RecordLockReason (type)", "RecordLockReasonSchema (const)", "RecordLockSchema (const)", + "RecordLockSource (type)", "RecordLockSourceSchema (const)", "RecordPageActivityRequest (type)", "RecordPageActivityRequestParsed (type)", diff --git a/packages/spec/docs/references/README.md b/packages/spec/docs/references/README.md index 2ffe7512dc0..dee85b33bea 100644 --- a/packages/spec/docs/references/README.md +++ b/packages/spec/docs/references/README.md @@ -13,7 +13,7 @@ Zod sources and JSON Schema, at the version your project uses. | Module | Pages | Description | | :--- | ---: | :--- | -| [API Protocol](api/README.md) | 37 | REST contracts, endpoints, routing, realtime, batch, discovery. | +| [API Protocol](api/README.md) | 38 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Identity Protocol](identity/README.md) | 5 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](integration/README.md) | 1 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](kernel/README.md) | 30 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | diff --git a/packages/spec/docs/references/api/README.md b/packages/spec/docs/references/api/README.md index 600b5aa9784..ca6b385c127 100644 --- a/packages/spec/docs/references/api/README.md +++ b/packages/spec/docs/references/api/README.md @@ -54,5 +54,6 @@ stay there). - [Package Lifecycle](package-lifecycle.md) — `packages/spec/src/api/package-lifecycle.zod.ts` - [Push Delivery](push-delivery.md) — `packages/spec/src/api/push-delivery.zod.ts` - [Push Relay](push-relay.md) — `packages/spec/src/api/push-relay.zod.ts` +- [Record Lock](record-lock.md) — `packages/spec/src/api/record-lock.zod.ts` - [Record Page](record-page.md) — `packages/spec/src/api/record-page.zod.ts` - [Sortability](sortability.md) — `packages/spec/src/api/sortability.zod.ts` diff --git a/packages/spec/docs/references/api/record-lock.md b/packages/spec/docs/references/api/record-lock.md new file mode 100644 index 00000000000..51acb5c3c8e --- /dev/null +++ b/packages/spec/docs/references/api/record-lock.md @@ -0,0 +1,176 @@ +# Record Lock schema — API Protocol reference + + + +[ADR-0162 D9] The one lock read, owned by the data layer: +`GET /api/v1/data/{object}/{id}/lock` for one record and +`POST /api/v1/data/{object}/locks` for a page of records. + +It answers "is this record locked, and by which lock" for both producers the +record names: the engine's closed-state judgement (an object's +`closedStates`) and the approvals plugin's judgement of a pending request +under a node that locks, or of a passage of an approval on an object that +declares `closedStates`. It is there whether or not the approvals plugin is +installed; without it, only closed states lock. + +- **Who is answered.** Every caller who can read the record, whether or not + it may write it, and whether or not field permissions let it read the + state field. A record the caller cannot read answers as one that does not + exist. +- **What it never carries.** Which field or value closed the record, a + request id, or participants. +- **`locked` means locked for a caller.** A system context is bound by + neither lock; the read does not describe it. + +The approvals-family read (`GET /api/v1/approvals/records/{object}/{id}/lock`, +`IApprovalService.getRecordLock`) is a different read and stays as +published: it answers for a pending request only. + +> **Source:** `packages/spec/src/api/record-lock.zod.ts` + +## TypeScript Usage + +```typescript +import { GetRecordLocksRequestSchema, GetRecordLocksResponseSchema, RecordLockSchema, RecordLockEntrySchema, RecordLockReasonSchema, RecordLockSourceSchema } from '@objectstack/spec/api'; +import type { GetRecordLocksRequest, GetRecordLocksResponse, RecordLock, RecordLockEntry, RecordLockReason, RecordLockSource } from '@objectstack/spec/api'; + +// Validate data +const result = GetRecordLocksRequestSchema.parse(data); +``` + +--- + +## GetRecordLocksRequest + +The page lock read's body. + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **recordIds** | `string[]` | ✅ | The records to answer, at least one and at most 200; a repeated id is answered at each of its positions. | + + +--- + +## GetRecordLocksResponse + +The page lock read's answer (ADR-0162 D9). + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **records** | `({ recordId: string; locked: true; lockSource: Enum<'record' \| 'master'>; lockReason: Enum<'closed_state' \| 'approval'> } \| { recordId: string; locked: false \| null })[]` | ✅ | One entry per asked id, in order. | + +### Nested Shape: `GetRecordLocksResponse.records[number][option 1]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **recordId** | `string` | ✅ | The id as asked. | +| **locked** | `true` | ✅ | A caller's write of the record is refused by a lock. | +| **lockSource** | `Enum<'record' \| 'master'>` | ✅ | Whose lock holds the record: `record` (its own state or its own approval) or `master` (the master of a master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the request) and a line of a held master may not. Under `closed_state`, a caller's delete is refused for either source. | +| **lockReason** | `Enum<'closed_state' \| 'approval'>` | ✅ | Which lock holds the record: `closed_state` (a declared closed state, ADR-0162) or `approval` (a pending request under a node that locks, or a passage of an approval on an object that declares closedStates). When both hold, `closed_state` is answered. | + +### Nested Shape: `GetRecordLocksResponse.records[number][option 2]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **recordId** | `string` | ✅ | The id as asked. | +| **locked** | `false \| null` | ✅ | `false` when no lock holds the record; `null` when the caller cannot read it or it does not exist. | + + +--- + +## RecordLock + +One record's lock, as `GET /api/v1/data/{object}/{id}/lock` answers it (ADR-0162 D9). + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **locked** | `true` | ✅ | A caller's write of the record is refused by a lock. | +| **lockSource** | `Enum<'record' \| 'master'>` | ✅ | Whose lock holds the record: `record` (its own state or its own approval) or `master` (the master of a master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the request) and a line of a held master may not. Under `closed_state`, a caller's delete is refused for either source. | +| **lockReason** | `Enum<'closed_state' \| 'approval'>` | ✅ | Which lock holds the record: `closed_state` (a declared closed state, ADR-0162) or `approval` (a pending request under a node that locks, or a passage of an approval on an object that declares closedStates). When both hold, `closed_state` is answered. | + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **locked** | `false` | ✅ | No lock refuses a caller's write of the record. | + +--- + + +--- + +## RecordLockEntry + +One record of the page lock read. + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **recordId** | `string` | ✅ | The id as asked. | +| **locked** | `true` | ✅ | A caller's write of the record is refused by a lock. | +| **lockSource** | `Enum<'record' \| 'master'>` | ✅ | Whose lock holds the record: `record` (its own state or its own approval) or `master` (the master of a master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the request) and a line of a held master may not. Under `closed_state`, a caller's delete is refused for either source. | +| **lockReason** | `Enum<'closed_state' \| 'approval'>` | ✅ | Which lock holds the record: `closed_state` (a declared closed state, ADR-0162) or `approval` (a pending request under a node that locks, or a passage of an approval on an object that declares closedStates). When both hold, `closed_state` is answered. | + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **recordId** | `string` | ✅ | The id as asked. | +| **locked** | `false \| null` | ✅ | `false` when no lock holds the record; `null` when the caller cannot read it or it does not exist. | + +--- + + +--- + +## RecordLockReason + +Which lock holds the record: `closed_state` (a declared closed state, ADR-0162) or `approval` (a pending request under a node that locks, or a passage of an approval on an object that declares closedStates). When both hold, `closed_state` is answered. + +### Allowed Values + +* `closed_state` +* `approval` + + +--- + +## RecordLockSource + +Whose lock holds the record: `record` (its own state or its own approval) or `master` (the master of a master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the request) and a line of a held master may not. Under `closed_state`, a caller's delete is refused for either source. + +### Allowed Values + +* `record` +* `master` + + +--- + diff --git a/packages/spec/src/api/record-lock.zod.ts b/packages/spec/src/api/record-lock.zod.ts index c9794b431d0..9afc00c0d4a 100644 --- a/packages/spec/src/api/record-lock.zod.ts +++ b/packages/spec/src/api/record-lock.zod.ts @@ -46,6 +46,7 @@ export const RecordLockSourceSchema = z.enum(['record', 'master']).describe( + 'master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the ' + 'request) and a line of a held master may not. Under `closed_state`, a caller\'s delete is refused for either source.', ); +export type RecordLockSource = z.infer; /** Which producer holds a locked record. */ export const RecordLockReasonSchema = z.enum(['closed_state', 'approval']).describe( @@ -53,6 +54,7 @@ export const RecordLockReasonSchema = z.enum(['closed_state', 'approval']).descr + 'under a node that locks, or a passage of an approval on an object that declares closedStates). When both ' + 'hold, `closed_state` is answered.', ); +export type RecordLockReason = z.infer; /** * The answer for one readable record (ADR-0162 D9): From 2350ac495fd412f81ae5949b8f4d5b7b7c76fb62 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 13:03:55 +0000 Subject: [PATCH 07/11] chore(changeset): the lock read schemas enter the authorable surface, so spec is a minor The authorable-surface api shard records the two new request and response shapes, which the level axis reads as Metadata-protocol: added. Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- .changeset/37770-one-record-lock-read.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/37770-one-record-lock-read.md b/.changeset/37770-one-record-lock-read.md index 754b0a6e62c..e01b57a5d26 100644 --- a/.changeset/37770-one-record-lock-read.md +++ b/.changeset/37770-one-record-lock-read.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/objectql': patch '@objectstack/metadata-protocol': patch '@objectstack/rest': patch @@ -11,7 +11,7 @@ feat(data): one record lock read, for closed states and approvals Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added An app can now ask whether a record is locked, and by which lock, in one read that covers both locks a record can be under: a declared closed state (an object's `closedStates`, or a `master_detail` line of a closed record) and an approval. Before this, a client could only ask the approvals read, which knows nothing of closed states, so a closed invoice looked editable until the save was refused. From d0bec12201e942101e8b28dddce139028f85fd27 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 13:06:56 +0000 Subject: [PATCH 08/11] chore(spec): export origins and the llms.txt inventory count for the lock read module Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- packages/spec/export-origins/api.json | 13 +++++++++++++ packages/spec/llms.txt | 4 ++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/spec/export-origins/api.json b/packages/spec/export-origins/api.json index d218e9d6b2d..f218331770b 100644 --- a/packages/spec/export-origins/api.json +++ b/packages/spec/export-origins/api.json @@ -562,6 +562,10 @@ "GetRecordFieldAccessResponse": "src/api/protocol.zod.ts#GetRecordFieldAccessResponse (type)", "GetRecordFieldAccessResponseParsed": "src/api/protocol.zod.ts#GetRecordFieldAccessResponseParsed (type)", "GetRecordFieldAccessResponseSchema": "src/api/protocol.zod.ts#GetRecordFieldAccessResponseSchema (const)", + "GetRecordLocksRequest": "src/api/record-lock.zod.ts#GetRecordLocksRequest (type)", + "GetRecordLocksRequestSchema": "src/api/record-lock.zod.ts#GetRecordLocksRequestSchema (const)", + "GetRecordLocksResponse": "src/api/record-lock.zod.ts#GetRecordLocksResponse (type)", + "GetRecordLocksResponseSchema": "src/api/record-lock.zod.ts#GetRecordLocksResponseSchema (const)", "GetRunRequest": "src/api/automation-api.zod.ts#GetRunRequest (type)", "GetRunRequestSchema": "src/api/automation-api.zod.ts#GetRunRequestSchema (const)", "GetRunResponse": "src/api/automation-api.zod.ts#GetRunResponse (type)", @@ -931,6 +935,7 @@ "QueryOptimizationConfig": "src/api/contract.zod.ts#QueryOptimizationConfig (type)", "QueryOptimizationConfigParsed": "src/api/contract.zod.ts#QueryOptimizationConfigParsed (type)", "QueryOptimizationConfigSchema": "src/api/contract.zod.ts#QueryOptimizationConfigSchema (const)", + "RECORD_LOCKS_MAX_RECORD_IDS": "src/api/record-lock.zod.ts#RECORD_LOCKS_MAX_RECORD_IDS (const)", "RECORD_PAGE_MAX_ACTIVITY_ROWS": "src/api/record-page.zod.ts#RECORD_PAGE_MAX_ACTIVITY_ROWS (const)", "RECORD_PAGE_MAX_ATTACHMENT_ROWS": "src/api/record-page.zod.ts#RECORD_PAGE_MAX_ATTACHMENT_ROWS (const)", "RECORD_PAGE_MAX_RELATED": "src/api/record-page.zod.ts#RECORD_PAGE_MAX_RELATED (const)", @@ -972,6 +977,14 @@ "RealtimeUnsubscribeResponseSchema": "src/api/protocol.zod.ts#RealtimeUnsubscribeResponseSchema (const)", "RecordData": "src/api/contract.zod.ts#RecordData (type)", "RecordDataSchema": "src/api/contract.zod.ts#RecordDataSchema (const)", + "RecordLock": "src/api/record-lock.zod.ts#RecordLock (type)", + "RecordLockEntry": "src/api/record-lock.zod.ts#RecordLockEntry (type)", + "RecordLockEntrySchema": "src/api/record-lock.zod.ts#RecordLockEntrySchema (const)", + "RecordLockReason": "src/api/record-lock.zod.ts#RecordLockReason (type)", + "RecordLockReasonSchema": "src/api/record-lock.zod.ts#RecordLockReasonSchema (const)", + "RecordLockSchema": "src/api/record-lock.zod.ts#RecordLockSchema (const)", + "RecordLockSource": "src/api/record-lock.zod.ts#RecordLockSource (type)", + "RecordLockSourceSchema": "src/api/record-lock.zod.ts#RecordLockSourceSchema (const)", "RecordPageActivityRequest": "src/api/record-page.zod.ts#RecordPageActivityRequest (type)", "RecordPageActivityRequestParsed": "src/api/record-page.zod.ts#RecordPageActivityRequestParsed (type)", "RecordPageActivityRequestSchema": "src/api/record-page.zod.ts#RecordPageActivityRequestSchema (const)", diff --git a/packages/spec/llms.txt b/packages/spec/llms.txt index 874bd2d21a8..61b6d8a0fd6 100644 --- a/packages/spec/llms.txt +++ b/packages/spec/llms.txt @@ -77,7 +77,7 @@ const query = { --- -## 3. Schema Inventory by Domain (233 schemas) +## 3. Schema Inventory by Domain (234 schemas) Counted as `*.zod.ts` modules under `packages/spec/src//` — the sources that ship in this tarball (`files` includes `src/**/*.zod.ts`), so every number @@ -88,7 +88,7 @@ here is verifiable from the installed package. | system | 40 | Auth, Cache, Demo Staff, Dev Login, Email / SMS / Push Config, Push Device, Encryption, Fate Supplement (organization ownership), HTTP Server, License, Logging, Metrics, Restriction Profile | | kernel | 31 | Plugin, Manifest, Events (6 sub-modules), Feature, Context, Package Registry, Override Declaration | | data | 37 | Object, Field, Picklist, Query, Filter, Driver (SQL/NoSQL/Memory/Mongo/Postgres/Oracle/SQL Server), Cube, Seed, Recycle Bin, Declared Entry (refusal / text) | -| api | 36 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, App Metadata Bundle, Push Delivery, Push Relay, AI Answer Follow-ups | +| api | 37 | Endpoint, REST Server, Discovery, OData, Batch, WebSocket, Response Envelope, Package Lifecycle, Package API (assembled stage), Record Page, Record Lock, App Metadata Bundle, Push Delivery, Push Relay, AI Answer Follow-ups | | ui | 19 | View, App (incl. AI Chat Nav Params), Action, Dashboard, Page, Chart, Component, Animation | | automation | 16 | Flow, Approval, Assignment Rule, BPMN Interop, Control Flow, Webhook, Schedule Organization | | shared | 16 | Enums, HTTP, Identifiers, Mapping, Metadata Types, Connector Auth, Retry Policy, Conditional Formatting, Value Domain, Epoch Instant (EpochMs), Duration (DurationMs / DurationSeconds) | From 98e8699ea9d7b4e6d4fafb3f58bc99d9d706d001 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 13:33:58 +0000 Subject: [PATCH 09/11] fix(data): one-line engine forwarders, shared refusal door, isomorphic pins (#37770) - engine.ts: getRecordLock/getRecordLocks are one-statement forwarders handing record-lock-read.ts the update facet host and the engine. - record-lock-routes.ts answers refusals through handleRouteError and is declared conformant in check-route-envelope. - RecordLockSource/RecordLockReason are z.input aliases; the six record lock shapes are pinned isomorphic (ADR-0122). - The integration test passes its engine options untyped-cast-free. Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- packages/objectql/src/engine.ts | 38 ++----------- packages/objectql/src/record-lock-read.ts | 53 +++++++++++++------ ...rd-lock-one-read-37770.integration.test.ts | 14 ++--- packages/rest/src/record-lock-routes.ts | 14 ++--- packages/spec/src/api/record-lock.zod.ts | 4 +- .../src/type-alias-convention.pin.test.ts | 20 +++++-- scripts/check-route-envelope.mjs | 3 ++ 7 files changed, 73 insertions(+), 73 deletions(-) diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 0529ba5c20a..9fddad36aaf 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -283,9 +283,7 @@ import { validate } from './engine-validate.js'; // [#32768] The write-free `readonlyWhen` judgement's body; `judgeFieldWriteLock` // below hands it the members it reads (`FieldWriteLockHost`). import { judgeFieldWriteLock, type FieldWriteLock } from './engine-field-write-lock.js'; -// [ADR-0162 D9] The one lock read's body; `getRecordLock` / `getRecordLocks` below hand it a host. -import { getRecordLock as getRecordLockBody, getRecordLocks as getRecordLocksBody, type RecordLockReadHost } from './record-lock-read.js'; -import type { RecordLock } from '@objectstack/spec/api'; +import * as RecordLockRead from './record-lock-read.js'; // [#25522 cut 20] The `where`-lowering bodies (`QueryLoweringHost`), imported // after every module they import, so module evaluation order is unchanged. import { lowerRelationConditions, resolveSearchQueryableFields, resolveWhereTokens } from './engine-query-lowering.js'; @@ -4722,38 +4720,8 @@ export class ObjectQL implements IObjectQLEngine { return judgeFieldWriteLock.call(host, object, id, field, options); } - /** - * [ADR-0162 D9] The one lock read for one record, as the caller: - * `{ locked, lockSource?, lockReason? }`, both kinds present exactly when - * `locked` is true, composed from the closed-state judgement and the - * approvals producer when one is bound; `null` when the caller cannot read - * the record or it does not exist. See `record-lock-read.ts`. - */ - getRecordLock(object: string, recordId: string, options?: { context?: ExecutionContext }): Promise { - return getRecordLockBody.call(this.recordLockReadHost(), object, recordId, options?.context); - } - - /** - * [ADR-0162 D9] {@link getRecordLock} for a page of records (at most - * `RECORD_LOCKS_MAX_RECORD_IDS`): entry `i` answers `recordIds[i]`. A row - * counts as readable only when the caller's read hands back the row whose - * id IS the asked id. See `record-lock-read.ts`. - */ - getRecordLocks(object: string, recordIds: readonly string[], options?: { context?: ExecutionContext }): Promise> { - return getRecordLocksBody.call(this.recordLockReadHost(), object, recordIds, options?.context); - } - - private recordLockReadHost(): RecordLockReadHost { - const readRegistry = () => this._registry; - return { - get _registry() { return readRegistry(); }, - resolveObjectName: (...a) => this.resolveObjectName(...a), - getDriver: (...a) => this.getDriver(...a), - buildDriverOptions: (...a) => this.buildDriverOptions(...a), - find: (object, query) => this.find(object, query as EngineQueryOptions), - facade: this, - }; - } + getRecordLock(object: string, recordId: string, options?: { context?: ExecutionContext }) { return RecordLockRead.getRecordLock(updateHost.of(this), this, object, recordId, options); } + getRecordLocks(object: string, recordIds: readonly string[], options?: { context?: ExecutionContext }) { return RecordLockRead.getRecordLocks(updateHost.of(this), this, object, recordIds, options); } private updateByIdExpecting( driver: IDataDriver, diff --git a/packages/objectql/src/record-lock-read.ts b/packages/objectql/src/record-lock-read.ts index 148097b93b1..dd74dc847e6 100644 --- a/packages/objectql/src/record-lock-read.ts +++ b/packages/objectql/src/record-lock-read.ts @@ -82,11 +82,26 @@ export type ApprovalRecordLockProducer = ( recordIds: readonly string[], ) => Promise>; -/** The engine members the read uses. */ -export interface RecordLockReadHost extends Pick { +/** + * The engine's store members the closed-state producer uses — the engine's + * update facet host (`updateHost`), which the closed-state lock's own write + * judgements are handed too. + */ +export type RecordLockStoreHost = Pick; + +/** + * The engine itself, as the read sees it: its public read (the readability + * anchor, as the caller), and the object whose + * {@link APPROVAL_RECORD_LOCK_PRODUCER} slot is read at use. + */ +export interface RecordLockEngine { find(object: string, query: Record): Promise; - /** The engine itself, whose {@link APPROVAL_RECORD_LOCK_PRODUCER} slot is read at use. */ - readonly facade: object; +} + +/** What the two bodies are handed: the store host and the engine. */ +interface RecordLockReadHost { + readonly store: RecordLockStoreHost; + readonly engine: RecordLockEngine; } /** The refusal of a page over {@link RECORD_LOCKS_MAX_RECORD_IDS}, or of a malformed id list. */ @@ -122,7 +137,7 @@ interface ClosedStateLocks { * caller's organization scope. */ async function closedStateLocks( - this: RecordLockReadHost, + this: RecordLockStoreHost, object: string, ids: readonly string[], context: ExecutionContext | undefined, @@ -191,14 +206,14 @@ async function judge( ): Promise> { const out = new Map(); if (ids.length === 0) return out; - const closed = await closedStateLocks.call(this, object, ids, context); - const producer = approvalProducerOf(this.facade); + const closed = await closedStateLocks.call(this.store, object, ids, context); + const producer = approvalProducerOf(this.engine); const approval = producer ? await producer(object, ids) : new Map(); for (const id of ids) out.set(id, composeAnswer(id, closed, approval)); return out; } -function registryName(host: Pick, object: string): string { +function registryName(host: Pick, object: string): string { try { return host.resolveObjectName(object); } catch { @@ -211,20 +226,23 @@ function registryName(host: Pick, objec * read it or it does not exist. */ export async function getRecordLock( - this: RecordLockReadHost, + store: RecordLockStoreHost, + engine: RecordLockEngine, object: string, recordId: string, - context: ExecutionContext | undefined, + options?: { context?: ExecutionContext }, ): Promise { + const host: RecordLockReadHost = { store, engine }; + const context = options?.context; const name = String(object ?? '').trim(); const id = String(recordId ?? '').trim(); if (!name || !id) return null; // The anchor, as the CALLER: any row the by-id read hands back counts. - const rows = await this.find(name, { where: { id }, fields: ['id'], limit: 1, context }); + const rows = await engine.find(name, { where: { id }, fields: ['id'], limit: 1, context }); const found = Array.isArray(rows) ? rows[0] : undefined; if (!found || found.id == null) return null; const spelled = String(found.id); - const answers = await judge.call(this, registryName(this, name), [spelled], context); + const answers = await judge.call(host, registryName(store, name), [spelled], context); return answers.get(spelled) ?? { locked: false }; } @@ -235,11 +253,14 @@ export async function getRecordLock( * (`400 VALIDATION_ERROR`); a blank id answers `null`. */ export async function getRecordLocks( - this: RecordLockReadHost, + store: RecordLockStoreHost, + engine: RecordLockEngine, object: string, recordIds: readonly string[], - context: ExecutionContext | undefined, + options?: { context?: ExecutionContext }, ): Promise> { + const host: RecordLockReadHost = { store, engine }; + const context = options?.context; if (!Array.isArray(recordIds)) throw recordLocksRefusal('The page lock read takes a list of record ids.'); if (recordIds.length > RECORD_LOCKS_MAX_RECORD_IDS) { throw recordLocksRefusal( @@ -251,9 +272,9 @@ export async function getRecordLocks( const asked = [...new Set(ids.filter((id) => id !== ''))]; if (!name || asked.length === 0) return ids.map(() => null); // The anchor, as the CALLER: a row counts only when its id IS the asked id. - const rows = await this.find(name, { where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context }); + const rows = await engine.find(name, { where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context }); const readable = new Set((Array.isArray(rows) ? rows : []).filter((r) => r && r.id != null).map((r) => String(r.id))); const readableAsked = asked.filter((id) => readable.has(id)); - const answers = await judge.call(this, registryName(this, name), readableAsked, context); + const answers = await judge.call(host, registryName(store, name), readableAsked, context); return ids.map((id) => (readable.has(id) ? answers.get(id) ?? { locked: false } : null)); } diff --git a/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts index bfbda9ec1b9..3b409b3e387 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-one-read-37770.integration.test.ts @@ -189,15 +189,15 @@ async function boot(options: { approvals: boolean } = { approvals: true }): Prom const svc = services.approvals as ApprovalService | undefined; for (const id of Object.values(I)) { - await engine.insert(INV, { id, title: id, stage: 'draft' }, { context: SYSTEM } as any); + await engine.insert(INV, { id, title: id, stage: 'draft' }, { context: SYSTEM }); } const lineUnder: Array<[string, string]> = [ [L.ofClosed, I.closed], [L.ofHeld, I.held], [L.ofBoth, I.both], [L.ofOpen, I.open], [L.hidden, I.open], ]; for (const [id, master] of lineUnder) { - await engine.insert(LINE, { id, title: id, invoice: master }, { context: SYSTEM } as any); + await engine.insert(LINE, { id, title: id, invoice: master }, { context: SYSTEM }); } - await engine.insert(MEMO, { id: 'memo_a', title: 'memo_a' }, { context: SYSTEM } as any); + await engine.insert(MEMO, { id: 'memo_a', title: 'memo_a' }, { context: SYSTEM }); const requests = new Map(); if (svc) { @@ -212,7 +212,7 @@ async function boot(options: { approvals: boolean } = { approvals: true }): Prom } // Closed after the approvals opened: a system write is bound by neither lock. for (const id of [I.closed, I.both]) { - await engine.update(INV, { id, stage: 'done' }, { context: SYSTEM } as any); + await engine.update(INV, { id, stage: 'done' }, { context: SYSTEM }); } return { engine, svc, plugin, requests }; } @@ -241,7 +241,7 @@ describe('[ADR-0162 D9] ObjectQL#getRecordLock — one read for closed states an expect(await lockAs(rig, SUBMITTER, INV, I.hidden)).toEqual(OPEN); expect(await lockAs(rig, READER, INV, I.hidden)).toBeNull(); expect(await lockAs(rig, READER, LINE, L.hidden)).toBeNull(); - await rig.engine.update(INV, { id: I.hidden, stage: 'done' }, { context: SYSTEM } as any); + await rig.engine.update(INV, { id: I.hidden, stage: 'done' }, { context: SYSTEM }); expect(await lockAs(rig, SUBMITTER, INV, I.hidden)).toEqual(CLOSED_OWN); expect(await lockAs(rig, READER, INV, I.hidden)).toBeNull(); }); @@ -250,7 +250,7 @@ describe('[ADR-0162 D9] ObjectQL#getRecordLock — one read for closed states an const rig = await boot(); const writeAs = async (object: string, id: string) => { try { - await rig.engine.update(object, { id, title: 'edited' }, { context: asUser(SUBMITTER) } as any); + await rig.engine.update(object, { id, title: 'edited' }, { context: asUser(SUBMITTER) }); return 'written'; } catch (err: any) { return String(err?.code ?? err?.message); @@ -266,7 +266,7 @@ describe('[ADR-0162 D9] ObjectQL#getRecordLock — one read for closed states an it('tells a reader whose field permissions hide the state field that the record is closed', async () => { const rig = await boot(); // The stand-in refuses the reader any query naming `stage`… - const direct = await rig.engine.find(INV, { where: { stage: 'done' }, context: asUser(READER) } as any) + const direct = await rig.engine.find(INV, { where: { stage: 'done' }, context: asUser(READER) }) .then(() => 'read', (err: any) => String(err?.code)); expect(direct).toBe('FIELD_NOT_ACCESSIBLE'); // …and the lock read tells them all the same, naming neither field nor value. diff --git a/packages/rest/src/record-lock-routes.ts b/packages/rest/src/record-lock-routes.ts index d93ff87f9b1..f86f39aaccf 100644 --- a/packages/rest/src/record-lock-routes.ts +++ b/packages/rest/src/record-lock-routes.ts @@ -36,9 +36,9 @@ import { RECORD_LOCKS_MAX_RECORD_IDS, type RecordLock } from '@objectstack/spec/api'; import { recordNotFoundError } from '@objectstack/core'; -import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; +import { sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; import { refuseUnknownQueryParams } from './query-allowlist.js'; -import { logUnexpectedRouteError, mapDataError } from './error-response.js'; +import { handleRouteError } from './error-response.js'; import type { DataActionRouteHost } from './data-action-routes.js'; /** @@ -150,10 +150,7 @@ export function registerRecordLockEndpoints(this: RecordLockRouteHost, basePath: if (lock === null) throw recordNotFoundError(object, id, context); sendOk(res, recordLockAnswer(lock)); } catch (error: any) { - const mapped = mapDataError(error, req.params?.object); - logUnexpectedRouteError(error, mapped); - if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); - res.status(mapped.status).json(mapped.body); + handleRouteError(res, error, req.params?.object); } }, metadata: { @@ -195,10 +192,7 @@ export function registerRecordLockEndpoints(this: RecordLockRouteHost, basePath: }), }); } catch (error: any) { - const mapped = mapDataError(error, req.params?.object); - logUnexpectedRouteError(error, mapped); - if (answerVariesByLanguage(mapped.body)) res.header('Vary', [LOCALIZED_ANSWER_VARY]); - res.status(mapped.status).json(mapped.body); + handleRouteError(res, error, req.params?.object); } }, metadata: { diff --git a/packages/spec/src/api/record-lock.zod.ts b/packages/spec/src/api/record-lock.zod.ts index 9afc00c0d4a..481417fd3a4 100644 --- a/packages/spec/src/api/record-lock.zod.ts +++ b/packages/spec/src/api/record-lock.zod.ts @@ -46,7 +46,7 @@ export const RecordLockSourceSchema = z.enum(['record', 'master']).describe( + 'master_detail line). Under `approval`, a record held on its own may still be deleted (the delete cancels the ' + 'request) and a line of a held master may not. Under `closed_state`, a caller\'s delete is refused for either source.', ); -export type RecordLockSource = z.infer; +export type RecordLockSource = z.input; /** Which producer holds a locked record. */ export const RecordLockReasonSchema = z.enum(['closed_state', 'approval']).describe( @@ -54,7 +54,7 @@ export const RecordLockReasonSchema = z.enum(['closed_state', 'approval']).descr + 'under a node that locks, or a passage of an approval on an object that declares closedStates). When both ' + 'hold, `closed_state` is answered.', ); -export type RecordLockReason = z.infer; +export type RecordLockReason = z.input; /** * The answer for one readable record (ADR-0162 D9): diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index e4148007f59..c4a64bb79ae 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -303,9 +303,11 @@ import type * as M204 from './ai/dataset-tools.zod.js'; import type * as M205 from './ai/object-query-source.zod.js'; // The AI answer follow-up routes (saved questions, answer artifact, answer feedback) -- new module, next free index. import type * as M207 from './api/ai-answer.zod.js'; +// [ADR-0162 D9] The one record lock read's answer and page shapes -- new module, next free index. +import type * as M208 from './api/record-lock.zod.js'; // --------------------------------------------------------------------------- -// 882 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 888 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -728,6 +730,14 @@ export type Iso_api_realtime__SubscriptionEventSchema = Assert, z.infer< typeof M31.SubscriptionSchema > >>; export type Iso_api_realtime__TransportProtocol = Assert, z.infer< typeof M31.TransportProtocol > >>; +// api/record-lock.zod.ts +export type Iso_api_recordLock__GetRecordLocksRequestSchema = Assert, z.infer< typeof M208.GetRecordLocksRequestSchema > >>; +export type Iso_api_recordLock__GetRecordLocksResponseSchema = Assert, z.infer< typeof M208.GetRecordLocksResponseSchema > >>; +export type Iso_api_recordLock__RecordLockEntrySchema = Assert, z.infer< typeof M208.RecordLockEntrySchema > >>; +export type Iso_api_recordLock__RecordLockReasonSchema = Assert, z.infer< typeof M208.RecordLockReasonSchema > >>; +export type Iso_api_recordLock__RecordLockSchema = Assert, z.infer< typeof M208.RecordLockSchema > >>; +export type Iso_api_recordLock__RecordLockSourceSchema = Assert, z.infer< typeof M208.RecordLockSourceSchema > >>; + // api/rest-server.zod.ts export type Iso_api_restServer__CrudOperation = Assert, z.infer< typeof M32.CrudOperation > >>; export type Iso_api_restServer__EndpointRegistrySchema = Assert, z.infer< typeof M32.EndpointRegistrySchema > >>; @@ -1849,7 +1859,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 882 isomorphic pins', () => { + it('still declares all 888 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2997,7 +3007,11 @@ describe('ADR-0122 type-alias convention', () => { // `KnowledgeRetrievalModeSchema` (`ai/knowledge-source.zod.ts`), a plain // enum with no default or transform // (Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema). +1 added. - expect(pins).toHaveLength(882); + // 882 -> 888 is #37770 (ADR-0162 D9): the one record lock read's shapes + // (`api/record-lock.zod.ts`), two closed enums, two unions of strict + // objects and two strict objects, none with a default or a transform + // (Iso_api_recordLock__*). +6 added. + expect(pins).toHaveLength(888); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either diff --git a/scripts/check-route-envelope.mjs b/scripts/check-route-envelope.mjs index 4729309e965..d35aae7c146 100644 --- a/scripts/check-route-envelope.mjs +++ b/scripts/check-route-envelope.mjs @@ -254,6 +254,9 @@ const MODULES = { // #35402: the Change Owner doors answer only through the shared writers (and // `handleRouteError`, the `/data` write door's own classification of a throw). 'packages/rest/src/change-owner-routes.ts': { responses: 0, ok: 0, err: 0 }, + // #37770 (ADR-0162 D9): the record lock read's two doors answer only through + // the shared writers and `handleRouteError`. + 'packages/rest/src/record-lock-routes.ts': { responses: 0, ok: 0, err: 0 }, // #3636 put the right envelope on this module's three read routes but built it // inline in four places, so it carried a ratchet at 5 / 4 / 1 until those // collapsed behind a local `sendOk` — and then onto the shared one. From dd7675de607d7781f7c27e8126dbc2b5ea85b8a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 13:46:10 +0000 Subject: [PATCH 10/11] test(data): register the lock routes in the REST censuses; protocol facet names (#37770) - record-lock-routes.ts joins REST_SERVER_REGISTRAR_FILES, with its query-slot floor (0) and docblock floor (9); the page door's #8497 disposition is no-record-echo. - The protocol facet functions are readRecordLock / readRecordLocks, so the canonical-fold census resolves the stubs to their bodies. - The approvals producer's record-id sets no longer read as pending slates. - engine.ts drops the blank line after the two forwarders (+3). Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- packages/metadata-protocol/src/protocol-record-lock.ts | 4 ++-- packages/metadata-protocol/src/protocol.ts | 6 +++--- packages/objectql/src/engine.ts | 1 - .../plugins/plugin-approvals/src/record-lock-producer.ts | 6 +++--- packages/rest/src/rest-server-canonical-query-ast.test.ts | 3 +++ packages/rest/src/rest-server-docblock-position.test.ts | 7 ++++++- packages/rest/src/rest-server-registrar-files.ts | 3 +++ .../rest-write-response-internal-fields.tripwire.test.ts | 6 ++++++ 8 files changed, 26 insertions(+), 10 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-record-lock.ts b/packages/metadata-protocol/src/protocol-record-lock.ts index bb8e13d3931..2c541601692 100644 --- a/packages/metadata-protocol/src/protocol-record-lock.ts +++ b/packages/metadata-protocol/src/protocol-record-lock.ts @@ -21,7 +21,7 @@ import type { RecordLock } from '@objectstack/spec/api'; import type { ProtocolHost } from './protocol-host.js'; /** One record's lock, as the caller; `null` unreadable or missing; `undefined` when the engine has no read. */ -export async function getRecordLock( +export async function readRecordLock( host: Pick, request: { object: string; id: string; context?: any }, ): Promise { @@ -35,7 +35,7 @@ export async function getRecordLock( * A page of records' locks, as the caller: entry `i` answers `recordIds[i]`. * `undefined` when the engine has no read. The bound is the engine's. */ -export async function getRecordLocks( +export async function readRecordLocks( host: Pick, request: { object: string; recordIds: readonly string[]; context?: any }, ): Promise | undefined> { diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index df5e3d589cd..b0eff0aac4b 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -624,7 +624,7 @@ import { ProtocolPackageCommitsFacet } from './protocol-package-commits.js'; import { ProtocolPackageMoveInFacet, type MoveIntoPackageRequest } from './protocol-package-move-in.js'; // [#29985 codemod] Diff, deleteMetaItem, loadMetaFromDb, load reports, findReferencesToMeta: the members below delegate to its facet, `ProtocolDiffDeleteLoadFacet`. import { ProtocolDiffDeleteLoadFacet } from './protocol-diff-delete-load.js'; -import { getRecordLock as getRecordLockFacet, getRecordLocks as getRecordLocksFacet } from './protocol-record-lock.js'; +import { readRecordLock, readRecordLocks } from './protocol-record-lock.js'; import type { RecordLock } from '@objectstack/spec/api'; /** @@ -5204,7 +5204,7 @@ export class ObjectStackProtocolImplementation implements * record or it does not exist; `undefined` when the engine has no read. */ async getRecordLock(request: { object: string, id: string, context?: any }): Promise { - return getRecordLockFacet(protocolHost(this), request); + return readRecordLock(protocolHost(this), request); } /** @@ -5212,7 +5212,7 @@ export class ObjectStackProtocolImplementation implements * `recordIds[i]` (`protocol-record-lock.ts`). */ async getRecordLocks(request: { object: string, recordIds: readonly string[], context?: any }): Promise | undefined> { - return getRecordLocksFacet(protocolHost(this), request); + return readRecordLocks(protocolHost(this), request); } /** diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 9fddad36aaf..cee30fc8315 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4722,7 +4722,6 @@ export class ObjectQL implements IObjectQLEngine { getRecordLock(object: string, recordId: string, options?: { context?: ExecutionContext }) { return RecordLockRead.getRecordLock(updateHost.of(this), this, object, recordId, options); } getRecordLocks(object: string, recordIds: readonly string[], options?: { context?: ExecutionContext }) { return RecordLockRead.getRecordLocks(updateHost.of(this), this, object, recordIds, options); } - private updateByIdExpecting( driver: IDataDriver, object: string, diff --git a/packages/plugins/plugin-approvals/src/record-lock-producer.ts b/packages/plugins/plugin-approvals/src/record-lock-producer.ts index 445c9889238..3561a845894 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-producer.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-producer.ts @@ -129,15 +129,15 @@ export async function approvalRecordLocks( const out = new Map(); const ids = [...new Set(recordIds.map(String).filter((id) => id !== ''))]; if (ids.length === 0) return out; - const [ownPending, ownPassage, linePending, linePassage] = await Promise.all([ + const [ownLockingNode, ownPassage, lineLockingNode, linePassage] = await Promise.all([ recordsHeldByLockingApproval(engine, objectName, ids), recordsHeldInPassage(engine, objectName, ids), detailRowsHeldByLockingApproval(engine, objectName, ids), detailRowsHeldInPassage(engine, objectName, ids), ]); for (const id of ids) { - if (linePending.has(id) || linePassage.has(id)) out.set(id, 'master'); - else if (ownPending.has(id) || ownPassage.has(id)) out.set(id, 'record'); + if (lineLockingNode.has(id) || linePassage.has(id)) out.set(id, 'master'); + else if (ownLockingNode.has(id) || ownPassage.has(id)) out.set(id, 'record'); } return out; } diff --git a/packages/rest/src/rest-server-canonical-query-ast.test.ts b/packages/rest/src/rest-server-canonical-query-ast.test.ts index 85da7f34e23..dab6fffb3f9 100644 --- a/packages/rest/src/rest-server-canonical-query-ast.test.ts +++ b/packages/rest/src/rest-server-canonical-query-ast.test.ts @@ -257,6 +257,9 @@ const REGISTRAR_QUERY_SLOT_FLOORS: Readonly = REST_SERVER_REGISTRAR_FILES .filter((file): file is Exclude => file !== FILE) @@ -333,6 +337,7 @@ describe('[#23050 slice 3] the registrar list this pin reads', () => { // [#30237] 108 + 11 = 119: `recycle-bin-routes.ts`, a new registrar. // [ADR-0158 U7 R1] 119 + 6 = 125: `meta-unit-code-backfill-route.ts`, a new registrar. // [#35402] 125 + 14 = 139: `change-owner-routes.ts`, a new registrar. - expect(MOVED_FILES.reduce((n, { minBlocks }) => n + minBlocks, 0)).toBe(139); + // [#37770] 139 + 9 = 148: `record-lock-routes.ts`, a new registrar. + expect(MOVED_FILES.reduce((n, { minBlocks }) => n + minBlocks, 0)).toBe(148); }); }); diff --git a/packages/rest/src/rest-server-registrar-files.ts b/packages/rest/src/rest-server-registrar-files.ts index 4ea6c0ccee9..5c8adba1954 100644 --- a/packages/rest/src/rest-server-registrar-files.ts +++ b/packages/rest/src/rest-server-registrar-files.ts @@ -91,6 +91,9 @@ export const REST_SERVER_REGISTRAR_FILES = [ // [#35402] `registerChangeOwnerEndpoints`' body, the Change Owner action's doors under // `{data}/:object/change-owner` and `{data}/:object/:id/change-owner`. New, not a moved slice. 'change-owner-routes.ts', + // [#37770] `registerRecordLockEndpoints`' body, the one record lock read's doors + // `{data}/:object/:id/lock` and `{data}/:object/locks`. New, not a moved slice. + 'record-lock-routes.ts', ] as const; /** One file on {@link REST_SERVER_REGISTRAR_FILES}. */ diff --git a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts index 4def3367a6c..5874392c363 100644 --- a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts +++ b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts @@ -361,6 +361,12 @@ const DISPOSITIONS: Record = { // Metadata plane: bodies carry metadata ITEMS. `internal: true` is a field // flag on a data object's field, and a metadata item is not a data record. 'POST /api/v1/meta/_migrate-stored': { kind: 'no-record-echo', why: 'Metadata plane: migration receipt.' }, + // [#37770] A READ over POST: each entry is the asked id plus the lock's two + // closed enums (`lockSource`, `lockReason`) or `locked: false | null`. + [`POST ${D}/:object/locks`]: { + kind: 'no-record-echo', + why: 'Record lock page read: the asked ids and closed lock enums, never a stored field value.', + }, // [#30675] Writes a data object's rows, but answers only the run's report: // counts, a few record ids, and per-row failure sentences — no stored value. 'POST /api/v1/meta/_migrate-record-currency-codes': { From 1eb27e75b91a3da4f1bf9aa4ad2d54a970e572d3 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 14:35:22 +0000 Subject: [PATCH 11/11] chore(objectql): engine.ts facade ceiling 6857 -> 6860, ruling 7314474264 (#37770) The maintainer ruled the engine.ts line ceiling may rise by the measured growth of the record lock read's two forwarders and their import (+3), ruling record 7314474264 on #37770. baseLines/baseCommit re-measured at dd7675de60 (6860 lines); maxLines 6860. Claude-Session: https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM Co-authored-by: Claude --- scripts/facade-delegation-registry.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/facade-delegation-registry.json b/scripts/facade-delegation-registry.json index 9e5a678d705..5fbac0c75f4 100644 --- a/scripts/facade-delegation-registry.json +++ b/scripts/facade-delegation-registry.json @@ -243,10 +243,10 @@ }, { "file": "packages/objectql/src/engine.ts", - "baseLines": 6853, - "baseCommit": "170ca481f0", - "maxLines": 6857, - "ruling": "7051956587" + "baseLines": 6860, + "baseCommit": "dd7675de60", + "maxLines": 6860, + "ruling": "7314474264" }, { "file": "packages/drivers/driver-sql/src/sql-driver.ts",