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
12 changes: 12 additions & 0 deletions .changeset/38995-record-page-data-lock.md
Original file line number Diff line number Diff line change
@@ -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.
7 changes: 7 additions & 0 deletions content/docs/api/data-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
224 changes: 224 additions & 0 deletions packages/rest/src/record-page-data-lock-38995.test.ts
Original file line number Diff line number Diff line change
@@ -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<unknown>;
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<string, unknown>) => {
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();
});
});
Loading
Loading