From 5bc748dc4d269dab87942ec1ce8bce108e72b21f Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Thu, 5 Nov 2026 23:14:14 +0900 Subject: [PATCH] fix(auction): prevent skipped players and incomplete completion --- .../modules/auction/auction-rejection.spec.ts | 9 + .../src/modules/auction/auction-rejection.ts | 9 +- .../modules/auction/auction.service.spec.ts | 261 ++++++++++++++++++ .../src/modules/auction/auction.service.ts | 65 ++++- apps/web/src/api/auction-action-retry.ts | 87 ++++++ apps/web/src/api/auctionRejectionMessages.ts | 10 +- apps/web/src/api/useAuctionSocket.ts | 37 +-- apps/web/src/pages/AuctionPage.tsx | 5 +- apps/web/test/auction-action-retry.test.ts | 199 +++++++++++++ .../test/auction-rejection-messages.test.ts | 27 ++ 10 files changed, 677 insertions(+), 32 deletions(-) create mode 100644 apps/web/src/api/auction-action-retry.ts create mode 100644 apps/web/test/auction-action-retry.test.ts create mode 100644 apps/web/test/auction-rejection-messages.test.ts diff --git a/apps/api/src/modules/auction/auction-rejection.spec.ts b/apps/api/src/modules/auction/auction-rejection.spec.ts index dfa73ea5..aaf89184 100644 --- a/apps/api/src/modules/auction/auction-rejection.spec.ts +++ b/apps/api/src/modules/auction/auction-rejection.spec.ts @@ -5,6 +5,15 @@ import { } from './auction-rejection'; describe('resolveAuctionRejectionReason', () => { + it('reports roster validation failures without recommending a retry', () => { + const reason = resolveAuctionRejectionReason( + 'AUCTION_ROSTER_INVALID', + 'Auction roster validation failed.', + ); + expect(reason).toBe('AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID'); + expect(isAuctionResyncRecommended(reason)).toBe(false); + }); + it('maps the internal CONFLICT code to the descriptive transition reason', () => { expect(resolveAuctionRejectionReason('CONFLICT')).toBe( AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, diff --git a/apps/api/src/modules/auction/auction-rejection.ts b/apps/api/src/modules/auction/auction-rejection.ts index 8a20e67c..e29ce974 100644 --- a/apps/api/src/modules/auction/auction-rejection.ts +++ b/apps/api/src/modules/auction/auction-rejection.ts @@ -16,7 +16,7 @@ * resync 권장 여부: * - `AUCTION_RESYNC_RECOMMENDED_REASONS`에 속한 reason은 "클라가 본 상태가 이미 * 바뀌었다(낙관적 동시성 충돌/만료/단계 전이)"는 신호다. 이 경우 클라는 최신 - * state로 rebaseline한 뒤 (구조 액션이라면) 1회 재시도하는 것이 안전하다. + * state로 rebaseline한다. 구조 액션 재시도는 원래 대상과 단계가 같을 때만 허용한다. * - 반대로 정원 초과/포인트 부족처럼 "상태를 새로고침해도 결과가 같은" 거부는 * resync 권장 대상이 아니다(재시도해도 또 거부됨). */ @@ -29,9 +29,12 @@ export const AUCTION_REJECTION_REASON = { /** 입찰 단계가 아닌데 입찰 단계 전환을 시도함(이미 sold/passed/presenting 등). */ AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: 'AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE', - /** 현재 단계에서 "다음"으로 진행할 수 없음(sold/passed/presenting이 아님 — 보통 이미 진행됨). */ + /** 낙찰 또는 유찰이 확정되지 않아 다음 선수로 진행할 수 없음. */ AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE: 'AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE', + /** 원 참가자 명단과 실제 팀 배정이 일치하지 않아 완료할 수 없음. */ + AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID: + 'AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID', /** 낙찰 처리할 유효한 최고 입찰이 없음(만료 처리로 이미 정리됐을 수 있음). */ AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD: 'AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD', @@ -83,6 +86,8 @@ export type AuctionRejectionReason = /** 내부 짧은 코드 → 설명적 reason. */ const INTERNAL_CODE_TO_REASON: Record = { + AUCTION_ROSTER_INVALID: + AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID, CONFLICT: AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY, STALE_BID_ROUND: diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index bcadd1fa..811be915 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -1365,6 +1365,267 @@ describe('AuctionService', () => { } }); + describe('redis next safety', () => { + function createFortyPlayerAuction() { + const matchId = new mongoose.Types.ObjectId(); + const participantIds = Array.from( + { length: 40 }, + () => new mongoose.Types.ObjectId(), + ); + const auction = { + _id: new mongoose.Types.ObjectId(), + matchId, + auctionEngineVersion: 'redis-v1', + auctionLifecycleId: 'life-1', + }; + const state = { + auctionLifecycleId: 'life-1', + auctionTeams: participantIds + .slice(0, 8) + .map((captainUserId, index) => ({ + teamIndex: index + 1, + captainUserId: captainUserId.toString(), + remainingBidPointAmount: 960, + members: participantIds + .slice(8 + index * 4, 12 + index * 4) + .map((userId) => ({ + userId: userId.toString(), + assignedPosition: 'MID', + memberAcquisitionBidPointAmount: 10, + })), + })), + auctionPlayerOrder: participantIds.slice(8).map((userId) => ({ + userId: userId.toString(), + preferredPositions: [{ position: 'MID', priority: 1 }], + passCount: 0, + })), + bidRoundExtensionSeconds: 5, + currentAuctionHistorySequence: 121, + currentAuctionPlayerOrderIndex: 31, + currentAuctionRound: 1, + initialTeamBidPointAmount: 1000, + maximumBidRoundDurationSeconds: 15, + passedAuctionPlayerQueue: [] as Array<{ + userId: string; + preferredPositions: Array<{ position: string; priority: number }>; + passCount: number; + }>, + phase: 'sold', + revision: 479, + topTierAuctionPriorityThreshold: 'NONE', + }; + const match = { + _id: matchId, + participants: participantIds.map((userId) => ({ + userId, + excluded: false, + preferredPositions: [{ position: 'MID', priority: 1 }], + })), + status: 'team-built', + teams: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const dependencies = createService({ + auction: { findOne: jest.fn().mockResolvedValue(auction) }, + match: { findById: jest.fn().mockResolvedValue(match) }, + }); + dependencies.auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue( + state, + ); + dependencies.auctionRedisCommandService.applyTransition.mockImplementation( + async (_matchId: string, input: Record) => { + Object.assign( + state, + parseJsonRecord( + input.afterAuctionStructureStateJson, + 'afterAuctionStructureStateJson', + ), + input.liveStatePatch, + { + revision: Number(input.expectedRevision) + 1, + currentAuctionHistorySequence: input.auctionHistorySequence, + }, + ); + return { + auctionStateTransitionId: String(input.auctionStateTransitionId), + currentServerTimestampMS: 1780000000000, + ok: true, + revision: state.revision, + }; + }, + ); + return { ...dependencies, matchId, match, state, participantIds }; + } + + it.each([12, 31])( + 'rejects next for a presenting player at index %i without skipping or completing', + async (index) => { + const { service, matchId, state, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.phase = 'presenting'; + state.currentAuctionPlayerOrderIndex = index; + const before = structuredClone(state); + + await expect(service.next(matchId)).rejects.toThrow( + 'Cannot advance from current phase.', + ); + + expect(state).toEqual(before); + expect( + auctionRedisCommandService.reserveActionRequest, + ).not.toHaveBeenCalled(); + expect( + auctionRedisCommandService.applyTransition, + ).not.toHaveBeenCalled(); + }, + ); + + it('rejects completion when only 39 of the 40 participants are assigned', async () => { + const { service, matchId, state, match, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.auctionTeams[6].members.pop(); + const before = structuredClone(state); + + await expect(service.next(matchId)).rejects.toThrow( + 'Auction roster validation failed.', + ); + + expect(state).toEqual(before); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + expect(match.save).not.toHaveBeenCalled(); + }); + + it('checks original eligible participants even if a missing player also disappeared from the order', async () => { + const { service, matchId, state, auctionRedisCommandService } = + createFortyPlayerAuction(); + const missingPlayer = state.auctionTeams[6].members.pop()!; + state.auctionPlayerOrder = state.auctionPlayerOrder.filter( + (player) => player.userId !== missingPlayer.userId, + ); + state.currentAuctionPlayerOrderIndex = + state.auctionPlayerOrder.length - 1; + const before = structuredClone(state); + + await expect(service.next(matchId)).rejects.toThrow( + 'Auction roster validation failed.', + ); + + expect(state).toEqual(before); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + }); + + it('rejects a duplicate assignment even when the assigned count still equals 40', async () => { + const { service, matchId, state, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.auctionTeams[0].members[0].userId = + state.auctionTeams[1].members[0].userId; + + await expect(service.next(matchId)).rejects.toThrow( + 'Auction roster validation failed.', + ); + + expect(state.phase).toBe('sold'); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + }); + + it('rejects duplicate captain membership even when every expected user is present', async () => { + const { service, matchId, state, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.auctionTeams[0].members.push({ + userId: state.auctionTeams[0].captainUserId, + assignedPosition: 'MID', + memberAcquisitionBidPointAmount: 10, + }); + + await expect(service.next(matchId)).rejects.toThrow( + 'Auction roster validation failed.', + ); + + expect(state.phase).toBe('sold'); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + }); + + it('rejects an unexpected assigned user even when all 40 assignments are unique', async () => { + const { service, matchId, state, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.auctionTeams[0].members[0].userId = + new mongoose.Types.ObjectId().toString(); + + await expect(service.next(matchId)).rejects.toThrow( + 'Auction roster validation failed.', + ); + + expect(state.phase).toBe('sold'); + expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled(); + }); + + it('completes all 40 eligible participants once, allowing repeat order entries after passes and excluding cut participants', async () => { + const { service, matchId, state, match, auctionRedisCommandService } = + createFortyPlayerAuction(); + state.auctionPlayerOrder.push({ + ...state.auctionPlayerOrder[12], + passCount: 1, + }); + state.currentAuctionPlayerOrderIndex = + state.auctionPlayerOrder.length - 1; + state.currentAuctionRound = 2; + match.participants.push({ + userId: new mongoose.Types.ObjectId(), + excluded: true, + preferredPositions: [{ position: 'MID', priority: 1 }], + }); + + await expect(service.next(matchId)).resolves.toMatchObject({ + phase: 'complete', + revision: 480, + }); + + expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes( + 1, + ); + expect(state.auctionTeams).toHaveLength(8); + expect( + state.auctionTeams.every((team) => team.members.length === 4), + ).toBe(true); + expect(match.save).not.toHaveBeenCalled(); + }); + + it.each(['sold', 'passed'])( + 'advances a nonterminal %s player without demanding a completed roster', + async (phase) => { + const { service, matchId, state } = createFortyPlayerAuction(); + state.phase = phase; + state.currentAuctionPlayerOrderIndex = 12; + state.auctionTeams.forEach((team) => { + team.members = []; + }); + + await expect(service.next(matchId)).resolves.toMatchObject({ + phase: 'presenting', + currentAuctionPlayerOrderIndex: 13, + }); + }, + ); + + it('requeues passed players for another round without completing an incomplete roster', async () => { + const { service, matchId, state } = createFortyPlayerAuction(); + state.phase = 'passed'; + state.auctionTeams[7].members.pop(); + state.passedAuctionPlayerQueue.push({ + ...state.auctionPlayerOrder[31], + passCount: 1, + }); + + await expect(service.next(matchId)).resolves.toMatchObject({ + phase: 'presenting', + currentAuctionPlayerOrderIndex: 32, + currentAuctionRound: 2, + passedAuctionPlayerQueue: [], + }); + expect(state.auctionPlayerOrder).toHaveLength(33); + }); + }); + it('syncs match teams when a redis-v1 auction completes', async () => { const matchId = new mongoose.Types.ObjectId(); const captainUserId = new mongoose.Types.ObjectId(); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts index 3737ea2f..e105b122 100644 --- a/apps/api/src/modules/auction/auction.service.ts +++ b/apps/api/src/modules/auction/auction.service.ts @@ -1193,11 +1193,7 @@ export class AuctionService { ): Promise { const matchId = auction.matchId.toString(); const state = await this.requireRedisAuctionState(matchId); - if ( - state.phase !== 'sold' && - state.phase !== 'presenting' && - state.phase !== 'passed' - ) { + if (state.phase !== 'sold' && state.phase !== 'passed') { throw new BadRequestException('Cannot advance from current phase.'); } @@ -1218,6 +1214,10 @@ export class AuctionService { structureInput.currentAuctionRound += 1; structureInput.currentAuctionPlayerOrderIndex = nextIndex; } else { + await this.assertCompleteAuctionRoster( + auction.matchId, + structureInput.auctionTeams, + ); action = 'complete'; nextPhase = 'complete'; } @@ -1332,17 +1332,16 @@ export class AuctionService { if (this.isRedisV1Auction(auction)) { return this.advanceRedisAuction(auction, actionRequest); } - if ( - auction.phase !== 'sold' && - auction.phase !== 'presenting' && - auction.phase !== 'passed' - ) { + if (auction.phase !== 'sold' && auction.phase !== 'passed') { throw new BadRequestException('Cannot advance from current phase.'); } const nextIndex = auction.currentIndex + 1; const completesAuction = nextIndex >= auction.order.length && (auction.passedQueue?.length ?? 0) === 0; + if (completesAuction) { + await this.assertCompleteAuctionRoster(matchId, auction.teams); + } await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next'); if (nextIndex >= auction.order.length) { if ((auction.passedQueue?.length ?? 0) > 0) { @@ -2515,6 +2514,52 @@ export class AuctionService { return ordered.slice(0, desiredAuctionCount); } + private async assertCompleteAuctionRoster( + matchId: mongoose.Types.ObjectId, + teams: Array<{ + captainUserId: mongoose.Types.ObjectId; + members: Array<{ userId: mongoose.Types.ObjectId }>; + }>, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId); + if (!match) throw new NotFoundException('Match not found.'); + + // The queue can contain reauction entries or be corrupted; use the original roster. + const expectedIds = match.participants + .filter((participant) => !participant.excluded) + .map((participant) => participant.userId.toString()); + const expected = new Set(expectedIds); + const assignedIds = teams.flatMap((team) => [ + team.captainUserId.toString(), + ...team.members.map((member) => member.userId.toString()), + ]); + const assigned = new Set(assignedIds); + const missingUserIds = expectedIds.filter((id) => !assigned.has(id)); + const unexpectedUserIds = [...assigned].filter((id) => !expected.has(id)); + if ( + expected.size === 0 || + expected.size !== expectedIds.length || + assigned.size !== assignedIds.length || + missingUserIds.length > 0 || + unexpectedUserIds.length > 0 + ) { + this.logger.error({ + event: 'auction_roster_validation_failed', + matchId: matchId.toString(), + expectedCount: expectedIds.length, + assignedCount: assignedIds.length, + assignedUniqueCount: assigned.size, + missingUserIds, + unexpectedUserIds, + }); + throw new BadRequestException({ + code: 'AUCTION_ROSTER_INVALID', + message: 'Auction roster validation failed.', + }); + } + } + private assertCaptainAssignments( captains: StartAuctionParams['captains'], activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>, diff --git a/apps/web/src/api/auction-action-retry.ts b/apps/web/src/api/auction-action-retry.ts new file mode 100644 index 00000000..6287e87f --- /dev/null +++ b/apps/web/src/api/auction-action-retry.ts @@ -0,0 +1,87 @@ +import type { ApiAuction } from './types'; + +type AuctionActionState = Pick< + ApiAuction, + | 'auctionLifecycleId' + | 'currentAuctionPlayerOrderIndex' + | 'currentBidRoundPlayerUserId' + | 'phase' + | 'revision' +>; + +interface AuctionActionObservation { + clientObservedAuctionLifecycleId?: string; + clientObservedCurrentAuctionPlayerOrderIndex?: number; + clientObservedCurrentBidRoundPlayerUserId?: string; + clientObservedPhase?: string; + clientObservedRevision?: number; +} + +export function resolveAuctionActionRejection( + params: Parameters[0], +): { applyServerState: boolean; retry: boolean } { + const { request, currentState, serverState } = params; + // Decide from the live screen before applying the ACK: an old response may force resync. + const applyServerState = Boolean( + currentState && + serverState && + request.clientObservedAuctionLifecycleId && + currentState.auctionLifecycleId === + request.clientObservedAuctionLifecycleId && + (serverState.auctionLifecycleId !== currentState.auctionLifecycleId || + (Number.isSafeInteger(serverState.revision) && + (serverState.revision ?? -1) > (currentState.revision ?? -1))), + ); + return { applyServerState, retry: shouldRetryAuctionAction(params) }; +} + +export function shouldRetryAuctionAction(params: { + action: string; + request: AuctionActionObservation; + serverState?: AuctionActionState | null; + currentState?: AuctionActionState | null; + resyncRecommended: boolean; + retryAttempt: number; +}): boolean { + const { action, request, serverState, currentState } = params; + if ( + !params.resyncRecommended || + params.retryAttempt >= 1 || + !serverState || + !currentState + ) { + return false; + } + + const phase = request.clientObservedPhase; + const phaseAllowsAction = + (action === 'next' && (phase === 'sold' || phase === 'passed')) || + (action === 'open-bidding' && phase === 'presenting') || + ((action === 'sold' || action === 'passed') && phase === 'bidding'); + if ( + !phaseAllowsAction || + !request.clientObservedAuctionLifecycleId || + !request.clientObservedCurrentBidRoundPlayerUserId || + !Number.isSafeInteger( + request.clientObservedCurrentAuctionPlayerOrderIndex, + ) || + (request.clientObservedCurrentAuctionPlayerOrderIndex ?? -1) < 0 || + !Number.isSafeInteger(request.clientObservedRevision) || + (request.clientObservedRevision ?? -1) < 0 + ) { + return false; + } + + // A delayed rejection must not turn the original action into one for another player. + return [serverState, currentState].every( + (state) => + state.auctionLifecycleId === request.clientObservedAuctionLifecycleId && + state.currentAuctionPlayerOrderIndex === + request.clientObservedCurrentAuctionPlayerOrderIndex && + state.currentBidRoundPlayerUserId === + request.clientObservedCurrentBidRoundPlayerUserId && + state.phase === phase && + Number.isSafeInteger(state.revision) && + (state.revision ?? -1) >= request.clientObservedRevision!, + ); +} diff --git a/apps/web/src/api/auctionRejectionMessages.ts b/apps/web/src/api/auctionRejectionMessages.ts index cdbee3a9..8d13ab01 100644 --- a/apps/web/src/api/auctionRejectionMessages.ts +++ b/apps/web/src/api/auctionRejectionMessages.ts @@ -14,11 +14,13 @@ const REASON_TO_USER_MESSAGE: Record = { // 구조 전환 AUCTION_TRANSITION_REJECTED_BECAUSE_LIVE_STATE_CHANGED_BEFORE_APPLY: - '경매 상태가 바뀌어 최신 상태로 맞췄어요. 다시 시도해 주세요.', + '경매 상태가 바뀌었어요. 현재 선수와 진행 상태를 확인해 주세요.', AUCTION_TRANSITION_REJECTED_BECAUSE_AUCTION_NOT_IN_BIDDING_PHASE: '이미 입찰 단계가 아니에요. 최신 상태로 맞췄어요.', AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE: - '이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.', + '현재 단계에서는 다음 선수로 넘어갈 수 없어요. 현재 선수를 확인해 주세요.', + AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID: + '팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다.', AUCTION_TRANSITION_REJECTED_BECAUSE_NO_WINNING_BID_TO_MARK_SOLD: '낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.', AUCTION_TRANSITION_REJECTED_BECAUSE_ACTIVE_BID_PRESENT: @@ -56,7 +58,9 @@ const ENGLISH_MESSAGE_TO_USER_MESSAGE: Record = { 'Unknown team.': '알 수 없는 팀이에요.', 'Bid request conflicts with an earlier request.': '중복된 요청이에요.', 'Cannot advance from current phase.': - '이미 다음 단계로 넘어간 상태예요. 최신 상태로 맞췄어요.', + '현재 단계에서는 다음 선수로 넘어갈 수 없어요. 현재 선수를 확인해 주세요.', + 'Auction roster validation failed.': + '팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다.', 'No bid to mark sold.': '낙찰할 입찰이 없어요. 최신 상태로 맞췄어요.', 'Cannot pass a player with an active bid.': '진행 중인 입찰이 있어 유찰할 수 없어요.', diff --git a/apps/web/src/api/useAuctionSocket.ts b/apps/web/src/api/useAuctionSocket.ts index f0bcb3fb..2fa09c00 100644 --- a/apps/web/src/api/useAuctionSocket.ts +++ b/apps/web/src/api/useAuctionSocket.ts @@ -3,6 +3,7 @@ import { io, type Socket } from 'socket.io-client'; import { API_BASE_URL, useAuthUserId } from '../config'; import { acquireAccessToken } from '../lib/auth/token-provider'; import type { ApiAuction, ApiAuctionChatMessage, Position } from './types'; +import { resolveAuctionActionRejection } from './auction-action-retry'; import { isAuctionResyncRecommended, resolveAuctionErrorMessage, @@ -691,13 +692,21 @@ export function useAuctionSocket(matchId: string | undefined) { clearPendingActionRequest( ack?.auctionActionRequestId ?? auctionActionRequestId, ); - // 2) 자동 재시도: "낡은 화면 때문에 거부"였고 동기 rebaseline 소스(state)가 - // 있을 때만 1회. assignedPosition 등 원래 payload는 유지하고 관측값/요청 - // id만 새로 만든다. 재시도 시에는 중간 에러 문구를 띄우지 않는다(무음 복구). - const canAutoRetry = - Boolean(ack.state) && - isAuctionResyncRecommended(ack) && - retryAttempt < 1; + // 최신 화면과 거부 응답이 모두 원래 요청의 대상일 때만 한 번 재시도한다. + const { applyServerState, retry: canAutoRetry } = + resolveAuctionActionRejection({ + action: eventName, + request: payload, + serverState: ack.state, + currentState: latestAuctionRef.current, + resyncRecommended: isAuctionResyncRecommended(ack), + retryAttempt, + }); + if (ack.state && applyServerState) { + commitAuctionState(ack.state, 'action-reject-rebaseline'); + } else if (!ack.state && isAuctionResyncRecommended(ack)) { + resyncAuctionState(); + } // 거부 시 "클라가 보낸 관측 revision"과 "서버가 동봉한 진짜 state"를 함께 // 기록한다. observedRevision < serverRevision 이면 stale-client CONFLICT 확정. addNewRelicPageAction('AuctionClientActionRejected', { @@ -725,18 +734,14 @@ export function useAuctionSocket(matchId: string | undefined) { ...describeAuctionForTelemetry('observed', latestAuctionRef.current), ...describeAuctionForTelemetry('server', ack?.state ?? null), }); - // 1) rebaseline: 서버가 동봉한 최신 state를 즉시 반영(없으면 join으로 재요청). - // commitAuctionState는 latestAuctionRef를 동기로 갱신하므로, 이후 - // buildAuctionActionPayload는 최신 관측값(revision/phase/선수)을 읽는다. - if (ack.state) { - commitAuctionState(ack.state, 'action-reject-rebaseline'); - } else if (isAuctionResyncRecommended(ack)) { - resyncAuctionState(); - } if (canAutoRetry) { emitAuctionAction( eventName, - { ...payload, ...buildAuctionActionPayload() }, + { + ...payload, + auctionActionRequestId: createClientRequestId(), + clientObservedRevision: latestAuctionRef.current?.revision, + }, retryAttempt + 1, ); } else { diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 2c94187c..6b4c782a 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -2144,7 +2144,10 @@ export default function AuctionPage() { {errorMessage && ( -
+
{errorMessage}
)} diff --git a/apps/web/test/auction-action-retry.test.ts b/apps/web/test/auction-action-retry.test.ts new file mode 100644 index 00000000..c814c348 --- /dev/null +++ b/apps/web/test/auction-action-retry.test.ts @@ -0,0 +1,199 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + resolveAuctionActionRejection, + shouldRetryAuctionAction, +} from "../src/api/auction-action-retry.ts"; + +const request = { + clientObservedAuctionLifecycleId: "auction-1", + clientObservedCurrentAuctionPlayerOrderIndex: 11, + clientObservedCurrentBidRoundPlayerUserId: "player-11", + clientObservedPhase: "sold", + clientObservedRevision: 130, +}; +const state = { + auctionLifecycleId: "auction-1", + currentAuctionPlayerOrderIndex: 11, + currentBidRoundPlayerUserId: "player-11", + phase: "sold" as const, + revision: 131, +}; +const input = { + action: "next", + request, + serverState: state, + currentState: state, + resyncRecommended: true, + retryAttempt: 0, +}; + +test("a delayed old-lifecycle rejection cannot roll back the screen and retry", () => { + const currentState = { + ...state, + auctionLifecycleId: "auction-2", + revision: 1, + }; + const decision = resolveAuctionActionRejection({ ...input, currentState }); + assert.deepEqual(decision, { applyServerState: false, retry: false }); +}); + +test("an older forced-resync rejection cannot roll back an already advanced player", () => { + const serverState = { ...state, shouldForceAuctionStateResync: true }; + const currentState = { + ...state, + revision: 132, + currentAuctionPlayerOrderIndex: 12, + }; + assert.deepEqual( + resolveAuctionActionRejection({ ...input, serverState, currentState }), + { + applyServerState: false, + retry: false, + }, + ); +}); + +test("a fresh rejection updates the screen to the new player without retrying", () => { + const serverState = { + ...state, + currentAuctionPlayerOrderIndex: 12, + phase: "presenting" as const, + }; + assert.deepEqual( + resolveAuctionActionRejection({ + ...input, + serverState, + currentState: { ...state, revision: 130 }, + }), + { applyServerState: true, retry: false }, + ); +}); + +test("a same-target revision update is applied and permits one retry", () => { + assert.deepEqual( + resolveAuctionActionRejection({ + ...input, + currentState: { ...state, revision: 130 }, + }), + { applyServerState: true, retry: true }, + ); +}); + +test("retries a revision conflict only while the original action target is unchanged", () => { + assert.equal(shouldRetryAuctionAction(input), true); +}); + +test("does not retry next for the following player after a conflict", () => { + const nextPlayer = { + ...state, + currentAuctionPlayerOrderIndex: 12, + currentBidRoundPlayerUserId: "player-12", + phase: "presenting" as const, + }; + assert.equal( + shouldRetryAuctionAction({ + ...input, + serverState: nextPlayer, + currentState: nextPlayer, + }), + false, + ); +}); + +for (const patch of [ + { auctionLifecycleId: "auction-2" }, + { currentAuctionPlayerOrderIndex: 12 }, + { currentBidRoundPlayerUserId: "player-12" }, + { phase: "passed" as const }, +]) { + test(`does not retarget a retry when ${Object.keys(patch)[0]} changes`, () => { + assert.equal( + shouldRetryAuctionAction({ + ...input, + serverState: { ...state, ...patch }, + }), + false, + ); + }); +} + +test("does not retry from an older acknowledgement after the live screen has advanced", () => { + assert.equal( + shouldRetryAuctionAction({ + ...input, + currentState: { ...state, currentAuctionPlayerOrderIndex: 12 }, + }), + false, + ); +}); + +test("does not retry with missing original target identity", () => { + for (const field of Object.keys(request)) { + assert.equal( + shouldRetryAuctionAction({ + ...input, + request: { ...request, [field]: undefined }, + }), + false, + ); + } +}); + +test("does not retry without a current state, a server state, or a retry recommendation", () => { + assert.equal( + shouldRetryAuctionAction({ ...input, currentState: null }), + false, + ); + assert.equal( + shouldRetryAuctionAction({ ...input, serverState: undefined }), + false, + ); + assert.equal( + shouldRetryAuctionAction({ ...input, resyncRecommended: false }), + false, + ); + assert.equal(shouldRetryAuctionAction({ ...input, retryAttempt: 1 }), false); +}); + +test("does not retry next in presenting even if the target is unchanged", () => { + assert.equal( + shouldRetryAuctionAction({ + ...input, + request: { ...request, clientObservedPhase: "presenting" }, + serverState: { ...state, phase: "presenting" }, + currentState: { ...state, phase: "presenting" }, + }), + false, + ); +}); + +test("does not retry using a revision older than the original request", () => { + assert.equal( + shouldRetryAuctionAction({ + ...input, + serverState: { ...state, revision: 129 }, + }), + false, + ); +}); + +for (const [action, phase] of [ + ["open-bidding", "presenting"], + ["sold", "bidding"], + ["passed", "bidding"], + ["next", "passed"], +] as const) { + test(`allows a same-target ${action} retry in ${phase}`, () => { + assert.equal( + shouldRetryAuctionAction({ + ...input, + action, + request: { ...request, clientObservedPhase: phase }, + serverState: { ...state, phase }, + currentState: { ...state, phase }, + }), + true, + ); + }); +} diff --git a/apps/web/test/auction-rejection-messages.test.ts b/apps/web/test/auction-rejection-messages.test.ts new file mode 100644 index 00000000..5c2acc23 --- /dev/null +++ b/apps/web/test/auction-rejection-messages.test.ts @@ -0,0 +1,27 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + resolveAuctionErrorMessage, + resolveAuctionRejectionMessage, +} from "../src/api/auctionRejectionMessages.ts"; + +const rosterMessage = "팀 배정 상태를 확인해야 해 경매를 완료하지 못했습니다."; + +test("shows the common error message when roster validation blocks completion", () => { + assert.equal( + resolveAuctionRejectionMessage({ + auctionRejectionReason: + "AUCTION_TRANSITION_REJECTED_BECAUSE_ROSTER_INVALID", + code: "AUCTION_ROSTER_INVALID", + message: "Auction roster validation failed.", + }), + rosterMessage, + ); +}); + +test("shows the same roster message for the socket error event", () => { + assert.equal( + resolveAuctionErrorMessage("Auction roster validation failed."), + rosterMessage, + ); +});