diff --git a/.changeset/39065-claim-no-longer-waiting.md b/.changeset/39065-claim-no-longer-waiting.md new file mode 100644 index 00000000000..3c5236f2782 --- /dev/null +++ b/.changeset/39065-claim-no-longer-waiting.md @@ -0,0 +1,15 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +fix(console): a claim answered 404 or 403 says the record is no longer waiting to be claimed + +Clause-②: no +Metadata-protocol: none + +Two queue members who claim the same record at once still end with exactly one owner. What the loser is told depends on when the server checks its claim: a claim checked while the record was still unowned answers `409 CONCURRENT_UPDATE`, and a claim checked after the other member's claim committed answers what any request gets at that moment, `404 RECORD_NOT_FOUND` when the record left the caller's sight (a `private` object) or `403 PERMISSION_DENIED` when the caller can still read it. Through the HTTP data door the late answers are the common ones. Status codes, messages and the ownership gate are unchanged. + +`claimQueuedRecord` (`@object-ui/plugin-detail`) now reports a `404` or `403` as a new outcome, `{ outcome: 'unavailable', error }`, where it reported `refused` before. The Console's record page shows one sentence for it, "This record is no longer waiting to be claimed.", and re-reads the record, as it does for a `409`. The sentence does not say someone else claimed the record, because a `404` is also what a deleted record answers. `@object-ui/i18n` carries the sentence as `detail.claimUnavailable` in every shipped locale. + +If you call `claimQueuedRecord` yourself and branch on its outcome, handle `unavailable` beside `taken`: both mean the record is not yours to claim, so reload it or move on. Any other refusal is still `refused`. diff --git a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts index 4fbe2233bd5..2d412820ecd 100644 --- a/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts +++ b/packages/plugins/plugin-security/src/ownership-claim-race-sqlite.test.ts @@ -4,11 +4,24 @@ * [ADR-0142 D4] Two members of one queue claim the same parked row at the same * moment, over the REAL stack: `ObjectQL`, `SqlDriver` on better-sqlite3 * `:memory:` (a single-connection pool), `SecurityPlugin` and - * `SharingService`. Exactly one claim lands; the loser answers - * `409 CONCURRENT_UPDATE`, never "not found" and never "forbidden" because it - * lost a race; the stored owner is the winner. + * `SharingService`. Exactly one claim lands and the stored owner is the winner: + * that is the invariant, in every cell of this file. * - * The cells cross the two answers a lost race used to get with the two unit + * What the loser is told depends on when its authorization gate reads the row + * (ADR-0142 D4 as ruled on #39065, option B). A loser whose gate read the row + * unowned, before the winner committed, answers `409 CONCURRENT_UPDATE`. A + * loser whose gate runs after the winner's commit is answered as any request + * is at that moment: `404 RECORD_NOT_FOUND` under `private` (the row left its + * sight) and `403 PERMISSION_DENIED` under `public_read` (it can read the row + * but not edit it). So every loser is answered from the set 409, 404, 403. + * + * The lockstep cells below start both claims in the same tick with no I/O on + * either path, so both gates read the parked row before either commits, and + * they pin the 409. The I/O-tick cells put one awaited I/O tick ahead of one + * claimant, the order a cold first request or any networked door produces, + * and pin the invariant and the set. + * + * The lockstep cells cross the two answers a lost race used to get with the two unit * shapes the engine has: an object with no metadata update hook opens no unit * of work for the write; one with a metadata `beforeUpdate` hook opens the * after-abort unit (`opensAfterAbortUnit`'s side-writing term), and so does one @@ -25,6 +38,9 @@ * (no existence leak), on the hooked object whose writes open the unit. */ +import { access } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { describe, it, expect, vi } from 'vitest'; import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; @@ -50,7 +66,20 @@ const SET = PermissionSetSchema.parse({ name: 'cq_member', objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, }); -const SETS = [MEMBER_DEFAULT, SET]; +/** A user in no queue, holding no share: a transfer-grant holder from outside the queue. */ +const C = 'usr_cq_c'; +/** The two permissions that satisfy the gate's transfer grant on the case object. */ +const TRANSFER_SETS = { + allowTransfer: PermissionSetSchema.parse({ + name: 'cq_transfer', + objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowTransfer: true } }, + }), + modifyAllRecords: PermissionSetSchema.parse({ + name: 'cq_modify_all', + objects: { [CASE]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, modifyAllRecords: true } }, + }), +} as const; +const SETS = [MEMBER_DEFAULT, SET, TRANSFER_SETS.allowTransfer, TRANSFER_SETS.modifyAllRecords]; const memberOf = (userId: string) => ({ userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER', }); @@ -83,7 +112,7 @@ async function boot(opts: { sharingModel: 'private' | 'public_read'; hook: HookS : { name: 'cq_touch', object: CASE, events: ['beforeUpdate'], handler: () => {} }; bindHooksToEngine(engine as never, [hook as never], { packageId: 'app:cq', logger: QUIET as never }); } - await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@cq.test` })), SYS); + await engine.insert('sys_user', [A, B, C].map((id) => ({ id, name: id, email: `${id}@cq.test` })), SYS); await engine.insert('sys_organization', [{ id: ORG, name: 'CQ', slug: 'cq' }], SYS); let securityService: unknown; let sharing: SharingService | undefined; @@ -165,6 +194,117 @@ for (const { sharingModel, hook } of CELLS) { }); } +/** The answers a losing claim may get (ruling B on #39065), as `code/status`. */ +const LOSER_ANSWERS = new Set(['CONCURRENT_UPDATE/409', 'RECORD_NOT_FOUND/404', 'PERMISSION_DENIED/403']); +/** + * One real I/O tick: a failed `fs.access` completes on the libuv pool, so its + * callback waits for the event loop while the other claimant's synchronous + * better-sqlite3 write runs to its commit. + */ +const ioTick = () => access(join(tmpdir(), `claim-race-io-tick-${process.pid}-missing`)).catch(() => undefined); + +for (const sharingModel of ['private', 'public_read'] as const) { + describe(`[ADR-0142 D4] concurrent claims, one I/O tick ahead of one claimant — ${sharingModel} OWD`, () => { + it(`exactly one claim lands and the loser is answered from 409, 404, 403, over ${ROUNDS} rounds`, async () => { + const engine = await boot({ sharingModel, hook: 'none' }); + const losers: Record = {}; + for (let round = 0; round < ROUNDS; round++) { + const id = `case_io_${round}`; + await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); + // The tick goes ahead of A on even rounds and of B on odd ones, so + // neither claimant's position decides the outcome. + const [first, late] = round % 2 === 0 ? [B, A] : [A, B]; + const settled = await Promise.allSettled([ + claim(engine, id, first), + ioTick().then(() => claim(engine, id, late)), + ]); + const won = settled.flatMap((r, i) => (r.status === 'fulfilled' ? [[first, late][i]] : [])); + expect(won, `round ${round}: ${settled.map(outcome).join(' | ')}`).toHaveLength(1); + const stored = await engine.findOne(CASE, { where: { id } } as never, SYS); + expect((stored as any)?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0]); + for (const r of settled) { + if (r.status === 'rejected') { + const key = outcome(r); + expect(LOSER_ANSWERS.has(key), `round ${round}: loser answered ${key}`).toBe(true); + losers[key] = (losers[key] ?? 0) + 1; + } + } + } + // The tick did reach the gate: at least one loser was answered after the + // winner's commit (404 or 403). Without this the cells would only repeat + // the lockstep ones above. + const late = Object.entries(losers).filter(([k]) => k !== 'CONCURRENT_UPDATE/409').reduce((n, [, c]) => n + c, 0); + expect(late, JSON.stringify(losers)).toBeGreaterThan(0); + }); + }); +} + +/** + * Holders of the transfer grant, measured and pinned as they stand (contract + * review 7365351117 on PR #39233). + * + * Ruling B's invariant above, exactly one owner and each loser answered 409, + * 404 or 403, is for claimants WITHOUT the transfer grant. The grant is the + * gate's `hasTransferGrant()`: `allowTransfer`, or `modifyAllRecords`, which + * satisfies it alone. A holder's owner write is a transfer, not a claim: it + * skips the conditional write, so two holders both succeed and the last + * writer owns the row. A holder is not a loser. + * + * `allowTransfer` opens an ownership change only on a row the holder can + * already read and edit, because the row check runs first. So a holder of + * `allowTransfer` alone, outside the queue and with no share, who writes after + * a member's claim committed, is answered as any request is: 404 under + * `private`, 403 under `public_read`, and the member stays the owner. + * `modifyAllRecords` opens the row too, so that holder's write lands. + */ +const TRANSFER_ROUNDS = 4; +const holderOf = (userId: string, grant: keyof typeof TRANSFER_SETS) => ({ + ...memberOf(userId), permissions: [TRANSFER_SETS[grant].name, SET.name, 'member_default'], +}); +const transferAs = (engine: ObjectQL, id: string, user: string, grant: keyof typeof TRANSFER_SETS) => + engine.update(CASE, { id, owner_id: user }, { where: { id }, context: holderOf(user, grant) } as never); +const answerOf = (p: Promise): Promise => + p.then(() => 'ok', (e: unknown) => `${(e as any)?.code}/${(e as any)?.status}`); +const ownerOf = async (engine: ObjectQL, id: string): Promise => + ((await engine.findOne(CASE, { where: { id } } as never, SYS)) as any)?.owner_id; + +for (const sharingModel of ['private', 'public_read'] as const) { + describe(`[ADR-0142 D4] transfer-grant holders are not claimants — ${sharingModel} OWD`, () => { + for (const grant of ['allowTransfer', 'modifyAllRecords'] as const) { + it(`two ${grant} holders writing an unowned record at once both succeed; the last writer owns it`, async () => { + const engine = await boot({ sharingModel, hook: 'none' }); + for (let round = 0; round < TRANSFER_ROUNDS; round++) { + const id = `case_tx_${grant}_${round}`; + await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); + const answers = await Promise.all([answerOf(transferAs(engine, id, A, grant)), answerOf(transferAs(engine, id, B, grant))]); + expect(answers, `round ${round}`).toEqual(['ok', 'ok']); + expect(await ownerOf(engine, id), `round ${round}: the last writer owns the row`).toBe(B); + } + }); + } + + const late: Record<'allowTransfer' | 'modifyAllRecords', { answer: string; owner: string }> = { + modifyAllRecords: { answer: 'ok', owner: C }, + allowTransfer: sharingModel === 'private' + ? { answer: 'RECORD_NOT_FOUND/404', owner: A } + : { answer: 'PERMISSION_DENIED/403', owner: A }, + }; + for (const grant of ['modifyAllRecords', 'allowTransfer'] as const) { + const { answer, owner } = late[grant]; + it(`a ${grant} holder outside the queue, after a member's claim committed: ${answer}, owner ${owner === C ? 'moves to the holder' : 'stays the member'}`, async () => { + const engine = await boot({ sharingModel, hook: 'none' }); + for (let round = 0; round < TRANSFER_ROUNDS; round++) { + const id = `case_late_${grant}_${round}`; + await seed(engine, { id, name: 'parked', owner_id: null, queue: QUEUE }); + expect(await answerOf(claim(engine, id, A)), `round ${round}: the member's claim`).toBe('ok'); + expect(await answerOf(transferAs(engine, id, C, grant)), `round ${round}: the holder's write`).toBe(answer); + expect(await ownerOf(engine, id), `round ${round}: the stored owner`).toBe(owner); + } + }); + } + }); +} + describe('[ADR-0142 D4] the unit around the engine body keeps the gate\'s refusals — private OWD, hooked object', () => { it('a row that is gone still answers 404 RECORD_NOT_FOUND', async () => { const engine = await boot({ sharingModel: 'private', hook: 'beforeUpdate' }); diff --git a/packages/verify/src/claim-race-http-door-39065.test.ts b/packages/verify/src/claim-race-http-door-39065.test.ts new file mode 100644 index 00000000000..bdb5e32045b --- /dev/null +++ b/packages/verify/src/claim-race-http-door-39065.test.ts @@ -0,0 +1,128 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// #39065, ruling B on ADR-0142 D4: two members of one queue claim the same +// parked record at once through the real HTTP data door +// (`PATCH /api/v1/data/OBJECT/ID` with `{ owner_id: }`), on a booted +// stack with the real SecurityPlugin, sharing and a declared queue whose +// members are a position. +// +// The invariant is that exactly one claim lands and the stored owner is the +// winner. The loser is answered from the set 409, 404, 403: `409 +// CONCURRENT_UPDATE` when its gate read the record unowned before the winner +// committed, otherwise what any request gets at that moment, `404 +// RECORD_NOT_FOUND` where the record left its sight (`private`) and `403 +// PERMISSION_DENIED` where it can still read it (`public_read`). Through this +// door one request usually runs to its commit before the other reads its +// session, so the late answers are the common ones here; which of the three a +// loser gets is timing, and is not pinned. + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { defineStack } from '@objectstack/spec'; +// The harness loads these two inside a function body; paid here, during collection, not in a clocked window. +import '@objectstack/service-datasource'; +import '@objectstack/service-automation'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { bootStack, type VerifyStack } from './harness.js'; +import { warmUpBoot } from './boot-warm-up.testkit.js'; + +// Booting the full in-process stack runs well past vitest's 5s default. +const BOOT_TIMEOUT = 120_000; + +await warmUpBoot(); + +const PRIVATE_CASE = 'cqh_case'; +const PUBLIC_CASE = 'cqh_public_case'; +const QUEUE = 'cqh_intake'; +const POSITION = 'cqh_agent'; +/** Rounds per object: the race is a scheduling fact, so one round proves little. */ +const ROUNDS = 4; +/** The answers a losing claim may get, as `code/status`. */ +const LOSER_ANSWERS = new Set(['CONCURRENT_UPDATE/409', 'RECORD_NOT_FOUND/404', 'PERMISSION_DENIED/403']); + +const memberSet = PermissionSetSchema.parse({ + name: 'cqh_member', + label: 'Claim race member', + isDefault: true, + objects: Object.fromEntries( + [PRIVATE_CASE, PUBLIC_CASE].map((o) => [o, { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }]), + ), +}); + +const config = () => + defineStack({ + manifest: { id: 'com.example.claim-race-http', namespace: 'cqh', version: '0.0.1', type: 'app', name: 'Claim race over HTTP' }, + objects: [ + { name: PRIVATE_CASE, label: 'Case', pluralLabel: 'Cases', sharingModel: 'private', fields: { name: { type: 'text', label: 'Name' } } }, + { name: PUBLIC_CASE, label: 'Public case', pluralLabel: 'Public cases', sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } } }, + ], + queues: [{ name: QUEUE, label: 'Intake', members: [{ type: 'position', value: POSITION }] }], + permissions: [memberSet], + } as never); + +interface Member { + token: string; + userId: string; +} + +describe('[ADR-0142 D4, #39065] concurrent claims through the HTTP data door', () => { + let stack: VerifyStack; + let a: Member; + let b: Member; + let organizationId: string; + + beforeAll(async () => { + stack = await bootStack(config()); + const members: Member[] = []; + for (const email of ['cqh-a@verify.test', 'cqh-b@verify.test']) { + const token = await stack.signUp(email); + const ctx = await stack.contextFor(token); + members.push({ token, userId: String(ctx.userId) }); + organizationId = String(ctx.tenantId); + } + [a, b] = members; + const ql = (await stack.kernel.getServiceAsync('objectql')) as { + insert(object: string, row: Record, opts: unknown): Promise; + }; + for (const m of members) { + await ql.insert( + 'sys_user_position', + { user_id: m.userId, position: POSITION, organization_id: organizationId }, + { context: { isSystem: true } }, + ); + } + }, BOOT_TIMEOUT); + + afterAll(async () => { + await stack?.stop(); + }); + + /** One claim through the door: `ok`, or the loser's `code/status`. */ + const claim = async (object: string, id: string, m: Member): Promise => { + const res = await stack.apiAs(m.token, 'PATCH', `/data/${object}/${id}`, { owner_id: m.userId }); + if (res.ok) return 'ok'; + const body = (await res.json()) as { code?: unknown; error?: { code?: unknown } }; + return `${String(body.code ?? body.error?.code)}/${res.status}`; + }; + + for (const object of [PRIVATE_CASE, PUBLIC_CASE]) { + it(`${object}: exactly one claim lands and the loser is answered from 409, 404, 403, over ${ROUNDS} rounds`, async () => { + const losers: Record = {}; + for (let round = 0; round < ROUNDS; round++) { + const id = `${object}_${round}`; + await stack.hooks.run(object, 'insert', { id, name: 'parked', owner_id: null, queue: QUEUE, organization_id: organizationId }, { system: true }); + // Alternate who sends first, so neither member's position decides. + const pair = round % 2 === 0 ? [a, b] : [b, a]; + const answers = await Promise.all(pair.map((m) => claim(object, id, m))); + const won = pair.filter((_, i) => answers[i] === 'ok'); + expect(won.map((m) => m.userId), `round ${round}: ${answers.join(' | ')}`).toHaveLength(1); + const [stored] = await stack.rows(object, { id }); + expect(stored?.owner_id, `round ${round}: the stored owner is the winner`).toBe(won[0].userId); + for (const answer of answers.filter((x) => x !== 'ok')) { + expect(LOSER_ANSWERS.has(answer), `round ${round}: loser answered ${answer}`).toBe(true); + losers[answer] = (losers[answer] ?? 0) + 1; + } + } + expect(Object.values(losers).reduce((n, c) => n + c, 0), JSON.stringify(losers)).toBe(ROUNDS); + }); + } +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 0825f5238a8..1ee892b0ddc 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -2604,6 +2604,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri toast.success(t('detail.claimed', { defaultValue: 'You own this record now.' })); } else if (result.outcome === 'taken') { toast.error(t('detail.claimTaken', { defaultValue: 'Someone else claimed this record first.' })); + } else if (result.outcome === 'unavailable') { + // A 404 or 403 straight after a claim: the sentence names no claimant, + // since a 404 is also what a deleted record answers. + toast.error(t('detail.claimUnavailable', { defaultValue: 'This record is no longer waiting to be claimed.' })); } else { toast.error( extractWriteErrorMessage(result.error) diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c28933051a3..28c8b940301 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1857,6 +1857,7 @@ const ar = { claimed: "أصبحت مالك هذا السجل الآن.", claimTaken: "استلم شخص آخر هذا السجل قبلك.", claimFailed: "لم يُقبل الاستلام.", + claimUnavailable: "لم يعد هذا السجل بانتظار الاستلام.", cancel: "إلغاء", cancelEdit: "تجاهل التغييرات", sectionMoreDetails: "مزيد من التفاصيل", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 5771326a1f2..1f489b38ba6 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1672,6 +1672,7 @@ const de = { claimed: "Dieser Datensatz gehört jetzt Ihnen.", claimTaken: "Jemand anderes hat diesen Datensatz zuerst übernommen.", claimFailed: "Die Übernahme wurde nicht angenommen.", + claimUnavailable: "Dieser Datensatz wartet nicht mehr auf eine Übernahme.", cancel: "Abbrechen", cancelEdit: "Änderungen verwerfen", sectionMoreDetails: "Weitere Details", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 8366b04280a..63d2b4868a7 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1797,6 +1797,7 @@ const en = { claimed: 'You own this record now.', claimTaken: 'Someone else claimed this record first.', claimFailed: 'The claim was not accepted.', + claimUnavailable: 'This record is no longer waiting to be claimed.', cancel: 'Cancel', cancelEdit: 'Discard changes', sectionMoreDetails: 'More details', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ff3ab9e6f80..5d1ee852ebb 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1718,6 +1718,7 @@ const es = { claimed: "Ahora este registro es tuyo.", claimTaken: "Otra persona reclamó este registro primero.", claimFailed: "No se aceptó la reclamación.", + claimUnavailable: "Este registro ya no está esperando a ser reclamado.", cancel: "Cancelar", cancelEdit: "Descartar cambios", sectionMoreDetails: "Más detalles", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 7fd5cd744af..94c1deb08ff 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1722,6 +1722,7 @@ const fr = { claimed: "Cet enregistrement vous appartient désormais.", claimTaken: "Quelqu'un d'autre a pris cet enregistrement en premier.", claimFailed: "La prise en charge n'a pas été acceptée.", + claimUnavailable: "Cet enregistrement n'attend plus d'être pris en charge.", cancel: "Annuler", cancelEdit: "Abandonner les modifications", sectionMoreDetails: "Plus de détails", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 74c354b55a1..60b8ea47500 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1756,6 +1756,7 @@ const ja = { claimed: "このレコードの担当者になりました。", claimTaken: "他のユーザーが先にこのレコードを担当しました。", claimFailed: "担当の申請は受け付けられませんでした。", + claimUnavailable: "このレコードはもう担当待ちではありません。", cancel: "キャンセル", cancelEdit: "変更を破棄", sectionMoreDetails: "詳細情報", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 30776c303fe..60278ce0bd1 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1672,6 +1672,7 @@ const ko = { claimed: "이제 이 레코드의 담당자입니다.", claimTaken: "다른 사용자가 먼저 이 레코드를 담당했습니다.", claimFailed: "담당 요청이 수락되지 않았습니다.", + claimUnavailable: "이 레코드는 더 이상 담당 대기 중이 아닙니다.", cancel: "취소", cancelEdit: "변경 사항 취소", sectionMoreDetails: "추가 세부 정보", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 1fd8936aa6b..d9128dbd7c0 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1722,6 +1722,7 @@ const pt = { claimed: "Este registro agora é seu.", claimTaken: "Outra pessoa assumiu este registro primeiro.", claimFailed: "A solicitação não foi aceita.", + claimUnavailable: "Este registro não está mais aguardando para ser assumido.", cancel: "Cancelar", cancelEdit: "Descartar alterações", sectionMoreDetails: "Mais detalhes", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index b25c50198bf..6c4fa5eef1d 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1870,6 +1870,7 @@ const ru = { claimed: "Теперь эта запись ваша.", claimTaken: "Кто-то другой взял эту запись раньше вас.", claimFailed: "Запрос не был принят.", + claimUnavailable: "Эта запись больше не ожидает исполнителя.", cancel: "Отмена", cancelEdit: "Отменить изменения", sectionMoreDetails: "Подробнее", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 997ea2d98ba..050de37fd2b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1502,6 +1502,7 @@ const zh = { claimed: '这条记录现在归你了。', claimTaken: '已有其他人先认领了这条记录。', claimFailed: '认领未被接受。', + claimUnavailable: '这条记录已不在待认领状态。', cancel: '取消', cancelEdit: '放弃更改', sectionMoreDetails: '更多详情', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 756686e1c2a..ccc0a98a6cc 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1502,6 +1502,7 @@ const zhHant = { claimed: '這條記錄現在歸你了。', claimTaken: '已有其他人先認領了這條記錄。', claimFailed: '認領未被接受。', + claimUnavailable: '這條記錄已不在待認領狀態。', cancel: '取消', cancelEdit: '放棄更改', sectionMoreDetails: '更多詳情', diff --git a/ui/packages/plugin-detail/src/queueClaim-25769.test.tsx b/ui/packages/plugin-detail/src/queueClaim-25769.test.tsx index 8caa9517174..ffe474da473 100644 --- a/ui/packages/plugin-detail/src/queueClaim-25769.test.tsx +++ b/ui/packages/plugin-detail/src/queueClaim-25769.test.tsx @@ -170,8 +170,54 @@ describe('claimQueuedRecord — one write, the server’s answer reported as giv }); it('carries any other refusal through as refused, with its error', async () => { - const denied = Object.assign(new Error('Forbidden'), { status: 403 }); + const invalid = Object.assign(new Error('Validation failed'), { httpStatus: 400, code: 'VALIDATION_FAILED' }); + const writer = { update: vi.fn(async () => { throw invalid; }) }; + await expect(claimQueuedRecord(writer, 'ticket', 'r1', 'u_me')).resolves.toEqual({ outcome: 'refused', error: invalid }); + }); +}); + +/** + * objectstack#39065, ruling B: a claim whose server check runs after another + * member's claim committed is answered as any request is at that moment: + * `404 RECORD_NOT_FOUND` when the record left the caller's sight, `403 + * PERMISSION_DENIED` when the caller can still read it. Straight after a claim + * either answer means one thing to the user: the record is no longer waiting + * to be claimed. The client does not tell a lost race from a deleted record; + * it reports `unavailable`, and the page reloads the record. + */ +describe('claimQueuedRecord — a 404 or 403 straight after a claim is "no longer waiting" (objectstack#39065)', () => { + const refusedWith = (status: number, code: string, message: string) => + Object.assign(new Error(message), { httpStatus: status, code }); + + it('reports 404 RECORD_NOT_FOUND as unavailable, with its error', async () => { + const gone = refusedWith(404, 'RECORD_NOT_FOUND', 'This record does not exist, or you do not have access to it.'); + const writer = { update: vi.fn(async () => { throw gone; }) }; + await expect(claimQueuedRecord(writer, 'ticket', 'r1', 'u_me')).resolves.toEqual({ outcome: 'unavailable', error: gone }); + }); + + it('reports 403 PERMISSION_DENIED as unavailable, with its error', async () => { + const denied = refusedWith(403, 'PERMISSION_DENIED', 'You do not have permission to change this record.'); const writer = { update: vi.fn(async () => { throw denied; }) }; - await expect(claimQueuedRecord(writer, 'ticket', 'r1', 'u_me')).resolves.toEqual({ outcome: 'refused', error: denied }); + await expect(claimQueuedRecord(writer, 'ticket', 'r1', 'u_me')).resolves.toEqual({ outcome: 'unavailable', error: denied }); + }); + + it('reads the status a raw fetch caller carries too (status, statusCode)', async () => { + for (const refusal of [ + Object.assign(new Error('Forbidden'), { status: 403 }), + Object.assign(new Error('Not Found'), { statusCode: 404 }), + ]) { + const writer = { update: vi.fn(async () => { throw refusal; }) }; + await expect(claimQueuedRecord(writer, 'ticket', 'r1', 'u_me')).resolves.toEqual({ outcome: 'unavailable', error: refusal }); + } + }); + + it('keeps a 409 CONCURRENT_UPDATE as taken and a 401 as refused', async () => { + const lost = Object.assign(new Error('taken'), { httpStatus: 409, code: 'CONCURRENT_UPDATE' }); + const unauthenticated = refusedWith(401, 'UNAUTHENTICATED', 'Sign in again.'); + const outcomes: unknown[] = []; + for (const err of [lost, unauthenticated]) { + outcomes.push(await claimQueuedRecord({ update: vi.fn(async () => { throw err; }) }, 'ticket', 'r1', 'u_me')); + } + expect(outcomes).toEqual([{ outcome: 'taken' }, { outcome: 'refused', error: unauthenticated }]); }); }); diff --git a/ui/packages/plugin-detail/src/queueClaim.ts b/ui/packages/plugin-detail/src/queueClaim.ts index 0433a0b215b..c0b5887a655 100644 --- a/ui/packages/plugin-detail/src/queueClaim.ts +++ b/ui/packages/plugin-detail/src/queueClaim.ts @@ -14,9 +14,12 @@ * `queue` column names Q. A claim is an ordinary update of `owner_id` to the * caller's own id: the server's ownership gate admits it when the record is * unowned and the sharing model positively admits the caller (a member of the - * queue is the common case), writes it on the condition that the owner is - * still empty, and answers the loser of a race `409 CONCURRENT_UPDATE` ("the - * record was taken"). + * queue is the common case), and writes it on the condition that the owner is + * still empty: exactly one claim lands. A losing claim whose check saw the + * record unowned answers `409 CONCURRENT_UPDATE` ("the record was taken"); one + * whose check ran after the owner was set answers what any request gets at + * that moment, `404` when the record left the caller's sight and `403` when + * the caller can still read it (ADR-0142 D4 as ruled on objectstack#39065). * * The server is the only judge. This module holds two reads and one write: * @@ -32,7 +35,8 @@ * replaces. * - {@link claimQueuedRecord} sends `{ owner_id: }` through the normal * update path and reports the server's answer as it came: claimed, taken by - * someone else (the 409), or refused for another reason. + * someone else (the 409), no longer waiting to be claimed (a 404 or 403), + * or refused for another reason. * * Unlike `useRecordEditable`, the probe FAILS CLOSED: Edit is an affordance the * record already has and a hint must never hide it; Claim exists only where @@ -168,9 +172,29 @@ export type QueueClaimOutcome = | { readonly outcome: 'claimed' } /** `409 CONCURRENT_UPDATE`: another user took the record first. */ | { readonly outcome: 'taken' } + /** + * `404` or `403` straight after a claim: the record is no longer waiting to + * be claimed. It may have been claimed by someone else, moved or deleted; + * the answer does not say which, so neither does the caller. + */ + | { readonly outcome: 'unavailable'; readonly error: unknown } /** Any other refusal, carried as thrown so the caller can say what it was. */ | { readonly outcome: 'refused'; readonly error: unknown }; +/** + * The HTTP status a refused write carries: `httpStatus` as the ObjectStack + * client sets it, or `status` / `statusCode` as a raw fetch caller does (the + * spellings `is404Error` in `@object-ui/data-objectstack` reads). + */ +function refusalStatusOf(error: unknown): number | undefined { + if (!error || typeof error !== 'object') return undefined; + const e = error as { httpStatus?: unknown; status?: unknown; statusCode?: unknown }; + for (const s of [e.httpStatus, e.status, e.statusCode]) { + if (typeof s === 'number') return s; + } + return undefined; +} + /** The one write a claim is: `owner_id` set to the caller, through `update`. */ export interface ClaimWriter { update(objectName: string, recordId: string, data: Record): Promise; @@ -193,6 +217,8 @@ export async function claimQueuedRecord( return { outcome: 'claimed' }; } catch (error) { if (isConcurrentUpdateError(error)) return { outcome: 'taken' }; + const status = refusalStatusOf(error); + if (status === 404 || status === 403) return { outcome: 'unavailable', error }; return { outcome: 'refused', error }; } }