Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/37770-one-record-lock-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@objectstack/spec': minor
'@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: 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.

- `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.
16 changes: 16 additions & 0 deletions content/docs/api/client-sdk.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
57 changes: 57 additions & 0 deletions content/docs/api/data-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 10 additions & 2 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down Expand Up @@ -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

Expand Down
9 changes: 5 additions & 4 deletions content/docs/references/index.mdx
Original file line number Diff line number Diff line change
@@ -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/. */}
Expand All @@ -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. |
Expand All @@ -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 |

---

Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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` |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate.

| Dir | Sites |
|---|---|
| `api/` | 544 |
| `api/` | 550 |
40 changes: 40 additions & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
BatchUpdateRequest,
BatchUpdateResponse,
GetRecordFieldAccessResponse,
RecordLock,
GetRecordLocksResponse,
RecordPageRequest,
RecordPageResponse,
// [#32200] The batch dataset-query answer `analytics.queryDatasetBatch`
Expand Down Expand Up @@ -8662,6 +8664,40 @@ export class ObjectStackClient {
return this.unwrapResponse<GetRecordFieldAccessResponse>(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<RecordLock> => {
const route = this.getRoute('data');
const res = await this.fetch(
`${this.baseUrl}${route}/${encodeURIComponent(object)}/${encodeURIComponent(id)}/lock`,
);
return this.unwrapResponse<RecordLock>(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<GetRecordLocksResponse> => {
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<GetRecordLocksResponse>(res);
},

/**
* [#27627] The record page payload — `POST /data/:object/:id/page`,
* declared by `RecordPageRequestSchema` / `RecordPageResponseSchema`
Expand Down Expand Up @@ -9651,6 +9687,10 @@ export type {
GetObjectPermissionsResponse,
GetEffectivePermissionsResponse,
GetRecordFieldAccessResponse,
RecordLock,
GetRecordLocksRequest,
GetRecordLocksResponse,
RecordLockEntry,
RecordPageRequest,
RecordPageResponse,
RealtimeConnectRequest,
Expand Down
11 changes: 11 additions & 0 deletions packages/metadata-protocol/src/host-engine.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<RecordLock | null>;
/** [ADR-0162 D9] The page form of {@link getRecordLock}: entry `i` answers `recordIds[i]`. */
getRecordLocks?(object: string, recordIds: readonly string[], options?: { context?: any }): Promise<Array<RecordLock | null>>;
[key: string]: any;
}
46 changes: 46 additions & 0 deletions packages/metadata-protocol/src/protocol-record-lock.ts
Original file line number Diff line number Diff line change
@@ -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 readRecordLock(
host: Pick<ProtocolHost, 'engine' | 'assertObjectRegistered'>,
request: { object: string; id: string; context?: any },
): Promise<RecordLock | null | undefined> {
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 readRecordLocks(
host: Pick<ProtocolHost, 'engine' | 'assertObjectRegistered'>,
request: { object: string; recordIds: readonly string[]; context?: any },
): Promise<Array<RecordLock | null> | 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 });
}
Loading
Loading