fix(auction): prevent skipped players and incomplete completion
This commit is contained in:
1 parent
de84ad5309
commit
5bc748dc4d
10 files changed
+677
-32
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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<string, AuctionRejectionReason> = {
|
||||
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:
|
||||
|
||||
@@ -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<string, unknown>) => {
|
||||
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();
|
||||
|
||||
@@ -1193,11 +1193,7 @@ export class AuctionService {
|
||||
): Promise<AuctionStateResponse> {
|
||||
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<void> {
|
||||
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 }>,
|
||||
|
||||
Reference in new issue
Block a user