Skip to content

Commit d36a5bf

Browse files
committed
fix(app-shell): the record page reads the lock service's 501 silently and asks no more
Claude-Session: https://claude.ai/code/session_01J8VVAojjEQUUoMeSBSdgW4 Co-authored-by: Claude <noreply@anthropic.com>
1 parent f6ffd72 commit d36a5bf

2 files changed

Lines changed: 147 additions & 55 deletions

File tree

‎ui/packages/app-shell/src/hooks/useRecordApprovals.ts‎

Lines changed: 59 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,16 @@
3333
* override actor), so for anyone else an answered empty read cannot tell "no
3434
* approval is running" from "one is running that you may not see". When the
3535
* list finds no pending request, the hook also asks the server whether the
36-
* record is held by a locking approval (`client.approvals.getRecordLock`,
36+
* record is held by a locking approval (`GET /approvals/records/:object/:recordId/lock`,
3737
* answered to every caller who can read the record — objectstack#25934 ruling
38-
* A) and hands the answer back as `recordLock`.
38+
* A) and hands the answer back as `recordLock`. That door has no empty answer:
39+
* a composition without the approvals service answers it 501, the designed
40+
* "no lock service", which is read silently and never asked again
41+
* (objectstack#26632); any other failure still logs.
3942
*/
4043

4144
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
42-
import { useAdapter } from '../providers/AdapterProvider.js';
45+
import { createQuietHttpLogger } from '@object-ui/data-objectstack';
4346
import { bearerAuthHeaders } from '../utils/authToken.js';
4447
import type { DecisionOutputDef } from '../utils/decisionOutputParams.js';
4548

@@ -302,10 +305,10 @@ interface UseRecordApprovalsResult {
302305
* `{ locked: true }` means a pending approval whose node locks the record is
303306
* running, though this viewer cannot see its request. `null` when there is
304307
* no answer to give: a pending request was found (it decides, with its own
305-
* `lock_record`), no adapter is mounted, or the read has never answered — a
306-
* composition without the approvals service answers it 501, so there the
307-
* record is not locked by this signal. A later failed read keeps the last
308-
* answer, as the list read does.
308+
* `lock_record`), or the read has never answered — a composition without
309+
* the approvals service answers it 501, so there the record is not locked
310+
* by this signal, and the read is not sent again. A later failed read keeps
311+
* the last answer, as the list read does.
309312
*/
310313
recordLock: { locked: boolean } | null;
311314
refresh: () => Promise<void>;
@@ -317,6 +320,7 @@ export function __resetRecordApprovalsStore(): void {
317320
inFlight.clear();
318321
listeners.clear();
319322
latestSeq.clear();
323+
recordLockAbsent = false;
320324
}
321325

322326
function apiBase() {
@@ -500,16 +504,50 @@ function holdEntry(key: string): () => void {
500504
};
501505
}
502506

503-
/** Reads the server's record lock for the record a read is for. */
504-
type RecordLockReader = () => Promise<{ locked: boolean }>;
507+
/**
508+
* Set once the record-lock read answered 501: this deployment has no approvals
509+
* service, so no record is held by a locking approval and the read is not sent
510+
* again (objectstack#26632). Module-scoped, not per record: the answer is the
511+
* deployment's, and the read goes to the one base every read here goes to.
512+
*/
513+
let recordLockAbsent = false;
514+
515+
/** Logs a failed lock read exactly as the console's SDK client logs one. */
516+
const lockReadLogger = createQuietHttpLogger();
517+
518+
/**
519+
* The server's record lock (`IApprovalService.getRecordLock`, objectstack#25934).
520+
*
521+
* Read through `fetchJson`, not `client.approvals.getRecordLock`: the client
522+
* logs every non-2xx as an error before its caller sees the answer, and the
523+
* 501 of a composition without the approvals service is this read's designed
524+
* answer, not a failure (objectstack#26632). So the 501 is read silently and
525+
* latched, and every other failure is logged here, through the same logger
526+
* the client would have used.
527+
*/
528+
async function readRecordLock(objectName: string, recordId: string): Promise<{ locked: boolean }> {
529+
const path = `/approvals/records/${encodeURIComponent(objectName)}/${encodeURIComponent(recordId)}/lock`;
530+
try {
531+
const body = await fetchJson<any>(path);
532+
// `{ success: true, data: { locked } }`, the declared envelope.
533+
return body && typeof body.success === 'boolean' && 'data' in body ? body.data : body;
534+
} catch (err: any) {
535+
if (err?.status === 501) {
536+
recordLockAbsent = true;
537+
} else {
538+
lockReadLogger.error('HTTP request failed', undefined, {
539+
method: 'GET',
540+
url: `${apiBase()}${path}`,
541+
status: err?.status,
542+
error: { code: err?.code, message: err?.message },
543+
});
544+
}
545+
throw err;
546+
}
547+
}
505548

506549
/** Send the record's read and publish its answer to every consumer of the key. */
507-
function startRead(
508-
key: string,
509-
objectName: string,
510-
recordId: string,
511-
readLock: RecordLockReader | null,
512-
): Promise<void> {
550+
function startRead(key: string, objectName: string, recordId: string): Promise<void> {
513551
const seq = ++readSeq;
514552
latestSeq.set(key, seq);
515553
const entry = entries.get(key);
@@ -529,10 +567,10 @@ function startRead(
529567
// `lock_record`. Without one, ask the record itself (objectstack#25934):
530568
// the list hides a request from a non-participant, the lock does not.
531569
let recordLock: { locked: boolean } | null = null;
532-
if (!pending && readLock) {
570+
if (!pending && !recordLockAbsent) {
533571
recordLock = entries.get(key)?.snapshot.recordLock ?? null;
534572
try {
535-
const lock = await readLock();
573+
const lock = await readRecordLock(objectName, recordId);
536574
recordLock = { locked: lock?.locked === true };
537575
} catch {
538576
// A read that never answered (501 without the approvals service)
@@ -599,15 +637,6 @@ export function useRecordApprovals(
599637
// for the render, mirrored into a ref the mount effect and `refresh` read.
600638
const [unavailable, setUnavailable] = useState(false);
601639
const unavailableRef = useRef(false);
602-
// The record-lock read goes through the SDK (`client.approvals.getRecordLock`),
603-
// so it needs the adapter's client; with no adapter mounted it is skipped.
604-
const adapter = useAdapter();
605-
const lockReader = useCallback(
606-
(object: string, id: string): RecordLockReader | null =>
607-
adapter ? () => adapter.getClient().approvals.getRecordLock(object, id) : null,
608-
[adapter],
609-
);
610-
611640
const subscribe = useCallback((l: () => void) => subscribeKey(readKey, l), [readKey]);
612641
const getSnapshot = useCallback(
613642
() => (readKey === null ? INITIAL_SNAPSHOT : entries.get(readKey)?.snapshot ?? INITIAL_SNAPSHOT),
@@ -629,19 +658,19 @@ export function useRecordApprovals(
629658
// read only when neither exists. The entry may be new while a read is in
630659
// flight (StrictMode's replayed mount): that read publishes into it.
631660
if (entry && !entry.read && !inFlight.has(readKey) && !unavailableRef.current) {
632-
void startRead(readKey, objectName, recordId, lockReader(objectName, recordId));
661+
void startRead(readKey, objectName, recordId);
633662
} else if (entry && inFlight.has(readKey)) {
634663
entry.read = true;
635664
if (!entry.snapshot.loading) publish(readKey, { loading: true });
636665
}
637666
return release;
638-
}, [readKey, objectName, recordId, lockReader]);
667+
}, [readKey, objectName, recordId]);
639668

640669
const refresh = useCallback(async () => {
641670
if (!objectName || !recordId || !readKey) return;
642671
if (unavailableRef.current) return;
643-
await startRead(readKey, objectName, recordId, lockReader(objectName, recordId));
644-
}, [objectName, recordId, readKey, lockReader]);
672+
await startRead(readKey, objectName, recordId);
673+
}, [objectName, recordId, readKey]);
645674

646675
const requests = readKey === null ? EMPTY_ROWS : snapshot.rows;
647676
const loading = snapshot.loading;

‎ui/packages/app-shell/src/views/RecordDetailView.approvalLock-25934.test.tsx‎

Lines changed: 88 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,12 @@
1616
* `200 { data: [] }` while a `lockRecord: true` approval runs. The page took
1717
* that for "no approval is running" and offered inline edit, and the save
1818
* answered `409 RECORD_LOCKED`. The page now asks the record's own lock
19-
* (`client.approvals.getRecordLock`, answered to every reader) when the list
20-
* finds no pending request.
19+
* (`GET /approvals/records/:object/:recordId/lock`, answered to every reader)
20+
* when the list finds no pending request.
21+
*
22+
* A composition without the approvals service answers that read 501, its
23+
* designed "no lock service": the page reads it silently and does not ask
24+
* again, while any other failure still logs (objectstack#26632).
2125
*
2226
* Same probe as `RecordDetailView.approvalLock-12220`: it prints what the page
2327
* threads into its `<InlineEditProvider>`. The record carries no
@@ -126,6 +130,7 @@ const pendingRequest = (over: Record<string, unknown> = {}) => ({
126130
});
127131

128132
let listGets: string[];
133+
let lockGets: string[];
129134

130135
const jsonResponse = (status: number, body: unknown) =>
131136
new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
@@ -137,12 +142,31 @@ const jsonResponse = (status: number, body: unknown) =>
137142
*/
138143
type ListAnswer = { row: Record<string, unknown> | null } | { absent: number };
139144

140-
function stubApprovalsApi(answer: ListAnswer) {
145+
/**
146+
* What the record-lock route answers: `{ locked }` in the declared envelope,
147+
* or a refusal carrying the route's status (501 when the approvals service is
148+
* absent, the body `respond501` sends).
149+
*/
150+
type LockAnswer = { locked: boolean } | { refused: number };
151+
152+
const LOCK_PATH = `/approvals/records/${OBJECT_NAME}/${RECORD_ID}/lock`;
153+
154+
function stubApprovalsApi(answer: ListAnswer, lock: LockAnswer) {
141155
listGets = [];
156+
lockGets = [];
142157
vi.stubGlobal(
143158
'fetch',
144159
vi.fn(async (url: string) => {
145160
const u = String(url);
161+
if (u.endsWith(LOCK_PATH)) {
162+
lockGets.push(u);
163+
if ('refused' in lock) {
164+
return lock.refused === 501
165+
? jsonResponse(501, { code: 'NOT_IMPLEMENTED', message: 'Approvals service is not configured on this deployment' })
166+
: jsonResponse(lock.refused, { success: false, error: { code: 'INTERNAL_ERROR', message: 'boom' } });
167+
}
168+
return jsonResponse(200, { success: true, data: { locked: lock.locked } });
169+
}
146170
if (u.includes('/approvals/requests?object=')) {
147171
listGets.push(u);
148172
if ('absent' in answer) return jsonResponse(answer.absent, { code: 'NOT_FOUND' });
@@ -181,24 +205,20 @@ function makeDataSource() {
181205
}
182206

183207
/**
184-
* The record-lock read as the SDK answers it: `{ locked }`, or a refusal
185-
* carrying the route's status (501 when the approvals service is absent).
208+
* The SDK's own record-lock read. The page must not use it: the client logs
209+
* every non-2xx as an error before the page sees the answer (objectstack#26632).
186210
*/
187-
type LockAnswer = { locked: boolean } | { refused: number };
188211
let getRecordLock: ReturnType<typeof vi.fn>;
189212

190-
function makeAdapter(answer: LockAnswer) {
191-
getRecordLock = vi.fn(async () => {
192-
if ('refused' in answer) throw Object.assign(new Error(`HTTP ${answer.refused}`), { status: answer.refused });
193-
return { locked: answer.locked };
194-
});
213+
function makeAdapter() {
214+
getRecordLock = vi.fn(async () => ({ locked: false }));
195215
return { getClient: () => ({ approvals: { getRecordLock } }) } as any;
196216
}
197217

198-
function renderRecordPage(lock: LockAnswer) {
218+
function renderRecordPage() {
199219
return render(
200220
<MemoryRouter initialEntries={[`/app/crm/${OBJECT_NAME}/${RECORD_ID}`]}>
201-
<AdapterCtx.Provider value={makeAdapter(lock)}>
221+
<AdapterCtx.Provider value={makeAdapter()}>
202222
<MetadataCtx.Provider value={METADATA}>
203223
<RecordDetailView
204224
dataSource={makeDataSource()}
@@ -216,24 +236,32 @@ function renderRecordPage(lock: LockAnswer) {
216236

217237
const attr = (probe: HTMLElement, name: string) => probe.getAttribute(`data-${name}`);
218238

239+
let consoleError: ReturnType<typeof vi.spyOn>;
240+
219241
beforeEach(() => {
220242
cleanup();
221243
__resetRecordApprovalsStore();
222244
authFetchSpy.mockClear();
245+
consoleError = vi.spyOn(console, 'error');
223246
});
224247

225248
afterEach(() => {
226249
vi.unstubAllGlobals();
250+
consoleError.mockRestore();
227251
});
228252

253+
/** The `console.error` lines that name the record-lock read. */
254+
const lockErrorLines = () =>
255+
consoleError.mock.calls.filter((args) => args.some((a) => String(a).includes(LOCK_PATH)));
256+
229257
describe('record page lock for a reader outside the approval (objectstack#25934)', () => {
230258
it('a non-participant on a record held by a locking approval is offered no inline edit', async () => {
231-
stubApprovalsApi({ row: null });
232-
renderRecordPage({ locked: true });
259+
stubApprovalsApi({ row: null }, { locked: true });
260+
renderRecordPage();
233261
const probe = await screen.findByTestId('inline-probe');
234262

235263
await waitFor(() => expect(attr(probe, 'locked')).toBe('true'));
236-
expect(getRecordLock).toHaveBeenCalledWith(OBJECT_NAME, RECORD_ID);
264+
expect(lockGets).toHaveLength(1);
237265
expect(attr(probe, 'approval-read-answered')).toBe('true');
238266
expect(attr(probe, 'approval-pending')).toBe('true');
239267
expect(attr(probe, 'can-edit')).toBe('false');
@@ -242,37 +270,72 @@ describe('record page lock for a reader outside the approval (objectstack#25934)
242270
});
243271

244272
it('a record the server reports unlocked opens editable', async () => {
245-
stubApprovalsApi({ row: null });
246-
renderRecordPage({ locked: false });
273+
stubApprovalsApi({ row: null }, { locked: false });
274+
renderRecordPage();
247275
const probe = await screen.findByTestId('inline-probe');
248276

249-
await waitFor(() => expect(getRecordLock).toHaveBeenCalled());
277+
await waitFor(() => expect(lockGets).toHaveLength(1));
250278
await waitFor(() => expect(attr(probe, 'approval-read-answered')).toBe('true'));
251279
expect(attr(probe, 'locked')).toBe('false');
252280
expect(attr(probe, 'approval-pending')).toBe('false');
253281
await waitFor(() => expect(attr(probe, 'can-edit')).toBe('true'));
254282
});
255283

256284
it('without the approvals service (lock read 501) nothing changes: an answered empty read is not locked', async () => {
257-
stubApprovalsApi({ row: null });
258-
renderRecordPage({ refused: 501 });
285+
stubApprovalsApi({ row: null }, { refused: 501 });
286+
renderRecordPage();
259287
const probe = await screen.findByTestId('inline-probe');
260288

261-
await waitFor(() => expect(getRecordLock).toHaveBeenCalled());
289+
await waitFor(() => expect(lockGets).toHaveLength(1));
262290
await waitFor(() => expect(attr(probe, 'approval-read-answered')).toBe('true'));
263291
expect(attr(probe, 'locked')).toBe('false');
264292
expect(attr(probe, 'approval-pending')).toBe('false');
265293
await waitFor(() => expect(attr(probe, 'can-edit')).toBe('true'));
266294
});
267295

296+
it('the 501 of a composition without the approvals service logs nothing, and the lock is not read again (objectstack#26632)', async () => {
297+
stubApprovalsApi({ row: null }, { refused: 501 });
298+
renderRecordPage();
299+
const probe = await screen.findByTestId('inline-probe');
300+
await waitFor(() => expect(attr(probe, 'approval-read-answered')).toBe('true'));
301+
await waitFor(() => expect(lockGets).toHaveLength(1));
302+
expect(lockErrorLines()).toEqual([]);
303+
expect(getRecordLock).not.toHaveBeenCalled();
304+
305+
// Open the record again: the list is read again, the lock is not.
306+
cleanup();
307+
renderRecordPage();
308+
await waitFor(() => expect(listGets.length).toBeGreaterThanOrEqual(2));
309+
const again = await screen.findByTestId('inline-probe');
310+
await waitFor(() => expect(attr(again, 'approval-read-answered')).toBe('true'));
311+
expect(attr(again, 'locked')).toBe('false');
312+
expect(lockGets).toHaveLength(1);
313+
expect(lockErrorLines()).toEqual([]);
314+
});
315+
316+
it('any other lock-read failure still logs, and the next open asks again', async () => {
317+
stubApprovalsApi({ row: null }, { refused: 500 });
318+
renderRecordPage();
319+
const probe = await screen.findByTestId('inline-probe');
320+
await waitFor(() => expect(attr(probe, 'approval-read-answered')).toBe('true'));
321+
await waitFor(() => expect(lockErrorLines()).toHaveLength(1));
322+
expect(String(lockErrorLines()[0][0])).toContain(`GET `);
323+
expect(String(lockErrorLines()[0][0])).toContain('-> 500');
324+
expect(attr(probe, 'locked')).toBe('false');
325+
326+
cleanup();
327+
renderRecordPage();
328+
await waitFor(() => expect(lockGets).toHaveLength(2));
329+
});
330+
268331
it('a participant\'s pending request decides, and the record lock is not read', async () => {
269-
stubApprovalsApi({ row: pendingRequest({ lock_record: false }) });
270-
renderRecordPage({ locked: true });
332+
stubApprovalsApi({ row: pendingRequest({ lock_record: false }) }, { locked: true });
333+
renderRecordPage();
271334
const probe = await screen.findByTestId('inline-probe');
272335

273336
await waitFor(() => expect(attr(probe, 'approval-pending')).toBe('true'));
274337
expect(attr(probe, 'locked')).toBe('false');
275338
await waitFor(() => expect(attr(probe, 'can-edit')).toBe('true'));
276-
expect(getRecordLock).not.toHaveBeenCalled();
339+
expect(lockGets).toEqual([]);
277340
});
278341
});

0 commit comments

Comments
 (0)