Skip to content
24 changes: 24 additions & 0 deletions .changeset/37151-record-lock-source.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@objectstack/spec': patch
'@objectstack/plugin-approvals': patch
'@objectstack/rest': patch
'@objectstack/client': patch
---

feat(plugin-approvals): the record lock reads say whether a row is held by its own approval or by its master's

Clause-②: yes (widening: both lock doors' published entry gains a field)
Metadata-protocol: none

Both approval lock reads (`IApprovalService.getRecordLock` and `getRecordLocks`, and their REST doors `GET /api/v1/approvals/records/:object/:recordId/lock` and `POST /api/v1/approvals/records/:object/locks`) now answer a locked record with `lockSource`, which approval holds it:

- `'record'`: a pending request on the record itself, from a node whose `lockRecord` is not `false`. Deleting the record still goes through and cancels the request.
- `'master'`: the record is a `master_detail` line of a record so held. The server refuses the line's insert, update and delete with `409 RECORD_LOCKED`.

When both hold (a line with a pending request of its own, under a held master), the answer is `'master'`, because that is the delete the server refuses. An unlocked record still answers `{ locked: false }`, with no `lockSource`, and `null` (`404 RECORD_NOT_FOUND` at the single door, `locked: null` in the batch door) still means unreadable or missing, never told apart. No request id, node, approvers or `pending` flag is served. A list can now hide Delete on a line whose master is under approval instead of offering a delete the server refuses.

The `IApprovalService` return types gain the optional `lockSource?: 'record' | 'master'`, so an implementation may omit it on a locked answer and still satisfies the contract; the REST doors then serve `{ locked: true }` without a kind.

Which rows count as readable is unchanged at both doors. The two doors keep different readability anchors on purpose: the single door counts any returned row, the batch door only the row whose id is the asked id; aligning them would narrow a published answer (seat ruling 7152650156 on #37151). So an id the database matches only under another spelling (a different letter case, `07` for a numeric `7`) answers `null` in the batch door. The single-record door counts the row it finds as readable and judges it, as before: a line of a held master answers `'master'`, because that check reads the row found, but a record's own request is looked up by the id as asked, so a record held by its own request may answer `{ locked: false }` under another spelling. A client asking with the ids the server gave it gets the same answer from both doors.

`@objectstack/client`: `client.approvals.getRecordLock` and `getRecordLocks` type the answer with the optional `lockSource?: 'record' | 'master'`.
37 changes: 27 additions & 10 deletions content/docs/automation/approvals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -450,16 +450,26 @@ request row:
```bash
curl -b cookies.txt \
"https://your-app.example.com/api/v1/approvals/records/expense/rec_123/lock"
# → { "success": true, "data": { "locked": true } }
# → { "success": true, "data": { "locked": true, "lockSource": "record" } }
```

The answer is `locked` and nothing else: no request, approvers or history,
which stay behind the object's `approvalsVisibleToReaders` switch. `locked` is
`true` while a pending request's node has `lockRecord` other than `false`. That
is the same check the server applies when it refuses an edit with `409
RECORD_LOCKED`, so a page that reads it never offers an edit the server will
refuse. Asked of a line, it answers `true` while the record the line belongs to
is locked. The record is read as the caller: a record they cannot read answers
The answer is `locked` and, on a locked record, `lockSource`, and nothing else:
no request, approvers or history, which stay behind the object's
`approvalsVisibleToReaders` switch. `locked` is `true` while a pending request's
node has `lockRecord` other than `false`. That is the same check the server
applies when it refuses an edit with `409 RECORD_LOCKED`, so a page that reads
it never offers an edit the server will refuse. Asked of a line, it answers
`true` while the record the line belongs to is locked.

`lockSource` says which approval holds the record, and so which delete the
server refuses. `"record"`: the record's own request holds it, and deleting the
record still goes through and cancels the request. `"master"`: the record is a
line of a locked record, and the server refuses its delete as well as its edit.
A line under a locked record that also has a pending request of its own answers
`"master"`. An unlocked record answers `{ "locked": false }` with no
`lockSource`.

The record is read as the caller: a record they cannot read answers
`404 RECORD_NOT_FOUND`, the same body a record id that does not exist gets. The
SDK call is `client.approvals.getRecordLock(object, recordId)`, and the service
member is `IApprovalService.getRecordLock`. An approvals service without that
Expand All @@ -473,14 +483,21 @@ 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_123", "locked": true, "lockSource": "record" },
# { "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
caller cannot read and one that does not exist look the same. Send the ids as
the server spelled them: an id the database matches only under another spelling
(a different letter case, `07` for `7`) answers `null` here. The single-record
read does find such a record and answers for it, but it looks up the record's
own request by the id as sent, so it may answer `{ "locked": false }` for a
record its own request holds; a line of a locked record still answers
`"master"`. The two reads keep these different rules on purpose (seat ruling
7152650156 on #37151). 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
Expand Down
16 changes: 13 additions & 3 deletions packages/client/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -758,19 +758,29 @@ describe('Approvals namespace (ADR-0019)', () => {
});

it('[#26314] reads a record\'s approval lock off the envelope, path segments encoded', async () => {
const { client, fetchMock } = createMockClient({ success: true, data: { locked: true } });
const { client, fetchMock } = createMockClient({ success: true, data: { locked: true, lockSource: 'record' } });
const result = await client.approvals.getRecordLock('order', 'rec/1');
expect(result).toEqual({ locked: true });
expect(result).toEqual({ locked: true, lockSource: 'record' });
// The answer types the kind (the test program compiles this line).
const kind: 'record' | 'master' | undefined = result.lockSource;
expect(kind).toBe('record');
const [url, opts] = fetchMock.mock.calls[0];
expect(String(url)).toBe('http://localhost:3000/api/v1/approvals/records/order/rec%2F1/lock');
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 records = [
{ recordId: 'rec_1', locked: true, lockSource: 'master' },
{ recordId: 'rec_2', locked: null },
{ recordId: 'rec_3', locked: false },
];
const { client, fetchMock } = createMockClient({ success: true, data: { records } });
const result = await client.approvals.getRecordLocks('sales order', ['rec_1', 'rec_2']);
expect(result).toEqual({ records });
// The entry types the kind (the test program compiles this line).
const kinds: Array<'record' | 'master' | undefined> = result.records.map((entry) => entry.lockSource);
expect(kinds).toEqual(['master', undefined, undefined]);
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');
Expand Down
20 changes: 14 additions & 6 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7148,18 +7148,24 @@ export class ObjectStackClient {
},

/**
* Whether a record is held by a locking approval — `{ locked }` and
* nothing else, answered to every caller who can read the record, whether
* Whether a record is held by a locking approval — `{ locked }`, plus on a
* locked record which approval holds it, `lockSource`: `'record'` (its own;
* deleting it cancels the request) or `'master'` (the record a
* master-detail line belongs to; the server refuses the line's delete too) —
* and nothing else, answered to every caller who can read the record, whether
* or not they take part in the approval (`IApprovalService.getRecordLock`).
* A record the caller cannot read answers 404, exactly as a record id that
* does not exist; a deployment without the read answers 501.
*/
getRecordLock: async (object: string, recordId: string): Promise<{ locked: boolean }> => {
getRecordLock: async (
object: string,
recordId: string,
): Promise<{ locked: boolean; lockSource?: 'record' | 'master' }> => {
const route = this.getRoute('approvals');
const res = await this.fetch(
`${this.baseUrl}${route}/records/${encodeURIComponent(object)}/${encodeURIComponent(recordId)}/lock`,
);
return this.unwrapResponse<{ locked: boolean }>(res);
return this.unwrapResponse<{ locked: boolean; lockSource?: 'record' | 'master' }>(res);
},

/**
Expand All @@ -7173,13 +7179,15 @@ export class ObjectStackClient {
getRecordLocks: async (
object: string,
recordIds: readonly string[],
): Promise<{ records: Array<{ recordId: string; locked: boolean | null }> }> => {
): Promise<{ records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }> }> => {
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);
return this.unwrapResponse<{
records: Array<{ recordId: string; locked: boolean | null; lockSource?: 'record' | 'master' }>;
}>(res);
},

/**
Expand Down
85 changes: 64 additions & 21 deletions packages/plugins/plugin-approvals/src/approval-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2232,6 +2232,23 @@ async function findChildRequestId(
*/
const REQUEST_VISIBILITY = new WeakMap<ApprovalService, RequestVisibilitySource>();

/**
* The answer both record-lock doors give a readable row
* (`IApprovalService.getRecordLock` / `getRecordLocks`, ruling 7148480184):
* which approval holds it, the master's winning when both do — a line of a held
* master refuses delete as well as edit, while a record held by its own request
* may be deleted, which cancels the request. One spelling, so the two doors
* cannot answer a row differently.
*/
function recordLockAnswer(
heldByMaster: boolean,
heldItself: boolean,
): { locked: boolean; lockSource?: 'record' | 'master' } {
if (heldByMaster) return { locked: true, lockSource: 'master' };
if (heldItself) return { locked: true, lockSource: 'record' };
return { locked: false };
}

/**
* [#23889] Each service's own slot labeller — the one its live writers label
* `pending_approver_labels` / `acted_as_label` with — for the boot backfills
Expand Down Expand Up @@ -11313,15 +11330,29 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
* detail object only — the detail-row lock's batch form
* ({@link detailRowsHeldByLockingApproval}: one FK read plus one lookup per
* `master_detail` edge), so a line of a held master answers `true` here as
* it does at {@link getRecordLock}. Entry `i` answers `recordIds[i]`.
* it does at {@link getRecordLock}, with the same `lockSource`. Entry `i`
* answers `recordIds[i]`.
*
* ## Which rows count as readable — the row whose id IS the asked id
*
* A row is readable here when the caller's read hands back a row whose id
* IS the asked id, spelled as asked: one `$in` read cannot say which asked
* id a row the engine spells differently answers (a case-insensitive
* collation, a numeric id asked as `'07'`), so such an id answers `null`
* here. {@link getRecordLock} counts any row its read hands back, so for
* such an id the two doors differ, deliberately: the two doors keep
* different readability anchors on purpose, and aligning them would narrow
* a published answer (seat ruling 7152650156 on #37151). For an id spelled as the
* engine spells it — what a list holds — entry `i` is exactly the single
* door's answer.
*
* 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>> {
): Promise<Array<{ locked: boolean; lockSource?: 'record' | 'master' } | null>> {
const objectName = String(object ?? '').trim();
const ids = recordIds.map((recordId) => String(recordId ?? '').trim());
const asked = Array.from(new Set(ids.filter((id) => id !== '')));
Expand All @@ -11335,12 +11366,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
const held = readableAsked.length > 0
? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked)
: new Set<string>();
// The single door's second half, for the rows the first left unlocked.
const unheld = readableAsked.filter((id) => !held.has(id));
const heldByMaster = unheld.length > 0
? await detailRowsHeldByLockingApproval(this.engine, objectName, unheld)
// The single door's second half, asked of every readable row: a line held
// by its own request under a held master answers `'master'` there too.
const heldByMaster = readableAsked.length > 0
? await detailRowsHeldByLockingApproval(this.engine, objectName, readableAsked)
: new Set<string>();
return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) || heldByMaster.has(id) } : null));
return ids.map((id) => (readableIds.has(id) ? recordLockAnswer(heldByMaster.has(id), held.has(id)) : null));
}

async getRequest(requestId: string, context: ExecutionContext): Promise<ApprovalRequestRow | null> {
Expand Down Expand Up @@ -11438,22 +11469,35 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
* id, existing or not. ⚠️ Probing with {@link SYSTEM_CTX} here would admit
* every authenticated user in the tenant.
*
* ## What is answered — the lock, and nothing about the request
*
* `{ locked }` only: no request id, node, participants or `pending`. Request
* content stays behind `approvalsVisibleToReaders` (#8652 ruling 5299823744,
* untouched). The judgement is the record-lock hook's own
* ({@link recordHeldByLockingApproval}), never a second copy of it — and,
* for a master-detail line, the detail-row lock's
* ({@link detailRowHeldByLockingApproval}): a locked record's lines are
* locked with it, so the read answers `true` for a line whose write the hook
* refuses.
* Any row the read hands back counts, whatever spelling of the id the
* engine hands back (a case-insensitive collation, a numeric id asked as
* `'07'`); {@link getRecordLocks} counts only the row whose id IS the asked
* id. The two doors keep different readability anchors on purpose:
* aligning them would narrow a published answer (seat ruling 7152650156 on #37151).
* For such an id the master half below reads the row the engine found, but
* the row's own request is looked up by the id as asked
* ({@link recordHeldByLockingApproval}), so a record held by its own request
* may answer `{ locked: false }` under another spelling.
*
* ## What is answered — the lock and its kind, nothing about the request
*
* `{ locked, lockSource }` (ruling 7148480184, option A): no request id,
* node, participants or `pending`. Request content stays behind
* `approvalsVisibleToReaders` (#8652 ruling 5299823744, untouched);
* `lockSource` is one kind bit. The judgement is the record-lock hook's own
* ({@link recordHeldByLockingApproval}), never a second copy of it —
* `lockSource: 'record'` — and, for a master-detail line, the detail-row
* lock's ({@link detailRowHeldByLockingApproval}): a locked record's lines
* are locked with it, so the read answers `true` for a line whose write the
* hook refuses — `lockSource: 'master'`, asked first because it wins when
* both hold: a line of a held master refuses delete too, a record held by
* its own request may be deleted (the delete cancels the request).
*/
async getRecordLock(
object: string,
recordId: string,
context: ExecutionContext,
): Promise<{ locked: boolean } | null> {
): Promise<{ locked: boolean; lockSource?: 'record' | 'master' } | null> {
const objectName = String(object ?? '').trim();
const id = String(recordId ?? '').trim();
if (!objectName || !id) return null;
Expand All @@ -11462,9 +11506,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega
where: { id }, fields: ['id'], limit: 1, context,
});
if (!Array.isArray(readable) || readable.length === 0) return null;
const locked = await recordHeldByLockingApproval(this.engine, objectName, id)
|| await detailRowHeldByLockingApproval(this.engine, objectName, id);
return { locked };
if (await detailRowHeldByLockingApproval(this.engine, objectName, id)) return recordLockAnswer(true, false);
return recordLockAnswer(false, await recordHeldByLockingApproval(this.engine, objectName, id));
}

private async loadRequest(
Expand Down
Loading
Loading