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
22 changes: 22 additions & 0 deletions .changeset/35795-batched-record-lock-read.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
'@objectstack/spec': patch
'@objectstack/rest': patch
'@objectstack/plugin-approvals': patch
'@objectstack/client': patch
'@object-ui/plugin-grid': patch
'@object-ui/components': patch
'@object-ui/i18n': patch
---

fix(approvals, list): a list cell no longer opens an editor before it knows the record's approval lock, and the list reads the locks of a page in one request

Clause-②: yes (widening)
Metadata-protocol: none

**What a list user sees.** On a list that edits in place, a double-click, Enter, F2 or a typed key on a cell whose record's approval lock or edit permission is still being read no longer opens an editor that the server would then refuse on save. The cell says "Checking whether this record can be edited…", and when the answer arrives the same edit goes ahead by itself (with the typed key), or the cell says why it does not: the record is locked while it is in approval, or the reader has no permission to edit it. Selecting another cell in the meantime drops the wait. Moving the selection with the arrow keys no longer sends a lock request per row: the first cell selected on a page asks the locks of every row on it at once.

**New route.** `POST /api/v1/approvals/records/:object/locks` with the body `{ "recordIds": ["<id>", ...] }` (at least one id, at most `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`, 200) answers `{ success: true, data: { records: [{ recordId, locked }] } }`, one entry per id in order. `locked` is what `GET /api/v1/approvals/records/:object/:recordId/lock` answers for that id, and `null` where that route answers 404: a record the caller cannot read and one that does not exist answer alike. Any other body (a key other than `recordIds`, an empty list, a non-string or blank id, more ids than the cap) and any query parameter are refused whole with `400 VALIDATION_ERROR`, never trimmed. A deployment whose approvals service does not implement the read answers `501`.

**Contract and SDK.** `IApprovalService` gains the optional member `getRecordLocks(object, recordIds, context)`, entry `i` answering `recordIds[i]` exactly as `getRecordLock` does; the approvals plugin implements it in two reads whatever the page size (the caller's read of the ids, then one pending-request lookup judged by the record-lock hook's own judgement). `@objectstack/spec/contracts` exports `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`. `@objectstack/client` gains `client.approvals.getRecordLocks(object, recordIds)`.

**Components.** `GridCellFacts` (the select-first table's per-cell facts) gains the optional `checking: { text, settled }`: while present, an edit asked on the cell shows `text` and is asked again when `settled` settles; a toggle, paste or clear shows `text` and writes nothing. A host that sets no `checking` sees no change.
23 changes: 23 additions & 0 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,29 @@ SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service
member is `IApprovalService.getRecordLock`. An approvals service without that
member answers `501`.

**Reading the locks of a page of records.** A list asks for every row on screen
in one request rather than one per row:

```bash
curl -b cookies.txt -X POST -H 'Content-Type: application/json' \
-d '{"recordIds":["rec_123","rec_456","rec_789"]}' \
"https://your-app.example.com/api/v1/approvals/records/expense/locks"
# → { "success": true, "data": { "records": [
# { "recordId": "rec_123", "locked": true },
# { "recordId": "rec_456", "locked": false },
# { "recordId": "rec_789", "locked": null } ] } }
```

Each entry is what the single-record read answers for that id, in the order the
ids were sent; `null` stands where that read answers `404`, so a record the
caller cannot read and one that does not exist look the same. One request
carries at most 200 ids (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`); a longer list,
an empty one or any other body key is refused with `400 VALIDATION_ERROR`. The
SDK call is `client.approvals.getRecordLocks(object, recordIds)`, the service
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.

Only `approvers` is required on the node; everything else has a default
(`behavior: 'first_response'`, `lockRecord: true`, `maxRevisions: 3`).

Expand Down
12 changes: 12 additions & 0 deletions packages/client/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -766,6 +766,18 @@ describe('Approvals namespace (ADR-0019)', () => {
expect(opts?.method ?? 'GET').toBe('GET');
});

it('reads the approval locks of a page of records in one POST, object segment encoded', async () => {
const records = [{ recordId: 'rec_1', locked: true }, { recordId: 'rec_2', locked: null }];
const { client, fetchMock } = createMockClient({ success: true, data: { records } });
const result = await client.approvals.getRecordLocks('sales order', ['rec_1', 'rec_2']);
expect(result).toEqual({ records });
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, opts] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/sales%20order/locks');
expect(opts.method).toBe('POST');
expect(JSON.parse(opts.body)).toEqual({ recordIds: ['rec_1', 'rec_2'] });
});

it('should record an approve decision', async () => {
const { client, fetchMock } = createMockClient({
request: { id: 'req-1', status: 'approved' }, finalized: true, decision: 'approve', resumed: true
Expand Down
20 changes: 20 additions & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7095,6 +7095,26 @@ export class ObjectStackClient {
return this.unwrapResponse<{ locked: boolean }>(res);
},

/**
* Whether each of a page of records of one object is held by a locking
* approval, in one request (`IApprovalService.getRecordLocks`): entry `i`
* answers `recordIds[i]` with what {@link getRecordLock} answers for that
* id, a record the caller cannot read (or that does not exist) as
* `locked: null`. At most `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS` ids per
* call, else 400; a deployment without the read answers 501.
*/
getRecordLocks: async (
object: string,
recordIds: readonly string[],
): Promise<{ records: Array<{ recordId: string; locked: boolean | null }> }> => {
const route = this.getRoute('approvals');
const res = await this.fetch(`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/locks`, {
method: 'POST',
body: JSON.stringify({ recordIds: [...recordIds] }),
});
return this.unwrapResponse<{ records: Array<{ recordId: string; locked: boolean | null }> }>(res);
},

/**
* Record an approve decision on a request. Finalises the request when the
* node's behaviour is satisfied and resumes the owning flow run.
Expand Down
32 changes: 32 additions & 0 deletions packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ import {
type ReaderLabels,
} from './reader-locale-labels.js';
import type { SlotLabelSource } from './display-label-backfill.js';
import { recordsHeldByLockingApproval } from './lifecycle-hooks.js';
import {
redactSnapshot,
resolveReadableSnapshotFields,
Expand Down Expand Up @@ -10963,6 +10964,37 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
return fresh;
}

/**
* `IApprovalService.getRecordLocks` — {@link getRecordLock} for a page of
* rows, in two reads whatever the page size: the caller's read of the ids
* (the same #8652 anchor, one `$in` read AS THE CALLER, so an unreadable row
* and a missing one both answer `null` and stay indistinguishable) and one
* pending-request lookup judged by the record-lock hook's own judgement
* ({@link recordsHeldByLockingApproval}). Entry `i` answers `recordIds[i]`.
*
* The cap is the door's to refuse loudly; here a blank id answers `null`.
*/
async getRecordLocks(
object: string,
recordIds: readonly string[],
context: ExecutionContext,
): Promise<Array<{ locked: boolean } | null>> {
const objectName = String(object ?? '').trim();
const ids = recordIds.map((recordId) => String(recordId ?? '').trim());
const asked = Array.from(new Set(ids.filter((id) => id !== '')));
if (!objectName || asked.length === 0) return ids.map(() => null);
// The anchor. As the CALLER — see getRecordLock's doc block.
const readable = await this.engine.find(objectName, {
where: { id: { $in: asked } }, fields: ['id'], limit: asked.length, context,
});
const readableIds = new Set((Array.isArray(readable) ? readable : []).map((row: any) => String(row?.id)));
const readableAsked = asked.filter((id) => readableIds.has(id));
const held = readableAsked.length > 0
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
: new Set<string>();
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null));
}

async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {
return this.loadRequest(requestId, context, true);
}
Expand Down
17 changes: 17 additions & 0 deletions packages/plugins/plugin-approvals/src/lifecycle-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,23 @@ async function lockingRequestsForRecords(
return gating.filter((pending) => nodeConfigLocksRecord(parseJson<unknown>(pending?.node_config_json, {})));
}

/**
* {@link recordHeldByLockingApproval} for many records of one object at once:
* the ids among `recordIds` held by a LOCKING pending approval. One
* pending-request lookup for the whole list and the same judgement, so a page
* asked at once and a record asked alone cannot disagree.
*
* ⚠️ Like the one-record form, it answers for the records, not for a caller.
*/
export async function recordsHeldByLockingApproval(
engine: Pick<MinimalEngine, 'find'>,
objectName: string,
recordIds: ReadonlyArray<string>,
): Promise<Set<string>> {
const held = await lockingRequestsForRecords(engine, objectName, recordIds);
return new Set(held.map((pending) => String(pending?.record_id ?? '')));
}

/**
* Narrow `candidates` (pending requests) to the ones whose record the caller's
* predicate actually matches — asked of the engine as an intersection, so the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,56 @@ async function writeAs(rig: Rig, userId: string, object: string, recordId: strin
}
}

/**
* `ApprovalService.getRecordLocks` — the same read for a page of rows: entry
* `i` is what `getRecordLock` answers for `recordIds[i]`, so a list asking a
* page at once and a record page asking one record cannot disagree.
*/
describe('ApprovalService.getRecordLocks — the lock read for a page of rows', () => {
it('answers each id in order exactly as getRecordLock answers it, for every caller', async () => {
const rig = await boot();
const ids = [recordA(HELD), recordB(HELD), MISSING, recordA(HELD)];
for (const caller of [SUBMITTER, APPROVER, READER]) {
const page = await rig.svc.getRecordLocks(HELD, ids, asUser(caller));
const oneByOne = [];
for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(HELD, id, asUser(caller)));
expect(page, caller).toEqual(oneByOne);
}
// The reader: `_a` locked; `_b` unreadable and `MISSING` absent read alike.
expect(await rig.svc.getRecordLocks(HELD, ids, asUser(READER))).toEqual([{ locked: true }, null, null, { locked: true }]);
expect(await rig.svc.getRecordLocks(OPEN, [recordA(OPEN), recordB(OPEN)], asUser(SUBMITTER)))
.toEqual([{ locked: false }, { locked: false }]);
});

it('reads the page in two engine reads whatever its size, never one per row', async () => {
const rig = await boot();
const find = rig.engine.find.bind(rig.engine);
const reads: string[] = [];
(rig.engine as any).find = (object: string, query: any) => {
reads.push(object);
return find(object, query);
};
await rig.svc.getRecordLocks(HELD, [recordA(HELD), recordB(HELD), MISSING], asUser(SUBMITTER));
expect(reads).toEqual([HELD, 'sys_approval_request']);
});

it('refuses a caller with no read on the object as getRecordLock does, and answers a blank id null', async () => {
const rig = await boot();
const refusal = await rig.svc.getRecordLocks(HELD, [recordA(HELD)], asUser(OUTSIDER)).then(
() => 'answered', (err: any) => `${err?.code} ${err?.status}`,
);
expect(refusal).toBe('PERMISSION_DENIED 403');
expect(await rig.svc.getRecordLocks(HELD, ['', recordA(HELD)], asUser(READER))).toEqual([null, { locked: true }]);
});

it('unlocks the page once the request is decided, as the hook does', async () => {
const rig = await boot();
await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER));
expect(await rig.svc.getRecordLocks(HELD, [recordA(HELD)], asUser(READER))).toEqual([{ locked: false }]);
expect(await writeAs(rig, READER, HELD, recordA(HELD))).toBe('written');
});
});

describe('[#26314] ApprovalService.getRecordLock', () => {
it('tells a non-participant reader the record is locked, and nothing about the request', async () => {
const rig = await boot();
Expand Down
89 changes: 88 additions & 1 deletion packages/rest/src/approvals-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,11 @@ import { strandedDecisionDetails, sendError as sendEnvelopeError, sendOk } from
// object's select options are built FROM this list (#3786), so it is the
// object's own declaration, read where the object reads it, and not a second
// list kept beside it.
import { APPROVAL_STATUSES, type ApprovalStatus } from '@objectstack/spec/contracts';
import {
APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS,
APPROVAL_STATUSES,
type ApprovalStatus,
} from '@objectstack/spec/contracts';
import {
classifiedRefusalAnswer,
nestedRefusalEnvelope,
Expand All @@ -79,6 +83,52 @@ import {
*/
export const APPROVAL_RECORD_LOCK_PARAMS: readonly string[] = [];

/**
* The closed query-parameter set of
* `POST {basePath}/approvals/records/:object/locks`: EMPTY. **Measured**: the
* handler reads the object from the path and the ids from the body, nothing
* from the query string (the caller's context comes from the session and
* headers). A name sent there is refused with the located 400, never dropped.
*/
export const APPROVAL_RECORD_LOCKS_PARAMS: readonly string[] = [];

/** The body keys `POST {basePath}/approvals/records/:object/locks` reads: `recordIds` alone. */
const APPROVAL_RECORD_LOCKS_BODY_KEYS: readonly string[] = ['recordIds'];

/**
* Read the body of `POST {basePath}/approvals/records/:object/locks`: the ids,
* or the sentence that refuses the request. Every shape is refused whole,
* never trimmed: a body key the door does not read, a `recordIds` that is not
* a list of non-empty strings, an empty list and one over
* {@link APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS}.
*/
export function readRecordLocksBody(body: unknown): { recordIds: string[] } | { refusal: string } {
if (body === null || typeof body !== 'object' || Array.isArray(body)) {
return { refusal: 'The request body must be a JSON object of the form {"recordIds": ["<id>", ...]}.' };
}
const unknown = Object.keys(body).filter((key) => !APPROVAL_RECORD_LOCKS_BODY_KEYS.includes(key));
if (unknown.length > 0) {
return {
refusal: `Unknown body field${unknown.length > 1 ? 's' : ''} ${unknown.map((key) => `"${key}"`).join(', ')}: `
+ 'this request reads "recordIds" alone. Nothing was read.',
};
}
const ids = (body as { recordIds?: unknown }).recordIds;
if (!Array.isArray(ids) || ids.some((id) => typeof id !== 'string' || id.trim() === '')) {
return { refusal: '"recordIds" must be a list of record ids, each a non-empty string.' };
}
if (ids.length === 0) {
return { refusal: '"recordIds" names no record; send at least one id.' };
}
if (ids.length > APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS) {
return {
refusal: `"recordIds" carries ${ids.length} ids; one request carries at most `
+ `${APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS}. Send the rest in another request. Nothing was read.`,
};
}
return { recordIds: ids as string[] };
}

/**
* [#29880] Read `?status=` on `GET {basePath}/approvals/requests` against the
* value set `sys_approval_request.status` declares.
Expand Down Expand Up @@ -466,6 +516,43 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s
metadata: { summary: 'Whether a record is held by a locking approval', tags: ['approvals'] },
});

// The lock of a PAGE of records, in one request: what a list asks before it
// opens a cell editor, so moving through the rows sends no request per row.
// Each entry is exactly the single-record door's answer for that id, the
// 404 folded to `locked: null` (unreadable or missing, told apart by
// nothing); a service without `getRecordLocks` answers 501, never one
// `getRecordLock` per id.
this.routeManager.register({
method: 'POST',
path: `${dataPath}/approvals/records/:object/locks`,
handler: async (req: any, res: any) => {
try {
const environmentId = isScoped ? req.params?.environmentId : undefined;
const context = await this.resolveExecCtx(environmentId, req);
if (this.enforceAuth(req, res, context)) return;
if (refuseUnknownQueryParams(req, res, APPROVAL_RECORD_LOCKS_PARAMS)) return;
const read = readRecordLocksBody(req.body);
if ('refusal' in read) {
sendEnvelopeError(res, 400, 'VALIDATION_ERROR', read.refusal);
return;
}
const svc = await resolveService(environmentId, req);
if (!svc || typeof svc.getRecordLocks !== 'function') return respond501(res);
const { object } = req.params;
const answers = await svc.getRecordLocks(object, read.recordIds, context ?? {});
sendOk(res, {
records: read.recordIds.map((recordId, index) => ({
recordId,
locked: answers[index] ? answers[index]!.locked === true : null,
})),
});
} catch (error: any) {
handleRouteError(res, error);
}
},
metadata: { summary: 'Whether each of a page of records is held by a locking approval', tags: ['approvals'] },
});

// Record a decision on a node-driven request. Both branches funnel
// through the contract's `decide()`, which finalizes the request and
// resumes the owning flow run down the matching `approve` / `reject`
Expand Down
Loading
Loading