From af01817f5793fbf08ad047569a4cd3204b47ac88 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 2 Aug 2026 06:59:20 +0000 Subject: [PATCH] fix(cas): acquire document advisory lock before OH13 CAS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pass 5 P1b — assertCampaignDocCas now requires a transaction req, locks campaign-doc-cas:{collection}:{id}, and re-reads updatedAt under the lock. Leadership form updates and chip deltas share that key; political trend goes through the same helper. Concurrent writers int pin added. --- docs/IMPROVE-CODE-QUALITY-PLAN.md | 4 +- docs/TECH-DEBT.md | 6 +- .../campanha/actions/assertCampaignDocCas.ts | 20 +++- .../(campaign)/campanha/actions/leadership.ts | 101 ++++++++++-------- .../campanha/actions/municipality.ts | 34 +++--- tests/int/domainWritesCas.int.spec.ts | 47 ++++++++ 6 files changed, 141 insertions(+), 71 deletions(-) diff --git a/docs/IMPROVE-CODE-QUALITY-PLAN.md b/docs/IMPROVE-CODE-QUALITY-PLAN.md index a4fffa0f..95468257 100644 --- a/docs/IMPROVE-CODE-QUALITY-PLAN.md +++ b/docs/IMPROVE-CODE-QUALITY-PLAN.md @@ -238,8 +238,8 @@ Statuses: pending · in-progress · awaiting-evidence · done · deferred: \ + `campaign-doc-cas:${collection}:${id}` + /** - * OH13 — shared CAS gate used by domain writes (3+ call sites). When armed, - * loads the doc's `updatedAt` under the actor's row access and refuses on - * mismatch. Does not replace RBAC or wrap the mutation itself. + * OH13 / Pass 5 P1b — shared CAS gate. When armed, acquires a per-document + * advisory lock, re-reads `updatedAt` under the actor's row access, and refuses + * on mismatch. Callers must pass an active transaction `req` whenever CAS is + * enforced — check-then-write without a lock is not CAS. */ export const assertCampaignDocCas = async ( payload: Payload, @@ -19,11 +25,15 @@ export const assertCampaignDocCas = async ( actor: CampaignUser enforceCas: boolean baseUpdatedAt: string | null | undefined - req?: PayloadTransactionRequest + req: PayloadTransactionRequest }, ): Promise => { if (!args.enforceCas || args.baseUpdatedAt === undefined) return + await acquireTextAdvisoryLocks(payload, args.req, [ + campaignDocCasLockKey(args.collection, args.id), + ]) + const current = await payload.findByID({ collection: args.collection, id: args.id, @@ -31,7 +41,7 @@ export const assertCampaignDocCas = async ( select: { updatedAt: true }, user: args.actor, overrideAccess: false, - ...(args.req ? { req: args.req } : {}), + req: args.req, }) assertOpsUpdatedAtCas(true, args.baseUpdatedAt, current.updatedAt) diff --git a/src/app/(campaign)/campanha/actions/leadership.ts b/src/app/(campaign)/campanha/actions/leadership.ts index a3a5e50a..97dcbe8f 100644 --- a/src/app/(campaign)/campanha/actions/leadership.ts +++ b/src/app/(campaign)/campanha/actions/leadership.ts @@ -3,6 +3,10 @@ import { revalidatePath } from 'next/cache' import type { Payload } from 'payload' +import { + assertCampaignDocCas, + campaignDocCasLockKey, +} from '@/app/(campaign)/campanha/actions/assertCampaignDocCas' import { nextMunicipalityIdsAfterLeadershipMembership } from '@/lib/leadershipMunicipalityMembership' import { nextStateDeputyIdsAfterMembership } from '@/lib/leadershipStateDeputyMembership' import { relationshipId, uniqueRelationshipIds } from '@/lib/relationship' @@ -182,37 +186,55 @@ export const updateLeadershipInternalRecord = async ( const { id, municipalities, organizations, stateDeputies, baseUpdatedAt, ...data } = leadershipInternalUpdateSchema.parse(input) const enforceCas = options?.cas === true - const currentActor = await getFreshStaffActor(payload, actor) - // Row access verifies the current record is in the actor's scope. - const current = await payload.findByID({ - collection: 'leadership', - id, - depth: 0, - user: currentActor, - overrideAccess: false, - }) + return withPayloadTransaction( + payload, + async ({ req }) => { + const currentActor = await getFreshStaffActor(payload, actor, req) - // Stamp already loaded with the row — avoid a second find via assertCampaignDocCas. - assertOpsUpdatedAtCas(enforceCas, baseUpdatedAt, current.updatedAt) + // Lock + re-read under CAS (Pass 5 P1b). When CAS is not armed, keep the + // row-access preflight so out-of-scope updates fail closed before mutate. + await assertCampaignDocCas(payload, { + collection: 'leadership', + id, + actor: currentActor, + enforceCas, + baseUpdatedAt, + req, + }) + if (!enforceCas || baseUpdatedAt === undefined) { + await payload.findByID({ + collection: 'leadership', + id, + depth: 0, + select: { id: true }, + user: currentActor, + overrideAccess: false, + req, + }) + } - if (municipalities !== undefined) { - await assertMunicipalitiesWithinScope(payload, currentActor, municipalities) - } + if (municipalities !== undefined) { + await assertMunicipalitiesWithinScope(payload, currentActor, municipalities, req) + } - return payload.update({ - collection: 'leadership', - id: current.id, - data: { - ...data, - ...(municipalities === undefined ? {} : { municipalities }), - ...(organizations === undefined ? {} : { organizations: organizations ?? [] }), - ...(stateDeputies === undefined ? {} : { stateDeputies: stateDeputies ?? [] }), + return payload.update({ + collection: 'leadership', + id, + data: { + ...data, + ...(municipalities === undefined ? {} : { municipalities }), + ...(organizations === undefined ? {} : { organizations: organizations ?? [] }), + ...(stateDeputies === undefined ? {} : { stateDeputies: stateDeputies ?? [] }), + }, + depth: 0, + user: currentActor, + overrideAccess: false, + req, + }) }, - depth: 0, - user: currentActor, - overrideAccess: false, - }) + { beginFailureMessage: 'Não foi possível iniciar a atualização da liderança.' }, + ) } export const listMunicipalityLeaderships = async ( @@ -400,26 +422,17 @@ const revalidateLeadershipStateDeputyPaths = (leadershipId: number, stateDeputyS } } -const LEADERSHIP_RELATION_LOCK_KEYS = { - municipalities: 'leadership-municipalities', - stateDeputies: 'leadership-state-deputies', -} as const - /** * Opens a leadership for a delta write on one of its relations: reloads the - * actor, takes the lock that belongs to THAT relation, and reads the current - * ids under the actor's row access (the same guard - * `updateLeadershipInternalRecord` relies on). + * actor, takes the **document** CAS lock (same key as `assertCampaignDocCas` / + * ficha form), and reads the current ids under the actor's row access. * - * The pairing is the point: relation and lock key used to be two independent - * string literals a few lines apart, so a third relation could quietly take a - * lock that guards a different column. The rest of the two delta writes — the - * delta shape, the scope assertion, the slug lookup, the return — is genuinely - * different in each, and hoisting it would cost six callbacks to share ~24 lines. + * Relation-specific keys were dropped in Pass 5 P1b: the ficha form replaces + * the whole array under `campaign-doc-cas:leadership:{id}`, so a chip delta + * on a different lock could still lost-update against the form. Chip×chip on + * the same leadership now serializes too — correct and cheap at our write rate. */ -const openLeadershipForRelationDelta = async < - Relation extends keyof typeof LEADERSHIP_RELATION_LOCK_KEYS, ->( +const openLeadershipForRelationDelta = async ( payload: Payload, actor: CampaignUser, req: PayloadTransactionRequest, @@ -428,9 +441,7 @@ const openLeadershipForRelationDelta = async < ) => { const currentActor = await getFreshStaffActor(payload, actor, req) - await acquireTextAdvisoryLocks(payload, req, [ - `${LEADERSHIP_RELATION_LOCK_KEYS[relation]}:${leadershipId}`, - ]) + await acquireTextAdvisoryLocks(payload, req, [campaignDocCasLockKey('leadership', leadershipId)]) const current = await payload.findByID({ collection: 'leadership', diff --git a/src/app/(campaign)/campanha/actions/municipality.ts b/src/app/(campaign)/campanha/actions/municipality.ts index 9d420914..a21ac7a6 100644 --- a/src/app/(campaign)/campanha/actions/municipality.ts +++ b/src/app/(campaign)/campanha/actions/municipality.ts @@ -2,6 +2,7 @@ import type { Payload } from 'payload' +import { assertCampaignDocCas } from '@/app/(campaign)/campanha/actions/assertCampaignDocCas' import { ENGAGEMENT_LEVEL_PATTERN_ID, EngagementLevelBlockedError, @@ -89,29 +90,30 @@ export const setMunicipalityPoliticalTrendRecord = async ( const { municipality, status, note, baseUpdatedAt } = municipalityPoliticalTrendSchema.parse(input) const enforceCas = options?.cas === true - const currentActor = await getFreshStaffActor(payload, actor) - if (enforceCas && baseUpdatedAt !== undefined) { - const current = await payload.findByID({ + return withPayloadTransaction(payload, async ({ req }) => { + const currentActor = await getFreshStaffActor(payload, actor, req) + + await assertCampaignDocCas(payload, { collection: 'municipality', id: municipality, + actor: currentActor, + enforceCas, + baseUpdatedAt, + req, + }) + + return payload.update({ + collection: 'municipality', + id: municipality, + data: { + politicalTrend: { status, note }, + }, depth: 0, - select: { updatedAt: true }, user: currentActor, overrideAccess: false, + req, }) - assertOpsUpdatedAtCas(true, baseUpdatedAt, current.updatedAt) - } - - return payload.update({ - collection: 'municipality', - id: municipality, - data: { - politicalTrend: { status, note }, - }, - depth: 0, - user: currentActor, - overrideAccess: false, }) } diff --git a/tests/int/domainWritesCas.int.spec.ts b/tests/int/domainWritesCas.int.spec.ts index bdd53067..643312d0 100644 --- a/tests/int/domainWritesCas.int.spec.ts +++ b/tests/int/domainWritesCas.int.spec.ts @@ -124,6 +124,53 @@ describe('updateLeadershipInternalCas (OH13)', () => { expect(updated.supportStatus).toBe('engajado') expect(updated.updatedAt).not.toBe(leadership.updatedAt) }) + + it('serializes concurrent CAS writers — exactly one wins, the other conflicts', async () => { + const fixtures = campaignFixtures() + const municipality = await fixtures.getMunicipality() + const advisor = await fixtures.createCampaignUser('advisor') + await fixtures.assignMunicipalityAdvisors(municipality.id, [advisor.id]) + const contact = await fixtures.createContact() + const leadership = await fixtures.createLeadership({ + contact: contact.id, + municipalities: [municipality.id], + supportStatus: 'a_abordar', + }) + const baseUpdatedAt = leadership.updatedAt + + const results = await Promise.allSettled([ + updateLeadershipInternalCasRecord(payload, advisor, { + id: leadership.id, + supportStatus: 'engajado', + baseUpdatedAt, + }), + updateLeadershipInternalCasRecord(payload, advisor, { + id: leadership.id, + supportStatus: 'em_disputa', + baseUpdatedAt, + }), + ]) + + const fulfilled = results.filter((r) => r.status === 'fulfilled') + const rejected = results.filter((r) => r.status === 'rejected') + expect(fulfilled).toHaveLength(1) + expect(rejected).toHaveLength(1) + + const conflict = (rejected[0] as PromiseRejectedResult).reason + expect(conflict).toBeInstanceOf(Error) + expect(isOpsUpdatedAtConflictMessage((conflict as Error).message)).toBe(true) + + const current = await payload.findByID({ + collection: 'leadership', + id: leadership.id, + depth: 0, + overrideAccess: true, + }) + const winnerStatus = (fulfilled[0] as PromiseFulfilledResult<{ supportStatus: string }>).value + .supportStatus + expect(current.supportStatus).toBe(winnerStatus) + expect(['engajado', 'em_disputa']).toContain(current.supportStatus) + }) }) describe('transitionCampaignDemandCas (OH13)', () => {