diff --git a/.changeset/37041-batch-lock-detail-lines.md b/.changeset/37041-batch-lock-detail-lines.md new file mode 100644 index 00000000000..247804f3eec --- /dev/null +++ b/.changeset/37041-batch-lock-detail-lines.md @@ -0,0 +1,11 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/spec': patch +--- + +fix(plugin-approvals): the batch lock read answers a line of a held master as locked, as the single read does + +Clause-②: no +Metadata-protocol: none + +`getRecordLocks` (`POST /api/v1/approvals/records/:object/locks`) answered `locked: false` for a master-detail line whose master is held by a locking approval, while `getRecordLock` answered `locked: true` and the line's write was refused `RECORD_LOCKED`. The batch read now asks the detail-row lock too, through its new batch form `detailRowsHeldByLockingApproval`: one read of the rows' master-detail columns plus one lookup per master-detail edge, whatever the page size, never one read per row. The answer's shape is unchanged (`{ locked }` or `null`); a list page that reads the batch door now stops offering an editor on such a line. The `getRecordLock` / `getRecordLocks` contract docblocks in `@objectstack/spec` now say a line of a held master answers `true`. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index d419a1746fc..50e23203422 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -168,7 +168,9 @@ import { type FieldVisibilitySource, } from './payload-redaction.js'; import { APPROVAL_REQUEST_CHILD_OBJECTS, type RequestVisibilitySource } from './request-read-gate.js'; -import { detailRowHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval } from './lifecycle-hooks.js'; +import { + detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval, nodeConfigLocksRecord, recordHeldByLockingApproval, +} from './lifecycle-hooks.js'; import { PendingApproverReadGrantSource, type PendingApproverReadGrants } from './pending-approver-read-grant.js'; // The ADR-0043 pages — the ONE copy of their text, rendered by the plugin's // self-hosted mount and by `handleActionPage` alike. @@ -11303,11 +11305,15 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega /** * `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]`. + * rows, in a bounded number of 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), one pending-request lookup judged by the record-lock + * hook's own judgement ({@link recordsHeldByLockingApproval}) and — on a + * 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]`. * * The cap is the door's to refuse loudly; here a blank id answers `null`. */ @@ -11329,7 +11335,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const held = readableAsked.length > 0 ? await recordsHeldByLockingApproval(this.engine, objectName, readableAsked) : new Set(); - return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null)); + // 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) + : new Set(); + return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) || heldByMaster.has(id) } : null)); } async getRequest(requestId: string, context: ExecutionContext): Promise { diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index a0b422c4959..7fd8b445a39 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -540,23 +540,65 @@ export async function detailRowHeldByLockingApproval( objectName: string, recordId: string, ): Promise { - if (isApprovalBookkeepingObject(objectName)) return false; + // Asked of exactly one id, a non-empty answer is that row's: the set's member + // is the row's id as the engine spells it back, which need not be `recordId`'s + // spelling, so membership is never compared. + return (await detailRowsHeldByLockingApproval(engine, objectName, [recordId])).size > 0; +} + +/** + * {@link detailRowHeldByLockingApproval} for many rows of one object at once: + * the ids among `recordIds` that are DETAIL rows of a master held by a LOCKING + * pending approval. One SYSTEM read of the rows' FK columns for the whole list, + * then one lookup per `master_detail` edge for every master those rows name — + * `1 + edges` reads whatever the list's length, never one per row — and the + * same judgement ({@link lockingRequestsForRecords}), so a page asked at once + * and a row asked alone cannot disagree. An object with no `master_detail` + * edge reads nothing. + * + * The join is not pushed down to the database: the judgement is made in-app + * over each request's `node_config_json` snapshot and must be the write hook's + * own ({@link lockingRequestsForRecords}), and the id list is bounded by the + * door's 200-id cap (`APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`), so `1 + edges` + * bounded reads is the whole cost. + * + * ⚠️ Like the one-row form, it answers for the rows, not for a caller, and the + * FK read is SYSTEM. + */ +export async function detailRowsHeldByLockingApproval( + engine: Pick, + objectName: string, + recordIds: ReadonlyArray, +): Promise> { + const held = new Set(); + if (recordIds.length === 0 || isApprovalBookkeepingObject(objectName)) return held; const edges = masterEdgesOf(engine, objectName); - if (edges.length === 0) return false; + if (edges.length === 0) return held; const rows = await engine.find(objectName, { - where: { id: recordId }, + // One id keeps the by-id shape the one-row read always sent. + where: recordIds.length === 1 ? { id: recordIds[0] } : { id: { $in: [...recordIds] } }, fields: ['id', ...edges.map((e) => e.fk)], - limit: 1, + limit: recordIds.length, // SYSTEM_CTX's arrays are `as const` (readonly); the declared type wants mutable ones. context: { ...SYSTEM_CTX, positions: [], permissions: [] }, } satisfies EngineQueryOptions); - const row = Array.isArray(rows) ? (rows[0] as Record | undefined) : undefined; - if (!row) return false; + const found = (Array.isArray(rows) ? rows : []) as Array>; + if (found.length === 0) return held; for (const e of edges) { - const masterId = scalarFk(row[e.fk]); - if (masterId && (await lockingRequestsForRecords(engine, e.master, [masterId])).length > 0) return true; + const masterIds = Array.from(new Set( + found.map((row) => scalarFk(row[e.fk])).filter((id): id is string => id !== null), + )); + if (masterIds.length === 0) continue; + const heldMasters = new Set( + (await lockingRequestsForRecords(engine, e.master, masterIds)).map((p) => String(p?.record_id ?? '')), + ); + if (heldMasters.size === 0) continue; + for (const row of found) { + const masterId = scalarFk(row[e.fk]); + if (masterId && heldMasters.has(masterId)) held.add(String(row.id)); + } } - return false; + return held; } /** diff --git a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts index 29389c24fe1..40208e771c8 100644 --- a/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/record-lock-read.integration.test.ts @@ -44,6 +44,7 @@ import { SysApprovalAction } from './sys-approval-action.object.js'; import { SysApprovalApprover } from './sys-approval-approver.object.js'; import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; +import { detailRowHeldByLockingApproval, detailRowsHeldByLockingApproval } from './lifecycle-hooks.js'; /** Its approval node locks the record. */ const HELD = 'held_sheet'; @@ -335,6 +336,62 @@ describe('a locked record\'s lines are locked with it — the record-lock read a expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('written'); }); + it('the page read answers a line of a held master as the single read does — held itself, held by its master, unheld', async () => { + const rig = await boot(); + // Held itself: record `_a` of the sheet. Held by its master: line `_a`. Unheld: record `_b` and line `_b`. + const scenes: Array<[string, string[]]> = [ + [HELD, [recordA(HELD), recordB(HELD), MISSING, recordA(HELD)]], + [LINE, [recordA(LINE), recordB(LINE), MISSING, recordA(LINE)]], + ]; + for (const caller of [SUBMITTER, APPROVER, READER]) { + for (const [object, ids] of scenes) { + const page = await rig.svc.getRecordLocks(object, ids, asUser(caller)); + const oneByOne = []; + for (const id of ids) oneByOne.push(await rig.svc.getRecordLock(object, id, asUser(caller))); + expect(page, `${caller} ${object}`).toEqual(oneByOne); + } + } + expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER))) + .toEqual([{ locked: true }, { locked: false }]); + // The reader: line `_a` locked, as its write is refused; line `_b` unreadable reads as missing. + expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE), MISSING], asUser(READER))) + .toEqual([{ locked: true }, null, null]); + expect(await writeAs(rig, READER, LINE, recordA(LINE))).toBe('RECORD_LOCKED'); + // A line held by a request of its own answers locked by both reads too. + await rig.svc.openNodeRequest({ + object: LINE, recordId: recordB(LINE), runId: 'run_line_b', nodeId: 'review', flowName: 'line_review', + config: nodeConfig(true) as any, submitterId: SUBMITTER, record: { id: recordB(LINE), title: recordB(LINE) }, + }, asUser(SUBMITTER)); + expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER))) + .toEqual([await rig.svc.getRecordLock(LINE, recordA(LINE), asUser(SUBMITTER)), + await rig.svc.getRecordLock(LINE, recordB(LINE), asUser(SUBMITTER))]); + expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE), recordB(LINE)], asUser(SUBMITTER))) + .toEqual([{ locked: true }, { locked: true }]); + // Decided: the line unlocks for the page read as for the hook. + await rig.svc.decide(rig.requests.get(HELD)!, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); + expect(await rig.svc.getRecordLocks(LINE, [recordA(LINE)], asUser(READER))).toEqual([{ locked: false }]); + }); + + it('reads a page of lines in a bounded number of engine reads whatever its size, never one per row', async () => { + const rig = await boot(); + for (let i = 0; i < 6; i += 1) { + await rig.engine.insert(LINE, { id: `${LINE}_x${i}`, title: `x${i}`, sheet: i % 2 ? recordA(HELD) : recordB(HELD) }, + { context: SYSTEM } as any); + } + 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); + }; + const ids = [recordA(LINE), recordB(LINE), ...Array.from({ length: 6 }, (_, i) => `${LINE}_x${i}`)]; + // As SYSTEM: the extra lines are outside the stand-in's per-user grants. + const page = await rig.svc.getRecordLocks(LINE, ids, SYSTEM); + // The caller's anchor, the rows' own requests, the rows' FK columns, the masters' requests. + expect(reads).toEqual([LINE, 'sys_approval_request', LINE, 'sys_approval_request']); + expect(page.map((entry) => entry?.locked)).toEqual([true, false, false, true, false, true, false, true]); + }); + it('answers a line the caller cannot read exactly as one that does not exist', async () => { const rig = await boot(); await rig.svc.openNodeRequest({ @@ -346,3 +403,25 @@ describe('a locked record\'s lines are locked with it — the record-lock read a expect(await rig.svc.getRecordLock(LINE, MISSING, asUser(READER))).toBeNull(); }); }); + +describe('the one-row detail read answers from the row it found, not from how the engine spells its id', () => { + // A stand-in engine that answers the by-id read with the row's id spelled + // differently from the asked one (a driver that normalizes case, or hands a + // numeric id back as a number) — the master it names is held by a locking request. + const engine = { + getSchema: (name: string) => name === 'line' + ? { fields: { order: { name: 'order', type: 'master_detail', reference: 'order' } } } + : undefined, + find: async (name: string) => name === 'line' + ? [{ id: 'LINE-1', order: 'ord_1' }] + : name === 'sys_approval_request' + ? [{ record_id: 'ord_1', status: 'pending', node_config_json: '{}' }] + : [], + } as any; + + it('a held line asked by an id the engine spells back differently answers true', async () => { + expect(await detailRowHeldByLockingApproval(engine, 'line', 'line-1')).toBe(true); + // The batch form keeps answering with the ids as the engine spells them. + expect([...await detailRowsHeldByLockingApproval(engine, 'line', ['line-1'])]).toEqual(['LINE-1']); + }); +}); diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index e43d2d0c696..a2132f3fffd 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -1112,7 +1112,10 @@ export interface IApprovalService { * - **What is answered:** `locked` only. `true` when a pending request on the * record comes from a node whose `lockRecord` is not `false` — the same * judgement, off the same snapshot, the record-lock `beforeUpdate` hook - * enforces. ⛔ No request id, node, participants or `pending` flag: whether + * enforces. Asked of a master-detail line, it also answers `true` while + * a record the line belongs to is so held — the detail-row lock's judgement, + * which refuses the line's writes. + * ⛔ No request id, node, participants or `pending` flag: whether * the caller may see the request is still `approvalsVisibleToReaders`' * question, and this member does not answer it. * @@ -1140,7 +1143,9 @@ export interface IApprovalService { * {@link getRecordLock} answers for that id: `{ locked }` when the caller * can read the record, `null` when it cannot or when it does not exist, * ⛔ never an entry that tells the two apart. The same judgement, off the - * same snapshot, the record-lock `beforeUpdate` hook enforces. A repeated id + * same snapshot, the record-lock `beforeUpdate` hook enforces — and, for a + * master-detail line, the detail-row lock's: a line answers `true` while a + * record it belongs to is so held. A repeated id * is answered at each of its positions. A caller refused the object's read * outright is refused the same way for every id. *