Skip to content

Commit 7b68db9

Browse files
feat(data): one record lock read owned by the data layer (ADR-0162 D9) (#38913)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwB8bGG76Ba3qpTAkGh8yPgHA)_ Fixes #37770 Clause-②: yes (widening) Metadata-protocol: added Skills-docs: follow-up #38961 ## 维护者速读 - 新增一个由数据层回答的锁读取(单条和一页最多 200 条),告诉任何能读记录的人它是否被锁、是因关闭态还是因审批锁住。 - 不装审批插件也能用,此时只有关闭态会锁;审批原有的读取、SDK 方法和服务成员一字未改。 - 上传链接在发放前改问这个读取,关闭的记录用新句子拒绝,审批中的记录仍用原句子。 - 控制台记录页、表格和明细表格改问这个读取的工作归 #37773,不在本 PR。 ## What changes ADR-0162 D9: one answer to "is this record locked, and by which lock", for both locks a record can be under. - **Answer shape** (`packages/spec/src/api/record-lock.zod.ts`): `RecordLockSchema`, `GetRecordLocksRequestSchema`, `RecordLockEntrySchema`, `GetRecordLocksResponseSchema`, `RECORD_LOCKS_MAX_RECORD_IDS = 200`. Spelled as two strict arms (`locked: true` with both kinds, `locked: false` with none) so the published JSON Schema carries the "both kinds exactly when locked" rule too. Done-when item 5 (N12): **the internal seam requires the source**, so `lockSource` is never optional under `approval`. - **The read** (`packages/objectql/src/record-lock-read.ts`, `ObjectQL#getRecordLock` / `#getRecordLocks`). Readability is read as the caller, with each form's approvals-counterpart anchor (seat ruling 7152650156): the single read counts any row its by-id read returns and judges the engine-spelled id; the page counts a row only when its id is the asked id. The closed-state producer reads straight from the driver, above the caller's grants (so field permissions on the state field do not hide the answer, per D9) and inside the caller's org scope (`buildDriverOptions`). A store read that fails is thrown, never read as open. Order: `closed_state` before `approval`; within a reason `master` before `record`. - **The approvals producer** (`packages/plugins/plugin-approvals/src/record-lock-producer.ts`): pending under a locking node, or a passage on a `closedStates` object, for the record itself and for `master_detail` lines of such a master. It reuses the lock hooks' own helpers (four of them gain `export` in `lifecycle-hooks.ts`, which the package entry does not re-export). It is bound beside the lock hooks inside the `disableAutoHooks` block and cleared in `destroy()`, so a composition that binds no approval lock answers no approval lock. - **Data protocol** (`packages/metadata-protocol/src/protocol-record-lock.ts`): `getRecordLock` / `getRecordLocks`, the object-existence gate first, then the engine. An engine without the read answers `undefined`, which the REST doors turn into 501. - **REST** (`packages/rest/src/record-lock-routes.ts`, registered from `data-action-routes.ts`, so `rest-server.ts` does not move): closed empty query sets, `sendOk` envelope, the by-id read's localized `404 RECORD_NOT_FOUND` with `Vary`, 400 for a bad page body, 501 when the read is missing. Two ledger rows (`data.getRecordLock`, `data.getRecordLocks`) with their response schemas. - **SDK** (`packages/client`): `data.getRecordLock(object, id)` and `data.getRecordLocks(object, recordIds)`, with the types re-exported. - **Upload-link door** (`packages/services/service-storage/src/record-file-access.ts`): asks `engine.getRecordLock` as the caller before it issues a field link and refuses `409 RECORD_LOCKED` with "the record is closed, so no file can be added to it" on `closed_state`, or the existing approval sentence on `approval`. An engine without the read falls back to the approvals service, as before. - **Docs**: `content/docs/api/data-api.mdx` § Record locks, `content/docs/api/client-sdk.mdx`, and a pointer from the approvals lock reads in `content/docs/automation/approvals.mdx`. - **Engine line ceiling**: `engine.ts` gains one import line and two one-statement forwarders (+3, 6857 → 6860). The `check:facade-delegation-only` row is raised by that measured growth, per the maintainer's ruling record [7314474264](#37770 (comment)) on #37770 (「提到 6861」): `baseLines` 6860 at `dd7675de60`, `maxLines` 6860. No other engine growth is covered by that ruling. - **Level**: the two new request and response shapes enter the `api` authorable-surface shard, which the changeset level axis reads as `Metadata-protocol: added`, so `@objectstack/spec` is a `minor`; the other packages are `patch`. Out of scope here: moving the console askers (record page, grid, line grid) onto this read belongs to #37773, together with its wording. Follow-ups: #38961 (the skills page § Reading the lock points at this read) and #38962 (the contract review's nits: pin the passage arm and the read's jsdoc on a failed store read; the closed-state lines' semi-join and the repeated foreign-key read). ## Why 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. ADR-0162 D9 (adopted, ruling record 7200732942) puts one read in the data layer for both. ## Tests - `plugin-approvals/src/record-lock-one-read-37770.integration.test.ts` (11): real ObjectQL over better-sqlite3 with the real `ApprovalsServicePlugin`. Every Done-when combination: closed own, line of a closed master, held by an approval, line of a held master, both at once, neither, unreadable, missing; agreement with the write path; the reader whose field permissions hide the state field is told `closed_state`; no read on the object refuses the same for every id; `lockRecord: false` and a decided request let go; the approvals-family read still calls a closed record unlocked; without the plugin only closed states lock; `destroy()` empties the slot, and the cross-package key is the one the engine reads; the page answers entry by entry, refuses 201 ids and takes 200. - `rest/src/record-lock-routes.test.ts` (10): both doors, parsed against the ledgered schemas; only the three members are served; 404/Vary; relayed refusals; 501; 400 for each bad body; closed query sets. - `rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts`: the page door's write-verb row is driven. - `service-storage/src/record-file-access.integration.test.ts`: the fixture's approvals stand-in now also fills the engine slot; a new case pins the closed-state sentence and that closed wins over held. ## Acceptance notes - `git diff origin/main -- packages/rest/src/approvals-routes.ts packages/spec/src/contracts` and the client's `approvals.*` methods: no change (Done-when item 7). - The read answers for a caller. A system context is bound by neither lock and is not described. - No permission or sharing boundary moves: readability is the caller's existing read, and the answer carries no field, value, request id or participants. ## Verification - Package typechecks: objectql, metadata-protocol, rest, client, plugin-approvals, service-storage — clean. - Spec build with generated baselines regenerated and committed (authorable surface, json-schema manifest, api surface, export origins, strictness ledger counts, reference pages, llms.txt inventory). - `dispatch-gates --commands`: every derived gate was run locally. The ones that failed were fixed (route envelope, query-options erasure, ADR-0122 alias pins, api surface, docs, export origins, llms.txt, facade ceiling under ruling 7314474264). Four could not run here, for environment reasons only: `check-plugin-teardown-shape --self-test` needs an unshallow clone, and `check:skill-examples`, `check:dual-build-cjs-loads` and `check:i18n` need built dists. CI runs all four. - Package suites: objectql 14662, rest census and route tests, plugin-approvals, service-storage 94, metadata-protocol canonical-fold census — green. - `overlap-check`: clean against origin/main, #38908, #38888. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzfGw8DS75kHUYrjbLM <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzfGw8DS75kHUYrjbLM --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0543d59 commit 7b68db9

40 files changed

Lines changed: 1907 additions & 39 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/objectql': patch
4+
'@objectstack/metadata-protocol': patch
5+
'@objectstack/rest': patch
6+
'@objectstack/client': patch
7+
'@objectstack/plugin-approvals': patch
8+
'@objectstack/service-storage': patch
9+
---
10+
11+
feat(data): one record lock read, for closed states and approvals
12+
13+
Clause-②: yes (widening)
14+
Metadata-protocol: added
15+
16+
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.
17+
18+
- `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.
19+
- `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.
20+
- `client.data.getRecordLock(object, id)` and `client.data.getRecordLocks(object, recordIds)` call them. The shapes are `RecordLockSchema`, `GetRecordLocksRequestSchema` and `GetRecordLocksResponseSchema` in `@objectstack/spec/api`.
21+
22+
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.
23+
24+
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.
25+
26+
Nothing existing changes: the approvals read (`/api/v1/approvals/records/...`), its SDK methods and service members answer exactly as before.

‎content/docs/api/client-sdk.mdx‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,22 @@ const { results } = await client.data.batchTransaction([
328328
See [Batch Operations](/docs/protocol/kernel/http-protocol#batch-operations)
329329
for the underlying endpoint contract.
330330

331+
Whether a record is locked, and by which lock — a closed state or an approval
332+
([Record locks](/docs/api/data-api#record-locks)):
333+
334+
```typescript
335+
// One record: { locked, lockSource?, lockReason? }; rejects with 404 when
336+
// the record is missing or you cannot read it.
337+
const lock = await client.data.getRecordLock('invoice', 'inv_1');
338+
if (lock.locked && lock.lockReason === 'closed_state') {
339+
// closed: no edit will be taken
340+
}
341+
342+
// A page of at most 200 records: entry i answers recordIds[i];
343+
// `locked: null` for a record that is missing or that you cannot read.
344+
const { records } = await client.data.getRecordLocks('invoice', ['inv_1', 'inv_2']);
345+
```
346+
331347
### `client.analytics` — BI Queries
332348

333349
```typescript

‎content/docs/api/data-api.mdx‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,63 @@ refused `403 CHANGE_OWNER_DISABLED`.
616616
] } }
617617
```
618618

619+
## Record locks
620+
621+
Whether a record is locked, and by which lock (ADR-0162 D9). Two locks can hold
622+
a record: a **closed state** (its object declares `closedStates` and the record
623+
is in one of them, or it is a `master_detail` line of such a record) and an
624+
**approval** (a pending request under a node that locks, or, on an object that
625+
declares `closedStates`, an approval in passage). This is the one read for
626+
both, owned by the data layer: it is there whether or not the approvals plugin
627+
is installed, and without it only closed states lock.
628+
629+
Every caller who can read the record is told, whether or not it may write the
630+
record and whether or not field permissions let it read the state field. The
631+
answer never carries which field or value closed the record, a request id, or
632+
the approval's participants.
633+
634+
| Field | Present | Meaning |
635+
| :--- | :--- | :--- |
636+
| `locked` | always | `true` when a caller's write of the record is refused by a lock. |
637+
| `lockReason` | exactly when `locked` is `true` | `closed_state` or `approval`. When both hold, `closed_state`. |
638+
| `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. |
639+
640+
`locked` describes a caller's write. A system context is bound by neither lock,
641+
and the read does not describe it. The approvals-family read
642+
(`GET /approvals/records/:object/:id/lock`) is a different read: it answers for
643+
a pending request only, and stays as published.
644+
645+
### `GET /data/:object/:id/lock`
646+
647+
One record's lock (`RecordLockSchema`). A record the caller cannot read, or
648+
that does not exist, answers the by-id read's `404 RECORD_NOT_FOUND`, told
649+
apart by nothing. Takes no query parameter.
650+
651+
```json
652+
{ "success": true, "data": { "locked": true, "lockSource": "master", "lockReason": "closed_state" } }
653+
```
654+
655+
### `POST /data/:object/locks`
656+
657+
A page of records' locks. The body is `{ "recordIds": [...] }`, at least one
658+
and at most 200 ids (`GetRecordLocksRequestSchema`); a longer list, an empty
659+
one, or any other body key is refused whole with `400 VALIDATION_ERROR`, never
660+
trimmed. Entry `i` answers `recordIds[i]`; a record the caller cannot read, or
661+
that does not exist, answers `locked: null`. A row counts as readable only when
662+
the caller's read hands back the row whose id is the asked id. Takes no query
663+
parameter.
664+
665+
```json
666+
{ "success": true, "data": { "records": [
667+
{ "recordId": "inv_1", "locked": true, "lockSource": "record", "lockReason": "approval" },
668+
{ "recordId": "inv_2", "locked": false },
669+
{ "recordId": "inv_9", "locked": null }
670+
] } }
671+
```
672+
673+
A deployment whose data engine has no lock read answers both doors
674+
`501 NOT_IMPLEMENTED`, never "unlocked".
675+
619676
---
620677

621678
## Analytics

‎content/docs/automation/approvals.mdx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,12 @@ member `IApprovalService.getRecordLocks`, and an approvals service without it
520520
answers `501`. A list that edits in place reads it when a cell is first
521521
selected, and holds an edit asked before the answer arrives until it does.
522522

523+
These two reads answer for approvals alone. Whether a record is locked by
524+
either lock, its closed state (`closedStates`) or an approval, is the data
525+
layer's read, `GET /api/v1/data/:object/:id/lock` and
526+
`POST /api/v1/data/:object/locks` ([Record locks](/docs/api/data-api#record-locks)),
527+
which also says which lock holds it.
528+
523529
Only `approvers` is required on the node; everything else has a default
524530
(`behavior: 'first_response'`, `lockRecord: true`, `maxRevisions: 3`).
525531

@@ -1836,8 +1842,10 @@ left no marks, and is not held between its steps.
18361842

18371843
The approvals-family lock read (`getRecordLock`, above) answers for a pending
18381844
request only: in a passage it answers `{ "locked": false }` while an edit is
1839-
refused `409 RECORD_LOCKED`. A page that offers an edit in a passage learns of
1840-
the hold from the refusal.
1845+
refused `409 RECORD_LOCKED`. The data layer's lock read
1846+
(`GET /api/v1/data/:object/:id/lock`, [Record locks](/docs/api/data-api#record-locks))
1847+
answers the hold in a passage too, as `lockReason: "approval"`, beside the
1848+
closed-state lock, so a page that offers an edit can learn of the hold before the save.
18411849

18421850
## Why
18431851

‎content/docs/references/index.mdx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Protocol reference — every schema by module
33
navTitle: Protocol Reference
4-
description: Every schema published by @objectstack/spec — 1750 schemas across 14 protocol modules
4+
description: Every schema published by @objectstack/spec — 1756 schemas across 14 protocol modules
55
---
66

77
{/* ⚠️ 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
2323
| Module | Pages | Schemas | Description |
2424
| :--- | ---: | ---: | :--- |
2525
| [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. |
26-
| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. |
26+
| [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 38 | 534 | REST contracts, endpoints, routing, realtime, batch, discovery. |
2727
| [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. |
2828
| [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. |
2929
| [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
3636
| [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. |
3737
| [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. |
3838
| [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. |
39-
| **Total** | **224** | **1750** | 14 protocol modules |
39+
| **Total** | **225** | **1756** | 14 protocol modules |
4040

4141
---
4242

@@ -71,7 +71,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations.
7171

7272
## API Protocol
7373

74-
**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **37 pages, 528 schemas**
74+
**Source:** `packages/spec/src/api/` · **Import:** `@objectstack/spec/api` · **38 pages, 534 schemas**
7575

7676
REST contracts, endpoints, routing, realtime, batch, discovery.
7777

@@ -107,6 +107,7 @@ REST contracts, endpoints, routing, realtime, batch, discovery.
107107
| [`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` |
108108
| [`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` |
109109
| [`realtime-shared.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/realtime-shared.md) | `BasePresence`, `PresenceStatus`, `RealtimeRecordAction` |
110+
| [`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` |
110111
| [`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` |
111112
| [`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` |
112113
| [`router.zod.ts`](https://github.com/objectstack-ai/objectstack/blob/main/packages/spec/docs/references/api/router.md) | `ConflictResolutionStrategy`, `HttpMethod`, `RouteCategory`, `RouteDefinition`, `RouterConfig` |

‎docs/audits/2026-07-unknown-key-strictness-ledger.counts/api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate.
1919

2020
| Dir | Sites |
2121
|---|---|
22-
| `api/` | 544 |
22+
| `api/` | 550 |

‎packages/client/src/index.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import {
55
BatchUpdateRequest,
66
BatchUpdateResponse,
77
GetRecordFieldAccessResponse,
8+
RecordLock,
9+
GetRecordLocksResponse,
810
RecordPageRequest,
911
RecordPageResponse,
1012
// [#32200] The batch dataset-query answer `analytics.queryDatasetBatch`
@@ -8662,6 +8664,40 @@ export class ObjectStackClient {
86628664
return this.unwrapResponse<GetRecordFieldAccessResponse>(res);
86638665
},
86648666

8667+
/**
8668+
* [ADR-0162 D9] One record's lock — `GET /data/:object/:id/lock`, declared
8669+
* by `RecordLockSchema` (`@objectstack/spec/api`): `{ locked, lockSource?,
8670+
* lockReason? }`, the data layer's one lock read. `lockReason` is
8671+
* `closed_state` (a declared closed state) or `approval` (an approval holds
8672+
* it); `lockSource` is `record` or `master` (the master of a
8673+
* `master_detail` line). Both are present exactly when `locked` is true.
8674+
* Answered to every caller who can read the record; a record that is absent
8675+
* or that the caller cannot read rejects with the record read's 404.
8676+
*/
8677+
getRecordLock: async (object: string, id: string): Promise<RecordLock> => {
8678+
const route = this.getRoute('data');
8679+
const res = await this.fetch(
8680+
`${this.baseUrl}${route}/${encodeURIComponent(object)}/${encodeURIComponent(id)}/lock`,
8681+
);
8682+
return this.unwrapResponse<RecordLock>(res);
8683+
},
8684+
8685+
/**
8686+
* [ADR-0162 D9] A page of records' locks — `POST /data/:object/locks`,
8687+
* declared by `GetRecordLocksRequestSchema` / `GetRecordLocksResponseSchema`:
8688+
* entry `i` answers `recordIds[i]`, `locked: null` for a record the caller
8689+
* cannot read or that does not exist. At most `RECORD_LOCKS_MAX_RECORD_IDS`
8690+
* (200) ids per call; a longer list is refused whole with a 400.
8691+
*/
8692+
getRecordLocks: async (object: string, recordIds: string[]): Promise<GetRecordLocksResponse> => {
8693+
const route = this.getRoute('data');
8694+
const res = await this.fetch(
8695+
`${this.baseUrl}${route}/${encodeURIComponent(object)}/locks`,
8696+
{ method: 'POST', body: JSON.stringify({ recordIds }) },
8697+
);
8698+
return this.unwrapResponse<GetRecordLocksResponse>(res);
8699+
},
8700+
86658701
/**
86668702
* [#27627] The record page payload — `POST /data/:object/:id/page`,
86678703
* declared by `RecordPageRequestSchema` / `RecordPageResponseSchema`
@@ -9651,6 +9687,10 @@ export type {
96519687
GetObjectPermissionsResponse,
96529688
GetEffectivePermissionsResponse,
96539689
GetRecordFieldAccessResponse,
9690+
RecordLock,
9691+
GetRecordLocksRequest,
9692+
GetRecordLocksResponse,
9693+
RecordLockEntry,
96549694
RecordPageRequest,
96559695
RecordPageResponse,
96569696
RealtimeConnectRequest,

‎packages/metadata-protocol/src/host-engine.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
22

33
import type { IDataEngine, IObjectQLEngine } from '@objectstack/core';
4+
import type { RecordLock } from '@objectstack/spec/api';
45
import type { StoredExpressionFillCapture } from './protocol-stored-expression-fill.js';
56
import type { PublishedColumnChanges } from './protocol-registry-hydration.js';
67

@@ -75,5 +76,15 @@ export interface MetadataHostEngine extends IDataEngine {
7576
deferSummaryRecompute?: IObjectQLEngine['deferSummaryRecompute'];
7677
// Protocol accesses additional engine members structurally; keep it permissive
7778
// for this relocation (behavior unchanged — the concrete engine is injected).
79+
/**
80+
* [ADR-0162 D9] The one lock read the data layer owns (`@objectstack/objectql`
81+
* `ObjectQL#getRecordLock`), as the caller in `options.context`. Declared
82+
* explicitly for the reason `transaction` is; optional because a host may be a
83+
* test double or a metadata-only store, and degrading means the data door
84+
* answers `501`, never "unlocked".
85+
*/
86+
getRecordLock?(object: string, recordId: string, options?: { context?: any }): Promise<RecordLock | null>;
87+
/** [ADR-0162 D9] The page form of {@link getRecordLock}: entry `i` answers `recordIds[i]`. */
88+
getRecordLocks?(object: string, recordIds: readonly string[], options?: { context?: any }): Promise<Array<RecordLock | null>>;
7889
[key: string]: any;
7990
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0162 D9] The data protocol's two doors onto the one lock read the data
5+
* layer owns (`ObjectQL#getRecordLock` / `ObjectQL#getRecordLocks`,
6+
* `@objectstack/objectql` `record-lock-read.ts`): `getRecordLock` for one
7+
* record, `getRecordLocks` for a page.
8+
*
9+
* Thin by design. The object-existence gate every data entry point asks
10+
* (#3770) runs first, so an unknown object fails here as it fails on a read;
11+
* then the engine answers, as the caller. Readability, the producers and the
12+
* answer's shape are the engine's, not this door's: a door that re-judged any
13+
* of them would be a second read.
14+
*
15+
* An engine without the read (a test double, a metadata-only store) is
16+
* answered `undefined`, which the REST door turns into `501 NOT_IMPLEMENTED`:
17+
* a lock read that cannot be asked must not answer "unlocked".
18+
*/
19+
20+
import type { RecordLock } from '@objectstack/spec/api';
21+
import type { ProtocolHost } from './protocol-host.js';
22+
23+
/** One record's lock, as the caller; `null` unreadable or missing; `undefined` when the engine has no read. */
24+
export async function readRecordLock(
25+
host: Pick<ProtocolHost, 'engine' | 'assertObjectRegistered'>,
26+
request: { object: string; id: string; context?: any },
27+
): Promise<RecordLock | null | undefined> {
28+
host.assertObjectRegistered(request.object);
29+
const engine = host.engine;
30+
if (typeof engine?.getRecordLock !== 'function') return undefined;
31+
return engine.getRecordLock(request.object, request.id, { context: request.context });
32+
}
33+
34+
/**
35+
* A page of records' locks, as the caller: entry `i` answers `recordIds[i]`.
36+
* `undefined` when the engine has no read. The bound is the engine's.
37+
*/
38+
export async function readRecordLocks(
39+
host: Pick<ProtocolHost, 'engine' | 'assertObjectRegistered'>,
40+
request: { object: string; recordIds: readonly string[]; context?: any },
41+
): Promise<Array<RecordLock | null> | undefined> {
42+
host.assertObjectRegistered(request.object);
43+
const engine = host.engine;
44+
if (typeof engine?.getRecordLocks !== 'function') return undefined;
45+
return engine.getRecordLocks(request.object, request.recordIds, { context: request.context });
46+
}

0 commit comments

Comments
 (0)