fix: close competition cutover integrity gaps
This commit is contained in:
1 parent
7ea2002975
commit
683d602d63
57 files changed
+4805
-1582
No files matched your search
@@ -960,7 +960,10 @@ describe('auction durability projection helpers', () => {
|
||||
const sideEffectUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
|
||||
});
|
||||
const reserveForMatch = jest.fn().mockResolvedValue(match);
|
||||
const reserveForMatch = jest.fn().mockImplementation(() => {
|
||||
expect(match.teamBuiltAt).toBeUndefined();
|
||||
return Promise.resolve(match);
|
||||
});
|
||||
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
|
||||
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
|
||||
const broadcastMatchSideEffect = jest.fn();
|
||||
@@ -1010,7 +1013,7 @@ describe('auction durability projection helpers', () => {
|
||||
teamIndex: 1,
|
||||
},
|
||||
]);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(match.save).toHaveBeenCalledTimes(2);
|
||||
expect(reserveForMatch).toHaveBeenCalledWith(match);
|
||||
expect(scheduleInitialPoll).toHaveBeenCalledWith(match);
|
||||
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
|
||||
|
||||
@@ -80,6 +80,7 @@ type ParsedMatchSideEffectMutation =
|
||||
| { type: typeof UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE };
|
||||
|
||||
interface CleanupSideEffectMatchDocument {
|
||||
competitionId?: unknown;
|
||||
gameSchedule?: unknown[];
|
||||
participants: Array<{ excluded?: boolean }>;
|
||||
result?: unknown;
|
||||
@@ -420,13 +421,14 @@ export class AuctionDurabilityScheduler
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
const expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
|
||||
try {
|
||||
const match = (await execMaybe(
|
||||
MatchModel.findById(payload.matchId) as never,
|
||||
)) as {
|
||||
competitionId?: unknown;
|
||||
participants: Array<{
|
||||
preferredPositions?: Array<{ position?: Position }>;
|
||||
userId: { toString(): string };
|
||||
@@ -438,39 +440,50 @@ export class AuctionDurabilityScheduler
|
||||
} | null;
|
||||
if (!match)
|
||||
throw new Error(`Match not found: ${String(payload.matchId)}`);
|
||||
const matchTeams = buildMatchTeamsFromProjection(
|
||||
payload.afterAuctionMongoProjection,
|
||||
match,
|
||||
);
|
||||
// [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사
|
||||
// (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다).
|
||||
const allMemberUserIds = matchTeams.flatMap((team) =>
|
||||
team.members.map((member) => member.userId.toString()),
|
||||
);
|
||||
const distinctMemberCount = new Set(allMemberUserIds).size;
|
||||
recordNewRelicCustomEvent('AuctionServerTeamBuild', {
|
||||
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
|
||||
auctionStateTransitionId: payload.auctionStateTransitionId,
|
||||
teamCount: matchTeams.length,
|
||||
totalMemberCount: allMemberUserIds.length,
|
||||
distinctMemberCount,
|
||||
hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount,
|
||||
duplicateUserId:
|
||||
allMemberUserIds.find(
|
||||
(id, idx) => allMemberUserIds.indexOf(id) !== idx,
|
||||
) ?? null,
|
||||
});
|
||||
if (matchTeams.length === 0) {
|
||||
throw new Error(
|
||||
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
|
||||
if (match.competitionId) {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match as never);
|
||||
} else {
|
||||
const matchTeams = buildMatchTeamsFromProjection(
|
||||
payload.afterAuctionMongoProjection,
|
||||
match,
|
||||
);
|
||||
// [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사
|
||||
// (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다).
|
||||
const allMemberUserIds = matchTeams.flatMap((team) =>
|
||||
team.members.map((member) => member.userId.toString()),
|
||||
);
|
||||
const distinctMemberCount = new Set(allMemberUserIds).size;
|
||||
recordNewRelicCustomEvent('AuctionServerTeamBuild', {
|
||||
matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
|
||||
auctionStateTransitionId: payload.auctionStateTransitionId,
|
||||
teamCount: matchTeams.length,
|
||||
totalMemberCount: allMemberUserIds.length,
|
||||
distinctMemberCount,
|
||||
hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount,
|
||||
duplicateUserId:
|
||||
allMemberUserIds.find(
|
||||
(id, idx) => allMemberUserIds.indexOf(id) !== idx,
|
||||
) ?? null,
|
||||
});
|
||||
if (matchTeams.length === 0) {
|
||||
throw new Error(
|
||||
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
|
||||
);
|
||||
}
|
||||
const finalizedAt = match.teamBuiltAt ?? new Date();
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = undefined;
|
||||
await match.save();
|
||||
const preparedMatch =
|
||||
(await this.tournamentCodeService.reserveForMatch(match as never)) ??
|
||||
match;
|
||||
preparedMatch.teamBuiltAt = finalizedAt;
|
||||
await preparedMatch.save();
|
||||
await this.tournamentResultService.scheduleInitialPoll(
|
||||
preparedMatch as never,
|
||||
);
|
||||
}
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match as never);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match as never);
|
||||
|
||||
const completedAtTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
@@ -543,7 +556,9 @@ export class AuctionDurabilityScheduler
|
||||
await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params);
|
||||
if (invalidated) return;
|
||||
|
||||
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
|
||||
const historyOperation = buildAuctionHistoryUpsert(
|
||||
params.payload,
|
||||
).updateOne;
|
||||
await execMaybe(
|
||||
params.AuctionHistoryModel.updateOne(
|
||||
historyOperation.filter as never,
|
||||
@@ -700,7 +715,7 @@ export class AuctionDurabilityScheduler
|
||||
},
|
||||
);
|
||||
if (!processingDelta) return;
|
||||
let expectedMatchSideEffectRevision =
|
||||
const expectedMatchSideEffectRevision =
|
||||
processingDelta.matchSideEffectRevision;
|
||||
|
||||
try {
|
||||
@@ -710,6 +725,11 @@ export class AuctionDurabilityScheduler
|
||||
if (!match) {
|
||||
throw new Error(`Match not found: ${String(params.payload.matchId)}`);
|
||||
}
|
||||
if (match.competitionId) {
|
||||
throw new Error(
|
||||
'Cannot reset or undo Match teams after the immutable Competition has been created.',
|
||||
);
|
||||
}
|
||||
await params.updateMatch(match);
|
||||
|
||||
const completedAtTimestampMS =
|
||||
|
||||
@@ -2072,13 +2072,17 @@ describe('AuctionService', () => {
|
||||
findById: jest.fn().mockResolvedValue(match),
|
||||
},
|
||||
});
|
||||
tournamentCodeService.reserveForMatch.mockImplementation((candidate) => {
|
||||
expect(candidate.teamBuiltAt).toBeUndefined();
|
||||
return Promise.resolve(candidate);
|
||||
});
|
||||
|
||||
await service.next(matchId);
|
||||
|
||||
expect(auction.phase).toBe('complete');
|
||||
expect(auction.completedAt).toBeInstanceOf(Date);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
expect(match.save).toHaveBeenCalledTimes(1);
|
||||
expect(match.save).toHaveBeenCalledTimes(2);
|
||||
expect(match.teams).toEqual([
|
||||
{
|
||||
teamIndex: 1,
|
||||
@@ -2174,6 +2178,55 @@ describe('AuctionService', () => {
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('rejects auction reset after Competition bootstrap', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const session = {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const auction = {
|
||||
deleteOne: jest.fn(),
|
||||
};
|
||||
const match = {
|
||||
communityId,
|
||||
competitionId: new mongoose.Types.ObjectId(),
|
||||
status: 'team-built',
|
||||
teams: [{ teamIndex: 1 }],
|
||||
tournamentCodeIds: [],
|
||||
gameSchedule: [],
|
||||
participants: [],
|
||||
save: jest.fn(),
|
||||
};
|
||||
const { service, connectionService, tournamentCodeService } = createService(
|
||||
{
|
||||
auction: {
|
||||
findOne: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(auction),
|
||||
}),
|
||||
},
|
||||
match: {
|
||||
findById: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
connectionService.createSession.mockResolvedValue(session);
|
||||
|
||||
await expect(service.reset({ matchId, communityId })).rejects.toThrow(
|
||||
'immutable Competition',
|
||||
);
|
||||
|
||||
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(session.commitTransaction).not.toHaveBeenCalled();
|
||||
expect(auction.deleteOne).not.toHaveBeenCalled();
|
||||
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
||||
expect(match.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fully deletes redis-v1 auction data when cancelling an auction', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
Logger,
|
||||
@@ -471,7 +472,7 @@ export class AuctionService {
|
||||
? auction.toObject({ depopulate: true })
|
||||
: auction;
|
||||
return {
|
||||
...JSON.parse(JSON.stringify(mongoState)),
|
||||
...this.cloneJson(mongoState),
|
||||
...redisState,
|
||||
chatMessages: auction.chatMessages ?? [],
|
||||
};
|
||||
@@ -1061,8 +1062,8 @@ export class AuctionService {
|
||||
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
||||
}
|
||||
|
||||
const passedPlayer = {
|
||||
...JSON.parse(JSON.stringify(currentPlayer)),
|
||||
const passedPlayer: AuctionPlayerSnapshot = {
|
||||
...this.cloneAuctionPlayerSnapshot(currentPlayer),
|
||||
passCount: this.numberFromState(currentPlayer.passCount) + 1,
|
||||
};
|
||||
structureInput.auctionPlayerOrder[
|
||||
@@ -1157,8 +1158,8 @@ export class AuctionService {
|
||||
];
|
||||
if (!currentPlayer) throw new BadRequestException('No current player.');
|
||||
|
||||
const passedPlayer = {
|
||||
...JSON.parse(JSON.stringify(currentPlayer)),
|
||||
const passedPlayer: AuctionPlayerSnapshot = {
|
||||
...this.cloneAuctionPlayerSnapshot(currentPlayer),
|
||||
passCount: this.numberFromState(currentPlayer.passCount) + 1,
|
||||
};
|
||||
structureInput.auctionPlayerOrder[
|
||||
@@ -1210,7 +1211,7 @@ export class AuctionService {
|
||||
structureInput.auctionPlayerOrder = [
|
||||
...structureInput.auctionPlayerOrder,
|
||||
...structureInput.passedAuctionPlayerQueue.map((player) =>
|
||||
JSON.parse(JSON.stringify(player)),
|
||||
this.cloneAuctionPlayerSnapshot(player),
|
||||
),
|
||||
];
|
||||
structureInput.passedAuctionPlayerQueue = [];
|
||||
@@ -1434,6 +1435,7 @@ export class AuctionService {
|
||||
if (!match.communityId.equals(params.communityId)) {
|
||||
throw new BadRequestException('Community mismatch.');
|
||||
}
|
||||
this.assertCompetitionLifecycleMutable(match, 'reset the auction');
|
||||
|
||||
if (this.isRedisV1Auction(auction)) {
|
||||
redisRuntimeToClear = {
|
||||
@@ -1543,11 +1545,17 @@ export class AuctionService {
|
||||
|
||||
const undoingCompletedAuction =
|
||||
Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
||||
if (undoingCompletedAuction) {
|
||||
this.assertCompetitionLifecycleMutable(
|
||||
match,
|
||||
'undo a completed auction',
|
||||
);
|
||||
}
|
||||
if (this.isRedisV1Auction(auction)) {
|
||||
redisUndoContext = {
|
||||
auction,
|
||||
actionRequestParams: params,
|
||||
snapshot: snapshot as Record<string, unknown>,
|
||||
snapshot: snapshot,
|
||||
targetHistorySequence: params.sequence,
|
||||
undoingCompletedAuction,
|
||||
};
|
||||
@@ -2111,7 +2119,7 @@ export class AuctionService {
|
||||
? (auction.toObject({ depopulate: true }) as Record<string, unknown>)
|
||||
: (auction as unknown as Record<string, unknown>);
|
||||
return {
|
||||
...JSON.parse(JSON.stringify(base)),
|
||||
...this.cloneJson(base),
|
||||
...this.buildAuctionMongoProjectionFromState(auction, state),
|
||||
_id: auction._id,
|
||||
matchId: auction.matchId,
|
||||
@@ -2220,11 +2228,11 @@ export class AuctionService {
|
||||
>[0]['auctionTeams'],
|
||||
): AuctionTeam[] {
|
||||
return auctionTeams.map((team) => ({
|
||||
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
|
||||
captainUserId: team.captainUserId,
|
||||
members: (team.members ?? []).map((member) => ({
|
||||
assignedPosition: member.assignedPosition,
|
||||
cost: member.memberAcquisitionBidPointAmount,
|
||||
userId: member.userId as mongoose.Types.ObjectId,
|
||||
userId: member.userId,
|
||||
})),
|
||||
points: team.remainingBidPointAmount,
|
||||
teamIndex: team.teamIndex,
|
||||
@@ -2247,7 +2255,11 @@ export class AuctionService {
|
||||
// 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다.
|
||||
// structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로
|
||||
// JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다.
|
||||
return JSON.parse(JSON.stringify(this.arrayFromState<T>(value))) as T[];
|
||||
return this.cloneJson(this.arrayFromState<T>(value));
|
||||
}
|
||||
|
||||
private cloneJson<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
private numberFromState(value: unknown, fallback = 0): number {
|
||||
@@ -2455,7 +2467,7 @@ export class AuctionService {
|
||||
sequence: (latest?.sequence ?? 0) + 1,
|
||||
action,
|
||||
actorUserId,
|
||||
snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)),
|
||||
snapshotBefore: this.cloneJson(snapshotBefore),
|
||||
takenAt: new Date(),
|
||||
});
|
||||
}
|
||||
@@ -2612,6 +2624,17 @@ export class AuctionService {
|
||||
return auction.auctionEngineVersion === 'redis-v1';
|
||||
}
|
||||
|
||||
private assertCompetitionLifecycleMutable(
|
||||
match: Pick<MatchDocument, 'competitionId'>,
|
||||
action: string,
|
||||
): void {
|
||||
if (match.competitionId) {
|
||||
throw new ConflictException(
|
||||
`Cannot ${action} after the immutable Competition has been created. Create a new Match instead.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private isRestartableResetRedisAuction(auction: AuctionDocument): boolean {
|
||||
return (
|
||||
this.isRedisV1Auction(auction) &&
|
||||
@@ -2661,6 +2684,10 @@ export class AuctionService {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(auction.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (match.competitionId) {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
return;
|
||||
}
|
||||
|
||||
const participantByUserId = new Map(
|
||||
match.participants.map((participant) => [
|
||||
@@ -2698,12 +2725,16 @@ export class AuctionService {
|
||||
`Auction completed without teams for match ${match._id.toString()}.`,
|
||||
);
|
||||
}
|
||||
const finalizedAt = match.teamBuiltAt ?? new Date();
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
match.teamBuiltAt = undefined;
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
const preparedMatch =
|
||||
(await this.tournamentCodeService.reserveForMatch(match)) ?? match;
|
||||
preparedMatch.teamBuiltAt = finalizedAt;
|
||||
await preparedMatch.save();
|
||||
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
|
||||
}
|
||||
|
||||
private async syncMatchTeamsFromRedisAuctionState(
|
||||
@@ -2713,6 +2744,10 @@ export class AuctionService {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const match = await MatchModel.findById(auction.matchId);
|
||||
if (!match) throw new NotFoundException('Match not found.');
|
||||
if (match.competitionId) {
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
return;
|
||||
}
|
||||
|
||||
const participantByUserId = new Map(
|
||||
match.participants.map((participant) => [
|
||||
@@ -2757,12 +2792,16 @@ export class AuctionService {
|
||||
`Redis auction completed without teams for match ${match._id.toString()}.`,
|
||||
);
|
||||
}
|
||||
const finalizedAt = match.teamBuiltAt ?? new Date();
|
||||
match.teams = matchTeams;
|
||||
match.status = 'team-built';
|
||||
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
|
||||
match.teamBuiltAt = undefined;
|
||||
await match.save();
|
||||
await this.tournamentCodeService.reserveForMatch(match);
|
||||
await this.tournamentResultService.scheduleInitialPoll(match);
|
||||
const preparedMatch =
|
||||
(await this.tournamentCodeService.reserveForMatch(match)) ?? match;
|
||||
preparedMatch.teamBuiltAt = finalizedAt;
|
||||
await preparedMatch.save();
|
||||
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
|
||||
}
|
||||
|
||||
private async hydrateRedisStateFromAuctionDocument(
|
||||
@@ -2948,7 +2987,7 @@ export class AuctionService {
|
||||
void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => {
|
||||
this.logger.warn(
|
||||
`Auction background Riot refresh failed for ${params.auctionId.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
});
|
||||
@@ -3004,7 +3043,7 @@ export class AuctionService {
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn(
|
||||
`Failed to refresh auction Riot snapshot for ${target.puuid}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
error instanceof Error ? error.message : String(error)
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user