diff --git a/.changeset/38995-record-page-data-lock.md b/.changeset/38995-record-page-data-lock.md new file mode 100644 index 00000000000..0a76707b008 --- /dev/null +++ b/.changeset/38995-record-page-data-lock.md @@ -0,0 +1,12 @@ +--- +'@objectstack/spec': minor +'@objectstack/rest': minor +'@objectstack/client': minor +--- + +feat(spec,rest): the record page payload answers the data lock read, so a record page learns a closed record in its one request + +Clause-②: yes (widening) +Metadata-protocol: added + +Widened: `RecordPageRequestSchema` gains an optional `dataLock: boolean`, and `RecordPageResponseSchema` an optional `dataLock` part: the record's lock exactly as `GET /api/v1/data/{object}/{id}/lock` answers the caller (`RecordLockSchema`: `locked`, and on a locked record `lockSource` and `lockReason`, ADR-0162 D9), or that read's refusal as a part error. `POST /api/v1/data/{object}/{id}/page` (`@objectstack/rest`) answers it from the data protocol's `getRecordLock`, served through the lock door's own projection, so nothing about the state field or value rides along; a deployment whose data engine has no lock read answers the part `501 NOT_IMPLEMENTED`, never "unlocked". A body that does not ask gets no part and the read is not asked. The approval part's own `lock` is the approvals-family read and is unchanged. `client.data.recordPage` takes and returns the new part through the spec types. Nothing an author writes in metadata changes. diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index 022e0b5ae0f..cf5c6550bf9 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -673,6 +673,13 @@ parameter. A deployment whose data engine has no lock read answers both doors `501 NOT_IMPLEMENTED`, never "unlocked". +The record page payload (`POST /data/:object/:id/page`) answers the same read +when its body asks `"dataLock": true`: its `dataLock` part is exactly what +`GET /data/:object/:id/lock` answers the caller, or that read's refusal as a +part error (`501 NOT_IMPLEMENTED` included), so a record page learns that a +record is closed without a second request. The payload's `approvals.lock` is +the approvals-family read and is unchanged. + --- ## Analytics diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index 72763246491..209a0771218 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -8703,8 +8703,9 @@ export class ObjectStackClient { * declared by `RecordPageRequestSchema` / `RecordPageResponseSchema` * (`@objectstack/spec/api`): the record, the count and first rows of each * related list `request.related` names, and — when asked — the record's - * field projection, its record-grained access decisions and its approval - * state, in one round trip. Each part is the answer of the read it replaces + * field projection, its record-grained access decisions, its approval + * state and its data lock (`request.dataLock`, the answer of + * `data.getRecordLock`, #38995), in one round trip. Each part is the answer of the read it replaces * for the same caller; a part whose read refused carries `error` instead. * A record that is absent or that the caller cannot read rejects with the * record read's 404. diff --git a/packages/rest/src/record-page-data-lock-38995.test.ts b/packages/rest/src/record-page-data-lock-38995.test.ts new file mode 100644 index 00000000000..d896f7f80dc --- /dev/null +++ b/packages/rest/src/record-page-data-lock-38995.test.ts @@ -0,0 +1,224 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#38995] The record page payload's `dataLock` part: the data layer's one lock + * read (ADR-0162 D9, `GET /data/:object/:id/lock`), answered inside the one + * request a record page opens with, so the page learns a closed record without + * a second request. + * + * What each pin holds: + * + * - the part is the data protocol's `getRecordLock`, asked as the caller, and + * it answers exactly what the single lock door answers that caller, for each + * combination the read names (parity, both doors driven over one protocol); + * - nothing the engine might add rides along: the part is the door's own + * projection, field by field, so a reader whose field permissions hide the + * state field is told `closed_state` and nothing about the field or value; + * - a protocol without the read is the door's `501`, carried as the part's + * refusal, never "unlocked"; a throwing read is that read's refusal, and the + * other parts still answer; + * - the approval part's own `lock` is a different read and is unchanged; + * - a body that does not ask for the part gets none, and asks nothing. + * + * The engine's half (the combinations, the hidden state field, the master + * line) is `plugin-approvals/src/record-lock-one-read-37770.integration.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { RecordPageResponseSchema } from '@objectstack/spec/api'; +import { RestServer } from './rest-server.js'; +// The server reaches `@objectstack/objectql` only through a dynamic import inside a +// handler; paid here at module scope so the first load lands during collection, +// not inside a clocked window (`pnpm check:test-source-alias`). +import '@objectstack/objectql'; + +const ACCOUNT = { + name: 'account', + label: 'Account', + fields: { id: { name: 'id', type: 'text' }, name: { name: 'name', type: 'text' }, stage: { name: 'stage', type: 'text' } }, +}; +const CTX = { userId: 'u1', permissions: ['member_default'] }; +const RECORD = { id: 'a1', name: 'Acme' }; + +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, + header: vi.fn(function (this: any) { 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; +} + +interface BootOpts { + /** The protocol's lock read; absent leaves the protocol without one. */ + getRecordLock?: (req: any) => Promise; + security?: unknown; + approvals?: unknown; +} + +function boot(opts: BootOpts = {}) { + const getData = vi.fn(async () => ({ object: 'account', id: 'a1', record: RECORD })); + const findData = vi.fn(async (req: any) => ({ object: req.object, records: [], total: 0 })); + const getRecordLock = opts.getRecordLock ? vi.fn(opts.getRecordLock) : undefined; + const protocol: any = { + getDiscovery: vi.fn().mockResolvedValue({ + version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' }, + }), + getMetaTypes: vi.fn().mockResolvedValue([]), + getMetaItems: vi.fn().mockResolvedValue({ items: [ACCOUNT] }), + getMetaItem: vi.fn(async ({ name }: any) => (name === 'account' ? { type: 'object', name, item: ACCOUNT } : null)), + getData, + findData, + ...(getRecordLock ? { getRecordLock } : {}), + }; + const rest = new RestServer(mockServer() as any, protocol as any, { api: { requireAuth: false } } as any); + (rest as any).resolveExecCtx = async () => CTX; + (rest as any).resolveSecurityService = async () => opts.security; + (rest as any).approvalsServiceProvider = opts.approvals === undefined ? undefined : async () => opts.approvals; + rest.registerRoutes(); + const routes = (rest as any).getRoutes(); + const page = routes.find((r: any) => r.method === 'POST' && r.path === '/api/v1/data/:object/:id/page'); + const door = routes.find((r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/:id/lock'); + const drive = async (route: any, req: Record) => { + if (!route) throw new Error('route not registered'); + const res = mockRes(); + await route.handler({ query: {}, headers: {}, ...req } as any, res); + return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] }; + }; + const callPage = (body: unknown) => drive(page, { method: 'POST', params: { object: 'account', id: 'a1' }, body }); + const callDoor = () => drive(door, { method: 'GET', params: { object: 'account', id: 'a1' }, body: {} }); + return { callPage, callDoor, getRecordLock, getData }; +} + +describe('[#38995] the record page\'s dataLock part is the data lock read', () => { + // What the protocol's `getRecordLock` answers in each combination ADR-0162 + // D9 names. `field` / `value` / `requestId` stand for anything an engine + // might add; neither door may serve them. + const CASES: Array<[string, unknown]> = [ + ['a record closed by its own state', { locked: true, lockSource: 'record', lockReason: 'closed_state', field: 'stage', value: 'done' }], + ['a line of a closed master', { locked: true, lockSource: 'master', lockReason: 'closed_state' }], + ['a record held by its own approval', { locked: true, lockSource: 'record', lockReason: 'approval', requestId: 'ar1' }], + ['a line of a held master', { locked: true, lockSource: 'master', lockReason: 'approval' }], + ['an unlocked record', { locked: false }], + ]; + + for (const [name, served] of CASES) { + it(`${name}: the part equals GET /data/:object/:id/lock for the same caller`, async () => { + const { callPage, callDoor, getRecordLock } = boot({ getRecordLock: async () => served }); + const page = await callPage({ dataLock: true }); + expect(page.status).toBe(200); + const composite = RecordPageResponseSchema.parse(page.body.data).dataLock; + + const single = await callDoor(); + expect(single.status).toBe(200); + + expect(composite).toEqual(single.body.data); + expect(Object.keys(composite as object).sort()).toEqual( + (served as any).locked ? ['lockReason', 'lockSource', 'locked'] : ['locked'], + ); + // Both doors asked the one read, as the caller, for this record. + expect(getRecordLock!.mock.calls.map(([req]) => req)).toEqual([ + { object: 'account', id: 'a1', context: CTX }, + { object: 'account', id: 'a1', context: CTX }, + ]); + }); + } + + it('a reader whose field permissions hide the state field is told closed_state, and nothing about the field', async () => { + const getRecordFieldAccess = vi.fn().mockResolvedValue({ + object: 'account', recordId: 'a1', readable: ['id', 'name'], editable: [], writable: false, + }); + const { callPage } = boot({ + security: { getRecordFieldAccess }, + getRecordLock: async () => ({ locked: true, lockSource: 'record', lockReason: 'closed_state', field: 'stage', value: 'done' }), + }); + const page = await callPage({ dataLock: true, fieldAccess: true }); + expect(page.status).toBe(200); + const data = RecordPageResponseSchema.parse(page.body.data); + expect((data.fieldAccess as any).readable).not.toContain('stage'); + expect(data.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); + expect(JSON.stringify(data.dataLock)).not.toMatch(/stage|done/); + }); + + it('a protocol without the read is the door\'s 501, carried as the part\'s refusal, never "unlocked"', async () => { + const { callPage, callDoor } = boot(); + const page = await callPage({ dataLock: true }); + expect(page.status).toBe(200); + const data = RecordPageResponseSchema.parse(page.body.data); + expect(data.dataLock).toMatchObject({ error: { code: 'NOT_IMPLEMENTED', status: 501 } }); + expect(data.record).toEqual(RECORD); + const door = await callDoor(); + expect([door.status, door.body?.error?.code]).toEqual([501, 'NOT_IMPLEMENTED']); + }); + + it('a read that answers nothing (undefined) is the same 501', async () => { + const { callPage } = boot({ getRecordLock: async () => undefined }); + const data = RecordPageResponseSchema.parse((await callPage({ dataLock: true })).body.data); + expect(data.dataLock).toMatchObject({ error: { code: 'NOT_IMPLEMENTED', status: 501 } }); + }); + + it('a read that refuses carries its own refusal, and the other parts answer', async () => { + const getRecordFieldAccess = vi.fn().mockResolvedValue({ + object: 'account', recordId: 'a1', readable: ['id', 'name', 'stage'], editable: ['name'], writable: true, + }); + const { callPage } = boot({ + security: { getRecordFieldAccess }, + getRecordLock: async () => { + throw Object.assign(new Error('[Security] Access denied: read on account'), { code: 'PERMISSION_DENIED', status: 403 }); + }, + }); + const page = await callPage({ dataLock: true, fieldAccess: true }); + expect(page.status).toBe(200); + const data = RecordPageResponseSchema.parse(page.body.data); + expect(data.dataLock).toMatchObject({ error: { code: 'PERMISSION_DENIED', status: 403 } }); + expect((data.fieldAccess as any).readable).toContain('stage'); + }); + + it('a record the read calls unreadable (null) is the by-id read\'s 404, as a part refusal', async () => { + const { callPage } = boot({ getRecordLock: async () => null }); + const data = RecordPageResponseSchema.parse((await callPage({ dataLock: true })).body.data); + expect(data.dataLock).toMatchObject({ error: { code: 'RECORD_NOT_FOUND', status: 404 } }); + }); + + it('the approval part keeps its own lock: a closed record the approvals read calls unlocked stays unlocked there', async () => { + const approvals = { + listRequests: vi.fn().mockResolvedValue([]), + getRecordLock: vi.fn().mockResolvedValue({ locked: false }), + }; + const { callPage } = boot({ + approvals, + getRecordLock: async () => ({ locked: true, lockSource: 'record', lockReason: 'closed_state' }), + }); + const data = RecordPageResponseSchema.parse((await callPage({ dataLock: true, approvals: true })).body.data); + expect(data.approvals).toEqual({ requests: [], lock: { locked: false } }); + expect(data.dataLock).toEqual({ locked: true, lockSource: 'record', lockReason: 'closed_state' }); + }); + + it('a body that does not ask for the part gets none, and the read is not asked', async () => { + const { callPage, getRecordLock } = boot({ getRecordLock: async () => ({ locked: false }) }); + const page = await callPage({}); + expect(page.status).toBe(200); + expect(page.body.data).not.toHaveProperty('dataLock'); + expect(getRecordLock).not.toHaveBeenCalled(); + }); + + it('a dataLock that is not a boolean is refused by the strict body, before anything is read', async () => { + const { callPage, getData, getRecordLock } = boot({ getRecordLock: async () => ({ locked: false }) }); + const page = await callPage({ dataLock: 'yes' }); + expect(page.status).toBe(400); + expect(page.body.error.code).toBe('VALIDATION_FAILED'); + expect(getData).not.toHaveBeenCalled(); + expect(getRecordLock).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/rest/src/record-page-routes.ts b/packages/rest/src/record-page-routes.ts index 95888d33f19..9d3cd6d00c5 100644 --- a/packages/rest/src/record-page-routes.ts +++ b/packages/rest/src/record-page-routes.ts @@ -13,7 +13,10 @@ * `findData` with `count` after the child's own exposure gate, filtered by the * parent condition this route composes AND the list's declared scope; then * `getRecordFieldAccess`, the security service's `explain` and the approval - * service's `listRequests` / `getRequest` / `getRecordLock`. [#28470] A + * service's `listRequests` / `getRequest` / `getRecordLock`. [#38995] The + * `dataLock` part is the data protocol's own `getRecordLock`, served through + * the `GET /data/:object/:id/lock` door's projection (`recordLockAnswer`), so + * the page learns a closed record without a second request. [#28470] A * related list's `expand` is that list read's own `$expand`; the record's * streams — `discussion`, `activity`, `attachments` — are `findData` over * `sys_comment` (then `sys_comment_reaction`), `sys_activity` and @@ -41,6 +44,7 @@ import { zodIssuesToFields, type GetDataRequest, type FindDataRequest, + type RecordLock, type RecordPageRequest, } from '@objectstack/spec/api'; import { isMultiValueField, parseFilterAST, referenceTargetOf } from '@objectstack/spec/data'; @@ -49,6 +53,7 @@ import { answerVariesByLanguage, LOCALIZED_ANSWER_VARY, sendError, sendOk } from import { recordNotFoundError } from '@objectstack/core'; import { refuseUnknownQueryParams } from './query-allowlist.js'; import { recordLockPayload } from './approvals-routes.js'; +import { recordLockAnswer } from './record-lock-routes.js'; import { logUnexpectedRouteError, mapDataError, nestedRefusalEnvelope } from './error-response.js'; import type { ServerScopedDataRequest } from './data-action-routes.js'; import { apiAccessDenialFromEnable, type RestServer } from './rest-server.js'; @@ -56,6 +61,13 @@ import { apiAccessDenialFromEnable, type RestServer } from './rest-server.js'; /** The closed query-parameter set of `POST {basePath}/data/:object/:id/page`: EMPTY. */ export const RECORD_PAGE_PARAMS: readonly string[] = []; +/** [#38995] The `dataLock` part's refusal on a protocol without the lock read: the lock door's own `501`. */ +const DATA_LOCK_NOT_IMPLEMENTED = { + code: 'NOT_IMPLEMENTED', + status: 501, + message: 'The record lock read is not available on this deployment (its data engine has no getRecordLock / getRecordLocks).', +} as const; + /** [#28470] The objects the record's stream parts read. */ const COMMENT_OBJECT = 'sys_comment'; const COMMENT_REACTION_OBJECT = 'sys_comment_reaction'; @@ -498,11 +510,30 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: } }; - const [relatedAnswers, fieldAccess, explain, approvals, discussion, activity, attachments, timeline] = await Promise.all([ + // [#38995] The data layer's lock, as `GET /data/:object/:id/lock` + // reads it: the protocol's `getRecordLock` as the caller, served + // through that door's projection, field by field. A protocol + // without the read is that door's `501`, carried as the part's + // refusal and never "unlocked"; an unreadable record (the door's + // 404) cannot reach here, as the record read above refused first. + const answerDataLock = async () => { + try { + const read = (p as { getRecordLock?: (request: Record) => Promise }).getRecordLock; + const lock = typeof read === 'function' ? await read.call(p, { object, id, ...scope }) : undefined; + if (lock === undefined) return { error: { ...DATA_LOCK_NOT_IMPLEMENTED } }; + if (lock === null) throw recordNotFoundError(object, id, context); + return recordLockAnswer(lock); + } catch (error) { + return { error: refusalOf(error, object) }; + } + }; + + const [relatedAnswers, fieldAccess, explain, approvals, dataLock, discussion, activity, attachments, timeline] = await Promise.all([ Promise.all(related.map(answerRelated)), body.fieldAccess ? answerFieldAccess() : Promise.resolve(undefined), body.explain && body.explain.length > 0 ? answerExplain() : Promise.resolve(undefined), body.approvals ? answerApprovals() : Promise.resolve(undefined), + body.dataLock ? answerDataLock() : Promise.resolve(undefined), body.discussion ? answerDiscussion() : Promise.resolve(undefined), body.activity ? answerActivity(body.activity.top) : Promise.resolve(undefined), body.attachments ? answerAttachments(body.attachments.top) : Promise.resolve(undefined), @@ -517,6 +548,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: ...(fieldAccess !== undefined ? { fieldAccess } : {}), ...(explain !== undefined ? { explain } : {}), ...(approvals !== undefined ? { approvals } : {}), + ...(dataLock !== undefined ? { dataLock } : {}), ...(discussion !== undefined ? { discussion } : {}), ...(activity !== undefined ? { activity } : {}), ...(attachments !== undefined ? { attachments } : {}), @@ -534,7 +566,7 @@ export function registerRecordPageEndpoints(this: RecordPageRouteHost, basePath: } }, metadata: { - summary: 'Record page payload: the record, its related lists\' counts and first rows, its field projection, access verdicts, approval state, discussion, activity, attachments and timeline count in one request', + summary: 'Record page payload: the record, its related lists\' counts and first rows, its field projection, access verdicts, approval state, data lock, discussion, activity, attachments and timeline count in one request', tags: ['data'], }, }); diff --git a/packages/spec/authorable-surface/api.json b/packages/spec/authorable-surface/api.json index a7b02dae6b1..90a03916edb 100644 --- a/packages/spec/authorable-surface/api.json +++ b/packages/spec/authorable-surface/api.json @@ -1667,6 +1667,7 @@ "api/RecordPageRequest:activity", "api/RecordPageRequest:approvals", "api/RecordPageRequest:attachments", + "api/RecordPageRequest:dataLock", "api/RecordPageRequest:discussion", "api/RecordPageRequest:expand", "api/RecordPageRequest:explain", @@ -1676,6 +1677,7 @@ "api/RecordPageResponse:activity", "api/RecordPageResponse:approvals", "api/RecordPageResponse:attachments", + "api/RecordPageResponse:dataLock", "api/RecordPageResponse:discussion", "api/RecordPageResponse:explain", "api/RecordPageResponse:fieldAccess", diff --git a/packages/spec/declaration-map/api.json b/packages/spec/declaration-map/api.json index d590a2b762d..141bc8631e2 100644 --- a/packages/spec/declaration-map/api.json +++ b/packages/spec/declaration-map/api.json @@ -436,6 +436,10 @@ "GetPublishedMetaItemResponseSchema": "api/GetPublishedMetaItemResponse", "GetRecordFieldAccessResponse": "api/GetRecordFieldAccessResponse", "GetRecordFieldAccessResponseSchema": "api/GetRecordFieldAccessResponse", + "GetRecordLocksRequest": "api/GetRecordLocksRequest", + "GetRecordLocksRequestSchema": "api/GetRecordLocksRequest", + "GetRecordLocksResponse": "api/GetRecordLocksResponse", + "GetRecordLocksResponseSchema": "api/GetRecordLocksResponse", "GetRunRequest": "api/GetRunRequest", "GetRunRequestSchema": "api/GetRunRequest", "GetRunResponse": "api/GetRunResponse", @@ -743,6 +747,14 @@ "RealtimeUnsubscribeResponseSchema": "api/RealtimeUnsubscribeResponse", "RecordData": "api/RecordData", "RecordDataSchema": "api/RecordData", + "RecordLock": "api/RecordLock", + "RecordLockEntry": "api/RecordLockEntry", + "RecordLockEntrySchema": "api/RecordLockEntry", + "RecordLockReason": "api/RecordLockReason", + "RecordLockReasonSchema": "api/RecordLockReason", + "RecordLockSchema": "api/RecordLock", + "RecordLockSource": "api/RecordLockSource", + "RecordLockSourceSchema": "api/RecordLockSource", "RecordPageActivityRequest": "api/RecordPageActivityRequest", "RecordPageActivityRequestSchema": "api/RecordPageActivityRequest", "RecordPageApprovals": "api/RecordPageApprovals", diff --git a/packages/spec/docs/references/api/record-page.md b/packages/spec/docs/references/api/record-page.md index 12f8b04229c..eef53240506 100644 --- a/packages/spec/docs/references/api/record-page.md +++ b/packages/spec/docs/references/api/record-page.md @@ -8,9 +8,10 @@ One request that answers everything a record page asks of the server when it opens: the record (with the lookups it names resolved), the count and first rows of every related list the page draws (with the lookups of those rows it names resolved), the caller's field projection of the record, the approval -state that locks it, the record-grained access verdicts its header actions -are gated on, and the record's own streams the page draws — its discussion, -its activity feed and its attachments. +state that locks it, the data layer's lock on it (closed state or approval), +the record-grained access verdicts its header actions are gated on, and the +record's own streams the page draws — its discussion, its activity feed and +its attachments. The request NAMES the parts. Which related lists a page draws (their order, their declared scope, which of them the reader may see) is the page's own @@ -26,7 +27,8 @@ the record is `GET /data/{object}/{id}`, a related list is `fieldAccess` is `GET /data/{object}/{id}/field-access`, `explain` is `POST /security/explain` with the record id, `approvals` is `GET /approvals/requests` for the record plus -`GET /approvals/records/{object}/{id}/lock`, `discussion` is +`GET /approvals/records/{object}/{id}/lock`, `dataLock` is +`GET /data/{object}/{id}/lock` (ADR-0162 D9, `RecordLockSchema`), `discussion` is `GET /data/sys_comment` for the record's thread plus `GET /data/sys_comment_reaction` for those comments, `activity` is `GET /data/sys_activity` for the record with its actor expanded, and @@ -410,6 +412,7 @@ This schema accepts one of the following structures: | **explain** | `Enum<'update' \| 'delete' \| 'transfer'>[]` | optional | The operations to answer a record-grained access verdict for, as `POST /security/explain` answers them with this record id. | | **fieldAccess** | `boolean` | optional | Return the caller's field projection of the record, as `GET /data/{object}/{id}/field-access` does. | | **approvals** | `boolean` | optional | Return the record's approval requests and its approval lock. | +| **dataLock** | `boolean` | optional | Return the record's data lock, as `GET /data/{object}/{id}/lock` answers it (`RecordLockSchema`): whether a closed state or an approval locks the record for this caller, and which. | | **discussion** | `boolean` | optional | Return the record's discussion: its comment thread and those comments' reactions (`RecordPageDiscussionSchema`). | | **activity** | `{ top: integer }` | optional | Return the record's newest activity rows and their count (`RecordPageStreamRowsSchema`). | | **attachments** | `{ top: integer }` | optional | Return the record's newest attachments and their count (`RecordPageStreamRowsSchema`). | @@ -462,6 +465,7 @@ This schema accepts one of the following structures: | **fieldAccess** | `{ object: string; recordId: string; readable: string[]; editable: string[]; … } \| { error: object }` | optional | The field projection, when the request asked for it. | | **explain** | `{ update?: object \| object; delete?: object \| object; transfer?: object \| object }` | optional | One access decision per requested operation, keyed by operation, when the request asked for any. | | **approvals** | `{ requests: Record[]; lock: object \| null } \| { error: object }` | optional | The approval part, when the request asked for it. | +| **dataLock** | `{ locked: true; lockSource: Enum<'record' \| 'master'>; lockReason: Enum<'closed_state' \| 'approval'> } \| { locked: false } \| { error: object }` | optional | The data lock part, when the request asked for it: the record's lock exactly as `GET /data/{object}/{id}/lock` answers this caller (`locked`, and on a locked record `lockSource` and `lockReason`), or the refusal of that read. The approval part's own `lock` is a different read and is unchanged. | | **discussion** | `{ comments: Record[]; reactions: object \| object } \| { error: object }` | optional | The discussion part, when the request asked for it: the thread and its reactions, or the refusal of the comment read. | | **activity** | `{ total: integer; records: Record[] } \| { error: object }` | optional | The activity part, when the request asked for it: the newest rows and their count, or the refusal of their read. | | **attachments** | `{ total: integer; records: Record[] } \| { error: object }` | optional | The attachments part, when the request asked for it: the newest rows and their count, or the refusal of their read. | @@ -513,6 +517,26 @@ This schema accepts one of the following structures: | :--- | :--- | :--- | :--- | | **error** | `{ code: string; status: integer; message: string }` | ✅ | The refusal the replaced read answers, in place of this part's answer. | +### Nested Shape: `RecordPageResponse.dataLock[option 1][locked=true]` + +| 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. | + +### Nested Shape: `RecordPageResponse.dataLock[option 1][locked=false]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **locked** | `false` | ✅ | No lock refuses a caller's write of the record. | + +### Nested Shape: `RecordPageResponse.dataLock[option 2]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **error** | `{ code: string; status: integer; message: string }` | ✅ | The refusal the replaced read answers, in place of this part's answer. | + ### Nested Shape: `RecordPageResponse.discussion[option 1]` | Property | Type | Required | Description | diff --git a/packages/spec/src/api/record-page.test.ts b/packages/spec/src/api/record-page.test.ts index 1bf446c0b4a..43d9368ae36 100644 --- a/packages/spec/src/api/record-page.test.ts +++ b/packages/spec/src/api/record-page.test.ts @@ -177,3 +177,52 @@ describe('the approval part\'s lock carries which approval holds the record, as expect(answer.error?.issues[0]?.path).toEqual(['lock', 'lockSource']); }); }); + +describe('[#38995] the data lock part: asked by a flag, answered as the data lock read answers or refused', () => { + const base = { object: 'account', id: 'a1', record: { id: 'a1' }, related: [] }; + + it('takes the flag as a boolean only', () => { + expect(RecordPageRequestSchema.safeParse({ dataLock: true }).success).toBe(true); + expect(RecordPageRequestSchema.safeParse({ dataLock: false }).success).toBe(true); + expect(RecordPageRequestSchema.safeParse({ dataLock: 'yes' }).success).toBe(false); + expect(RecordPageRequestSchema.safeParse({ dataLock: { top: 1 } }).success).toBe(false); + }); + + it('answers each arm of the lock read, and a refusal alone', () => { + for (const dataLock of [ + { locked: false }, + { locked: true, lockSource: 'record', lockReason: 'closed_state' }, + { locked: true, lockSource: 'master', lockReason: 'closed_state' }, + { locked: true, lockSource: 'record', lockReason: 'approval' }, + { locked: true, lockSource: 'master', lockReason: 'approval' }, + { error: refusal }, + ]) { + expect(RecordPageResponseSchema.safeParse({ ...base, dataLock }).success, JSON.stringify(dataLock)).toBe(true); + } + }); + + it('refuses a locked answer without its source or reason, an unlocked one carrying them, a kind the read never answers, and anything beside the lock', () => { + for (const dataLock of [ + { locked: true }, + { locked: true, lockSource: 'record' }, + { locked: true, lockReason: 'closed_state' }, + { locked: false, lockSource: 'record', lockReason: 'closed_state' }, + { locked: true, lockSource: 'parent', lockReason: 'closed_state' }, + { locked: true, lockSource: 'record', lockReason: 'archived' }, + { locked: true, lockSource: 'record', lockReason: 'closed_state', field: 'stage' }, + { locked: null }, + ]) { + expect(RecordPageResponseSchema.safeParse({ ...base, dataLock }).success, JSON.stringify(dataLock)).toBe(false); + } + }); + + it('refuses a part that carries a lock answer and a refusal at once, or anything beside the refusal: a refused read is never "unlocked"', () => { + for (const dataLock of [ + { locked: false, error: refusal }, + { locked: true, lockSource: 'record', lockReason: 'closed_state', error: refusal }, + { error: refusal, extra: 1 }, + ]) { + expect(RecordPageResponseSchema.safeParse({ ...base, dataLock }).success, JSON.stringify(dataLock)).toBe(false); + } + }); +}); diff --git a/packages/spec/src/api/record-page.zod.ts b/packages/spec/src/api/record-page.zod.ts index deca792c26f..066e4832a48 100644 --- a/packages/spec/src/api/record-page.zod.ts +++ b/packages/spec/src/api/record-page.zod.ts @@ -4,6 +4,7 @@ import { z } from 'zod'; import { lazySchema } from '../shared/lazy-schema'; import { ExplainDecisionSchema } from '../security/explain.zod'; import { GetRecordFieldAccessResponseSchema } from './protocol.zod'; +import { RecordLockSchema } from './record-lock.zod'; import type { SysActivityBuiltinType } from '../data/feed.zod'; /** @@ -13,9 +14,10 @@ import type { SysActivityBuiltinType } from '../data/feed.zod'; * opens: the record (with the lookups it names resolved), the count and first * rows of every related list the page draws (with the lookups of those rows it * names resolved), the caller's field projection of the record, the approval - * state that locks it, the record-grained access verdicts its header actions - * are gated on, and the record's own streams the page draws — its discussion, - * its activity feed and its attachments. + * state that locks it, the data layer's lock on it (closed state or approval), + * the record-grained access verdicts its header actions are gated on, and the + * record's own streams the page draws — its discussion, its activity feed and + * its attachments. * * The request NAMES the parts. Which related lists a page draws (their order, * their declared scope, which of them the reader may see) is the page's own @@ -31,7 +33,8 @@ import type { SysActivityBuiltinType } from '../data/feed.zod'; * `fieldAccess` is `GET /data/{object}/{id}/field-access`, `explain` is * `POST /security/explain` with the record id, `approvals` is * `GET /approvals/requests` for the record plus - * `GET /approvals/records/{object}/{id}/lock`, `discussion` is + * `GET /approvals/records/{object}/{id}/lock`, `dataLock` is + * `GET /data/{object}/{id}/lock` (ADR-0162 D9, `RecordLockSchema`), `discussion` is * `GET /data/sys_comment` for the record's thread plus * `GET /data/sys_comment_reaction` for those comments, `activity` is * `GET /data/sys_activity` for the record with its actor expanded, and @@ -252,6 +255,10 @@ export const RecordPageRequestSchema = lazySchema(() => z.object({ approvals: z.boolean().optional().describe( 'Return the record\'s approval requests and its approval lock.', ), + dataLock: z.boolean().optional().describe( + 'Return the record\'s data lock, as `GET /data/{object}/{id}/lock` answers it (`RecordLockSchema`): whether a ' + + 'closed state or an approval locks the record for this caller, and which.', + ), discussion: z.boolean().optional().describe( 'Return the record\'s discussion: its comment thread and those comments\' reactions (`RecordPageDiscussionSchema`).', ), @@ -419,6 +426,11 @@ export const RecordPageResponseSchema = lazySchema(() => z.object({ approvals: z.union([RecordPageApprovalsSchema, RecordPagePartErrorSchema]).optional().describe( 'The approval part, when the request asked for it.', ), + dataLock: z.union([RecordLockSchema, RecordPageStreamRefusalSchema]).optional().describe( + 'The data lock part, when the request asked for it: the record\'s lock exactly as `GET /data/{object}/{id}/lock` ' + + 'answers this caller (`locked`, and on a locked record `lockSource` and `lockReason`), or the refusal of that read. ' + + 'The approval part\'s own `lock` is a different read and is unchanged.', + ), discussion: z.union([RecordPageDiscussionSchema, RecordPageStreamRefusalSchema]).optional().describe( 'The discussion part, when the request asked for it: the thread and its reactions, or the refusal of the comment read.', ),