diff --git a/.changeset/35795-batched-record-lock-read.md b/.changeset/35795-batched-record-lock-read.md new file mode 100644 index 00000000000..4b2f81a9e78 --- /dev/null +++ b/.changeset/35795-batched-record-lock-read.md @@ -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": ["", ...] }` (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. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 51f95502a7e..d022556a3ec 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -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`). diff --git a/packages/client/src/client.test.ts b/packages/client/src/client.test.ts index 35150f22227..abc25076e25 100644 --- a/packages/client/src/client.test.ts +++ b/packages/client/src/client.test.ts @@ -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 diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts index a12d08bc583..5f3586ee803 100644 --- a/packages/client/src/index.ts +++ b/packages/client/src/index.ts @@ -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. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 3368dc9f224..bf3fc08aed5 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -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, @@ -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> { + 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(); + return ids.map((id) => (readableIds.has(id) ? { locked: held.has(id) } : null)); + } + async getRequest(requestId: string, context: ExecutionContext): Promise { return this.loadRequest(requestId, context, true); } diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index b09bd39144b..08017041678 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -526,6 +526,23 @@ async function lockingRequestsForRecords( return gating.filter((pending) => nodeConfigLocksRecord(parseJson(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, + objectName: string, + recordIds: ReadonlyArray, +): Promise> { + 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 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 63c37071958..b8a86786026 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 @@ -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(); diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index 17fec4754be..b02a20c10eb 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -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, @@ -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": ["", ...]}.' }; + } + 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. @@ -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` diff --git a/packages/rest/src/rest-approvals-record-lock-route.test.ts b/packages/rest/src/rest-approvals-record-lock-route.test.ts index be895cf4d0e..4fb472e8e82 100644 --- a/packages/rest/src/rest-approvals-record-lock-route.test.ts +++ b/packages/rest/src/rest-approvals-record-lock-route.test.ts @@ -21,8 +21,13 @@ import { describe, it, expect, vi } from 'vitest'; import { RestServer } from './rest-server.js'; -import { APPROVAL_RECORD_LOCK_PARAMS } from './approvals-routes.js'; +import { APPROVAL_RECORD_LOCK_PARAMS, APPROVAL_RECORD_LOCKS_PARAMS } from './approvals-routes.js'; +import { APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS } from '@objectstack/spec/contracts'; import { unknownQueryParamMessage } from './query-allowlist.js'; +// The rest server's routes load `@objectstack/objectql` lazily, inside a +// handler; paying that load here, at collection, keeps it out of the first +// case's `testTimeout` window (check:test-source-alias). +import '@objectstack/objectql'; const LOCK = '/api/v1/approvals/records/:object/:recordId/lock'; const CALLER = { userId: 'u_reader', positions: [], permissions: [] }; @@ -47,7 +52,7 @@ function mockRes() { return res; } -function boot(approvals: Record) { +function bootRest(approvals: Record) { const protocol: any = { getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' }, @@ -72,7 +77,11 @@ function boot(approvals: Record) { ); (rest as any).resolveExecCtx = async () => CALLER; rest.registerRoutes(); + return rest; +} +function boot(approvals: Record) { + const rest = bootRest(approvals); return async (object: string, recordId: string, query: Record = {}) => { const found = (rest as any).getRoutes().find((r: any) => r.method === 'GET' && r.path === LOCK); if (!found) throw new Error(`route not registered: GET ${LOCK}`); @@ -137,3 +146,114 @@ describe('[#26314] GET /approvals/records/:object/:recordId/lock', () => { expect(answer.body?.data).toBeUndefined(); }); }); + +const LOCKS = '/api/v1/approvals/records/:object/locks'; + +/** Drive `POST …/records/:object/locks` with a body (and a query string). */ +function bootLocks(approvals: Record) { + const rest = bootRest(approvals); + return async (object: string, body: unknown, query: Record = {}) => { + const found = (rest as any).getRoutes().find((r: any) => r.method === 'POST' && r.path === LOCKS); + if (!found) throw new Error(`route not registered: POST ${LOCKS}`); + const res = mockRes(); + await found.handler( + { method: 'POST', path: LOCKS, params: { object }, query, headers: {}, body } as any, + res, + ); + return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] }; + }; +} + +/** + * `POST /api/v1/approvals/records/:object/locks` — the page form of the door + * above, the half of `IApprovalService.getRecordLocks` a list reads before it + * opens a cell editor. Each entry is the single door's answer for its id, the + * 404 folded into `locked: null`; the body is refused whole when it is not the + * one shape the door reads, and the service is never asked then. + */ +describe('POST /approvals/records/:object/locks — the lock of a page of records', () => { + it('asks the service once with the ids in order and the caller, and serves one entry per id', async () => { + const getRecordLocks = vi.fn().mockResolvedValue([ + { locked: true, requestId: 'req_1' }, null, { locked: false }, + ]); + const drive = bootLocks({ getRecordLocks }); + const answer = await drive('expense', { recordIds: ['rec_1', 'rec_hidden', 'rec_3'] }); + expect(answer).toEqual({ + status: 200, + body: { + success: true, + data: { + records: [ + { recordId: 'rec_1', locked: true }, + { recordId: 'rec_hidden', locked: null }, + { recordId: 'rec_3', locked: false }, + ], + }, + }, + }); + expect(getRecordLocks).toHaveBeenCalledTimes(1); + expect(getRecordLocks).toHaveBeenCalledWith('expense', ['rec_1', 'rec_hidden', 'rec_3'], CALLER); + }); + + it('takes a full page at the cap', async () => { + const ids = Array.from({ length: APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS }, (_, i) => `rec_${i}`); + const getRecordLocks = vi.fn().mockResolvedValue(ids.map(() => ({ locked: false }))); + const drive = bootLocks({ getRecordLocks }); + const answer = await drive('expense', { recordIds: ids }); + expect(answer.status).toBe(200); + expect(answer.body?.data?.records).toHaveLength(APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS); + expect(getRecordLocks).toHaveBeenCalledWith('expense', ids, CALLER); + }); + + it.each([ + ['no body', undefined, 'must be a JSON object'], + ['a list for a body', ['rec_1'], 'must be a JSON object'], + ['no recordIds', {}, '"recordIds" must be a list'], + ['a string for recordIds', { recordIds: 'rec_1' }, '"recordIds" must be a list'], + ['a number among the ids', { recordIds: ['rec_1', 7] }, '"recordIds" must be a list'], + ['a blank id', { recordIds: ['rec_1', ' '] }, '"recordIds" must be a list'], + ['an empty list', { recordIds: [] }, 'names no record'], + ['one id over the cap', { + recordIds: Array.from({ length: APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS + 1 }, (_, i) => `rec_${i}`), + }, `at most ${APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS}`], + ['a body key the door does not read', { recordIds: ['rec_1'], includeRequest: true }, 'Unknown body field "includeRequest"'], + ])('refuses %s whole with the located 400, and never asks the service', async (_label, body, sentence) => { + const getRecordLocks = vi.fn().mockResolvedValue([{ locked: true }]); + const drive = bootLocks({ getRecordLocks }); + const answer = await drive('expense', body); + expect(answer.status).toBe(400); + expect(answer.body?.success).toBe(false); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(answer.body?.error?.message).toContain(sentence); + expect(answer.body?.data).toBeUndefined(); + expect(getRecordLocks).not.toHaveBeenCalled(); + }); + + it('declares an EMPTY closed query set: a name is refused with the located 400 and the service is never asked', async () => { + expect([...APPROVAL_RECORD_LOCKS_PARAMS]).toEqual([]); + const getRecordLocks = vi.fn().mockResolvedValue([{ locked: true }]); + const drive = bootLocks({ getRecordLocks }); + const answer = await drive('expense', { recordIds: ['rec_1'] }, { ids: 'rec_2' }); + expect(answer.status).toBe(400); + expect(answer.body?.error?.code).toBe('VALIDATION_ERROR'); + expect(answer.body?.error?.message).toBe(unknownQueryParamMessage(['ids'], [])); + expect(getRecordLocks).not.toHaveBeenCalled(); + }); + + it('answers 501 when the service declares only the one-record member, never one read per id', async () => { + const getRecordLock = vi.fn().mockResolvedValue({ locked: true }); + const drive = bootLocks({ getRecordLock }); + const answer = await drive('expense', { recordIds: ['rec_1', 'rec_2'] }); + expect(answer.status).toBe(501); + expect(answer.body?.code).toBe('NOT_IMPLEMENTED'); + expect(getRecordLock).not.toHaveBeenCalled(); + }); + + it('relays a refusal of the read at its own status, not as a lock answer', async () => { + const denied = Object.assign(new Error('read on expense denied'), { code: 'PERMISSION_DENIED', statusCode: 403 }); + const drive = bootLocks({ getRecordLocks: vi.fn().mockRejectedValue(denied) }); + const answer = await drive('expense', { recordIds: ['rec_1'] }); + expect(answer.status).toBe(403); + expect(answer.body?.data).toBeUndefined(); + }); +}); diff --git a/packages/rest/src/rest-route-ledger.ts b/packages/rest/src/rest-route-ledger.ts index 63e61814a57..b0c18f15e78 100644 --- a/packages/rest/src/rest-route-ledger.ts +++ b/packages/rest/src/rest-route-ledger.ts @@ -483,6 +483,7 @@ export const REST_ROUTE_LEDGER: readonly RestRouteLedgerEntry[] = [ { route: 'GET /api/v1/approvals/requests', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.listRequests' }, { route: 'GET /api/v1/approvals/requests/:id', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.getRequest' }, { route: 'GET /api/v1/approvals/records/:object/:recordId/lock', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.getRecordLock' }, + { route: 'POST /api/v1/approvals/records/:object/locks', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.getRecordLocks' }, { route: 'POST /api/v1/approvals/requests/:id/approve', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.approve' }, { route: 'POST /api/v1/approvals/requests/:id/reject', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.reject' }, { route: 'POST /api/v1/approvals/requests/:id/recall', family: 'approvals', source: 'route-manager', disposition: 'sdk', client: 'approvals.recall' }, diff --git a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts index 423348bd8e5..8094cc4ba8d 100644 --- a/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts +++ b/packages/rest/src/rest-write-response-internal-fields.tripwire.test.ts @@ -403,6 +403,7 @@ const DISPOSITIONS: Record = { 'POST /api/v1/approvals/requests/:id/remind': { kind: 'no-record-echo', why: 'Reminder receipt.' }, 'POST /api/v1/approvals/requests/:id/request-info': { kind: 'no-record-echo', why: 'Approval request state.' }, 'POST /api/v1/approvals/requests/:id/comment': { kind: 'no-record-echo', why: 'Approval comment row.' }, + 'POST /api/v1/approvals/records/:object/locks': { kind: 'no-record-echo', why: 'A READ over POST: `{ recordId, locked }` per id, no field of the row.' }, 'POST /api/v1/analytics/dataset/query': { kind: 'no-record-echo', why: 'A READ (aggregated dataset) over POST.' }, 'POST /api/v1/analytics/dataset/query/batch': { kind: 'no-record-echo', why: 'A READ (aggregated datasets, one answer entry per query) over POST.' }, diff --git a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts index ef8cd6c58d9..217f16ad60e 100644 --- a/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts +++ b/packages/rest/src/rest-write-route-hook-refusal-sentence.ledger.test.ts @@ -427,6 +427,8 @@ const ANSWERS_THE_SENTENCE: Record = { answer: (res) => res.body?.data?.results?.[0]?.error?.message, }, 'POST /api/v1/security/explain': { called: 'security.explain', body: { object: OBJECT, operation: 'read' } }, + // A read over POST, like explain: the caller's read of the ids is the one awaited. + 'POST /api/v1/approvals/records/:object/locks': { called: 'approvals.getRecordLocks', body: { recordIds: ['r1'] } }, // [#30205] The hand-over answers per row, inside its `200`: a refused row's // entry in `failures` carries the `/data` door's sentence for that throw. 'POST /api/v1/security/users/:id/assigned-work/transfer': { diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 7f8acd80673..a02a00081ba 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -25,6 +25,7 @@ "APPROVAL_ACTION_KIND_LABELS (const)", "APPROVAL_CANCEL_REASONS (const)", "APPROVAL_CANCEL_REASON_LABELS (const)", + "APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS (const)", "APPROVAL_STATUSES (const)", "APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index e7fd61240ad..5cc6409708e 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -25,6 +25,7 @@ "APPROVAL_ACTION_KIND_LABELS": "src/contracts/approval-service.ts#APPROVAL_ACTION_KIND_LABELS (const)", "APPROVAL_CANCEL_REASONS": "src/contracts/approval-service.ts#APPROVAL_CANCEL_REASONS (const)", "APPROVAL_CANCEL_REASON_LABELS": "src/contracts/approval-service.ts#APPROVAL_CANCEL_REASON_LABELS (const)", + "APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS": "src/contracts/approval-service.ts#APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS (const)", "APPROVAL_STATUSES": "src/contracts/approval-service.ts#APPROVAL_STATUSES (const)", "APPROVAL_STATUS_LABELS": "src/contracts/approval-service.ts#APPROVAL_STATUS_LABELS (const)", "AUDIT_CHECKPOINT_SIGNER_SERVICE": "src/contracts/audit-checkpoint.ts#AUDIT_CHECKPOINT_SIGNER_SERVICE (const)", diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 9f077ff18a5..e43d2d0c696 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -72,6 +72,16 @@ export const APPROVAL_STATUSES = [ /** Lifecycle state of an approval request — derived from {@link APPROVAL_STATUSES}. */ export type ApprovalStatus = (typeof APPROVAL_STATUSES)[number]; +/** + * The most record ids one {@link IApprovalService.getRecordLocks} call — and + * one `POST {basePath}/approvals/records/:object/locks` request — carries. A + * longer list is refused whole (`400 VALIDATION_ERROR`), never truncated; a + * caller with more rows sends them in batches under it. The same cap as the + * record-grained explain batch, so a list page that asks both questions splits + * its rows the same way. + */ +export const APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS = 200; + /** * Authored English display label for each {@link APPROVAL_STATUSES} entry — * what an English reader sees in the `sys_approval_request.status` select, @@ -1120,6 +1130,36 @@ export interface IApprovalService { context: ExecutionContext, ): Promise<{ locked: boolean } | null>; + /** + * **Are these records held by a locking approval?** — {@link getRecordLock} + * for a page of rows of one object, in one call, so a list that must know + * the lock before it opens a cell editor asks once per page and never once + * per row. + * + * Entry `i` of the answer answers `recordIds[i]` with exactly what + * {@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 + * is answered at each of its positions. A caller refused the object's read + * outright is refused the same way for every id. + * + * At most {@link APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS} ids per call; a caller + * with more pages under the cap. + * + * **Optional, and its absence is loud:** a door probes for presence and + * answers `501`, never a guess and never one {@link getRecordLock} per id. + * + * @param object - The target object's name + * @param recordIds - The target records' ids, at least one + * @returns One entry per id, in order + */ + getRecordLocks?( + object: string, + recordIds: readonly string[], + context: ExecutionContext, + ): Promise>; + /** * Record a decision on a node-driven request. Honours the node's * `unanimous` behaviour, finalises the request when satisfied, and resumes diff --git a/ui/packages/components/src/context/gridCellSelection.tsx b/ui/packages/components/src/context/gridCellSelection.tsx index 39450027775..6c7c8a88304 100644 --- a/ui/packages/components/src/context/gridCellSelection.tsx +++ b/ui/packages/components/src/context/gridCellSelection.tsx @@ -34,6 +34,17 @@ export interface GridCellFacts { * (double-click, Enter, F2, typing) shows this sentence on the cell. */ readOnlyReason?: string | null; + /** + * The host is still reading what decides whether this cell edits (the + * record's lock, the reader's verdict on the record). An attempt to edit it + * meanwhile opens no editor: the cell shows `text`, and once `settled` + * settles (resolved or rejected) the same attempt, with the same typed key, + * is asked again — unless the reader selected another cell, asked something + * newer of it or opened an editor in the meantime. A toggle, a paste or a + * clear asked meanwhile waits the same way: nothing is written before the + * read settles. Absent ⇒ nothing is being read. + */ + checking?: { text: string; settled: Promise } | null; /** * What a printable key typed on the selected cell does: `replace` opens the * editor with the typed text in place of the value (text, numbers); `open` diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index 306c3e50105..bdd4df1d66a 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -3720,11 +3720,42 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // Why the cell an edit was asked of opens no editor, drawn on that cell. const [cellNotice, setCellNotice] = useState<{ rowIndex: number; colIndex: number; text: string } | null>(null); + // objectstack#35795 — an edit or a write asked while the host still reads + // what decides it (`GridCellFacts.checking`), asked again when that read + // settles. One at a time: a newer ask, another selected cell or an open + // editor drops it. + type WaitingAct = { rowKey: PendingRowKey; columnKey: string; run: (rowIndex: number, colIndex: number) => void }; + const waitingEditRef = useRef(null); + const retryWaitingEditRef = useRef<(waiting: WaitingAct) => void>(() => {}); + /** Say on the cell that it is being checked, and ask `run` again once `settled` settles. */ + const waitForChecking = ( + rowIndex: number, + colIndex: number, + row: any, + col: TableColumn, + checking: { text: string; settled: Promise }, + run: WaitingAct['run'], + ) => { + setCellNotice({ rowIndex, colIndex, text: checking.text }); + const waiting: WaitingAct = { rowKey: pendingRowKeyOf(row), columnKey: col.accessorKey, run }; + waitingEditRef.current = waiting; + const retry = () => { + if (waitingEditRef.current !== waiting) return; + waitingEditRef.current = null; + retryWaitingEditRef.current(waiting); + }; + checking.settled.then(retry, retry); + }; + const selectCell = (rowIndex: number, colIndex: number) => { const row = paginatedData[rowIndex]; const col = columns[colIndex]; if (row === undefined || col === undefined) return; setCellNotice(null); + const waiting = waitingEditRef.current; + if (waiting && (waiting.rowKey !== pendingRowKeyOf(row) || waiting.columnKey !== col.accessorKey)) { + waitingEditRef.current = null; + } // objectstack#35685 — a selected cell whose edit a refusal kept says why. const rowKey = pendingRowKeyOf(row); setFailureNotice(cellErrors.get(rowKey)?.[col.accessorKey] !== undefined ? { rowKey, columnKey: col.accessorKey } : null); @@ -3806,6 +3837,13 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { setCellNotice({ rowIndex, colIndex, text: reason }); return; } + // Asked again when what decides it has been read; it says so meanwhile. + const checking = factsOf(row, col)?.checking; + if (checking) { + waitForChecking(rowIndex, colIndex, row, col, checking, (r, c) => attemptEdit(r, c, seed)); + return; + } + waitingEditRef.current = null; // A rating is set in place (digits, a click on a star); it opens no editor. if (starsOf(row, col) !== null) return; setCellNotice(null); @@ -3820,6 +3858,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { setSelectedCell({ rowIndex, colIndex }); startEdit(row, col.accessorKey, seed); }; + // Read at settle time, so the retry sees the rows, the selection and the + // editor as they are then, not as they were when the edit was asked. + retryWaitingEditRef.current = (waiting) => { + if (editingCellRef.current) return; + if (!selectedCell || selectedCell.rowKey !== waiting.rowKey || selectedCell.columnKey !== waiting.columnKey) return; + const rowIndex = paginatedData.findIndex((r) => pendingRowKeyOf(r) === waiting.rowKey); + const colIndex = columns.findIndex((c) => c.accessorKey === waiting.columnKey); + if (rowIndex < 0 || colIndex < 0) return; + waiting.run(rowIndex, colIndex); + }; /** Write a value into a cell without an editor: the commit `saveEdit` makes. */ const commitCellValue = (row: any, columnKey: string, value: unknown, confirmed = false) => { @@ -3849,7 +3897,16 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { return; } const value = valueOf(row, col); - if (value !== undefined) commitCellValue(row, col.accessorKey, value); + if (value === undefined) return; + // Written once what decides the write has been read, the value worked out + // again then; it says so meanwhile. + const checking = factsOf(row, col)?.checking; + if (checking) { + waitForChecking(rowIndex, colIndex, row, col, checking, (r, c) => writeCell(r, c, valueOf)); + return; + } + waitingEditRef.current = null; + commitCellValue(row, col.accessorKey, value); }; const togglesCell = (row: any, col: TableColumn) => factsOf(row, col)?.toggles ?? col.type === 'boolean'; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 120b21bae5d..8146e576134 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -583,6 +583,7 @@ const ar = { objectReadOnly: "لا يمكن تحرير هذه السجلات هنا.", noPermission: "ليس لديك إذن بتحرير هذه السجلات.", approvalLocked: "هذا السجل مقفل أثناء الموافقة عليه.", + checking: "جارٍ التحقق مما إذا كان يمكن تعديل هذا السجل…", noRecordPermission: "ليس لديك إذن بتحرير هذا السجل.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 887d18748cc..9066440a839 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -549,6 +549,7 @@ const de = { objectReadOnly: "Diese Datensätze können hier nicht bearbeitet werden.", noPermission: "Sie haben keine Berechtigung, diese Datensätze zu bearbeiten.", approvalLocked: "Dieser Datensatz ist während der Genehmigung gesperrt.", + checking: "Es wird geprüft, ob dieser Datensatz bearbeitet werden kann…", noRecordPermission: "Sie haben keine Berechtigung, diesen Datensatz zu bearbeiten.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3cfe8d26b90..62b1cc2286b 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -817,6 +817,7 @@ const en = { objectReadOnly: 'These records can\'t be edited here.', noPermission: 'You don\'t have permission to edit these records.', approvalLocked: 'This record is locked while it\'s in approval.', + checking: 'Checking whether this record can be edited…', noRecordPermission: 'You don\'t have permission to edit this record.', }, // objectstack#35685 — the confirm before a list cell moves a state-machine field. diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index fb637668030..8e461c4ca1a 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -561,6 +561,7 @@ const es = { objectReadOnly: "Estos registros no se pueden editar aquí.", noPermission: "No tiene permiso para editar estos registros.", approvalLocked: "Este registro está bloqueado mientras está en aprobación.", + checking: "Comprobando si este registro se puede editar…", noRecordPermission: "No tiene permiso para editar este registro.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index dc29c1abdc3..a4b8b0eff87 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -556,6 +556,7 @@ const fr = { objectReadOnly: "Ces enregistrements ne peuvent pas être modifiés ici.", noPermission: "Vous n'avez pas l'autorisation de modifier ces enregistrements.", approvalLocked: "Cet enregistrement est verrouillé pendant son approbation.", + checking: "Vérification de la possibilité de modifier cet enregistrement…", noRecordPermission: "Vous n'avez pas l'autorisation de modifier cet enregistrement.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index e2958736230..cd1eafac9ba 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -549,6 +549,7 @@ const ja = { objectReadOnly: "これらのレコードはここでは編集できません。", noPermission: "これらのレコードを編集する権限がありません。", approvalLocked: "このレコードは承認中のためロックされています。", + checking: "このレコードを編集できるか確認しています…", noRecordPermission: "このレコードを編集する権限がありません。", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index e59c88644e2..098ba7db8e3 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -549,6 +549,7 @@ const ko = { objectReadOnly: "이 레코드는 여기에서 편집할 수 없습니다.", noPermission: "이 레코드를 편집할 권한이 없습니다.", approvalLocked: "이 레코드는 승인 중이라 잠겨 있습니다.", + checking: "이 레코드를 편집할 수 있는지 확인하는 중…", noRecordPermission: "이 레코드를 편집할 권한이 없습니다.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index ec8cec204fd..e23da6e986b 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -556,6 +556,7 @@ const pt = { objectReadOnly: "Estes registros não podem ser editados aqui.", noPermission: "Você não tem permissão para editar estes registros.", approvalLocked: "Este registro está bloqueado enquanto está em aprovação.", + checking: "Verificando se este registro pode ser editado…", noRecordPermission: "Você não tem permissão para editar este registro.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ca8a827371c..64fcfb6b4d6 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -566,6 +566,7 @@ const ru = { objectReadOnly: "Эти записи нельзя изменить здесь.", noPermission: "У вас нет прав на изменение этих записей.", approvalLocked: "Эта запись заблокирована, пока находится на согласовании.", + checking: "Проверяем, можно ли изменить эту запись…", noRecordPermission: "У вас нет прав на изменение этой записи.", }, stateChange: { diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 561f324b67c..b98fc6e3908 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -562,6 +562,7 @@ const zh = { objectReadOnly: '这些记录不能在这里编辑。', noPermission: '您没有编辑这些记录的权限。', approvalLocked: '此记录正在审批中,已锁定。', + checking: '正在确认这条记录能否编辑…', noRecordPermission: '您没有编辑此记录的权限。', }, stateChange: { diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 87ef15640b0..657bc8a5a0c 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -562,6 +562,7 @@ const zhHant = { objectReadOnly: '這些記錄不能在這裡編輯。', noPermission: '您沒有編輯這些記錄的權限。', approvalLocked: '此記錄正在審批中,已鎖定。', + checking: '正在確認這條記錄能否編輯…', noRecordPermission: '您沒有編輯此記錄的權限。', }, stateChange: { diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 5be74cc0aab..6a8d9d72548 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -1376,6 +1376,10 @@ export const ObjectGrid: React.FC = ({ describeCell: (row, columnKey) => { const fieldDef = objectFields?.[columnKey]; const recordId = rowRecordId(row); + // objectstack#35795 — read at call time, not from this render: an + // edit that waited for the verdict is re-asked before the render + // that publishes it. + const recordUpdate = recordVerdict.current(recordId, 'update'); const kind = cellReadOnlyKind({ fieldDef, fieldWritable: !objectName || resolveFieldAffordance('listInlineEdit', perms, objectName, columnKey), @@ -1383,12 +1387,20 @@ export const ObjectGrid: React.FC = ({ objectEditable: objectInlineEditable, canUpdate: resolveAffordanceGrant('listInlineEdit', affordanceSource), approvalLocked: approvalLocks.isLocked(recordId, row), - recordUpdate: recordVerdict(recordId, 'update'), + recordUpdate, }); + // objectstack#35795 — while the row's lock or `update` verdict is on + // its way, an edit waits for it rather than opening an editor the + // answer may refuse. + const reads = kind ? [] : [ + approvalLocks.settling(recordId), + recordUpdate === undefined ? recordVerdict.settling() : null, + ].filter((read): read is Promise => read !== null); const fromText = choiceFromText(fieldDef); const type = fieldDef?.type; return { readOnlyReason: kind ? readOnlyReasonText(kind, t) : null, + ...(reads.length > 0 ? { checking: { text: t('grid.readOnlyReason.checking'), settled: Promise.all(reads) } } : {}), typing: inlineTyping(type), ...(type === 'boolean' || type === 'toggle' ? { toggles: true } : {}), // objectstack#36023 — a rating is set in place: digits, or a click on a star. @@ -1403,7 +1415,8 @@ export const ObjectGrid: React.FC = ({ }, onCellSelect: (row) => { recordVerdict.requestVerdicts(); - approvalLocks.probe(rowRecordId(row)); + // objectstack#35795 — one lock read for the page, not one per row selected. + approvalLocks.probe([rowRecordId(row), ...pageRecordIds]); }, // objectstack#35685 — a move of a state-machine field is confirmed // before anything is written (`./objectGridStateConfirm`). A move that diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx index 723abb30640..ceff6fbdaa8 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.autosave-35685.test.tsx @@ -181,6 +181,89 @@ describe('ObjectGrid autosave — one update, this row only (objectstack#35685)' }); }); +describe("ObjectGrid autosave — a write asked while the row's lock is read waits for it (objectstack#35795)", () => { + /** + * The approvals service answers the page's locks after `delay` ms; explain + * answers after `explain.delay` ms (at once by default), refusing `update` + * on the rows in `explain.refused`. + */ + function stubSlowLocks( + locked: ReadonlySet, + delay: number, + explain: { delay?: number; refused?: ReadonlySet } = {}, + ) { + vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { + const body = init?.body ? JSON.parse(String(init.body)) : {}; + const ids: string[] = Array.isArray(body.recordIds) ? body.recordIds : []; + if (String(url).endsWith(`/api/v1/approvals/records/${OBJECT}/locks`)) { + const answer = { + ok: true, status: 200, + json: async () => ({ success: true, data: { records: ids.map((id) => ({ recordId: id, locked: locked.has(id) })) } }), + }; + return new Promise((resolve) => setTimeout(() => resolve(answer), delay)); + } + const verdicts = { + ok: true, status: 200, + json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: !explain.refused?.has(id) })) }), + }; + return explain.delay ? new Promise((resolve) => setTimeout(() => resolve(verdicts), explain.delay)) : verdicts; + })); + } + function paste(container: HTMLElement, cell: HTMLElement, text: string) { + fireEvent.click(cell); + const catcher = container.querySelector('[data-slot="cell-type-catcher"]')!; + fireEvent.paste(catcher, { clipboardData: { getData: () => text } }); + } + afterEach(() => { + vi.useRealTimers(); + }); + + it('a paste is not written while the lock is read, and is written once it answers unlocked', async () => { + stubSlowLocks(new Set(), 2000); + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + vi.useFakeTimers(); + paste(container, dataCell(container, 0, 'alpha'), 'zeta'); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent('Checking whether this record can be edited…'); + await act(async () => { await vi.advanceTimersByTimeAsync(1999); }); + expect(ds.update).not.toHaveBeenCalled(); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + vi.useRealTimers(); + await waitFor(() => expect(ds.update).toHaveBeenCalledTimes(1)); + expect(ds.update.mock.calls[0][2]).toEqual({ name: 'zeta' }); + }); + + it('a paste on a row the answer says is locked is never written, and the cell says why', async () => { + stubSlowLocks(new Set(['d1']), 2000); + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + vi.useFakeTimers(); + paste(container, dataCell(container, 0, 'alpha'), 'zeta'); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent("This record is locked while it's in approval."); + vi.useRealTimers(); + await act(async () => { await new Promise((r) => setTimeout(r, 20)); }); + expect(ds.update).not.toHaveBeenCalled(); + }); + + it('a paste on a row whose slow record verdict refuses it is never written, and the cell says why', async () => { + stubSlowLocks(new Set(), 0, { delay: 2000, refused: new Set(['d1']) }); + const ds = makeDataSource(); + const { container } = renderGrid(ds, true); + await screen.findByText('beta'); + vi.useFakeTimers(); + paste(container, dataCell(container, 0, 'alpha'), 'zeta'); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent('Checking whether this record can be edited…'); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent("You don't have permission to edit this record."); + vi.useRealTimers(); + await act(async () => { await new Promise((r) => setTimeout(r, 20)); }); + expect(ds.update).not.toHaveBeenCalled(); + }); +}); + describe('ObjectGrid autosave — a 409 kept as mine re-reads nothing either (objectstack#35685)', () => { /** The first write meets a newer version; the "Overwrite anyway" write lands and is announced. */ function conflictOnce(ds: any) { diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx index 953568ee83c..25e93292b31 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx @@ -16,9 +16,11 @@ * 1. With the prop a click selects; without it the same click edits. * 2. The field's reason (read-only, calculated), the reader's grant, the * view's opt-out, and the record's approval lock, each in its words. - * 3. The lock is read from the approvals service's per-record answer when a - * cell of the row is selected; with no answer the row's - * `approval_status` stands in (`resolveApprovalLock`). + * 3. The lock is read from the approvals service's answer for the page when + * a cell is first selected, in one request (objectstack#35795); with no + * answer the row's `approval_status` stands in (`resolveApprovalLock`). + * While the lock or the record verdict is on its way, an edit waits for it + * and says the record is being checked. * 4. A single click on a cell's email link or referenced record's chip only * selects it, the title link still opens the record, and the email cell * draws its copy button as the one the table hides (objectstack#36015). @@ -31,7 +33,7 @@ */ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react'; +import { render, screen, cleanup, fireEvent, waitFor, act } from '@testing-library/react'; import '@testing-library/jest-dom'; // The viewer's update grant, switchable per test. Stable stub identity: @@ -73,7 +75,18 @@ const FIELDS = { let lockedIds = new Set(); let lockStatus = 200; -let lockReads: string[] = []; +/** The ids of each lock read, one entry per request. */ +let lockReads: string[][] = []; +/** How long the lock read and the explain read take, in ms; 0 answers at once. */ +let lockDelay = 0; +let explainDelay = 0; +let explainReads = 0; +/** The rows the explain engine refuses `update` on. */ +let refusedIds = new Set(); + +const LOCKS_URL = '/api/v1/approvals/records/probe/locks'; +const after = (ms: number, value: T): Promise => + ms > 0 ? new Promise((resolve) => setTimeout(() => resolve(value), ms)) : Promise.resolve(value); beforeEach(() => { __clearRecordCrudVerdictCache(); @@ -81,17 +94,25 @@ beforeEach(() => { lockedIds = new Set(); lockStatus = 200; lockReads = []; - // The explain engine permits every row; the approvals service answers the lock. + lockDelay = 0; + explainDelay = 0; + explainReads = 0; + refusedIds = new Set(); + // The explain engine permits every row; the approvals service answers the locks of a page. vi.stubGlobal('fetch', vi.fn(async (url: unknown, init?: { body?: unknown }) => { const href = String(url); - const lock = /\/api\/v1\/approvals\/records\/probe\/([^/]+)\/lock$/.exec(href); - if (lock) { - lockReads.push(decodeURIComponent(lock[1])); - return { ok: lockStatus < 300, status: lockStatus, json: async () => ({ success: true, data: { locked: lockedIds.has(lock[1]) } }) }; - } const body = init?.body ? JSON.parse(String(init.body)) : {}; const ids: string[] = Array.isArray(body.recordIds) ? body.recordIds : []; - return { ok: true, status: 200, json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: true })) }) }; + if (href.endsWith(LOCKS_URL)) { + lockReads.push(ids); + return after(lockDelay, { + ok: lockStatus < 300, + status: lockStatus, + json: async () => ({ success: true, data: { records: ids.map((id) => ({ recordId: id, locked: lockedIds.has(id) })) } }), + }); + } + explainReads += 1; + return after(explainDelay, { ok: true, status: 200, json: async () => ({ allowed: true, records: ids.map((id) => ({ recordId: id, visible: !refusedIds.has(id) })) }) }); })); }); afterEach(() => { @@ -180,23 +201,152 @@ describe('ObjectGrid cellSelection — why a cell opens no editor', () => { await waitFor(() => expect(g.container.querySelector('td[data-editing-cell]')).not.toBeNull()); }); - it("a record the approvals service says is locked, asked when its cell is selected", async () => { + it("a record the approvals service says is locked, asked for the page when a cell is first selected", async () => { lockedIds = new Set(['3']); const g = await renderGrid(); expect(lockReads).toEqual([]); fireEvent.click(g.cell(2, 0)); - await waitFor(() => expect(lockReads).toEqual(['3'])); + await waitFor(() => expect(lockReads).toEqual([['3', '1', '2']])); // Let the answer land before the edit is asked for. await new Promise((r) => setTimeout(r, 0)); fireEvent.doubleClick(g.cell(2, 0)); expect((await screen.findByTestId('cell-readonly-reason')).textContent).toBe("This record is locked while it's in approval."); expect(g.container.querySelector('td[data-editing-cell]')).toBeNull(); - // An answer that says unlocked wins over the column: the pending row edits. + // An answer that says unlocked wins over the column: the pending row edits, + // and selecting it asks nothing again. fireEvent.click(g.cell(1, 0)); - await waitFor(() => expect(lockReads).toEqual(['3', '2'])); - await new Promise((r) => setTimeout(r, 0)); fireEvent.doubleClick(g.cell(1, 0)); await waitFor(() => expect(g.container.querySelector('td[data-editing-cell]')).not.toBeNull()); + expect(lockReads).toEqual([['3', '1', '2']]); + }); +}); + +describe('ObjectGrid cellSelection — an edit waits for the row\'s lock and verdict (objectstack#35795)', () => { + const CHECKING = 'Checking whether this record can be edited…'; + const LOCKED = "This record is locked while it's in approval."; + const NO_PERMISSION = "You don't have permission to edit this record."; + const editor = (g: { container: HTMLElement }) => g.container.querySelector('td[data-editing-cell]'); + const catcher = (g: { container: HTMLElement }) => g.container.querySelector('[data-slot="cell-type-catcher"]')!; + + // Real timers until the grid has drawn, then fake ones: the reads are slow + // and the test says how much time passes. + async function renderSlow() { + const g = await renderGrid(); + vi.useFakeTimers(); + return g; + } + afterEach(() => { + vi.useRealTimers(); + }); + + it('a slow lock read opens no editor on a locked row: the cell says it is checking, then that it is locked', async () => { + lockDelay = 2000; + lockedIds = new Set(['3']); + const g = await renderSlow(); + fireEvent.click(g.cell(2, 0)); + fireEvent.doubleClick(g.cell(2, 0)); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + expect(editor(g)).toBeNull(); + await act(async () => { await vi.advanceTimersByTimeAsync(1999); }); + expect(editor(g)).toBeNull(); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(LOCKED); + expect(editor(g)).toBeNull(); + }); + + it('a slow lock read on an unlocked row opens the editor once it answers, with no second double-click', async () => { + lockDelay = 2000; + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.doubleClick(g.cell(0, 0)); + expect(editor(g)).toBeNull(); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(editor(g)).not.toBeNull(); + expect(screen.queryByTestId('cell-readonly-reason')).toBeNull(); + }); + + it('a key typed while checking is the value the editor opens with', async () => { + lockDelay = 2000; + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.change(catcher(g), { target: { value: 'Z' } }); + expect(editor(g)).toBeNull(); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(g.cell(0, 0).querySelector('[data-slot="cell-editor-overlay"] input')).toHaveValue('Z'); + }); + + it('a slow record verdict holds the editor the same way', async () => { + explainDelay = 2000; + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.doubleClick(g.cell(0, 0)); + expect(editor(g)).toBeNull(); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(editor(g)).not.toBeNull(); + }); + + // The answer that settles the wait is the one the re-asked edit reads, not + // the verdict of the render the wait began in. + it('a slow record verdict that refuses the row opens no editor: the cell says the reader may not edit it', async () => { + explainDelay = 2000; + refusedIds = new Set(['1']); + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.doubleClick(g.cell(0, 0)); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(editor(g)).toBeNull(); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(NO_PERMISSION); + }); + + it('a key typed while a refusing verdict is read opens nothing and writes nothing', async () => { + explainDelay = 2000; + refusedIds = new Set(['1']); + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.change(catcher(g), { target: { value: 'Z' } }); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(CHECKING); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(editor(g)).toBeNull(); + expect(screen.getByTestId('cell-readonly-reason')).toHaveTextContent(NO_PERMISSION); + expect(g.cell(0, 0)).toHaveTextContent('Alpha'); + }); + + it('selecting another cell while checking drops the wait: the answer opens nothing', async () => { + lockDelay = 2000; + const g = await renderSlow(); + fireEvent.click(g.cell(0, 0)); + fireEvent.doubleClick(g.cell(0, 0)); + fireEvent.click(g.cell(2, 0)); + await act(async () => { await vi.advanceTimersByTimeAsync(2000); }); + expect(editor(g)).toBeNull(); + }); + + it('a page of rows sends one lock read, and moving the selection with the arrow keys sends none', async () => { + const g = await renderGrid(); + fireEvent.click(g.cell(0, 0)); + await waitFor(() => expect(lockReads).toEqual([['1', '2', '3']])); + await waitFor(() => expect(explainReads).toBeGreaterThan(0)); + const explainedOnce = explainReads; + fireEvent.keyDown(catcher(g), { key: 'ArrowDown' }); + fireEvent.keyDown(catcher(g), { key: 'ArrowDown' }); + fireEvent.keyDown(catcher(g), { key: 'ArrowUp' }); + await new Promise((r) => setTimeout(r, 0)); + expect(g.cell(1, 0)).toHaveAttribute('data-selected-cell'); + expect(lockReads).toEqual([['1', '2', '3']]); + expect(explainReads).toBe(explainedOnce); + }); + + it('a deployment with no approvals service is asked once, and its rows edit', async () => { + lockStatus = 501; + const g = await renderGrid(); + fireEvent.click(g.cell(0, 0)); + fireEvent.doubleClick(g.cell(0, 0)); + await waitFor(() => expect(editor(g)).not.toBeNull()); + expect(lockReads).toHaveLength(1); }); }); diff --git a/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts b/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts index f493414f8d9..c4a90335f0a 100644 --- a/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts +++ b/ui/packages/plugin-grid/src/hooks/useRecordCrudVerdicts.ts @@ -468,16 +468,34 @@ export interface RecordCrudVerdicts extends RecordCrudVerdictLookup { * clicked into a refused write. */ readonly pending: boolean; + /** + * The questions on the wire, as one promise that settles when they have all + * answered (or failed), or `null` when none is. Read when asked, so it sees a + * question sent since the last render (objectstack#35795: an inline cell + * asked to edit waits for its row's verdict instead of opening an editor the + * verdict may refuse). + */ + readonly settling: () => Promise | null; + /** + * The same lookup as the function itself, but answered from the verdicts + * published LAST — not the ones of the render that made this object. A + * caller that holds on to this object across an answer (a wait that is + * re-asked once {@link settling} settles, before React has re-rendered) + * reads the answer that just landed here (objectstack#35795). + */ + readonly current: RecordCrudVerdictLookup; } function lookupOf( verdicts: ReadonlyMap, requestVerdicts: () => void, pending: boolean, + settling: () => Promise | null, + current: RecordCrudVerdictLookup, ): RecordCrudVerdicts { const lookup: RecordCrudVerdictLookup = (recordId, operation) => recordId == null ? undefined : verdicts.get(`${operation}:${String(recordId)}`); - return Object.assign(lookup, { requestVerdicts, pending }); + return Object.assign(lookup, { requestVerdicts, pending, settling, current }); } export function useRecordCrudVerdicts(opts: { @@ -526,6 +544,17 @@ export function useRecordCrudVerdicts(opts: { const [verdicts, setVerdicts] = React.useState>(() => new Map()); const [pending, setPending] = React.useState(false); + const wireRef = React.useRef | null>(null); + const settling = React.useCallback(() => wireRef.current, []); + // What was published last, written in the same stroke as `setVerdicts`: a + // wait re-asked as soon as the wire settles runs before the re-render that + // publishes the answer, so it reads the answer here (objectstack#35795). + const publishedRef = React.useRef>(new Map()); + const current = React.useCallback( + (recordId, operation) => + recordId == null ? undefined : publishedRef.current.get(`${operation}:${String(recordId)}`), + [], + ); // [objectstack#34208] The object whose rows' actions have been reached for on // this list, or `null` until then. Until then nothing is asked: the @@ -548,8 +577,10 @@ export function useRecordCrudVerdicts(opts: { if (wantUpdate) operations.push('update'); if (wantDelete) operations.push('delete'); if (!objectName || ids.length === 0 || operations.length === 0) { - setVerdicts(new Map()); + publishedRef.current = new Map(); + setVerdicts(publishedRef.current); setPending(false); + wireRef.current = null; return; } // What is ASKED: every wanted operation once the row actions were reached @@ -569,6 +600,7 @@ export function useRecordCrudVerdicts(opts: { if (typeof verdict === 'boolean') next.set(`${operation}:${id}`, verdict); } } + publishedRef.current = next; setVerdicts(next); }; @@ -591,12 +623,15 @@ export function useRecordCrudVerdicts(opts: { } } setPending(settled.length > 0); + wireRef.current = null; if (settled.length > 0) { - void Promise.all(settled).then(() => { + const wire = Promise.all(settled).then(() => { + if (wireRef.current === wire) wireRef.current = null; if (cancelled) return; publish(); setPending(false); }); + wireRef.current = wire; } // Rows already in the cache answer on this render rather than after the @@ -610,7 +645,7 @@ export function useRecordCrudVerdicts(opts: { }, [objectName, ids, wantUpdate, wantDelete, updateOnMount, demanded, apiFetch, principal, invalidationNonce]); return React.useMemo( - () => lookupOf(verdicts, requestVerdicts, pending), - [verdicts, requestVerdicts, pending], + () => lookupOf(verdicts, requestVerdicts, pending, settling, current), + [verdicts, requestVerdicts, pending, settling, current], ); } diff --git a/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts index b403024b971..2cfa8657cdc 100644 --- a/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts +++ b/ui/packages/plugin-grid/src/hooks/useRowApprovalLocks.ts @@ -11,20 +11,27 @@ * * The record-grained `update` verdict a list reads (`useRecordCrudVerdicts`, * the explain engine) does not see approvals: the lock is the approvals - * plugin's own `beforeUpdate` hook. So a cell asks the approvals service's - * per-record answer (`GET /api/v1/approvals/records/:object/:recordId/lock`) - * when the reader selects a cell of the row: one read for a row the reader - * touches, never one for every row on screen. The answer is read through - * `resolveApprovalLock`, the record page's one rule, so a list and a record - * page cannot disagree about a lock; while no read has answered, the row's - * `approval_status` column stands in, as it does there. + * plugin's own `beforeUpdate` hook. So the list asks the approvals service's + * answer for the rows on screen, in ONE request per page + * (`POST /api/v1/approvals/records/:object/locks`, at most + * `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS` ids each), when the reader first + * selects a cell: never on first paint, and never one request per row the + * selection passes (objectstack#35795). Rows already asked are joined, not + * asked again; rows a later page or re-read brings are asked on the next + * select. Each answer is read through `resolveApprovalLock`, the record + * page's one rule, so a list and a record page cannot disagree about a lock; + * while no read has answered, the row's `approval_status` column stands in, + * as it does there. * - * Fail open: a read in flight, refused or failing leaves the column fallback, - * and the server refuses a locked write whatever this says. A 501 (no - * approvals service in this deployment) is latched and the read is not sent - * again, like the record page's. + * While a row's read is on the wire it is `settling`: an edit asked on the + * cell waits for the answer and says the record is being checked, instead of + * opening an editor the lock will refuse. A read refused or failing, and a row the caller cannot read, fall + * back to the column (fail open: the server refuses a locked write whatever + * this says). A 501 (no approvals service in this deployment) is latched and + * the read is not sent again, like the record page's. */ import * as React from 'react'; +import { APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS } from '@objectstack/spec/contracts'; import { SchemaRendererContext, resolveApprovalLock, useDataInvalidation } from '@object-ui/react'; /** Set once a lock read answered 501: the deployment runs no approvals service. */ @@ -35,48 +42,92 @@ export function __resetApprovalsServiceLatch(): void { approvalsServiceAbsent = false; } +/** + * `'unanswered'` is a read that failed or answered nothing usable. It is not + * asked again until the object's data is invalidated; until then the row falls + * back to its `approval_status` column (fail open: the server still refuses a + * write to a locked record). + */ type LockAnswer = { locked: boolean } | 'asking' | 'unanswered'; export interface RowApprovalLocks { - /** Ask the lock of a row's record, unless it has been asked (the cell-select prefetch). */ - probe: (recordId: unknown) => void; + /** + * Ask the locks of the page's records (the cell-select prefetch): the ids not + * asked yet go out in one request per `APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS`. + */ + probe: (recordIds: readonly unknown[]) => void; /** Whether the row is locked by an approval, from what has answered so far. */ isLocked: (recordId: unknown, row: any) => boolean; + /** The row's lock read while it is on the wire (it settles when it answers or fails), else `null`. */ + settling: (recordId: unknown) => Promise | null; +} + +/** The `{ success, data }` envelope's payload, or the body itself. */ +function payloadOf(body: any): any { + return body && typeof body.success === 'boolean' && 'data' in body ? body.data : body; } export function useRowApprovalLocks(objectName: string | undefined): RowApprovalLocks { const apiFetch = React.useContext(SchemaRendererContext)?.apiFetch; - // A change to the object (a submit, a recall, a decision) drops every answer. + // A change to the object (a submit, a recall, a decision) drops every answer, + // and an answer still on the wire lands in the map it was asked for. const invalidation = useDataInvalidation(objectName); const answersRef = React.useRef(new Map()); + /** The read each row asked is waiting on, while it is on the wire. */ + const wiresRef = React.useRef(new Map>()); React.useEffect(() => { answersRef.current = new Map(); + wiresRef.current = new Map(); }, [objectName, invalidation]); - const probe = React.useCallback((recordId: unknown) => { - if (!objectName || recordId == null || recordId === '' || approvalsServiceAbsent) return; - const id = String(recordId); + const probe = React.useCallback((recordIds: readonly unknown[]) => { + if (!objectName || approvalsServiceAbsent) return; const answers = answersRef.current; - if (answers.has(id)) return; - answers.set(id, 'asking'); + const wires = wiresRef.current; + const toAsk = Array.from(new Set( + recordIds.filter((id) => id != null && id !== '').map((id) => String(id)), + )).filter((id) => !answers.has(id)); + if (toAsk.length === 0) return; const doFetch = apiFetch ?? fetch; - const path = `/api/v1/approvals/records/${encodeURIComponent(objectName)}/${encodeURIComponent(id)}/lock`; - void (async () => { - try { - const res = await doFetch(path, { credentials: 'include' }); - if (res.status === 501) approvalsServiceAbsent = true; - if (!res.ok) { - answers.set(id, 'unanswered'); - return; + const path = `/api/v1/approvals/records/${encodeURIComponent(objectName)}/locks`; + for (let i = 0; i < toAsk.length; i += APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS) { + const chunk = toAsk.slice(i, i + APPROVAL_RECORD_LOCKS_MAX_RECORD_IDS); + for (const id of chunk) answers.set(id, 'asking'); + const wire = (async () => { + const answered = new Map(); + try { + const res = await doFetch(path, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ recordIds: chunk }), + }); + if (res.status === 501) approvalsServiceAbsent = true; + if (res.ok) { + const records = payloadOf(await res.json())?.records; + if (Array.isArray(records)) { + // `records[i]` answers `chunk[i]`; an entry that names another id + // answers nothing, and a row the caller cannot read (`null`) keeps + // the column fallback. + chunk.forEach((id, index) => { + const entry = records[index]; + if (entry && entry.recordId === id && typeof entry.locked === 'boolean') { + answered.set(id, { locked: entry.locked }); + } + }); + } + } + } catch { + /* network / parse failure: fail open */ + } finally { + for (const id of chunk) { + answers.set(id, answered.get(id) ?? 'unanswered'); + wires.delete(id); + } } - const body: any = await res.json(); - // `{ success: true, data: { locked } }`, the declared envelope. - const data = body && typeof body.success === 'boolean' && 'data' in body ? body.data : body; - answers.set(id, { locked: data?.locked === true }); - } catch { - answers.set(id, 'unanswered'); - } - })(); + })(); + for (const id of chunk) if (answers.get(id) === 'asking') wires.set(id, wire); + } }, [objectName, apiFetch]); const isLocked = React.useCallback((recordId: unknown, row: any) => { @@ -89,5 +140,10 @@ export function useRowApprovalLocks(objectName: string | undefined): RowApproval }).locked; }, []); - return React.useMemo(() => ({ probe, isLocked }), [probe, isLocked]); + const settling = React.useCallback( + (recordId: unknown) => (recordId == null ? null : wiresRef.current.get(String(recordId)) ?? null), + [], + ); + + return React.useMemo(() => ({ probe, isLocked, settling }), [probe, isLocked, settling]); } diff --git a/ui/packages/plugin-grid/src/objectGridTranslations.ts b/ui/packages/plugin-grid/src/objectGridTranslations.ts index 45be44a4d42..9d8bba05801 100644 --- a/ui/packages/plugin-grid/src/objectGridTranslations.ts +++ b/ui/packages/plugin-grid/src/objectGridTranslations.ts @@ -118,6 +118,7 @@ const GRID_DEFAULT_TRANSLATIONS: Record = { 'grid.readOnlyReason.objectReadOnly': 'These records can\'t be edited here.', 'grid.readOnlyReason.noPermission': 'You don\'t have permission to edit these records.', 'grid.readOnlyReason.approvalLocked': 'This record is locked while it\'s in approval.', + 'grid.readOnlyReason.checking': 'Checking whether this record can be edited…', 'grid.readOnlyReason.noRecordPermission': 'You don\'t have permission to edit this record.', // objectstack#35685 — the confirm before a list cell moves a state-machine // field (`objectGridStateConfirm`). Byte-identical to the `en` pack.