fix: close competition cutover integrity gaps

This commit is contained in:
dahyeon committed 2026-07-12 21:22:22 +00:00
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();
+59 -20
View File
@@ -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)
}`,
);
}
@@ -8,7 +8,11 @@ import type {
} from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service';
import type { InternalGameDetail, InternalRecord } from './match-stats.types';
import {
MATCH_STATS_BUILDER_VERSION,
type InternalGameDetail,
type InternalRecord,
} from './match-stats.types';
function objectives() {
return {
@@ -219,8 +223,9 @@ describe('CommunityStatsService', () => {
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
jest.fn().mockResolvedValue({
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
@@ -275,7 +280,12 @@ describe('CommunityStatsService', () => {
participant.userId = userId.toString();
let resolveFragments:
| ((fragments: Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>) => void)
| ((
fragments: Array<{
matchId: mongoose.Types.ObjectId;
records: InternalRecord[];
}>,
) => void)
| undefined;
const fragmentsPromise = new Promise<
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
@@ -296,8 +306,9 @@ describe('CommunityStatsService', () => {
matchStatsRepository,
{} as MatchStatsService,
);
(service as unknown as { resolveContext: jest.Mock }).resolveContext =
jest.fn().mockResolvedValue({
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
.fn()
.mockResolvedValue({
community: {},
season: {
id: 'all',
@@ -329,4 +340,83 @@ describe('CommunityStatsService', () => {
);
expect(cacheService.set).toHaveBeenCalledTimes(1);
});
it('self-heals Competition fragments when their source revision is stale', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const matches = [{ _id: matchId, competitionId }];
const MatchModel = {
find: jest.fn().mockReturnValue({
sort: jest.fn().mockReturnValue({
limit: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(matches),
}),
}),
}),
}),
};
const CompetitionModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([
{
_id: competitionId,
revision: 7,
projectorVersion: 3,
},
]),
}),
}),
}),
};
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') return Promise.resolve(MatchModel);
if (name === 'competition') return Promise.resolve(CompetitionModel);
throw new Error(`Unexpected model ${name}`);
}),
} as unknown as ConnectionService;
const matchStatsRepository = {
findByCommunity: jest.fn().mockResolvedValue([
{
matchId,
builderVersion: MATCH_STATS_BUILDER_VERSION,
sourceCompetitionId: competitionId,
sourceRevision: 6,
projectorVersion: 3,
},
]),
} as unknown as jest.Mocked<MatchStatsRepository>;
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const service = new CommunityStatsService(
connectionService,
{} as CommunityStatsCacheService,
matchStatsRepository,
matchStatsService,
);
const rebuilt = await (
service as unknown as {
rebuildMissingOrStaleFragments(
communityId: mongoose.Types.ObjectId,
): Promise<number>;
}
).rebuildMissingOrStaleFragments(communityId);
expect(MatchModel.find).toHaveBeenCalledWith({
communityId,
status: { $in: ['finished', 'in-progress'] },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
});
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId);
expect(rebuilt).toBe(1);
});
});
@@ -238,58 +238,56 @@ export class CommunityStatsService {
}
const response: InternalMatchDetailResponse = {
match,
games: gameDetails.map(
(game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
win: team.win,
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex,
side: record.side,
teamPosition: record.teamPosition,
championId: record.championId,
championLevel: record.championLevel,
kills: record.kills,
deaths: record.deaths,
assists: record.assists,
cs: record.cs,
csPerMin: record.csPerMin,
gold: record.gold,
gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare,
killParticipation: record.killParticipation,
visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items,
trinket: record.trinket,
summonerSpells: record.summonerSpells,
perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win,
})),
games: gameDetails.map((game) => ({
gameNumber: game.gameNumber,
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
gameVersion: game.gameVersion,
timeline: game.timeline ?? [],
objectiveEvents: game.objectiveEvents ?? [],
teams: game.teams.map((team) => ({
teamIndex: team.teamIndex,
side: team.side,
win: team.win,
objectives: team.objectives,
bans: team.bans ?? [],
participants: team.participants.map((record) => ({
userId: record.userId,
summonerName: record.summonerName,
tagLine: record.tagLine,
teamIndex: record.teamIndex,
side: record.side,
teamPosition: record.teamPosition,
championId: record.championId,
championLevel: record.championLevel,
kills: record.kills,
deaths: record.deaths,
assists: record.assists,
cs: record.cs,
csPerMin: record.csPerMin,
gold: record.gold,
gpm: record.gpm,
damageDealtToChampions: record.damageDealtToChampions,
damageTaken: record.damageTaken,
damageShare: record.damageShare,
killParticipation: record.killParticipation,
visionScore: record.visionScore,
wardsPlaced: record.wardsPlaced,
wardsKilled: record.wardsKilled,
controlWardsBought: record.controlWardsBought,
firstBloodKill: record.firstBloodKill ?? false,
firstBloodAssist: record.firstBloodAssist ?? false,
items: record.items,
trinket: record.trinket,
summonerSpells: record.summonerSpells,
perks: record.perks,
itemBuild: record.itemBuild ?? [],
skillBuild: record.skillBuild ?? [],
win: record.win,
})),
}),
),
})),
})),
};
await this.cacheService.setDetail(key, response);
return response;
@@ -357,7 +355,7 @@ export class CommunityStatsService {
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
const filteredGames = fragment.gameDetails
.filter((game) => this.isGameInRange(game.gameCreation, context))
.sort((left, right) => left.gameNumber - right.gameNumber);
if (filteredGames.length === 0) continue;
@@ -373,7 +371,7 @@ export class CommunityStatsService {
filteredGames.map((game) => game.gameNumber),
);
records.push(
...(fragment.records as InternalRecord[]).filter((record) =>
...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber),
),
);
@@ -407,11 +405,7 @@ export class CommunityStatsService {
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
const allUserRecords = this.extractUserRecords(
fragments,
userId,
context,
);
const allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
const cursor = params.filters.cursor;
@@ -457,7 +451,7 @@ export class CommunityStatsService {
): InternalRecord[] {
return fragments
.flatMap((fragment) =>
(fragment.records as InternalRecord[]).filter(
fragment.records.filter(
(record) =>
record.userId === userId &&
this.isGameInRange(record.gameCreation, context),
@@ -493,7 +487,7 @@ export class CommunityStatsService {
for (const fragment of fragments) {
detailsByMatchId.set(
fragment.matchId.toString(),
(fragment.gameDetails as InternalGameDetail[]).filter((game) =>
fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
);
@@ -509,11 +503,14 @@ export class CommunityStatsService {
MatchModel.find({
communityId,
status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true },
$or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
})
.sort({ scheduledAt: -1 })
.limit(MAX_MATCH_SCAN)
.select({ _id: 1 })
.select({ _id: 1, competitionId: 1 })
.exec(),
this.matchStatsRepository.findByCommunity({
communityId,
@@ -523,11 +520,45 @@ export class CommunityStatsService {
const fragmentByMatchId = new Map(
fragments.map((fragment) => [fragment.matchId.toString(), fragment]),
);
const competitionIds = matches.flatMap((match) =>
match.competitionId ? [match.competitionId] : [],
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions =
competitionIds.length > 0
? await CompetitionModel.find({ _id: { $in: competitionIds } })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec()
: [];
const competitionById = new Map(
competitions.map((competition) => [
competition._id.toString(),
competition,
]),
);
let rebuilt = 0;
for (const match of matches) {
const fragment = fragmentByMatchId.get(match._id.toString());
if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) {
const competition = match.competitionId
? competitionById.get(match.competitionId.toString())
: undefined;
const sourceIsCurrent = match.competitionId
? Boolean(
competition &&
fragment?.sourceCompetitionId?.toString() ===
competition._id.toString() &&
(fragment.sourceRevision ?? -1) >= competition.revision &&
(fragment.projectorVersion ?? -1) >= competition.projectorVersion,
)
: true;
if (
fragment &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
sourceIsCurrent
) {
continue;
}
@@ -4,6 +4,47 @@ import type { MatchStats } from '../global/database/schema';
import { MatchStatsRepository } from './match-stats.repository';
describe('MatchStatsRepository', () => {
it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => {
const fragment = {
...statsFragment(12),
sourceCompetitionId: undefined,
sourceRevision: undefined,
projectorVersion: undefined,
};
const updateOne = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({ matchedCount: 0 }),
})
.mockReturnValueOnce({
exec: jest
.fn()
.mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.upsert(fragment);
expect(updateOne).toHaveBeenNthCalledWith(
1,
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: false },
);
expect(updateOne).toHaveBeenNthCalledWith(
2,
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
);
});
it('only updates a Competition projection when its revision is not stale', async () => {
const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
@@ -36,6 +77,122 @@ describe('MatchStatsRepository', () => {
{ upsert: false },
);
});
it('converges concurrent initial upserts to the highest Competition revision', async () => {
const older = statsFragment(12);
const newer = {
...statsFragment(13),
matchId: older.matchId,
sourceCompetitionId: older.sourceCompetitionId,
};
let stored: ReturnType<typeof statsFragment> | undefined;
let initialGuardCount = 0;
let releaseInitialGuards!: () => void;
const initialGuardsReady = new Promise<void>((resolve) => {
releaseInitialGuards = resolve;
});
let releaseOlderInsert!: () => void;
const olderInserted = new Promise<void>((resolve) => {
releaseOlderInsert = resolve;
});
const updateOne = jest.fn(
(
_filter: Record<string, unknown>,
update: {
$set?: ReturnType<typeof statsFragment>;
$setOnInsert?: ReturnType<typeof statsFragment>;
},
) => ({
exec: async () => {
const fragment = update.$set ?? update.$setOnInsert!;
if (update.$set && !stored && initialGuardCount < 2) {
initialGuardCount += 1;
if (initialGuardCount === 2) releaseInitialGuards();
await initialGuardsReady;
return { matchedCount: 0, upsertedCount: 0 };
}
if (update.$setOnInsert) {
if (fragment.sourceRevision === 13) await olderInserted;
const existed = stored !== undefined;
if (!stored) stored = fragment;
if (fragment.sourceRevision === 12) releaseOlderInsert();
return {
matchedCount: existed ? 1 : 0,
upsertedCount: existed ? 0 : 1,
};
}
if (
stored &&
stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) &&
stored.sourceRevision! <= fragment.sourceRevision!
) {
stored = fragment;
return { matchedCount: 1, upsertedCount: 0 };
}
return { matchedCount: 0, upsertedCount: 0 };
},
}),
);
const connection = {
getModel: jest.fn().mockResolvedValue({ updateOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await Promise.all([repository.upsert(older), repository.upsert(newer)]);
expect(stored?.sourceRevision).toBe(13);
});
it('guards a zero-game delete so an observed revision cannot remove newer stats', async () => {
const matchId = new Types.ObjectId();
const sourceCompetitionId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteByMatch(matchId, {
sourceCompetitionId,
sourceRevision: 12,
});
expect(deleteOne).toHaveBeenCalledWith({
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: 12 } },
],
},
],
});
});
it('deletes only non-Competition stats during legacy source cleanup', async () => {
const matchId = new Types.ObjectId();
const deleteOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ deletedCount: 0 }),
});
const connection = {
getModel: jest.fn().mockResolvedValue({ deleteOne }),
} as unknown as ConnectionService;
const repository = new MatchStatsRepository(connection);
await repository.deleteLegacyByMatch(matchId);
expect(deleteOne).toHaveBeenCalledWith({
matchId,
sourceCompetitionId: { $exists: false },
});
});
});
function statsFragment(sourceRevision: number) {
@@ -13,6 +13,11 @@ export type MatchStatsDetailFragment = Pick<
'matchId' | 'gameDetails'
>;
export interface MatchStatsDeleteGuard {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
@Injectable()
export class MatchStatsRepository {
constructor(private readonly connectionService: ConnectionService) {}
@@ -25,30 +30,33 @@ export class MatchStatsRepository {
!fragment.sourceCompetitionId ||
fragment.sourceRevision === undefined
) {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
const updated = await MatchStatsModel.updateOne(
{
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment },
{ upsert: true },
{ upsert: false },
).exec();
if (updated.matchedCount > 0) return;
// A legacy builder must never overwrite a Competition-backed fragment
// that appeared while the legacy source was being read.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
return;
}
const revisionGuard = competitionRevisionGuard(fragment);
const updated = await MatchStatsModel.updateOne(
{
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
},
revisionGuard,
{ $set: fragment },
{ upsert: false },
).exec();
@@ -56,16 +64,48 @@ export class MatchStatsRepository {
// If no read model exists, insert it. If a newer revision won the race,
// this filter matches it and $setOnInsert intentionally changes nothing.
try {
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
).exec();
} catch (error) {
if (!isDuplicateKeyError(error)) throw error;
}
// A lower revision can win the initial insert between the guarded miss and
// the upsert. Re-run the monotonic CAS so every concurrent builder converges
// to the highest source revision; a newer winner simply does not match.
await MatchStatsModel.updateOne(
{ matchId: fragment.matchId },
{ $setOnInsert: fragment },
{ upsert: true },
revisionGuard,
{ $set: fragment },
{ upsert: false },
).exec();
}
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
public async deleteByMatch(
matchId: mongoose.Types.ObjectId,
guard?: MatchStatsDeleteGuard,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({ matchId }).exec();
await MatchStatsModel.deleteOne(
guard
? {
matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{
sourceCompetitionId: guard.sourceCompetitionId,
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: guard.sourceRevision } },
],
},
],
}
: { matchId },
).exec();
}
public async deleteByMatches(
@@ -76,6 +116,16 @@ export class MatchStatsRepository {
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
}
public async deleteLegacyByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<void> {
const MatchStatsModel = await this.connectionService.getModel('matchStats');
await MatchStatsModel.deleteOne({
matchId,
sourceCompetitionId: { $exists: false },
}).exec();
}
public async findByMatch(
matchId: mongoose.Types.ObjectId,
): Promise<MatchStatsDocument | null> {
@@ -173,3 +223,32 @@ export class MatchStatsRepository {
return filter;
}
}
function competitionRevisionGuard(
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
) {
return {
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
};
}
function isDuplicateKeyError(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 11_000
);
}
@@ -39,6 +39,57 @@ describe('MatchStatsService', () => {
expect(repository.upsert).not.toHaveBeenCalled();
});
it('revision-guards deletion when a Competition reversal leaves zero games', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [],
projection: { phase: 'ready', games: [] },
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: () => queryResult(match, false) };
}
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert).not.toHaveBeenCalled();
});
it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
@@ -237,6 +288,92 @@ describe('MatchStatsService', () => {
);
});
it('removes a fragment written after its Competition Match was deleted', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 1, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 2, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
id: new mongoose.Types.ObjectId(),
displayNumber: 1,
evidence: { type: 'legacy', legacyReference: 'legacy:1' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
},
],
},
};
const findById = jest
.fn()
.mockReturnValueOnce(queryResult(match, false))
.mockReturnValueOnce(queryResult(null, false));
const findCompetition = jest.fn().mockReturnValue(queryResult(competition));
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: findCompetition };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn().mockResolvedValue(undefined),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.upsert).toHaveBeenCalled();
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert.mock.invocationCallOrder[0]).toBeLessThan(
repository.deleteByMatch.mock.invocationCallOrder[0],
);
});
it('does not rebuild before the requested Competition revision is visible', async () => {
const matchId = new mongoose.Types.ObjectId();
const riotFind = jest.fn();
@@ -48,7 +48,14 @@ export class MatchStatsService {
: undefined;
const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) {
await this.repository.deleteByMatch(matchId);
if (competitionSource) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: competitionSource.sourceCompetitionId,
sourceRevision: competitionSource.sourceRevision,
});
} else {
await this.repository.deleteByMatch(matchId);
}
return;
}
@@ -135,6 +142,11 @@ export class MatchStatsService {
}
: {}),
});
// Source reads and the read-model write are intentionally separated by
// Riot/timeline work. Revalidate after the write so a concurrent aggregate
// deletion cannot resurrect MatchStats after the delete transaction.
await this.removeFragmentIfSourceChanged(matchId, competitionSource);
}
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
@@ -196,6 +208,49 @@ export class MatchStatsService {
? (region as RiotRegionalRoute)
: 'asia';
}
private async removeFragmentIfSourceChanged(
matchId: mongoose.Types.ObjectId,
source:
| {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
| undefined,
): Promise<void> {
const [MatchModel, CompetitionModel] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const [currentMatch, currentCompetition] = await Promise.all([
MatchModel.findById(matchId).exec(),
CompetitionModel.findOne({
matchId,
...(source
? {
_id: source.sourceCompetitionId,
revision: source.sourceRevision,
}
: {}),
})
.lean()
.exec(),
]);
if (source) {
if (!currentMatch || !currentCompetition) {
await this.repository.deleteByMatch(matchId, {
sourceCompetitionId: source.sourceCompetitionId,
sourceRevision: source.sourceRevision,
});
}
return;
}
if (!currentMatch || currentCompetition) {
await this.repository.deleteLegacyByMatch(matchId);
}
}
}
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
@@ -193,8 +193,37 @@ describe('CompetitionBootstrapService', () => {
});
});
it('rejects double elimination until authoritative seeds are persisted', async () => {
const harness = createHarness();
const service = new CompetitionBootstrapService(
harness.connectionService as ConnectionService,
);
await expect(
service.bootstrap(
matchSnapshot({
gameMode: 'double-elimination',
teamCount: 4,
gameCount: 3,
}),
),
).rejects.toMatchObject({
code: 'INVALID_MATCH_TEAM_SNAPSHOT',
httpStatus: 422,
});
expect(harness.connectionService.createSession).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
'the Match lifecycle is still recruiting',
(match) => {
match.status = 'recruiting';
},
],
[
'an active participant is not assigned',
(match) => {
@@ -288,6 +317,8 @@ describe('CompetitionBootstrapService', () => {
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{
_id: MATCH_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
@@ -404,6 +435,8 @@ function matchSnapshot(params: {
return {
_id: MATCH_ID,
communityId: COMMUNITY_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
gameCount: params.gameCount ?? 3,
gameMode: params.gameMode,
...(params.roundRobinMaxRounds === undefined
@@ -5,6 +5,7 @@ import { ConnectionService } from '../global/database/connection.service';
import type {
MatchGameMode,
MatchParticipant,
MatchStatus,
MatchTeam,
} from '../global/database/schema';
import type {
@@ -30,6 +31,8 @@ export interface CompetitionBootstrapMatch {
_id: Types.ObjectId;
communityId: Types.ObjectId;
competitionId?: Types.ObjectId;
status: MatchStatus;
teamBuiltAt: Date;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
@@ -142,6 +145,8 @@ export class CompetitionBootstrapService {
const linkResult = await MatchModel.updateOne(
{
_id: match._id,
status: match.status,
teamBuiltAt: match.teamBuiltAt,
$or: [
{ competitionId: { $exists: false } },
{ competitionId: null },
@@ -206,6 +211,13 @@ function buildCompetitionInsertPayload(
): CompetitionInsertPayload {
assertObjectId(match._id, 'Match ID');
assertObjectId(match.communityId, 'Community ID');
if (match.status === 'recruiting' || !(match.teamBuiltAt instanceof Date)) {
throw new CompetitionBootstrapError(
'INVALID_MATCH_TEAM_SNAPSHOT',
'Competition bootstrap requires a finalized team-built Match lifecycle.',
422,
);
}
assertPositiveInteger(match.gameCount, 'Match game count');
const competitionId = stableObjectId(match._id, 'competition');
@@ -405,7 +417,11 @@ function applySeeds(
): void {
if (match.gameMode !== 'double-elimination') return;
const configuredSeeds = match.doubleElimination?.seeds ?? [];
if (configuredSeeds.length === 0) return;
if (configuredSeeds.length === 0) {
throw invalidTeamSnapshot(
'Double-elimination seeds must be finalized before Competition bootstrap.',
);
}
if (configuredSeeds.length !== teams.length) {
throw invalidTeamSnapshot(
'Double-elimination seeds must include every built team exactly once.',
@@ -106,6 +106,49 @@ describe('CompetitionCommandService', () => {
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('replays a concurrently committed identical command after a duplicate-key race', async () => {
const harness = createHarness();
let committedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(committedReceipt),
);
harness.factModel.insertMany.mockImplementationOnce(
async ([fact]: Array<Record<string, unknown>>) => {
committedReceipt = {
competitionId: COMPETITION_ID,
idempotencyKey: fact.idempotencyKey,
requestHash: fact.requestHash,
commandId: fact.commandId,
revision: fact.revision,
payload: {
projection: PROJECTION,
phase: PROJECTION.phase,
},
};
throw Object.assign(new Error('duplicate command fact'), {
code: 11_000,
});
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(
service.acceptGame(acceptGameCommand()),
).resolves.toMatchObject({
revision: 8,
replayed: true,
});
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('rejects the same Idempotency-Key when its payload hash differs', async () => {
const harness = createHarness();
harness.outboxModel.findOne.mockReturnValue(
@@ -382,6 +425,39 @@ describe('CompetitionCommandService', () => {
{ session: harness.session },
);
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled();
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: reversal.competition.matchId },
{
$pull: {
tournamentCodeIds: {
$in: [reversal.parentCodeId, reversal.childCodeId],
},
},
},
{ session: harness.session },
);
const [, codeReversalPipeline] = harness.tournamentCodeModel.updateMany.mock
.calls[0] as unknown as [
Record<string, unknown>,
Array<Record<string, any>>,
];
expect(codeReversalPipeline[0].$set).toMatchObject({
state: {
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
},
matchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$matchId'],
},
gameNumber: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$gameNumber'],
},
bracketMatchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$bracketMatchId'],
},
reservedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$reservedAt'],
},
});
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: COMPETITION_ID, revision: 7 },
expect.objectContaining({ $inc: { revision: 1 } }),
@@ -390,6 +466,50 @@ describe('CompetitionCommandService', () => {
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('retries a cascade reversal after a transient transaction conflict', async () => {
const reversal = reversalFixture();
const harness = createHarness({
competition: reversal.competition,
facts: reversal.facts,
assignments: reversal.assignments,
});
harness.factModel.insertMany
.mockRejectedValueOnce(
Object.assign(new Error('write conflict'), {
code: 112,
codeName: 'WriteConflict',
}),
)
.mockResolvedValueOnce([]);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const preview = await service.previewSeriesReversal({
competitionId: COMPETITION_ID,
expectedRevision: 7,
seriesId: reversal.parentSeriesId,
mode: 'cascade',
});
await expect(
service.reverseSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:reverse:transient-retry',
actor: { type: 'user', userId: USER_ID },
seriesId: reversal.parentSeriesId,
mode: 'cascade',
reason: 'Wrong result ingestion',
impactHash: preview.impactHash,
}),
).resolves.toMatchObject({ revision: 8, replayed: false });
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
@@ -496,12 +616,18 @@ function createHarness(
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
};
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
competitionFact: factModel,
competitionOutbox: outboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
match: matchModel,
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
@@ -515,6 +641,7 @@ function createHarness(
outboxModel,
assignmentModel,
tournamentCodeModel,
matchModel,
connectionService,
};
}
@@ -612,6 +739,8 @@ function reversalFixture() {
childFactId,
parentGameSlotId,
childGameSlotId,
parentCodeId,
childCodeId,
competition: {
...competitionDocument(7),
seriesGraph: [
@@ -14,6 +14,7 @@ import {
} from './domain/competition-reversal';
type PersistenceId = string | mongoose.Types.ObjectId;
const COMMAND_TRANSACTION_ATTEMPTS = 3;
export type CompetitionCommandActor =
| { type: 'system' }
@@ -211,283 +212,316 @@ export class CompetitionCommandService {
throw invalidCommandError();
}
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
}
try {
session.startTransaction();
const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] =
await Promise.all([
this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'),
]);
const requestHash = requestHashFor(envelope);
const commandId = commandIdFor(envelope);
const receipt = await OutboxModel.findOne({
competitionId: command.competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
command.competitionId,
requestHash,
receipt,
session,
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= COMMAND_TRANSACTION_ATTEMPTS;
attempt += 1
) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
await session.commitTransaction();
return replay;
}
const competition = await CompetitionModel.findById(command.competitionId)
.session(session)
.lean()
.exec();
if (!competition) throw competitionNotFound(command.competitionId);
assertExpectedRevision(competition.revision, command.expectedRevision);
const [existingFacts, assignments] = await Promise.all([
FactModel.find({ competitionId: command.competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
try {
session.startTransaction();
const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] =
await Promise.all([
this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'),
]);
const requestHash = requestHashFor(envelope);
const commandId = commandIdFor(envelope);
const receipt = await OutboxModel.findOne({
competitionId: command.competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec(),
AssignmentModel.find({ competitionId: command.competitionId })
.session(session)
.lean()
.exec() as Promise<AssignmentRecord[]>,
]);
const input = reversalInput(
competition,
command,
existingFacts,
assignments,
);
const preview = assertReversalPreview(input, command.impactHash);
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const occurredAt = command.occurredAt ?? recordedAt;
const rawFacts = buildReversalFacts({
preview,
facts: input.facts,
competitionId: idString(command.competitionId),
commandId,
nextRevision,
actor: toPlain(command.actor) as Readonly<Record<string, unknown>>,
reason: command.reason.trim(),
occurredAt,
});
const reversalFacts = rawFacts.map((rawFact) =>
persistenceReversalFact(rawFact, command, commandId, requestHash),
);
const projection = projectCompetition({
competitionId: idString(command.competitionId),
revision: nextRevision,
projectorVersion: competition.projectorVersion,
teams: toPlain(competition.teams) as never,
format: toPlain(competition.format) as never,
seriesGraph: toPlain(competition.seriesGraph) as never,
facts: [...existingFacts, ...reversalFacts].map(factForProjection),
});
await FactModel.insertMany(reversalFacts, { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: command.competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
)
.lean()
.exec();
if (!updated) throw staleRevisionError(command.expectedRevision);
await this.applyReversalAssignments(
command.competitionId,
preview,
assignments,
commandId,
recordedAt,
session,
);
await OutboxModel.insertMany(
[
buildOutbox(
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
command.competitionId,
envelope,
commandId,
requestHash,
nextRevision,
reversalFacts,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
throw error;
} finally {
await session.endSession();
receipt,
session,
);
await session.commitTransaction();
return replay;
}
const competition = await CompetitionModel.findById(
command.competitionId,
)
.session(session)
.lean()
.exec();
if (!competition) throw competitionNotFound(command.competitionId);
assertExpectedRevision(competition.revision, command.expectedRevision);
const [existingFacts, assignments] = await Promise.all([
FactModel.find({ competitionId: command.competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec(),
AssignmentModel.find({ competitionId: command.competitionId })
.session(session)
.lean()
.exec() as Promise<AssignmentRecord[]>,
]);
const input = reversalInput(
competition,
command,
existingFacts,
assignments,
);
const preview = assertReversalPreview(input, command.impactHash);
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const occurredAt = command.occurredAt ?? recordedAt;
const rawFacts = buildReversalFacts({
preview,
facts: input.facts,
competitionId: idString(command.competitionId),
commandId,
nextRevision,
actor: toPlain(command.actor) as Readonly<Record<string, unknown>>,
reason: command.reason.trim(),
occurredAt,
});
const reversalFacts = rawFacts.map((rawFact) =>
persistenceReversalFact(rawFact, command, commandId, requestHash),
);
const projection = projectCompetition({
competitionId: idString(command.competitionId),
revision: nextRevision,
projectorVersion: competition.projectorVersion,
teams: toPlain(competition.teams) as never,
format: toPlain(competition.format) as never,
seriesGraph: toPlain(competition.seriesGraph) as never,
facts: [...existingFacts, ...reversalFacts].map(factForProjection),
});
await FactModel.insertMany(reversalFacts, { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: command.competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
)
.lean()
.exec();
if (!updated) throw staleRevisionError(command.expectedRevision);
await this.applyReversalAssignments(
command.competitionId,
competition.matchId,
preview,
assignments,
commandId,
recordedAt,
session,
);
await OutboxModel.insertMany(
[
buildOutbox(
command.competitionId,
envelope,
commandId,
requestHash,
nextRevision,
reversalFacts,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
attempt < COMMAND_TRANSACTION_ATTEMPTS &&
isRetryableCommandTransactionError(error)
) {
lastRetryableError = error;
continue;
}
throw error;
} finally {
await session.endSession();
}
}
throw lastRetryableError;
}
private async runCommand(
command: CommandEnvelope,
): Promise<CompetitionCommandResult> {
validateEnvelope(command);
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
}
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= COMMAND_TRANSACTION_ATTEMPTS;
attempt += 1
) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
}
try {
session.startTransaction();
const CompetitionModel =
await this.connectionService.getModel('competition');
const FactModel =
await this.connectionService.getModel('competitionFact');
const OutboxModel =
await this.connectionService.getModel('competitionOutbox');
const requestHash = requestHashFor(command);
const commandId = commandIdFor(command);
const competitionId = command.competitionId;
try {
session.startTransaction();
const CompetitionModel =
await this.connectionService.getModel('competition');
const FactModel =
await this.connectionService.getModel('competitionFact');
const OutboxModel =
await this.connectionService.getModel('competitionOutbox');
const requestHash = requestHashFor(command);
const commandId = commandIdFor(command);
const competitionId = command.competitionId;
const receipt = await OutboxModel.findOne({
competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
const receipt = await OutboxModel.findOne({
competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
competitionId,
requestHash,
receipt,
session,
);
await session.commitTransaction();
return replay;
}
const competition = await CompetitionModel.findById(competitionId)
.session(session)
.lean()
.exec();
if (!competition) {
throw new CompetitionCommandError(
'COMPETITION_NOT_FOUND',
'Competition not found.',
404,
{ competitionId: idString(competitionId) },
);
}
assertExpectedRevision(competition.revision, command.expectedRevision);
const existingFacts = await FactModel.find({ competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const fact = buildFact(
command,
commandId,
requestHash,
receipt,
session,
nextRevision,
recordedAt,
);
const projection = projectCompetition({
competitionId: idString(competitionId),
revision: nextRevision,
projectorVersion: competition.projectorVersion,
teams: toPlain(competition.teams) as never,
format: toPlain(competition.format) as never,
seriesGraph: toPlain(competition.seriesGraph) as never,
facts: [...existingFacts, fact].map(factForProjection),
});
await FactModel.insertMany([fact], { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
)
.lean()
.exec();
if (!updated) {
throw staleRevisionError(command.expectedRevision);
}
await this.applyTournamentCode(command, commandId, recordedAt, session);
await OutboxModel.insertMany(
[
buildOutbox(
competitionId,
command,
commandId,
requestHash,
nextRevision,
fact,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return replay;
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
attempt < COMMAND_TRANSACTION_ATTEMPTS &&
isRetryableCommandTransactionError(error)
) {
lastRetryableError = error;
continue;
}
throw error;
} finally {
await session.endSession();
}
const competition = await CompetitionModel.findById(competitionId)
.session(session)
.lean()
.exec();
if (!competition) {
throw new CompetitionCommandError(
'COMPETITION_NOT_FOUND',
'Competition not found.',
404,
{ competitionId: idString(competitionId) },
);
}
assertExpectedRevision(competition.revision, command.expectedRevision);
const existingFacts = await FactModel.find({ competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const fact = buildFact(
command,
commandId,
requestHash,
nextRevision,
recordedAt,
);
const projection = projectCompetition({
competitionId: idString(competitionId),
revision: nextRevision,
projectorVersion: competition.projectorVersion,
teams: toPlain(competition.teams) as never,
format: toPlain(competition.format) as never,
seriesGraph: toPlain(competition.seriesGraph) as never,
facts: [...existingFacts, fact].map(factForProjection),
});
await FactModel.insertMany([fact], { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
)
.lean()
.exec();
if (!updated) {
throw staleRevisionError(command.expectedRevision);
}
await this.applyTournamentCode(command, commandId, recordedAt, session);
await OutboxModel.insertMany(
[
buildOutbox(
competitionId,
command,
commandId,
requestHash,
nextRevision,
fact,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
throw error;
} finally {
await session.endSession();
}
throw lastRetryableError;
}
private async replay(
@@ -595,6 +629,7 @@ export class CompetitionCommandService {
private async applyReversalAssignments(
competitionId: PersistenceId,
matchId: PersistenceId,
preview: SeriesReversalPreview,
assignments: AssignmentRecord[],
commandId: string,
@@ -638,6 +673,14 @@ export class CompetitionCommandService {
tournamentCodeReversalStatePipeline(recordedAt),
{ session },
);
const MatchModel = (await this.connectionService.getModel(
'match',
)) as mongoose.Model<any>;
await MatchModel.updateOne(
{ _id: matchId },
{ $pull: { tournamentCodeIds: { $in: codeIds } } },
{ session },
);
}
}
@@ -956,6 +999,22 @@ function tournamentCodeReversalStatePipeline(
releasedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$releasedAt'],
},
matchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$matchId'],
},
gameNumber: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$gameNumber'],
},
bracketMatchId: {
$cond: [
{ $eq: ['$state', 'reserved'] },
'$$REMOVE',
'$bracketMatchId',
],
},
reservedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$reservedAt'],
},
},
},
];
@@ -968,6 +1027,21 @@ function persistenceObjectId(value: PersistenceId): PersistenceId {
: value;
}
function isRetryableCommandTransactionError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.code === 11_000 ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict' ||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'),
);
}
function competitionNotFound(
competitionId: PersistenceId,
): CompetitionCommandError {
@@ -1,29 +1,24 @@
import { ForbiddenException } from '@nestjs/common';
import { ConflictException, ForbiddenException } from '@nestjs/common';
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionQueryService', () => {
it('bootstraps a built Match once when its Competition is first read', async () => {
it('does not let a public read race the team-build bootstrap workflow', async () => {
const harness = createHarness({ competition: null });
const bootstrapped = competitionDocument();
harness.bootstrapService.bootstrap.mockResolvedValue(bootstrapped);
const service = createService(harness);
const result = await service.getCompetition({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
});
await expect(
service.getCompetition({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
expect(harness.matchModel.findOne).toHaveBeenCalledWith({
_id: MATCH_ID,
communityId: COMMUNITY_ID,
});
expect(harness.bootstrapService.bootstrap).toHaveBeenCalledWith(
expect.objectContaining({ _id: MATCH_ID, status: 'team-built' }),
);
expect(result).toBe(bootstrapped);
});
it('returns an explicit team view with codes only for the callers team', async () => {
@@ -56,6 +51,7 @@ describe('CompetitionQueryService', () => {
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({
_id: { $in: [TEAM_A_CODE_ID] },
state: { $in: ['reserved', 'used'] },
});
});
@@ -71,6 +67,20 @@ describe('CompetitionQueryService', () => {
).rejects.toBeInstanceOf(ForbiddenException);
});
it('does not expose a stale code whose active assignment no longer matches', async () => {
const harness = createHarness();
harness.tournamentCodeModel.find.mockReturnValueOnce(queryResult([]));
const service = createService(harness);
await expect(
service.getTeamView({
communityId: COMMUNITY_ID,
matchId: MATCH_ID,
userId: TEAM_A_USER_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
});
it('pages facts in immutable revision order using an opaque cursor', async () => {
const harness = createHarness();
harness.factModel.find.mockReturnValueOnce(
@@ -116,7 +126,6 @@ const GAME_SLOT_ID = 'slot-1';
function createService(harness: ReturnType<typeof createHarness>) {
return new CompetitionQueryService(
harness.connectionService as ConnectionService,
harness.bootstrapService as unknown as CompetitionBootstrapService,
);
}
@@ -167,11 +176,15 @@ function createHarness(options: { competition?: unknown } = {}) {
{
_id: TEAM_A_CODE_ID,
code: 'TEAM-A-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
{
_id: TEAM_B_CODE_ID,
code: 'OPPONENT-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
]),
@@ -196,7 +209,6 @@ function createHarness(options: { competition?: unknown } = {}) {
connectionService: {
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
},
bootstrapService: { bootstrap: jest.fn() },
};
}
@@ -13,7 +13,6 @@ import {
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import type { Competition, CompetitionFact } from './competition.schema';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
type PersistenceId = string | mongoose.Types.ObjectId;
type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId };
@@ -30,25 +29,12 @@ interface CompetitionProjectionSource {
@Injectable()
export class CompetitionQueryService {
constructor(
private readonly connectionService: ConnectionService,
private readonly bootstrapService: CompetitionBootstrapService,
) {}
constructor(private readonly connectionService: ConnectionService) {}
/** Resolve the one-to-one aggregate, lazily freezing a completed team build. */
/** Resolve the aggregate created by the finalized team-build workflow. */
public async getCompetition(
scope: CompetitionScope,
): Promise<CompetitionRecord> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
matchId: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (existing) return existing as CompetitionRecord;
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({
_id: scope.matchId,
@@ -66,7 +52,19 @@ export class CompetitionQueryService {
'Competition is unavailable until team building is complete.',
);
}
return this.bootstrapService.bootstrap(match as never);
const CompetitionModel =
await this.connectionService.getModel('competition');
const existing = await CompetitionModel.findOne({
matchId: scope.matchId,
communityId: scope.communityId,
})
.lean()
.exec();
if (existing) return existing as CompetitionRecord;
throw new ConflictException(
'Competition is still being initialized by the team-build workflow.',
);
}
public async getTeamView(
@@ -126,7 +124,10 @@ export class CompetitionQueryService {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = codeIds.length
? await TournamentCodeModel.find({ _id: { $in: codeIds } })
? await TournamentCodeModel.find({
_id: { $in: codeIds },
state: { $in: ['reserved', 'used'] },
})
.lean()
.exec()
: [];
@@ -150,6 +151,17 @@ export class CompetitionQueryService {
const code = assignment
? codeById.get(idString(assignment.tournamentCodeId))
: undefined;
if (
assignment &&
(!code ||
code.state !== assignment.state ||
!code.matchId ||
!sameId(code.matchId, competition.matchId))
) {
throw new ConflictException(
'Tournament Code assignment is inconsistent and cannot be exposed.',
);
}
return {
gameSlotId: gameSlotId as never,
seriesId: idString(slot.seriesId as PersistenceId) as never,
@@ -1,4 +1,5 @@
import {
COMPETITION_OUTBOX_STATES,
CompetitionFactSchema,
CompetitionOutboxSchema,
CompetitionSchema,
@@ -93,6 +94,13 @@ describe('Competition persistence schemas', () => {
]);
});
it('defines a terminal dead-letter state for poison outbox events', () => {
expect(COMPETITION_OUTBOX_STATES).toContain('dead-letter');
expect(CompetitionOutboxSchema.path('state').options.enum).toContain(
'dead-letter',
);
});
it('allows only one active assignment for a code or GameSlot', () => {
expectIndexes(TournamentCodeAssignmentSchema, [
{
@@ -20,6 +20,7 @@ export const COMPETITION_OUTBOX_STATES = [
'pending',
'published',
'failed',
'dead-letter',
] as const;
export type CompetitionOutboxState = (typeof COMPETITION_OUTBOX_STATES)[number];
@@ -32,6 +33,110 @@ export const TOURNAMENT_CODE_ASSIGNMENT_STATES = [
export type TournamentCodeAssignmentState =
(typeof TOURNAMENT_CODE_ASSIGNMENT_STATES)[number];
export interface CompetitionDomainInvariantIndex {
collection:
| 'match'
| 'competition'
| 'competition_fact'
| 'competition_outbox'
| 'tournament_code_assignment';
key: mongoose.IndexDefinition;
options: mongoose.IndexOptions & { name: string; unique: true };
}
/**
* Database-enforced Competition identities. Runtime schemas and the one-off
* migration consume this same list so production cannot silently run with a
* weaker set of uniqueness guarantees than command handling expects.
*/
export const COMPETITION_DOMAIN_INVARIANT_INDEXES: CompetitionDomainInvariantIndex[] =
[
{
collection: 'match',
key: { competitionId: 1 },
options: {
name: 'competitionId_1',
unique: true,
partialFilterExpression: {
competitionId: { $type: 'objectId' },
},
},
},
{
collection: 'competition',
key: { matchId: 1 },
options: { name: 'matchId_1', unique: true },
},
{
collection: 'competition_fact',
key: { competitionId: 1, revision: 1, ordinalWithinRevision: 1 },
options: {
name: 'competitionId_1_revision_1_ordinalWithinRevision_1',
unique: true,
},
},
{
collection: 'competition_fact',
key: { competitionId: 1, commandId: 1, ordinalWithinRevision: 1 },
options: {
name: 'competitionId_1_commandId_1_ordinalWithinRevision_1',
unique: true,
},
},
{
collection: 'competition_fact',
key: { 'evidence.riotMatchId': 1 },
options: {
name: 'evidence.riotMatchId_1',
unique: true,
partialFilterExpression: {
type: 'game-accepted',
'evidence.riotMatchId': { $type: 'string' },
},
},
},
{
collection: 'competition_outbox',
key: { eventId: 1 },
options: { name: 'eventId_1', unique: true },
},
{
collection: 'competition_outbox',
key: { competitionId: 1, idempotencyKey: 1 },
options: {
name: 'competitionId_1_idempotencyKey_1',
unique: true,
},
},
{
collection: 'tournament_code_assignment',
key: { gameSlotId: 1 },
options: {
name: 'gameSlotId_1',
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
collection: 'tournament_code_assignment',
key: { tournamentCodeId: 1 },
options: {
name: 'tournamentCodeId_1',
unique: true,
partialFilterExpression: { state: { $in: ['reserved', 'used'] } },
},
},
{
collection: 'tournament_code_assignment',
key: { riotMatchId: 1 },
options: {
name: 'riotMatchId_1',
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
},
];
export interface CompetitionTeamMemberSnapshot {
userId: mongoose.Types.ObjectId;
displayName: string;
@@ -200,7 +305,7 @@ export const CompetitionSchema: mongoose.Schema<Competition> =
{ timestamps: true, collection: 'competition' },
);
CompetitionSchema.index({ matchId: 1 }, { unique: true });
applyCompetitionDomainInvariantIndexes(CompetitionSchema, 'competition');
CompetitionSchema.index({ communityId: 1, phase: 1, updatedAt: -1 });
export const CompetitionFactSchema = new Schema<CompetitionFact>(
@@ -238,23 +343,9 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
{ timestamps: true, collection: 'competition_fact' },
);
CompetitionFactSchema.index(
{ competitionId: 1, revision: 1, ordinalWithinRevision: 1 },
{ unique: true },
);
CompetitionFactSchema.index(
{ competitionId: 1, commandId: 1, ordinalWithinRevision: 1 },
{ unique: true },
);
CompetitionFactSchema.index(
{ 'evidence.riotMatchId': 1 },
{
unique: true,
partialFilterExpression: {
type: 'game-accepted',
'evidence.riotMatchId': { $type: 'string' },
},
},
applyCompetitionDomainInvariantIndexes(
CompetitionFactSchema,
'competition_fact',
);
CompetitionFactSchema.index({ competitionId: 1, seriesId: 1, recordedAt: 1 });
@@ -286,12 +377,11 @@ export const CompetitionOutboxSchema = new Schema<CompetitionOutbox>(
{ timestamps: true, collection: 'competition_outbox' },
);
CompetitionOutboxSchema.index({ eventId: 1 }, { unique: true });
CompetitionOutboxSchema.index({ state: 1, availableAt: 1 });
CompetitionOutboxSchema.index(
{ competitionId: 1, idempotencyKey: 1 },
{ unique: true },
applyCompetitionDomainInvariantIndexes(
CompetitionOutboxSchema,
'competition_outbox',
);
CompetitionOutboxSchema.index({ state: 1, availableAt: 1 });
export const TournamentCodeAssignmentSchema =
new Schema<TournamentCodeAssignment>(
@@ -323,30 +413,22 @@ export const TournamentCodeAssignmentSchema =
{ timestamps: true, collection: 'tournament_code_assignment' },
);
const activeAssignmentFilter = { state: { $in: ['reserved', 'used'] } };
TournamentCodeAssignmentSchema.index(
{ gameSlotId: 1 },
{
unique: true,
partialFilterExpression: activeAssignmentFilter,
},
);
TournamentCodeAssignmentSchema.index(
{ tournamentCodeId: 1 },
{
unique: true,
partialFilterExpression: activeAssignmentFilter,
},
);
TournamentCodeAssignmentSchema.index(
{ riotMatchId: 1 },
{
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
applyCompetitionDomainInvariantIndexes(
TournamentCodeAssignmentSchema,
'tournament_code_assignment',
);
TournamentCodeAssignmentSchema.index({ competitionId: 1, state: 1 });
export function applyCompetitionDomainInvariantIndexes(
schema: mongoose.Schema,
collection: CompetitionDomainInvariantIndex['collection'],
): void {
for (const index of COMPETITION_DOMAIN_INVARIANT_INDEXES) {
if (index.collection !== collection) continue;
schema.index(index.key, index.options);
}
}
export const competitionModelDefinitions: Array<{
name: string;
schema: mongoose.Schema;
@@ -307,6 +307,114 @@ describe('projectCompetition', () => {
expect(projection.games).toEqual([]);
});
it('rejects an accepted game that targets a Series outside the graph', () => {
const competitionId = 'competition-unknown-game-series';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const accepted = acceptedGameFactory(competitionId)(
seriesGraph[0],
1,
'team-1',
'team-2',
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, seriesId: 'series-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SERIES_MISMATCH',
}),
);
});
it('rejects an accepted game that targets an unknown GameSlot', () => {
const competitionId = 'competition-unknown-game-slot';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
const accepted = acceptedGameFactory(competitionId)(
seriesGraph[0],
1,
'team-1',
'team-2',
'team-1',
);
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [{ ...accepted, gameSlotId: 'slot-does-not-exist' }],
}),
).toThrow(
expect.objectContaining({
code: 'GAME_SLOT_INVALID',
}),
);
});
it('rejects an adjudication that targets a Series outside the graph', () => {
const competitionId = 'competition-unknown-adjudication-series';
const teams = [seededTeam('team-1', 1), seededTeam('team-2', 2)];
const format = {
type: 'paired-series' as const,
rule: fixedGames(1),
};
const seriesGraph = generateSeriesGraph({ competitionId, teams, format });
expect(() =>
projectCompetition({
competitionId,
revision: 1,
projectorVersion: 1,
teams,
format,
seriesGraph,
facts: [
{
id: 'fact-unknown-adjudication-series',
type: 'series-adjudicated',
competitionId,
revision: 1,
ordinalWithinRevision: 1,
commandId: 'command-unknown-adjudication-series',
schemaVersion: 1,
actor: { type: 'user' },
occurredAt: new Date('2026-07-12T00:00:01.000Z'),
recordedAt: new Date('2026-07-12T00:00:02.000Z'),
seriesId: 'series-does-not-exist',
decision: { type: 'administrative', winnerTeamId: 'team-1' },
reason: 'Manual correction',
},
],
}),
).toThrow(
expect.objectContaining({
code: 'ADJUDICATION_INVALID',
}),
);
});
it('completes an eight-team double elimination with shared elimination-round placements', () => {
const competitionId = 'competition-eight-team-completion';
const teams = Array.from({ length: 8 }, (_, index) =>
@@ -1,3 +1,4 @@
import { assertCompetitionInvariant } from './domain-error';
import type {
CompetitionGraphFormat,
CompetitionGraphTeam,
@@ -130,6 +131,7 @@ export interface CompetitionProjection {
export function projectCompetition(
input: ProjectCompetitionInput,
): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>();
for (const team of input.teams) {
@@ -279,6 +281,68 @@ export function projectCompetition(
}
}
function assertPrimaryFactTargetsGraph(
graph: readonly SeriesDefinition[],
facts: readonly unknown[],
): void {
const definitionsById = new Map(
graph.map((definition) => [definition.id, definition]),
);
for (const fact of facts) {
if (!isRecord(fact)) continue;
if (fact.type === 'game-accepted') {
const seriesId =
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
const definition = seriesId ? definitionsById.get(seriesId) : undefined;
assertCompetitionInvariant(
definition !== undefined,
'GAME_SERIES_MISMATCH',
`Accepted game targets an unknown Series ${String(fact.seriesId)}`,
{ factId: fact.id, seriesId: fact.seriesId },
);
const gameSlot = definition.gameSlots.find(
({ id }) => id === fact.gameSlotId,
);
assertCompetitionInvariant(
gameSlot !== undefined,
'GAME_SLOT_INVALID',
`Accepted game targets an unknown GameSlot ${String(fact.gameSlotId)}`,
{
factId: fact.id,
seriesId: definition.id,
gameSlotId: fact.gameSlotId,
},
);
assertCompetitionInvariant(
gameSlot.ordinal === fact.ordinal,
'GAME_ORDINAL_INVALID',
`Accepted game ordinal does not match GameSlot ${gameSlot.id}`,
{
factId: fact.id,
gameSlotId: gameSlot.id,
expectedOrdinal: gameSlot.ordinal,
actualOrdinal: fact.ordinal,
},
);
continue;
}
if (fact.type === 'series-adjudicated') {
const seriesId =
typeof fact.seriesId === 'string' ? fact.seriesId : undefined;
assertCompetitionInvariant(
seriesId !== undefined && definitionsById.has(seriesId),
'ADJUDICATION_INVALID',
`Adjudication targets an unknown Series ${String(fact.seriesId)}`,
{ factId: fact.id, seriesId: fact.seriesId },
);
}
}
}
function asProjectorDefinition(
definition: SeriesDefinition,
): SeriesDefinitionLike {
@@ -36,6 +36,7 @@ describe('migrateCompetitionDomain', () => {
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(0);
expect(db.createdIndexes).toHaveLength(0);
});
it('applies one Match atomically and converges on an already-applied replay', async () => {
@@ -181,6 +182,309 @@ describe('migrateCompetitionDomain', () => {
});
expect(db.writeCount).toBe(0);
});
it('ensures every Competition unique or partial index before the first apply write', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive()],
tournamentCode: [usedTournamentCode(match)],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.indexPreflight).toMatchObject({
status: 'ensured',
requiredIndexes: 10,
conflicts: [],
});
expect(result.indexPreflight.ensuredIndexes).toHaveLength(10);
expect(db.createdIndexes).toHaveLength(10);
expect(db.createdIndexes).toEqual(
expect.arrayContaining([
expect.objectContaining({
collection: 'match',
key: { competitionId: 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: {
competitionId: { $type: 'objectId' },
},
}),
}),
expect.objectContaining({
collection: 'competition',
key: { matchId: 1 },
options: expect.objectContaining({ unique: true }),
}),
expect.objectContaining({
collection: 'competition_fact',
key: { 'evidence.riotMatchId': 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: expect.any(Object),
}),
}),
expect.objectContaining({
collection: 'tournament_code_assignment',
key: { gameSlotId: 1 },
options: expect.objectContaining({
unique: true,
partialFilterExpression: expect.any(Object),
}),
}),
]),
);
expect(db.operations.indexOf('create-index')).toBeLessThan(
db.operations.indexOf('write'),
);
});
it('blocks apply with a machine-readable report when a required index cannot be created', async () => {
const match = readyMatch();
const db = new MemoryMigrationDb({ match: [match] });
db.indexCreationError = Object.assign(
new Error('E11000 duplicate key while building competitionId_1'),
{
code: 11000,
keyPattern: { competitionId: 1 },
keyValue: { competitionId: match._id },
},
);
const startSession = jest.fn(() => Promise.resolve(new FakeSession()));
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession,
});
expect(result.indexPreflight).toMatchObject({
status: 'blocked',
conflicts: [
expect.objectContaining({
collection: 'match',
code: 11000,
keyValue: {
competitionId: (match._id as mongoose.Types.ObjectId).toHexString(),
},
}),
],
});
expect(result.matches).toEqual([]);
expect(result.summary.scanned).toBe(0);
expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0);
});
it('quarantines a later Match that reuses an already accepted global Riot identity', async () => {
const firstMatch = readyMatch('KR_SHARED_MIGRATION');
const secondMatch = readyMatch('KR_SHARED_MIGRATION');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_SHARED_MIGRATION')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_SHARED_MIGRATION'),
usedTournamentCode(secondMatch, 'KR_SHARED_MIGRATION'),
],
});
const result = await migrateCompetitionDomain(db, {
dryRun: false,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(result.summary).toMatchObject({ applied: 1, quarantined: 1 });
expect(result.matches).toContainEqual(
expect.objectContaining({
status: 'quarantined',
reasons: expect.arrayContaining([
expect.objectContaining({ code: 'GLOBAL_UNIQUE_INDEX_CONFLICT' }),
]),
}),
);
expect(db.docs('competition_fact')).toHaveLength(1);
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
});
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
const firstMatch = readyMatch('KR_BATCH_1');
const secondMatch = readyMatch('KR_BATCH_2');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_BATCH_1'), riotArchive('KR_BATCH_2')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_BATCH_1'),
usedTournamentCode(secondMatch, 'KR_BATCH_2'),
],
});
const first = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
const second = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(first.summary).toMatchObject({ scanned: 1, applied: 1 });
expect(first.resume).toMatchObject({
strategy: 'checkpoint',
hasMore: true,
completed: false,
});
expect(second.summary).toMatchObject({ scanned: 1, applied: 1 });
expect(second.matches[0].matchId).not.toBe(first.matches[0].matchId);
expect(second.resume).toMatchObject({
strategy: 'checkpoint',
startedAfterMatchId: first.matches[0].matchId,
hasMore: false,
completed: true,
});
expect(db.docs('competition')).toHaveLength(2);
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
});
it('does not let an apply checkpoint silently narrow a later dry-run', async () => {
const firstMatch = readyMatch('KR_DRY_RUN_1');
const secondMatch = readyMatch('KR_DRY_RUN_2');
const db = new MemoryMigrationDb({
match: [firstMatch, secondMatch],
riotMatch: [riotArchive('KR_DRY_RUN_1'), riotArchive('KR_DRY_RUN_2')],
tournamentCode: [
usedTournamentCode(firstMatch, 'KR_DRY_RUN_1'),
usedTournamentCode(secondMatch, 'KR_DRY_RUN_2'),
],
});
const applied = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
const dryRun = await migrateCompetitionDomain(db, {
dryRun: true,
limit: 1,
});
expect(dryRun.resume.strategy).toBe('none');
expect(dryRun.matches[0].matchId).toBe(applied.matches[0].matchId);
});
it('does not advance a limited-run checkpoint past a failed Match', async () => {
const match = readyMatch('KR_RETRY_AFTER_FAILURE');
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_RETRY_AFTER_FAILURE')],
tournamentCode: [usedTournamentCode(match, 'KR_RETRY_AFTER_FAILURE')],
});
const failed = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(undefined),
});
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
expect(failed.resume).toMatchObject({
strategy: 'checkpoint',
hasMore: true,
completed: false,
});
expect(db.docs('competition_migration_checkpoint')).toHaveLength(0);
const retried = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(db.docs('competition_migration_checkpoint')).toHaveLength(1);
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
});
it('durably overrides a later checkpoint before an explicit earlier retry can fail', async () => {
const retryMatch = readyMatch('KR_EXPLICIT_RETRY');
const laterMatch = readyMatch('KR_LATER_CHECKPOINT');
const explicitAfter = '000000000000000000000000';
const migrationRunId = '20260712-competition-domain';
const db = new MemoryMigrationDb({
match: [retryMatch, laterMatch],
riotMatch: [
riotArchive('KR_EXPLICIT_RETRY'),
riotArchive('KR_LATER_CHECKPOINT'),
],
tournamentCode: [
usedTournamentCode(retryMatch, 'KR_EXPLICIT_RETRY'),
usedTournamentCode(laterMatch, 'KR_LATER_CHECKPOINT'),
],
competition_migration_checkpoint: [
{
_id: migrationRunId,
migrationRunId,
lastMatchId: laterMatch._id,
status: 'running',
},
],
});
const failed = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
afterMatchId: explicitAfter,
startSession: () => Promise.resolve(undefined),
});
expect(failed.summary).toMatchObject({ scanned: 1, failed: 1 });
expect(
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
).toBe(explicitAfter);
const retried = await migrateCompetitionDomain(db, {
dryRun: false,
limit: 1,
startSession: () => Promise.resolve(new FakeSession()),
});
expect(retried.matches[0].matchId).toBe(failed.matches[0].matchId);
expect(retried.summary).toMatchObject({ scanned: 1, applied: 1 });
});
it('does not persist an explicit checkpoint override during dry-run', async () => {
const match = readyMatch('KR_DRY_EXPLICIT_CURSOR');
const migrationRunId = '20260712-competition-domain';
const persistedCheckpoint = objectId();
const db = new MemoryMigrationDb({
match: [match],
riotMatch: [riotArchive('KR_DRY_EXPLICIT_CURSOR')],
tournamentCode: [usedTournamentCode(match, 'KR_DRY_EXPLICIT_CURSOR')],
competition_migration_checkpoint: [
{
_id: migrationRunId,
migrationRunId,
lastMatchId: persistedCheckpoint,
status: 'running',
},
],
});
await migrateCompetitionDomain(db, {
dryRun: true,
limit: 1,
afterMatchId: '000000000000000000000000',
});
expect(
String(db.docs('competition_migration_checkpoint')[0].lastMatchId),
).toBe(persistedCheckpoint.toHexString());
expect(db.writeCount).toBe(0);
});
});
class FakeSession implements CompetitionDomainMigrationSession {
@@ -211,6 +515,13 @@ type AnyDoc = Record<string, any> & { _id: unknown };
class MemoryMigrationDb implements CompetitionDomainMigrationDb {
private readonly collections = new Map<string, AnyDoc[]>();
public writeCount = 0;
public readonly createdIndexes: Array<{
collection: string;
key: Record<string, unknown>;
options: Record<string, unknown>;
}> = [];
public readonly operations: string[] = [];
public indexCreationError?: Error;
constructor(seed: Record<string, AnyDoc[]> = {}) {
for (const [name, docs] of Object.entries(seed)) {
@@ -227,6 +538,23 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
collection(name: string) {
const owner = this;
return {
createIndex(
key: Record<string, unknown>,
options: Record<string, unknown>,
) {
owner.operations.push('create-index');
if (owner.indexCreationError) {
const error = owner.indexCreationError;
owner.indexCreationError = undefined;
return Promise.reject(error);
}
owner.createdIndexes.push({ collection: name, key, options });
return Promise.resolve(
typeof options.name === 'string'
? options.name
: Object.keys(key).join('_'),
);
},
find(filter: Record<string, unknown>) {
return new MemoryCursor(() =>
owner.docs(name).filter((doc) => matches(doc, filter)),
@@ -240,6 +568,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
update: Record<string, Record<string, unknown>>,
options: { upsert?: boolean } = {},
) {
owner.operations.push('write');
owner.writeCount += 1;
const docs = owner.docs(name);
let doc = docs.find((candidate) => matches(candidate, filter));
@@ -251,6 +580,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
if (!doc) return { matchedCount: 0, modifiedCount: 0 };
if (inserted) Object.assign(doc, update.$setOnInsert ?? {});
Object.assign(doc, update.$set ?? {});
for (const field of Object.keys(update.$unset ?? {})) delete doc[field];
return {
matchedCount: inserted ? 0 : 1,
modifiedCount: 1,
@@ -258,6 +588,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
};
},
async deleteOne(filter: Record<string, unknown>) {
owner.operations.push('write');
owner.writeCount += 1;
const docs = owner.docs(name);
const index = docs.findIndex((doc) => matches(doc, filter));
@@ -318,6 +649,9 @@ function matches(doc: AnyDoc, filter: Record<string, unknown>): boolean {
sameValue(actual, candidate),
);
}
if ('$gt' in expected) {
return String(actual) > String(expected.$gt);
}
}
return sameValue(actual, expected);
});
@@ -348,7 +682,7 @@ function isRecord(value: unknown): value is Record<string, any> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function readyMatch(): AnyDoc {
function readyMatch(riotMatchId = 'KR_MIGRATION_1'): AnyDoc {
const matchId = objectId();
const codeId = objectId();
return {
@@ -362,11 +696,11 @@ function readyMatch(): AnyDoc {
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
tournamentCodeIds: [codeId],
result: {
riotMatchIds: ['KR_MIGRATION_1'],
riotMatchIds: [riotMatchId],
games: [
{
gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1',
riotMatchId,
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
@@ -383,23 +717,26 @@ function readyMatch(): AnyDoc {
};
}
function usedTournamentCode(match = readyMatch()): AnyDoc {
function usedTournamentCode(
match = readyMatch(),
riotMatchId = 'KR_MIGRATION_1',
): AnyDoc {
return {
_id: match.tournamentCodeIds[0],
matchId: match._id,
state: 'used',
gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1',
riotMatchId,
reservedAt: new Date('2026-07-01T00:30:00.000Z'),
usedAt: new Date('2026-07-01T01:00:00.000Z'),
};
}
function riotArchive(): AnyDoc {
function riotArchive(matchId = 'KR_MIGRATION_1'): AnyDoc {
return {
_id: objectId(),
matchId: 'KR_MIGRATION_1',
raw: { metadata: { matchId: 'KR_MIGRATION_1' } },
matchId,
raw: { metadata: { matchId } },
};
}
@@ -1,6 +1,10 @@
import { createHash } from 'node:crypto';
import mongoose from 'mongoose';
import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
COMPETITION_DOMAIN_INVARIANT_INDEXES,
type CompetitionDomainInvariantIndex,
} from '../../../competition/competition.schema';
import {
planCompetitionMigration,
type CompetitionMigrationAssignment,
@@ -21,6 +25,10 @@ export interface CompetitionDomainMigrationCursor extends AsyncIterable<AnyDocum
}
export interface CompetitionDomainMigrationCollection {
createIndex(
key: mongoose.IndexDefinition,
options: mongoose.IndexOptions,
): Promise<string>;
find(
filter: Record<string, unknown>,
options?: { session?: CompetitionDomainMigrationSession },
@@ -34,6 +42,7 @@ export interface CompetitionDomainMigrationCollection {
update: {
$set?: Record<string, unknown>;
$setOnInsert?: Record<string, unknown>;
$unset?: Record<string, unknown>;
},
options?: {
session?: CompetitionDomainMigrationSession;
@@ -64,6 +73,7 @@ export interface CompetitionDomainMigrationSession {
export interface CompetitionDomainMigrationOptions {
dryRun?: boolean;
limit?: number;
afterMatchId?: string;
migrationRunId?: string;
now?: Date;
startSession?: () => Promise<CompetitionDomainMigrationSession | undefined>;
@@ -118,10 +128,37 @@ export interface CompetitionDomainMigrationSummary {
export interface CompetitionDomainMigrationResult {
migrationRunId: string;
mode: 'dry-run' | 'apply';
indexPreflight: CompetitionDomainIndexPreflight;
resume: CompetitionDomainMigrationResume;
summary: CompetitionDomainMigrationSummary;
matches: CompetitionDomainMigrationMatchResult[];
}
export interface CompetitionDomainMigrationResume {
strategy: 'none' | 'cursor' | 'checkpoint';
startedAfterMatchId?: string;
checkpointAfterMatchId?: string;
hasMore: boolean;
completed: boolean;
}
export interface CompetitionDomainIndexConflict {
collection: CompetitionDomainInvariantIndex['collection'];
indexName: string;
key: Record<string, unknown>;
code?: number;
keyPattern?: Record<string, unknown>;
keyValue?: unknown;
message: string;
}
export interface CompetitionDomainIndexPreflight {
status: 'dry-run' | 'ensured' | 'blocked';
requiredIndexes: number;
ensuredIndexes: string[];
conflicts: CompetitionDomainIndexConflict[];
}
/**
* Plans or applies the clean-break Competition migration. Apply mode owns one
* Mongo transaction per Match so a process can be stopped and safely resumed.
@@ -135,9 +172,43 @@ export async function migrateCompetitionDomain(
options.migrationRunId?.trim() || DEFAULT_MIGRATION_RUN_ID;
assertOptions(options);
const matchSnapshots = await scanMatches(db, options.limit);
const resumeStart = await resolveResumeStart(
db,
migrationRunId,
options,
dryRun,
);
const indexPreflight = await ensureCompetitionDomainIndexes(db, dryRun);
if (indexPreflight.status === 'blocked') {
return {
migrationRunId,
mode: 'apply',
indexPreflight,
resume: resumeReport(resumeStart, undefined, true, false),
summary: summarize([]),
matches: [],
};
}
if (!dryRun && options.limit !== undefined && options.afterMatchId) {
await persistMigrationCheckpoint(db, {
migrationRunId,
matchId: options.afterMatchId,
completed: false,
resetMatchStatus: true,
observedAt: options.now ?? new Date(),
});
}
const scan = await scanMatches(
db,
options.limit,
resumeStart.startedAfterMatchId,
);
const matches: CompetitionDomainMigrationMatchResult[] = [];
for (const [index, scannedMatch] of matchSnapshots.entries()) {
let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
let haltedOnFailure = false;
for (const [index, scannedMatch] of scan.matches.entries()) {
const result = dryRun
? await inspectMatch(db, scannedMatch, migrationRunId)
: await applyMatch(db, scannedMatch, migrationRunId, options);
@@ -146,29 +217,216 @@ export async function migrateCompetitionDomain(
index: index + 1,
matchId: result.matchId,
status: result.status,
total: matchSnapshots.length,
total: scan.matches.length,
});
if (!dryRun && options.limit !== undefined) {
if (result.status === 'failed') {
haltedOnFailure = true;
break;
}
await persistMigrationCheckpoint(db, {
migrationRunId,
matchId: result.matchId,
matchStatus: result.status,
completed: false,
observedAt: options.now ?? new Date(),
});
checkpointAfterMatchId = result.matchId;
}
}
const hasMore =
scan.hasMore || haltedOnFailure || matches.length < scan.matches.length;
const completed =
!hasMore && !matches.some(({ status }) => status === 'failed');
if (!dryRun && options.limit !== undefined && completed) {
await persistMigrationCheckpoint(db, {
migrationRunId,
matchId: checkpointAfterMatchId,
completed: true,
observedAt: options.now ?? new Date(),
});
}
return {
migrationRunId,
mode: dryRun ? 'dry-run' : 'apply',
indexPreflight,
resume: resumeReport(
resumeStart,
checkpointAfterMatchId,
hasMore,
completed,
),
summary: summarize(matches),
matches,
};
}
interface ResumeStart {
strategy: CompetitionDomainMigrationResume['strategy'];
startedAfterMatchId?: string;
}
async function resolveResumeStart(
db: CompetitionDomainMigrationDb,
migrationRunId: string,
options: CompetitionDomainMigrationOptions,
dryRun: boolean,
): Promise<ResumeStart> {
if (dryRun || options.limit === undefined) {
return {
strategy: options.afterMatchId ? 'cursor' : 'none',
...(options.afterMatchId
? { startedAfterMatchId: options.afterMatchId }
: {}),
};
}
if (options.afterMatchId) {
return {
strategy: 'cursor',
startedAfterMatchId: options.afterMatchId,
};
}
const checkpoint = await db
.collection('competition_migration_checkpoint')
.findOne({ _id: migrationRunId });
const checkpointMatchId = optionalIdString(checkpoint?.lastMatchId);
if (checkpointMatchId) assertMatchCursor(checkpointMatchId);
return {
strategy: 'checkpoint',
...(checkpointMatchId ? { startedAfterMatchId: checkpointMatchId } : {}),
};
}
function resumeReport(
start: ResumeStart,
checkpointAfterMatchId: string | undefined,
hasMore: boolean,
completed: boolean,
): CompetitionDomainMigrationResume {
return {
strategy: start.strategy,
...(start.startedAfterMatchId
? { startedAfterMatchId: start.startedAfterMatchId }
: {}),
...(checkpointAfterMatchId ? { checkpointAfterMatchId } : {}),
hasMore,
completed,
};
}
async function persistMigrationCheckpoint(
db: CompetitionDomainMigrationDb,
params: {
migrationRunId: string;
matchId?: string;
matchStatus?: CompetitionDomainMigrationMatchResult['status'];
completed: boolean;
resetMatchStatus?: boolean;
observedAt: Date;
},
): Promise<void> {
await db.collection('competition_migration_checkpoint').updateOne(
{ _id: params.migrationRunId },
{
$set: {
migrationRunId: params.migrationRunId,
status: params.completed ? 'completed' : 'running',
...(params.matchId
? { lastMatchId: persistenceId(params.matchId) }
: {}),
...(params.matchStatus ? { lastMatchStatus: params.matchStatus } : {}),
updatedAt: params.observedAt,
},
$setOnInsert: {
_id: params.migrationRunId,
createdAt: params.observedAt,
},
...(params.resetMatchStatus ? { $unset: { lastMatchStatus: 1 } } : {}),
},
{ upsert: true },
);
}
async function ensureCompetitionDomainIndexes(
db: CompetitionDomainMigrationDb,
dryRun: boolean,
): Promise<CompetitionDomainIndexPreflight> {
if (dryRun) {
return {
status: 'dry-run',
requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length,
ensuredIndexes: [],
conflicts: [],
};
}
const ensuredIndexes: string[] = [];
const conflicts: CompetitionDomainIndexConflict[] = [];
for (const index of COMPETITION_DOMAIN_INVARIANT_INDEXES) {
try {
const createdName = await db
.collection(index.collection)
.createIndex(index.key, index.options);
ensuredIndexes.push(createdName);
} catch (error) {
conflicts.push(indexConflict(index, error));
}
}
return {
status: conflicts.length > 0 ? 'blocked' : 'ensured',
requiredIndexes: COMPETITION_DOMAIN_INVARIANT_INDEXES.length,
ensuredIndexes,
conflicts,
};
}
function indexConflict(
index: CompetitionDomainInvariantIndex,
error: unknown,
): CompetitionDomainIndexConflict {
const record = isRecord(error) ? error : {};
const code =
typeof record.code === 'number' && Number.isInteger(record.code)
? record.code
: undefined;
const keyPattern = isRecord(record.keyPattern)
? (canonicalValue(record.keyPattern) as Record<string, unknown>)
: undefined;
const keyValue =
record.keyValue === undefined ? undefined : canonicalValue(record.keyValue);
return {
collection: index.collection,
indexName: index.options.name,
key: canonicalValue(index.key) as Record<string, unknown>,
...(code === undefined ? {} : { code }),
...(keyPattern ? { keyPattern } : {}),
...(keyValue === undefined ? {} : { keyValue }),
message: error instanceof Error ? error.message : String(error),
};
}
async function scanMatches(
db: CompetitionDomainMigrationDb,
limit: number | undefined,
): Promise<AnyDocument[]> {
return readCursor(
afterMatchId: string | undefined,
): Promise<{ matches: AnyDocument[]; hasMore: boolean }> {
const scanned = await readCursor(
db
.collection('match')
.find(MATCH_SCAN_FILTER)
.find({
...MATCH_SCAN_FILTER,
...(afterMatchId ? { _id: { $gt: persistenceId(afterMatchId) } } : {}),
})
.sort({ _id: 1 })
.limit(limit ?? 0),
.limit(limit === undefined ? 0 : limit + 1),
);
if (limit === undefined) return { matches: scanned, hasMore: false };
return {
matches: scanned.slice(0, limit),
hasMore: scanned.length > limit,
};
}
async function inspectMatch(
@@ -260,6 +518,30 @@ async function applyMatch(
};
}
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
db,
plan,
session,
);
if (uniquenessConflicts.length > 0) {
await persistQuarantine(
db,
currentMatch,
uniquenessConflicts,
plan.warnings,
migrationRunId,
options.now ?? new Date(),
session,
);
await session.commitTransaction();
return {
status: 'quarantined',
matchId,
warnings: plan.warnings,
reasons: uniquenessConflicts,
};
}
await upsertReadyPlan(db, plan, session);
await verifyReadyPlan(db, plan, session);
@@ -305,6 +587,123 @@ async function applyMatch(
}
}
interface UniqueIdentityCheck {
collection: 'competition' | 'competition_fact' | 'tournament_code_assignment';
indexName: string;
filter: Record<string, unknown>;
expectedDocumentId: string;
}
async function findReadyPlanUniquenessConflicts(
db: CompetitionDomainMigrationDb,
plan: ReadyCompetitionMigrationPlan,
session: CompetitionDomainMigrationSession,
): Promise<CompetitionMigrationIssue[]> {
const checks: UniqueIdentityCheck[] = [
{
collection: 'competition',
indexName: 'matchId_1',
filter: { matchId: persistenceId(plan.competition.matchId) },
expectedDocumentId: plan.competition.id,
},
];
for (const fact of plan.facts) {
checks.push(
{
collection: 'competition_fact',
indexName: 'competitionId_1_revision_1_ordinalWithinRevision_1',
filter: {
competitionId: persistenceId(fact.competitionId),
revision: fact.revision,
ordinalWithinRevision: fact.ordinalWithinRevision,
},
expectedDocumentId: fact.id,
},
{
collection: 'competition_fact',
indexName: 'competitionId_1_commandId_1_ordinalWithinRevision_1',
filter: {
competitionId: persistenceId(fact.competitionId),
commandId: fact.commandId,
ordinalWithinRevision: fact.ordinalWithinRevision,
},
expectedDocumentId: fact.id,
},
);
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
checks.push({
collection: 'competition_fact',
indexName: 'evidence.riotMatchId_1',
filter: {
type: 'game-accepted',
'evidence.riotMatchId': fact.evidence.riotMatchId,
},
expectedDocumentId: fact.id,
});
}
}
for (const assignment of plan.assignments) {
if (assignment.state === 'reserved' || assignment.state === 'used') {
checks.push(
{
collection: 'tournament_code_assignment',
indexName: 'gameSlotId_1',
filter: {
gameSlotId: persistenceId(assignment.gameSlotId),
state: { $in: ['reserved', 'used'] },
},
expectedDocumentId: assignment.id,
},
{
collection: 'tournament_code_assignment',
indexName: 'tournamentCodeId_1',
filter: {
tournamentCodeId: persistenceId(assignment.tournamentCodeId),
state: { $in: ['reserved', 'used'] },
},
expectedDocumentId: assignment.id,
},
);
}
if (assignment.riotMatchId) {
checks.push({
collection: 'tournament_code_assignment',
indexName: 'riotMatchId_1',
filter: { riotMatchId: assignment.riotMatchId },
expectedDocumentId: assignment.id,
});
}
}
const conflicts: CompetitionMigrationIssue[] = [];
// Mongo sessions do not support parallel operations inside one transaction.
for (const check of checks) {
const existing = await db
.collection(check.collection)
.findOne(check.filter, { session });
if (!existing || idString(existing._id) === check.expectedDocumentId) {
continue;
}
conflicts.push({
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
details: {
collection: check.collection,
indexName: check.indexName,
key: canonicalValue(check.filter) as Record<string, unknown>,
expectedDocumentId: check.expectedDocumentId,
conflictingDocumentId: idString(existing._id),
...(existing.competitionId
? { conflictingCompetitionId: idString(existing.competitionId) }
: {}),
},
});
}
return conflicts;
}
async function hydrateLegacyMatch(
db: CompetitionDomainMigrationDb,
match: AnyDocument,
@@ -819,6 +1218,17 @@ function assertOptions(options: CompetitionDomainMigrationOptions): void {
if (options.dryRun === false && !options.startSession) {
throw new Error('Apply mode requires a transaction session factory.');
}
if (options.afterMatchId !== undefined) {
assertMatchCursor(options.afterMatchId);
}
}
function assertMatchCursor(value: string): void {
if (!/^[a-f\d]{24}$/i.test(value)) {
throw new Error(
'Competition migration afterMatchId must be a 24-character hexadecimal Match ObjectId.',
);
}
}
async function readCursor(
@@ -31,4 +31,22 @@ describe('competition domain migration CLI', () => {
nodeEnv: 'dev',
});
});
it('accepts an explicit Match cursor for limited-run recovery', () => {
expect(
parseCliOptions([
'--apply',
'--limit=25',
'--after',
'66a000000000000000000123',
]),
).toMatchObject({
dryRun: false,
limit: 25,
afterMatchId: '66a000000000000000000123',
});
expect(() => parseCliOptions(['--after', 'not-an-object-id'])).toThrow(
'--after requires a 24-character hexadecimal Match ObjectId.',
);
});
});
@@ -15,6 +15,7 @@ export interface CompetitionDomainCliOptions {
dryRun: boolean;
help: boolean;
limit?: number;
afterMatchId?: string;
nodeEnv: string;
}
@@ -60,6 +61,7 @@ export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
let dryRun = true;
let help = false;
let limit: number | undefined;
let afterMatchId: string | undefined;
let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index += 1) {
@@ -95,6 +97,15 @@ export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
limit = positiveInteger(argument.slice('--limit='.length), '--limit');
continue;
}
if (argument === '--after') {
afterMatchId = matchObjectId(argv[index + 1]);
index += 1;
continue;
}
if (argument.startsWith('--after=')) {
afterMatchId = matchObjectId(argument.slice('--after='.length));
continue;
}
if (argument === '--help' || argument === '-h') {
help = true;
continue;
@@ -105,7 +116,7 @@ export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.');
}
return { dryRun, help, limit, nodeEnv };
return { dryRun, help, limit, afterMatchId, nodeEnv };
}
function positiveInteger(value: string | undefined, label: string): number {
@@ -116,6 +127,15 @@ function positiveInteger(value: string | undefined, label: string): number {
return parsed;
}
function matchObjectId(value: string | undefined): string {
if (!value || !/^[a-f\d]{24}$/i.test(value)) {
throw new Error(
'--after requires a 24-character hexadecimal Match ObjectId.',
);
}
return value.toLowerCase();
}
function printHelp(): void {
process.stdout.write(`Usage:
pnpm --silent --filter api competition:migrate
@@ -125,7 +145,8 @@ Options:
--dry-run Plan and report without writes. Default.
--apply Apply one transaction per Match.
--env <env> dev | staging | prod. Default: NODE_ENV or dev.
--limit <n> Scan at most n Matches in deterministic _id order.
--limit <n> Scan at most n Matches. Apply resumes from a durable checkpoint.
--after <id> Override the checkpoint with a Match ObjectId cursor.
The JSON report is written to stdout; the concise human summary is written to stderr.
`);
@@ -153,6 +174,7 @@ async function main(): Promise<void> {
{
dryRun: options.dryRun,
limit: options.limit,
afterMatchId: options.afterMatchId,
startSession: options.dryRun
? undefined
: async () => connection.startSession(),
@@ -164,11 +186,15 @@ async function main(): Promise<void> {
`db=${resolveMongoDbName(options.nodeEnv)} scanned=${summary.scanned} ` +
`ready=${summary.ready} applied=${summary.applied} ` +
`alreadyApplied=${summary.alreadyApplied} quarantined=${summary.quarantined} ` +
`failed=${summary.failed} unclassified=${summary.unclassified}\n`,
`failed=${summary.failed} unclassified=${summary.unclassified} ` +
`indexPreflight=${result.indexPreflight.status} ` +
`resume=${result.resume.checkpointAfterMatchId ?? 'none'} ` +
`completed=${result.resume.completed}\n`,
);
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
if (summary.failed > 0) process.exitCode = 1;
if (result.indexPreflight.status === 'blocked') process.exitCode = 1;
else if (summary.failed > 0) process.exitCode = 1;
else if (summary.quarantined > 0) process.exitCode = 2;
} finally {
await app.close().catch((error: unknown) => {
@@ -8,6 +8,7 @@ import {
CompetitionFact,
CompetitionOutbox,
TournamentCodeAssignment,
applyCompetitionDomainInvariantIndexes,
competitionModelDefinitions,
} from '../../competition/competition.schema';
import { ModelDefinition } from './types';
@@ -465,6 +466,7 @@ export interface TournamentCode extends MongooseTimestamps {
reservedAt?: Date;
usedAt?: Date;
releasedAt?: Date;
voidedAt?: Date;
riotMatchId?: string;
uploadedBy: mongoose.Types.ObjectId;
uploadedAt: Date;
@@ -1501,6 +1503,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
reservedAt: { type: Date },
usedAt: { type: Date },
releasedAt: { type: Date },
voidedAt: { type: Date },
riotMatchId: { type: String },
uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
uploadedAt: { type: Date, required: true, default: Date.now },
@@ -1952,13 +1955,7 @@ export const MatchSchema = new Schema<Match>(
);
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
MatchSchema.index(
{ competitionId: 1 },
{
unique: true,
partialFilterExpression: { competitionId: { $type: 'objectId' } },
},
);
applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index(
{ communityId: 1, shortCode: 1 },
@@ -294,16 +294,40 @@ describe('Legacy import Competition result cutover', () => {
it('cascades admin deletion through Competition facts and read models', async () => {
const fixture = createImportFixture();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const competitionFactModel = deleteManyModel();
const competitionOutboxModel = deleteManyModel();
const assignmentModel = deleteManyModel();
const reservedCodeId = new mongoose.Types.ObjectId();
const usedCodeId = new mongoose.Types.ObjectId();
const assignmentModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{ tournamentCodeId: reservedCodeId, state: 'reserved' },
{ tournamentCodeId: usedCodeId, state: 'used' },
]),
),
}),
}),
}),
};
const competitionModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
}),
}),
}),
};
@@ -311,11 +335,44 @@ describe('Legacy import Competition result cutover', () => {
find: jest.fn().mockReturnValue({
select: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.match._id }])),
.mockReturnValue(sessionResult([{ _id: fixture.match._id }])),
}),
deleteMany: jest.fn().mockReturnValue(execResult({ deletedCount: 1 })),
deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
_id: reservedCodeId,
state: 'reserved',
matchId: fixture.match._id,
},
{
_id: usedCodeId,
state: 'used',
matchId: fixture.match._id,
},
]),
),
}),
}),
}),
updateMany: jest
.fn()
.mockReturnValue(sessionResult({ matchedCount: 1, modifiedCount: 1 })),
};
const matchStatsModel = deleteManyModel();
const quarantineCollection = {
deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getConnection: jest.fn().mockResolvedValue({
collection: jest.fn().mockReturnValue(quarantineCollection),
}),
getModel: jest.fn((name: string) => {
const models: Record<string, unknown> = {
match: matchModel,
@@ -323,6 +380,8 @@ describe('Legacy import Competition result cutover', () => {
competitionFact: competitionFactModel,
competitionOutbox: competitionOutboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
matchStats: matchStatsModel,
};
const model = models[name];
return model
@@ -330,15 +389,11 @@ describe('Legacy import Competition result cutover', () => {
: Promise.reject(new Error(`Unexpected model ${name}`));
}),
} as unknown as ConnectionService;
const matchStatsService = {
removeByMatches: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({
connectionService,
matchStatsService,
communityStatsService,
});
@@ -360,9 +415,98 @@ describe('Legacy import Competition result cutover', () => {
expect(competitionModel.deleteMany).toHaveBeenCalledWith({
_id: { $in: [fixture.competition._id] },
});
expect(matchStatsService.removeByMatches).toHaveBeenCalledWith([
fixture.match._id,
]);
expect(tournamentCodeModel.updateMany).toHaveBeenCalledTimes(2);
expect(matchStatsModel.deleteMany).toHaveBeenCalledWith({
matchId: { $in: [fixture.match._id] },
});
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(session.abortTransaction).not.toHaveBeenCalled();
expect(communityStatsService.invalidateCommunity).toHaveBeenCalledWith(
fixture.match.communityId,
);
});
it('aborts legacy deletion when an active assignment points to another Match code', async () => {
const harness = createBulkDeleteFailureHarness({
codeMatchId: new mongoose.Types.ObjectId(),
});
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow(/Tournament Code assignment/);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.matchModel.deleteMany).not.toHaveBeenCalled();
expect(harness.competitionFactModel.deleteMany).not.toHaveBeenCalled();
});
it('aborts legacy deletion when a validated Tournament Code transition does not update exactly once', async () => {
const harness = createBulkDeleteFailureHarness({
updateResult: { matchedCount: 0, modifiedCount: 0 },
});
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow(/Tournament Code transition/);
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.matchModel.deleteMany).not.toHaveBeenCalled();
});
it('invalidates community caches again when a committed deletion is retried', async () => {
const harness = createBulkDeleteFailureHarness({});
harness.matchModel.find
.mockReset()
.mockReturnValueOnce({
select: jest
.fn()
.mockReturnValue(sessionResult([{ _id: harness.fixture.match._id }])),
})
.mockReturnValueOnce({
select: jest.fn().mockReturnValue(sessionResult([])),
});
harness.communityStatsService.invalidateCommunity
.mockRejectedValueOnce(new Error('Redis unavailable'))
.mockResolvedValueOnce(0);
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).rejects.toThrow('Redis unavailable');
await expect(
harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
}),
).resolves.toEqual({ deleted: 0 });
expect(
harness.communityStatsService.invalidateCommunity,
).toHaveBeenCalledTimes(2);
});
it('removes migration quarantine records in the same legacy deletion transaction', async () => {
const harness = createBulkDeleteFailureHarness({});
await harness.service.bulkDeleteLegacyMatches({
communityId: harness.fixture.match.communityId,
body: { matchIds: [harness.fixture.match._id.toString()] },
});
expect(harness.quarantineCollection.deleteMany).toHaveBeenCalledWith(
{ _id: { $in: [harness.fixture.match._id] } },
{ session: harness.session },
);
});
it('rebuilds a historical legacy Match into Competition facts without rewriting Match.result', async () => {
@@ -707,10 +851,135 @@ function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function sessionResult<T>(value: T) {
const query = {
exec: jest.fn().mockResolvedValue(value),
session: jest.fn(),
};
query.session.mockReturnValue(query);
return query;
}
function deleteManyModel() {
return {
deleteMany: jest
.fn()
.mockReturnValue(execResult({ acknowledged: true, deletedCount: 1 })),
.mockReturnValue(sessionResult({ acknowledged: true, deletedCount: 1 })),
};
}
function createBulkDeleteFailureHarness(options: {
codeMatchId?: mongoose.Types.ObjectId;
codeState?: 'reserved' | 'used';
assignmentState?: 'reserved' | 'used';
updateResult?: { matchedCount: number; modifiedCount: number };
}) {
const fixture = createImportFixture();
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const tournamentCodeId = new mongoose.Types.ObjectId();
const assignmentState = options.assignmentState ?? 'reserved';
const codeState = options.codeState ?? assignmentState;
const assignmentModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(
execResult([{ tournamentCodeId, state: assignmentState }]),
),
}),
}),
}),
};
const competitionModel = {
...deleteManyModel(),
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
}),
}),
}),
};
const matchModel = {
find: jest.fn().mockReturnValue({
select: jest
.fn()
.mockReturnValue(sessionResult([{ _id: fixture.match._id }])),
}),
deleteMany: jest.fn().mockReturnValue(sessionResult({ deletedCount: 1 })),
};
const tournamentCodeModel = {
find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
session: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(
execResult([
{
_id: tournamentCodeId,
state: codeState,
matchId: options.codeMatchId ?? fixture.match._id,
},
]),
),
}),
}),
}),
updateMany: jest
.fn()
.mockReturnValue(
sessionResult(
options.updateResult ?? { matchedCount: 1, modifiedCount: 1 },
),
),
};
const competitionFactModel = deleteManyModel();
const competitionOutboxModel = deleteManyModel();
const matchStatsModel = deleteManyModel();
const quarantineCollection = {
deleteMany: jest.fn().mockResolvedValue({ deletedCount: 1 }),
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getConnection: jest.fn().mockResolvedValue({
collection: jest.fn().mockReturnValue(quarantineCollection),
}),
getModel: jest.fn((name: string) => {
const models: Record<string, unknown> = {
match: matchModel,
competition: competitionModel,
competitionFact: competitionFactModel,
competitionOutbox: competitionOutboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
matchStats: matchStatsModel,
};
const model = models[name];
return model
? Promise.resolve(model)
: Promise.reject(new Error(`Unexpected model ${name}`));
}),
} as unknown as ConnectionService;
const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(0),
} as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ connectionService, communityStatsService });
return {
fixture,
session,
service,
matchModel,
competitionFactModel,
communityStatsService,
quarantineCollection,
};
}
@@ -2,6 +2,7 @@ import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
@@ -381,60 +382,194 @@ export class LegacyImportService {
.filter((id) => mongoose.isValidObjectId(id))
.map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 };
const MatchModel = await this.connectionService.getModel('match');
const targets = await MatchModel.find({
_id: { $in: ids },
communityId: params.communityId,
legacyImported: true,
})
.select({ _id: 1 })
.exec();
const targetIds = targets.map((match) => match._id);
if (targetIds.length === 0) return { deleted: 0 };
const [
MatchModel,
CompetitionModel,
CompetitionFactModel,
CompetitionOutboxModel,
AssignmentModel,
TournamentCodeModel,
MatchStatsModel,
connection,
] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('matchStats'),
this.connectionService.getConnection(),
]);
const competitions = await CompetitionModel.find({
matchId: { $in: targetIds },
})
.select({ _id: 1 })
.lean()
.exec();
const competitionIds = competitions.map(({ _id }) => _id);
if (competitionIds.length > 0) {
await Promise.all([
CompetitionFactModel.deleteMany({
competitionId: { $in: competitionIds },
}).exec(),
CompetitionOutboxModel.deleteMany({
competitionId: { $in: competitionIds },
}).exec(),
AssignmentModel.deleteMany({
competitionId: { $in: competitionIds },
}).exec(),
]);
await CompetitionModel.deleteMany({
_id: { $in: competitionIds },
}).exec();
const session = await this.connectionService.createSession();
if (!session) {
throw new InternalServerErrorException(
'A MongoDB transaction is required to delete legacy Matches.',
);
}
let deleted = 0;
try {
session.startTransaction();
const targets = await MatchModel.find({
_id: { $in: ids },
communityId: params.communityId,
legacyImported: true,
})
.select({ _id: 1 })
.session(session)
.exec();
const targetIds = targets.map((match) => match._id);
if (targetIds.length === 0) {
await session.commitTransaction();
} else {
const competitions = await CompetitionModel.find({
matchId: { $in: targetIds },
})
.select({ _id: 1 })
.session(session)
.lean()
.exec();
const competitionIds = competitions.map(({ _id }) => _id);
if (competitionIds.length > 0) {
const assignments = await AssignmentModel.find({
competitionId: { $in: competitionIds },
state: { $in: ['reserved', 'used'] },
})
.select({ tournamentCodeId: 1, state: 1 })
.session(session)
.lean()
.exec();
const assignmentCodeIds = assignments.map(
({ tournamentCodeId }) => tournamentCodeId,
);
const uniqueAssignmentCodeIds = new Set(
assignmentCodeIds.map((id) => id.toString()),
);
if (uniqueAssignmentCodeIds.size !== assignmentCodeIds.length) {
throw new ConflictException(
'Tournament Code assignments contain a duplicate active code identity.',
);
}
const tournamentCodes =
assignmentCodeIds.length === 0
? []
: await TournamentCodeModel.find({
_id: { $in: assignmentCodeIds },
})
.select({ _id: 1, state: 1, matchId: 1 })
.session(session)
.lean()
.exec();
const tournamentCodeById = new Map(
tournamentCodes.map((code) => [code._id.toString(), code]),
);
const targetIdSet = new Set(targetIds.map((id) => id.toString()));
for (const assignment of assignments) {
const code = tournamentCodeById.get(
assignment.tournamentCodeId.toString(),
);
if (
!code ||
code.state !== assignment.state ||
!code.matchId ||
!targetIdSet.has(code.matchId.toString())
) {
throw new ConflictException(
'Tournament Code assignment ownership or state does not match the target legacy Match.',
);
}
}
const releasedCodeIds = assignments
.filter(({ state }) => state === 'reserved')
.map(({ tournamentCodeId }) => tournamentCodeId);
const voidedCodeIds = assignments
.filter(({ state }) => state === 'used')
.map(({ tournamentCodeId }) => tournamentCodeId);
const terminalAt = new Date();
if (releasedCodeIds.length > 0) {
const released = await TournamentCodeModel.updateMany(
{
_id: { $in: releasedCodeIds },
matchId: { $in: targetIds },
state: 'reserved',
},
{
$set: { state: 'released', releasedAt: terminalAt },
$unset: legacyTournamentCodeBindingUnset(),
},
)
.session(session)
.exec();
assertExactTournamentCodeTransition(
released,
releasedCodeIds.length,
);
}
if (voidedCodeIds.length > 0) {
const voided = await TournamentCodeModel.updateMany(
{
_id: { $in: voidedCodeIds },
matchId: { $in: targetIds },
state: 'used',
},
{
$set: { state: 'voided', voidedAt: terminalAt },
$unset: legacyTournamentCodeBindingUnset(),
},
)
.session(session)
.exec();
assertExactTournamentCodeTransition(voided, voidedCodeIds.length);
}
await CompetitionFactModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await CompetitionOutboxModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await AssignmentModel.deleteMany({
competitionId: { $in: competitionIds },
})
.session(session)
.exec();
await CompetitionModel.deleteMany({
_id: { $in: competitionIds },
})
.session(session)
.exec();
}
await connection
.collection('competition_migration_quarantine')
.deleteMany({ _id: { $in: targetIds } }, { session });
const result = await MatchModel.deleteMany({
_id: { $in: targetIds },
communityId: params.communityId,
legacyImported: true,
})
.session(session)
.exec();
await MatchStatsModel.deleteMany({ matchId: { $in: targetIds } })
.session(session)
.exec();
deleted = result.deletedCount ?? 0;
await session.commitTransaction();
}
} catch (error) {
await session.abortTransaction().catch(() => undefined);
throw error;
} finally {
await session.endSession().catch(() => undefined);
}
const result = await MatchModel.deleteMany({
_id: { $in: targetIds },
communityId: params.communityId,
legacyImported: true,
}).exec();
await this.matchStatsService.removeByMatches(targetIds);
await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted: result.deletedCount ?? 0 };
return { deleted };
}
public async rebuildLegacyMatches(params: {
@@ -1322,6 +1457,29 @@ function optionalNumber(value: unknown): number | undefined {
: undefined;
}
function legacyTournamentCodeBindingUnset(): Record<string, 1> {
return {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
};
}
function assertExactTournamentCodeTransition(
result: { matchedCount?: number; modifiedCount?: number },
expectedCount: number,
): void {
if (
result.matchedCount !== expectedCount ||
result.modifiedCount !== expectedCount
) {
throw new ConflictException(
'Tournament Code transition did not update every validated assignment.',
);
}
}
function deterministicObjectId(key: string): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId(
createHash('sha256').update(key).digest('hex').slice(0, 24),
@@ -1,7 +1,9 @@
import 'reflect-metadata';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { CreateMatchDto } from './create-match.dto';
import mongoose from 'mongoose';
import { CreateMatchDto, JoinMatchDto } from './create-match.dto';
describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => {
@@ -31,3 +33,31 @@ describe('CreateMatchDto game mode cutover', () => {
},
);
});
describe('JoinMatchDto self-join boundary', () => {
it('rejects a caller-supplied userId', async () => {
const pipe = new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
});
try {
await pipe.transform(
{
preferredPositions: [{ position: 'MID', priority: 1 }],
userId: new mongoose.Types.ObjectId().toString(),
},
{ type: 'body', metatype: JoinMatchDto },
);
throw new Error('Expected validation to reject userId.');
} catch (error) {
expect(error).toBeInstanceOf(BadRequestException);
expect((error as BadRequestException).getResponse()).toEqual({
error: 'Bad Request',
message: ['property userId should not exist'],
statusCode: 400,
});
}
});
});
@@ -215,10 +215,6 @@ export class JoinMatchDto {
@ValidateNested({ each: true })
@Type(() => PositionPreferenceDto)
preferredPositions!: PositionPreferenceDto[];
@IsOptional()
@IsString()
userId?: string;
}
export class AddParticipantDto {
@@ -234,13 +230,3 @@ export class AddParticipantDto {
@IsString()
riotPuuid?: string;
}
export class SwapDoubleEliminationSeedsDto {
@IsInt()
@Min(1)
leftSeedNumber!: number;
@IsInt()
@Min(1)
rightSeedNumber!: number;
}
@@ -9,6 +9,7 @@ describe('presentPublicMatch', () => {
competitionId: oid('3'),
shortCode: '33NW',
title: '내전',
joined: false,
description: '설명',
mapId: 11,
status: 'in-progress',
@@ -25,6 +26,16 @@ describe('presentPublicMatch', () => {
gameName: '선수',
tagLine: 'KR1',
profileIconId: 1,
tier: {
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'I',
leaguePoints: 42,
wins: 10,
losses: 5,
fetchedAt: new Date('2026-07-10T00:00:00.000Z'),
puuid: 'secret-tier-puuid',
},
preferredPositions: [
{ position: 'MID', priority: 1 },
{ position: 'SUP', priority: 2 },
@@ -65,6 +76,15 @@ describe('presentPublicMatch', () => {
expect.objectContaining({
userId: oid('5').toString(),
joinedAt: '2026-07-01T00:00:00.000Z',
tier: {
queueType: 'RANKED_SOLO_5x5',
tier: 'GOLD',
rank: 'I',
leaguePoints: 42,
wins: 10,
losses: 5,
fetchedAt: '2026-07-10T00:00:00.000Z',
},
}),
],
teams: [
@@ -89,6 +109,7 @@ describe('presentPublicMatch', () => {
expect(response).not.toHaveProperty('resultPollState');
expect(response).not.toHaveProperty('legacyImportSource');
expect(response.participants[0]).not.toHaveProperty('puuid');
expect(response.participants[0]?.tier).not.toHaveProperty('puuid');
});
});
@@ -1,3 +1,4 @@
import type { MatchDetailResponse, MatchTierView } from '@lolympus/contracts';
import type {
MatchGameMode,
MatchStatus,
@@ -57,12 +58,12 @@ interface PublicMatchSource {
export function presentPublicMatch(
source: PublicMatchSource,
options: { joined?: boolean } = {},
) {
): MatchDetailResponse {
return {
_id: source._id.toString(),
communityId: source.communityId.toString(),
_id: source._id.toString() as never,
communityId: source.communityId.toString() as never,
...(source.competitionId
? { competitionId: source.competitionId.toString() }
? { competitionId: source.competitionId.toString() as never }
: {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title,
@@ -82,32 +83,37 @@ export function presentPublicMatch(
source.doubleElimination?.resetFinalEnabled ?? false,
}
: {}),
...(source.hostUserId ? { hostUserId: source.hostUserId.toString() } : {}),
participants: source.participants.map((participant) => ({
userId: participant.userId.toString(),
...(participant.gameName ? { gameName: participant.gameName } : {}),
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
...(participant.tier === undefined
? {}
: { tier: toWireValue(participant.tier) }),
preferredPositions: participant.preferredPositions.map((preference) => ({
position: preference.position,
priority: preference.priority,
})),
joinedAt: asIso(participant.joinedAt),
excluded: participant.excluded ?? false,
})),
...(source.hostUserId
? { hostUserId: source.hostUserId.toString() as never }
: {}),
participants: source.participants.map((participant) => {
const tier = toPublicTier(participant.tier);
return {
userId: participant.userId.toString() as never,
...(participant.gameName ? { gameName: participant.gameName } : {}),
...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
...(participant.profileIconId === undefined
? {}
: { profileIconId: participant.profileIconId }),
...(tier ? { tier } : {}),
preferredPositions: participant.preferredPositions.map(
(preference) => ({
position: preference.position,
priority: preference.priority,
}),
),
joinedAt: asIso(participant.joinedAt),
excluded: participant.excluded ?? false,
};
}),
teams: source.teams.map((team) => ({
teamIndex: team.teamIndex,
name: team.name,
...(team.captainUserId
? { captainUserId: team.captainUserId.toString() }
? { captainUserId: team.captainUserId.toString() as never }
: {}),
members: team.members.map((member) => ({
userId: member.userId.toString(),
userId: member.userId.toString() as never,
assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }),
})),
@@ -115,7 +121,7 @@ export function presentPublicMatch(
prizes: [...source.prizes],
notices: [...source.notices],
schedule: source.schedule.map(({ time, label }) => ({ time, label })),
...(options.joined === undefined ? {} : { joined: options.joined }),
joined: options.joined ?? false,
createdAt: asIso(source.createdAt),
updatedAt: asIso(source.updatedAt),
};
@@ -125,13 +131,29 @@ function asIso(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
function toWireValue(value: unknown): unknown {
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toWireValue);
if (typeof value === 'object' && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWireValue(child)]),
);
function toPublicTier(value: unknown): MatchTierView | undefined {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
return undefined;
}
return value;
const tier = value as Record<string, unknown>;
if (
typeof tier.queueType !== 'string' ||
typeof tier.tier !== 'string' ||
typeof tier.rank !== 'string' ||
typeof tier.leaguePoints !== 'number' ||
typeof tier.wins !== 'number' ||
typeof tier.losses !== 'number' ||
!(typeof tier.fetchedAt === 'string' || tier.fetchedAt instanceof Date)
) {
return undefined;
}
return {
queueType: tier.queueType,
tier: tier.tier,
rank: tier.rank,
leaguePoints: tier.leaguePoints,
wins: tier.wins,
losses: tier.losses,
fetchedAt: asIso(tier.fetchedAt),
};
}
@@ -0,0 +1,93 @@
import 'reflect-metadata';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import mongoose from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { ROLES_KEY } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import type { UserDocument } from '../global/database/schema';
import { MatchController } from './match.controller';
describe('MatchController participant access', () => {
function createController() {
const joinedMatch = { _id: new mongoose.Types.ObjectId() };
const response = { _id: joinedMatch._id.toString(), joined: true };
const matchService = {
join: jest.fn().mockResolvedValue(joinedMatch),
serialize: jest.fn().mockReturnValue(response),
};
return {
controller: new MatchController(matchService as never),
joinedMatch,
matchService,
response,
};
}
function createUser(communityId: mongoose.Types.ObjectId): UserDocument {
return {
_id: new mongoose.Types.ObjectId(),
communityId,
role: 'member',
} as UserDocument;
}
it('requires an authenticated community member for the self-join route', () => {
// Metadata must be read from the unbound prototype method itself.
// eslint-disable-next-line @typescript-eslint/unbound-method
const handler = MatchController.prototype.joinMatch;
const roles = Reflect.getMetadata(ROLES_KEY, handler) as
| string[]
| undefined;
const guards = Reflect.getMetadata(GUARDS_METADATA, handler) as
| unknown[]
| undefined;
expect(
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
).not.toBe(true);
expect(roles).toHaveLength(3);
expect(roles).toEqual(expect.arrayContaining(['owner', 'admin', 'member']));
expect(guards).toEqual(expect.arrayContaining([RolesGuard]));
});
it('joins only the authenticated user', async () => {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const currentUser = createUser(communityId);
const preferredPositions = [{ position: 'MID' as const, priority: 1 }];
const { controller, joinedMatch, matchService, response } =
createController();
await expect(
controller.joinMatch(currentUser, communityId, matchId, {
preferredPositions,
}),
).resolves.toBe(response);
expect(matchService.join).toHaveBeenCalledWith({
matchId,
communityId,
userId: currentUser._id,
preferredPositions,
});
expect(matchService.serialize).toHaveBeenCalledWith(joinedMatch, {
joined: true,
});
});
it('rejects a dev-auth user from a different URL community', async () => {
const currentUser = createUser(new mongoose.Types.ObjectId());
const requestedCommunityId = new mongoose.Types.ObjectId();
const { controller, matchService } = createController();
await expect(
controller.joinMatch(
currentUser,
requestedCommunityId,
new mongoose.Types.ObjectId(),
{ preferredPositions: [{ position: 'TOP', priority: 1 }] },
),
).rejects.toThrow('Different community.');
expect(matchService.join).not.toHaveBeenCalled();
});
});
+53 -68
View File
@@ -1,3 +1,7 @@
import type {
MatchDetailResponse,
MatchListResponse,
} from '@lolympus/contracts';
import {
BadRequestException,
Body,
@@ -23,7 +27,6 @@ import {
AddParticipantDto,
CreateMatchDto,
JoinMatchDto,
SwapDoubleEliminationSeedsDto,
UpdateMatchDto,
UpdateParticipantDto,
} from './dto/create-match.dto';
@@ -41,9 +44,9 @@ export class MatchController {
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: CreateMatchDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.create({
const match = await this.matchService.create({
communityId,
hostUserId: currentUser._id,
data: {
@@ -62,6 +65,7 @@ export class MatchController {
schedule: body.schedule ?? [],
},
});
return this.matchService.serialize(match, { joined: false });
}
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@@ -78,7 +82,7 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc',
) {
): Promise<MatchListResponse> {
const result = await this.matchService.listPage({
communityId,
status,
@@ -108,10 +112,20 @@ export class MatchController {
@Get(':matchId')
@AllowPublicAccess()
public async getMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
const match = await this.matchService.getById(matchId);
return this.matchService.serialize(match);
): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match, {
joined: Boolean(
currentUser &&
match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
),
});
}
@Patch(':matchId')
@@ -123,48 +137,18 @@ export class MatchController {
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UpdateMatchDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
return this.matchService.update({ matchId, communityId, patch: body });
}
@Post(':matchId/double-elimination/seeds/reshuffle')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async reshuffleDoubleEliminationSeeds(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.reshuffleDoubleEliminationSeeds({
const match = await this.matchService.update({
matchId,
communityId,
actorUserId: currentUser._id,
patch: body,
});
return this.matchService.serialize(match);
}
@Post(':matchId/double-elimination/seeds/swap')
@Roles('admin', 'owner')
@UseGuards(RolesGuard)
public async swapDoubleEliminationSeeds(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: SwapDoubleEliminationSeedsDto,
) {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.swapDoubleEliminationSeeds({
matchId,
communityId,
actorUserId: currentUser._id,
leftSeedNumber: body.leftSeedNumber,
rightSeedNumber: body.rightSeedNumber,
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
return this.matchService.serialize(match);
}
@Delete(':matchId')
@@ -181,20 +165,25 @@ export class MatchController {
await this.matchService.remove({ matchId, communityId });
}
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용).
// 커뮤니티 멤버 본인 참여. 다른 유저 추가는 관리자 전용 경로를 사용한다.
@Post(':matchId/participants')
@AllowPublicAccess()
@Roles('owner', 'admin', 'member')
@UseGuards(RolesGuard)
public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: JoinMatchDto,
) {
const userId = this.resolveJoinerUserId(currentUser, body.userId);
return this.matchService.join({
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({
matchId,
userId,
communityId,
userId: currentUser._id,
preferredPositions: body.preferredPositions,
});
return this.matchService.serialize(match, { joined: true });
}
// 관리자 전용 — 커뮤니티 유저를 모집중 매치에 직접 추가한다.
@@ -208,15 +197,20 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: AddParticipantDto | undefined,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({
matchId,
communityId,
userId,
preferredPositions: body?.preferredPositions,
riotPuuid: body?.riotPuuid,
});
return this.matchService.serialize(match);
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
}
// 관리자 전용 — 참가자 주/부 포지션 변경.
@@ -230,7 +224,7 @@ export class MatchController {
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: UpdateParticipantDto,
) {
): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.updateParticipantPositions({
matchId,
@@ -239,7 +233,11 @@ export class MatchController {
mainPosition: body.mainPosition,
subPosition: body.subPosition,
});
return this.matchService.serialize(match);
return this.matchService.serialize(match, {
joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
});
}
// 관리자 전용 — 참가자 강제 제외.
@@ -262,19 +260,6 @@ export class MatchController {
});
}
private resolveJoinerUserId(
currentUser: UserDocument | undefined,
bodyUserId?: string,
): mongoose.Types.ObjectId {
if (currentUser) return currentUser._id;
if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) {
throw new BadRequestException(
'userId is required when not authenticated.',
);
}
return new mongoose.Types.ObjectId(bodyUserId);
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
+140 -24
View File
@@ -57,6 +57,7 @@ describe('MatchService', () => {
) {
const MatchModel = {
findById: jest.fn().mockResolvedValue(match),
findOne: jest.fn().mockResolvedValue(match),
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
};
const connectionService = {
@@ -203,6 +204,19 @@ describe('MatchService', () => {
});
});
it('scopes Match detail lookup to the URL community', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const match = { _id: matchId, communityId };
const { service, MatchModel } = createService(match);
await expect(service.getById(matchId, communityId)).resolves.toBe(match);
expect(MatchModel.findOne).toHaveBeenCalledWith({
_id: matchId,
communityId,
});
});
it('applies offset before page-based pagination', async () => {
const communityId = new mongoose.Types.ObjectId();
const { service, skip } = createServiceWithListModel();
@@ -344,6 +358,36 @@ describe('MatchService', () => {
expect(match.save).not.toHaveBeenCalled();
});
it('does not join a user from a different community', async () => {
const requestedCommunityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
const user = {
_id: userId,
communityId: new mongoose.Types.ObjectId(),
preferredPositions: [],
riotAccounts: [],
};
const match = {
_id: new mongoose.Types.ObjectId(),
communityId: requestedCommunityId,
status: 'recruiting',
participants: [],
};
const { service, MatchModel } = createServiceWithJoinModels({
user,
match,
});
await expect(
service.join({
matchId: match._id,
communityId: requestedCommunityId,
userId,
}),
).rejects.toThrow('Match not found.');
expect(MatchModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('cancels a join with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId();
@@ -525,7 +569,7 @@ describe('MatchService', () => {
expect(MatchModel.create).not.toHaveBeenCalled();
});
it('clears game schedule when a built match returns to recruiting', async () => {
it('rejects returning a finalized team build to recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
@@ -547,20 +591,23 @@ describe('MatchService', () => {
const { service, tournamentCodeService, matchStatsService } =
createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
expect(match.teamBuiltAt).toBeUndefined();
expect(match.result).toBeUndefined();
expect(match.resultPollState).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1);
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id);
expect(match.gameSchedule).toEqual([
{ gameNumber: 1, teamAIndex: 2, teamBIndex: 4 },
]);
expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.result).toEqual({ games: [] });
expect(match.resultPollState).toEqual({ state: 'polling' });
expect(match.save).not.toHaveBeenCalled();
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
});
it('rejects round-robin max round changes after recruiting', async () => {
@@ -581,12 +628,77 @@ describe('MatchService', () => {
patch: { roundRobinMaxRounds: 3 },
}),
).rejects.toThrow(
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
expect(match.set).not.toHaveBeenCalled();
});
it('releases reserved codes when returning a built match to recruiting', async () => {
it('rejects game count changes after recruiting', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn(),
};
const { service } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { gameCount: 5 },
}),
).rejects.toThrow('gameCount');
expect(match.set).not.toHaveBeenCalled();
});
it('rejects returning to recruiting after Competition bootstrap', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
communityId,
competitionId: new mongoose.Types.ObjectId(),
status: 'team-built',
tournamentCodeIds: [],
set: jest.fn(),
save: jest.fn(),
};
const { service, tournamentCodeService } = createService(match);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(match.set).not.toHaveBeenCalled();
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
});
it('rejects hard deletion after Competition bootstrap', async () => {
const communityId = new mongoose.Types.ObjectId();
const match = {
_id: new mongoose.Types.ObjectId(),
communityId,
competitionId: new mongoose.Types.ObjectId(),
status: 'recruiting',
tournamentCodeIds: [],
deleteOne: jest.fn(),
};
const { service, tournamentCodeService, matchStatsService } =
createService(match);
await expect(
service.remove({ matchId: match._id, communityId }),
).rejects.toThrow('cannot be hard-deleted');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(matchStatsService.removeByMatch).not.toHaveBeenCalled();
expect(match.deleteOne).not.toHaveBeenCalled();
});
it('preserves reserved codes when a recruiting rollback is rejected', async () => {
const communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const match = {
@@ -604,14 +716,18 @@ describe('MatchService', () => {
};
const { service, tournamentCodeService } = createService(match);
await service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
});
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match);
expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]);
await expect(
service.update({
matchId: new mongoose.Types.ObjectId(),
communityId,
patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([codeId]);
expect(match.gameSchedule).toEqual([
{ gameNumber: 1, teamAIndex: 1, teamBIndex: 3 },
]);
expect(match.save).not.toHaveBeenCalled();
});
});
+29 -155
View File
@@ -1,14 +1,11 @@
import {
BadRequestException,
ConflictException,
Injectable,
InternalServerErrorException,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import {
reshuffleDoubleEliminationSeeds,
swapDoubleEliminationSeeds,
} from '../double-elimination/double-elimination.util';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
@@ -76,6 +73,7 @@ interface MatchListFilter {
interface JoinMatchParams {
matchId: mongoose.Types.ObjectId;
communityId?: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId;
preferredPositions?: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
@@ -101,17 +99,6 @@ interface UpdateParticipantPositionsParams {
subPosition: Position;
}
interface DoubleEliminationAdminParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
actorUserId: mongoose.Types.ObjectId;
}
interface SwapDoubleEliminationSeedsParams extends DoubleEliminationAdminParams {
leftSeedNumber: number;
rightSeedNumber: number;
}
@Injectable()
export class MatchService {
constructor(
@@ -197,9 +184,10 @@ export class MatchService {
public async getById(
matchId: mongoose.Types.ObjectId,
communityId: mongoose.Types.ObjectId,
): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(matchId);
const match = await MatchModel.findOne({ _id: matchId, communityId });
if (!match) throw new NotFoundException('Match not found.');
return match;
}
@@ -224,15 +212,24 @@ export class MatchService {
throw new BadRequestException('Match does not belong to this community.');
}
const previousStatus = match.status;
if (
previousStatus !== 'recruiting' &&
params.patch.status === 'recruiting'
) {
throw new ConflictException(
'A finalized team build cannot return to recruiting. Preserve its immutable lifecycle and create a new Match instead.',
);
}
if (
previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch ||
'gameCount' in params.patch ||
'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch ||
'doubleEliminationResetFinalEnabled' in params.patch)
) {
throw new BadRequestException(
'maxParticipants, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
'maxParticipants, gameCount, gameMode, roundRobinMaxRounds, and doubleEliminationResetFinalEnabled can only be changed while recruiting.',
);
}
const patchToSet =
@@ -252,21 +249,8 @@ export class MatchService {
})
: this.stripMatchConfigInput(params.patch);
match.set(patchToSet);
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
if (match.tournamentCodeIds.length > 0) {
await this.tournamentCodeService.releaseFromMatch(match);
}
match.tournamentCodeIds = [];
match.gameSchedule = [];
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
}
await match.save();
if (previousStatus !== 'recruiting' && match.status === 'recruiting') {
await this.matchStatsService.removeByMatch(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
} else if (match.result?.games?.length) {
if (match.result?.games?.length) {
await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
}
@@ -283,62 +267,31 @@ export class MatchService {
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if (match.status !== 'recruiting') {
throw new ConflictException(
'Only a recruiting Match can be hard-deleted. Finalized Match history must be preserved.',
);
}
if (match.competitionId) {
throw new ConflictException(
'A Match with a Competition cannot be hard-deleted. Preserve the immutable ledger and archive the Match instead.',
);
}
await this.tournamentCodeService.releaseFromMatch(match);
await this.matchStatsService.removeByMatch(match._id);
await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId);
}
public async reshuffleDoubleEliminationSeeds(
params: DoubleEliminationAdminParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
await this.assertDoubleEliminationSeedsCanChange(match);
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = reshuffleDoubleEliminationSeeds(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
);
match.doubleElimination.events.push({
type: 'seeds-reshuffled',
actorUserId: params.actorUserId,
createdAt: new Date(),
});
match.markModified('doubleElimination');
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
return match;
}
public async swapDoubleEliminationSeeds(
params: SwapDoubleEliminationSeedsParams,
): Promise<MatchDocument> {
const match = await this.loadDoubleEliminationMatch(params);
await this.assertDoubleEliminationSeedsCanChange(match);
await this.releaseReservedDoubleEliminationCodes(match);
match.doubleElimination = swapDoubleEliminationSeeds(
match.doubleElimination as NonNullable<Match['doubleElimination']>,
{
leftSeedNumber: params.leftSeedNumber,
rightSeedNumber: params.rightSeedNumber,
},
);
match.doubleElimination.events.push({
type: 'seeds-swapped',
actorUserId: params.actorUserId,
createdAt: new Date(),
});
match.markModified('doubleElimination');
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
return match;
}
public async join(params: JoinMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.');
if (params.communityId && !user.communityId.equals(params.communityId)) {
throw new NotFoundException('Match not found.');
}
const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
@@ -362,7 +315,7 @@ export class MatchService {
const updatedMatch = await MatchModel.findOneAndUpdate(
{
_id: params.matchId,
communityId: user.communityId,
communityId: params.communityId ?? user.communityId,
status: 'recruiting',
'participants.userId': { $ne: user._id },
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
@@ -438,85 +391,6 @@ export class MatchService {
return gameCount % 2 === 0 ? gameCount + 1 : gameCount;
}
private async loadDoubleEliminationMatch(params: {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
}): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match');
let match = await MatchModel.findById(params.matchId);
if (!match) throw new NotFoundException('Match not found.');
if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.');
}
if ((match.gameMode ?? 'pair') !== 'double-elimination') {
throw new BadRequestException('Match is not double elimination.');
}
if (!match.doubleElimination?.bracketMatches?.length) {
match = await this.tournamentCodeService.reserveForMatch(match);
}
if (!match.doubleElimination?.bracketMatches?.length) {
throw new BadRequestException('Double elimination bracket is not ready.');
}
return match;
}
private async assertDoubleEliminationSeedsCanChange(
match: MatchDocument,
): Promise<void> {
if (
match.doubleElimination?.bracketMatches.some(
(bracketMatch) => bracketMatch.state === 'completed',
)
) {
throw new BadRequestException(
'Seeds cannot be changed after a bracket match is completed.',
);
}
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const usedCode = await TournamentCodeModel.exists({
_id: { $in: match.tournamentCodeIds ?? [] },
$or: [{ state: 'used' }, { riotMatchId: { $exists: true } }],
});
if (usedCode) {
throw new BadRequestException(
'Seeds cannot be changed after a tournament code is used.',
);
}
}
private async releaseReservedDoubleEliminationCodes(
match: MatchDocument,
): Promise<void> {
const ids = match.tournamentCodeIds ?? [];
if (ids.length === 0) return;
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const codes = await TournamentCodeModel.find({
_id: { $in: ids },
matchId: match._id,
state: 'reserved',
bracketMatchId: { $exists: true },
}).exec();
if (codes.length === 0) return;
const releasedIds = codes.map((code) => code._id.toString());
await TournamentCodeModel.updateMany(
{ _id: { $in: codes.map((code) => code._id) } },
{
$set: { state: 'released', releasedAt: new Date() },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
},
},
).exec();
match.tournamentCodeIds = ids.filter(
(id) => !releasedIds.includes(id.toString()),
);
}
public async cancelJoin(
params: CancelMatchJoinParams,
): Promise<MatchDocument> {
@@ -1,47 +0,0 @@
import mongoose from 'mongoose';
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import type { TournamentCodeService } from './tournament-code.service';
describe('TournamentCodeReplacementController', () => {
function createFixture() {
const service = {
replaceForMatchGame: jest.fn().mockResolvedValue({
gameNumber: 1,
code: 'NEW-CODE',
}),
} as unknown as jest.Mocked<
Pick<TournamentCodeService, 'replaceForMatchGame'>
>;
const controller = new TournamentCodeReplacementController(
service as unknown as TournamentCodeService,
);
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
return { controller, service, communityId, matchId };
}
it('allows public replacement requests', async () => {
const { controller, service, communityId, matchId } = createFixture();
await expect(
controller.replaceForMatchGame(communityId, matchId, 1),
).resolves.toEqual(expect.objectContaining({ code: 'NEW-CODE' }));
expect(service.replaceForMatchGame).toHaveBeenCalledWith({
communityId,
matchId,
gameNumber: 1,
});
});
it('marks the replacement endpoint as public access', () => {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
TournamentCodeReplacementController.prototype.replaceForMatchGame,
),
).toBe(true);
});
});
@@ -1,30 +0,0 @@
import {
Controller,
Param,
ParseIntPipe,
Post,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import { TournamentCodeService } from './tournament-code.service';
@Controller('communities/:communityId/tournament-codes')
export class TournamentCodeReplacementController {
constructor(private readonly tournamentCodeService: TournamentCodeService) {}
@Post('matches/:matchId/games/:gameNumber/replace')
@AllowPublicAccess()
public async replaceForMatchGame(
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('gameNumber', ParseIntPipe) gameNumber: number,
) {
return this.tournamentCodeService.replaceForMatchGame({
communityId,
matchId,
gameNumber,
});
}
}
@@ -3,14 +3,13 @@ import { AuctionRedisModule } from '../auction/redis/auction-redis.module';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import { TournamentCodeScheduler } from './tournament-code.scheduler';
import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service';
@Module({
imports: [TournamentResultModule, AuctionRedisModule],
controllers: [TournamentCodeController, TournamentCodeReplacementController],
controllers: [TournamentCodeController],
providers: [
TournamentCodeService,
TournamentCodeVendorService,
@@ -1,16 +1,28 @@
import mongoose from 'mongoose';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { TournamentCodeScheduler } from './tournament-code.scheduler';
describe('TournamentCodeScheduler', () => {
function createScheduler(params?: {
attachedMatches?: unknown[];
expirationResult?: {
affectedMatchIds: unknown[];
expiredCount: number;
failedCount: number;
};
scheduleInitialPoll?: jest.Mock;
}) {
const tournamentCodeService = {
attachPendingMatchDocuments: jest
.fn()
.mockResolvedValue(params?.attachedMatches ?? []),
markExpired: jest.fn().mockResolvedValue(0),
markExpired: jest.fn().mockResolvedValue(
params?.expirationResult ?? {
affectedMatchIds: [],
expiredCount: 0,
failedCount: 0,
},
),
};
const autoProvisionService = {
ensurePool: jest.fn().mockResolvedValue(undefined),
@@ -20,21 +32,26 @@ describe('TournamentCodeScheduler', () => {
params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null),
};
const distributedLockService = {
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
runWithRenewedLock: jest
.fn()
.mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
} as unknown as jest.Mocked<DistributedLockService>;
const scheduler = new TournamentCodeScheduler(
tournamentCodeService as never,
autoProvisionService as never,
tournamentResultService as never,
distributedLockService as never,
) as unknown as { attachPending(): Promise<void> };
) as unknown as {
attachPending(): Promise<void>;
markExpired(): Promise<void>;
};
return {
scheduler,
@@ -84,4 +101,21 @@ describe('TournamentCodeScheduler', () => {
tournamentCodeService.attachPendingMatchDocuments,
).not.toHaveBeenCalled();
});
it('reconciles Competition assignments after expiring Match-bound codes', async () => {
const matchId = new mongoose.Types.ObjectId();
const { scheduler, tournamentResultService } = createScheduler({
expirationResult: {
affectedMatchIds: [matchId],
expiredCount: 1,
failedCount: 0,
},
});
await scheduler.markExpired();
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith(
matchId,
);
});
});
@@ -1,4 +1,9 @@
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import {
Injectable,
Logger,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
@@ -31,13 +36,19 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
this.attachTimer = setInterval(() => {
void this.attachPending();
}, 30_000);
this.expireTimer = setInterval(() => {
void this.markExpired();
}, 60 * 60 * 1000);
this.expireTimer = setInterval(
() => {
void this.markExpired();
},
60 * 60 * 1000,
);
if (isAutoProvisionEnabled()) {
this.refillTimer = setInterval(() => {
void this.ensureVendorPool();
}, 5 * 60 * 1000);
this.refillTimer = setInterval(
() => {
void this.ensureVendorPool();
},
5 * 60 * 1000,
);
}
this.attachTimer.unref?.();
this.expireTimer.unref?.();
@@ -99,7 +110,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
},
async () => {
await this.tournamentCodeService.markExpired();
const result = await this.tournamentCodeService.markExpired();
for (const matchId of result.affectedMatchIds) {
try {
await this.tournamentResultService.scheduleInitialPoll(matchId);
} catch (error) {
this.logger.warn(
`Failed to reconcile Competition codes after expiring a code for Match ${matchId.toString()}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
},
);
} catch (error) {
@@ -136,8 +158,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
}
function isAutoProvisionEnabled(): boolean {
const raw = process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED
?.trim()
.toLowerCase();
const raw =
process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED?.trim().toLowerCase();
return raw !== 'false' && raw !== '0' && raw !== 'off';
}
@@ -2,6 +2,7 @@ import {
TournamentCodeSchema,
type MatchDocument,
} from '../global/database/schema';
import { Logger } from '@nestjs/common';
import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service';
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
@@ -13,11 +14,6 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void;
replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<unknown>;
attachPendingMatches(communityId?: mongoose.Types.ObjectId): Promise<number>;
};
@@ -37,6 +33,21 @@ function createSession() {
};
}
function mongoQuery<T>(value: T) {
const query = {
exec: jest.fn().mockResolvedValue(value),
lean: jest.fn(),
limit: jest.fn(),
select: jest.fn(),
session: jest.fn(),
};
query.lean.mockReturnValue(query);
query.limit.mockReturnValue(query);
query.select.mockReturnValue(query);
query.session.mockReturnValue(query);
return query;
}
function createService() {
return new TournamentCodeService(
{} as never,
@@ -51,6 +62,7 @@ interface MatchOverrides {
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
doubleElimination?: MatchDocument['doubleElimination'];
tournamentCodeIds?: mongoose.Types.ObjectId[];
gameSchedule?: Array<{
gameNumber: number;
roundNumber?: number;
@@ -261,6 +273,43 @@ describe('TournamentCodeService round-robin scheduling', () => {
).toMatchObject({ gameCount: 3, requiredWins: 2 });
});
it('builds a missing bracket from already-persisted authoritative seeds', () => {
const service = createService();
const match = createMatch({
gameMode: 'double-elimination',
gameCount: 3,
teams: Array.from({ length: 4 }, (_, index) => ({
teamIndex: index + 1,
})),
doubleElimination: {
teamCount: 4,
resetFinalEnabled: true,
resetFinalCreated: false,
seeds: [
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
],
bracketMatches: [],
placements: {},
events: [],
},
});
const random = jest.spyOn(Math, 'random').mockReturnValue(0);
service.ensureGameSchedule(match);
expect(match.doubleElimination?.seeds).toEqual([
{ seedNumber: 1, teamIndex: 3 },
{ seedNumber: 2, teamIndex: 1 },
{ seedNumber: 3, teamIndex: 4 },
{ seedNumber: 4, teamIndex: 2 },
]);
expect(random).not.toHaveBeenCalled();
random.mockRestore();
});
it('expands double-elimination winner bracket series into code slots', async () => {
const TournamentCodeModel = {
find: jest.fn().mockReturnValue({
@@ -437,6 +486,50 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(slots).toEqual([]);
});
it('shows the active replacement when a reversed terminal code shares its game number', async () => {
const oldCodeId = new mongoose.Types.ObjectId();
const replacementCodeId = new mongoose.Types.ObjectId();
const TournamentCodeModel = {
find: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue([
{
_id: replacementCodeId,
code: 'NEW-CODE',
gameNumber: 1,
state: 'reserved',
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
{
_id: oldCodeId,
code: 'OLD-CODE',
gameNumber: 1,
state: 'released',
expiresAt: new Date('2026-07-13T00:00:00.000Z'),
},
]),
}),
};
const service = new TournamentCodeService(
{ getModel: jest.fn().mockResolvedValue(TournamentCodeModel) } as never,
createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals;
const match = createMatch({
gameCount: 1,
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [oldCodeId, replacementCodeId],
});
const slots = await service.buildSlots(match);
expect(slots[0]).toEqual(
expect.objectContaining({
gameNumber: 1,
code: 'NEW-CODE',
state: 'reserved',
}),
);
});
});
describe('TournamentCodeService bulk upload', () => {
@@ -639,228 +732,278 @@ describe('TournamentCodeService pending match attachment', () => {
});
});
describe('TournamentCodeService code replacement', () => {
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function createCode(overrides: Record<string, unknown>) {
return {
describe('TournamentCodeService Competition assignment safety', () => {
it('does not restore an actively reserved code outside Competition commands', async () => {
const code = {
_id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved',
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
matchId: new mongoose.Types.ObjectId(),
gameNumber: 1,
reservedAt: new Date(),
releasedAt: undefined,
riotMatchId: undefined,
save: jest.fn().mockResolvedValue(undefined),
...overrides,
save: jest.fn(),
};
}
function createReplacementFixture(params?: {
currentCode?: Record<string, unknown> | null;
replacementCode?: Record<string, unknown> | null;
match?: MatchDocument;
}) {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const oldCodeId = new mongoose.Types.ObjectId();
const newCodeId = new mongoose.Types.ObjectId();
const match =
params?.match ??
createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [oldCodeId],
} as unknown as MatchOverrides);
const currentCode =
params?.currentCode === null
? null
: createCode({
_id: oldCodeId,
code: 'OLD-CODE',
matchId,
gameNumber: 1,
...(params?.currentCode ?? {}),
});
const replacementCode =
params?.replacementCode === null
? null
: createCode({
_id: newCodeId,
code: 'NEW-CODE',
matchId,
gameNumber: 1,
...(params?.replacementCode ?? {}),
});
const MatchModel = {
findOne: jest.fn().mockReturnValue(queryResult(match)),
};
const TournamentCodeModel = {
findOne: jest.fn().mockReturnValue(queryResult(currentCode)),
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(replacementCode)),
updateOne: jest.fn().mockReturnValue(queryResult({ modifiedCount: 1 })),
};
const session = createSession();
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn().mockImplementation((modelName: string) => {
if (modelName === 'match') return Promise.resolve(MatchModel);
if (modelName === 'tournamentCode') {
return Promise.resolve(TournamentCodeModel);
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'tournamentCode') {
return Promise.resolve({
findById: jest.fn().mockResolvedValue(code),
});
}
throw new Error(`Unexpected model: ${modelName}`);
if (name === 'match') return Promise.resolve({});
throw new Error(`Unexpected model ${name}`);
}),
};
const auctionRedisService = createAuctionRedisService();
const service = new TournamentCodeService(
connectionService as never,
auctionRedisService as never,
) as unknown as TournamentCodeServiceInternals;
createAuctionRedisService() as never,
);
return {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
};
}
it('replaces a reserved code on the same game slot', async () => {
const {
match,
communityId,
matchId,
currentCode,
replacementCode,
MatchModel,
TournamentCodeModel,
auctionRedisService,
session,
service,
} = createReplacementFixture();
const slot = await service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
});
expect(slot).toEqual(
expect.objectContaining({
gameNumber: 1,
teamAIndex: 1,
teamBIndex: 2,
code: 'NEW-CODE',
state: 'reserved',
}),
await expect(service.restoreToAvailable(code._id)).rejects.toThrow(
'Active Competition assignments',
);
expect(MatchModel.findOne).toHaveBeenCalledWith({
_id: matchId,
communityId,
});
expect(TournamentCodeModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
}),
expect.objectContaining({
$set: expect.objectContaining({
state: 'reserved',
matchId,
gameNumber: 1,
}),
}),
expect.objectContaining({ returnDocument: 'after' }),
);
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
`tournament-code:match:${matchId.toString()}:lock`,
expect.any(String),
expect.any(Number),
);
expect(session.startTransaction).toHaveBeenCalledTimes(1);
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
expect(auctionRedisService.releaseTokenLock).toHaveBeenCalledWith(
`tournament-code:match:${matchId.toString()}:lock`,
expect.any(String),
);
expect(TournamentCodeModel.updateOne).toHaveBeenCalledWith(
{ _id: currentCode?._id },
expect.objectContaining({
$set: expect.objectContaining({ state: 'released' }),
$unset: expect.objectContaining({
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
}),
}),
);
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.tournamentCodeIds.map((id) => id.toString())).toEqual([
replacementCode?._id.toString(),
]);
expect(match.save).toHaveBeenCalled();
expect(code.save).not.toHaveBeenCalled();
});
it('rejects replacement after the game result is collected', async () => {
it('expires a reserved code and releases its assignment and Match binding atomically', async () => {
const codeId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const fixture = createReplacementFixture({
match: createMatch({
_id: matchId,
communityId,
status: 'in-progress',
gameCount: 1,
participants: Array.from({ length: 10 }, () => ({})),
teams: [{ teamIndex: 1 }, { teamIndex: 2 }],
tournamentCodeIds: [new mongoose.Types.ObjectId()],
result: {
riotMatchIds: ['KR_1'],
games: [{ gameNumber: 1 }],
seriesResults: [],
},
} as unknown as MatchOverrides),
const competitionId = new mongoose.Types.ObjectId();
const assignmentId = new mongoose.Types.ObjectId();
const session = createSession();
const code = { _id: codeId, state: 'reserved', matchId };
const codeUpdate = jest.fn().mockReturnValue(mongoQuery(code));
const assignmentUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const matchUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const models = {
tournamentCode: {
find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])),
findOne: jest.fn().mockReturnValue(mongoQuery(code)),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn().mockReturnValue(
mongoQuery([
{
_id: assignmentId,
competitionId,
state: 'reserved',
},
]),
),
updateOne: assignmentUpdate,
},
competition: {
findById: jest.fn().mockReturnValue(mongoQuery({ matchId })),
},
match: { updateOne: matchUpdate },
};
const service = new TournamentCodeService(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [matchId],
expiredCount: 1,
failedCount: 0,
});
await expect(
fixture.service.replaceForMatchGame({
communityId,
matchId,
gameNumber: 1,
}),
).rejects.toThrow('already has a collected result');
expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled();
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(codeUpdate).toHaveBeenCalledWith(
{
_id: codeId,
expiresAt: { $lte: expect.any(Date) as Date },
state: 'reserved',
},
{
$set: { state: 'expired' },
$unset: {
bracketMatchId: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
},
},
{ returnDocument: 'before', session },
);
expect(assignmentUpdate).toHaveBeenCalledWith(
{ _id: assignmentId, state: 'reserved' },
{
$set: { releasedAt: expect.any(Date) as Date, state: 'released' },
},
{ session },
);
expect(matchUpdate).toHaveBeenCalledWith(
{ _id: matchId },
{ $pull: { tournamentCodeIds: codeId } },
{ session },
);
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('aborts the transaction when no replacement code is available', async () => {
const { match, communityId, matchId, currentCode, session, service } =
createReplacementFixture({
replacementCode: null,
});
it('isolates a used-assignment corruption and still expires the next valid candidate', async () => {
const corruptCodeId = new mongoose.Types.ObjectId();
const validCodeId = new mongoose.Types.ObjectId();
const corruptMatchId = new mongoose.Types.ObjectId();
const validMatchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const validAssignmentId = new mongoose.Types.ObjectId();
const sessions = [createSession(), createSession()];
const codeById = new Map([
[
corruptCodeId.toString(),
{ _id: corruptCodeId, state: 'reserved', matchId: corruptMatchId },
],
[
validCodeId.toString(),
{ _id: validCodeId, state: 'reserved', matchId: validMatchId },
],
]);
const codeUpdate = jest.fn((filter: { _id: mongoose.Types.ObjectId }) =>
mongoQuery(codeById.get(filter._id.toString())),
);
const assignmentUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const matchUpdate = jest
.fn()
.mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
const models = {
tournamentCode: {
find: jest
.fn()
.mockReturnValue(
mongoQuery([{ _id: corruptCodeId }, { _id: validCodeId }]),
),
findOne: jest.fn((filter: { _id: mongoose.Types.ObjectId }) =>
mongoQuery(codeById.get(filter._id.toString())),
),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn((filter: { tournamentCodeId: mongoose.Types.ObjectId }) =>
mongoQuery(
filter.tournamentCodeId.equals(corruptCodeId)
? [
{
_id: new mongoose.Types.ObjectId(),
competitionId,
state: 'used',
},
]
: [
{
_id: validAssignmentId,
competitionId,
state: 'reserved',
},
],
),
),
updateOne: assignmentUpdate,
},
competition: {
findById: jest
.fn()
.mockReturnValue(mongoQuery({ matchId: validMatchId })),
},
match: { updateOne: matchUpdate },
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const service = new TournamentCodeService(
{
createSession: jest
.fn()
.mockImplementation(() => Promise.resolve(sessions.shift())),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(
service.replaceForMatchGame({ communityId, matchId, gameNumber: 1 }),
).rejects.toThrow('No available tournament code');
expect(currentCode?.save).not.toHaveBeenCalled();
expect(match.save).not.toHaveBeenCalled();
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [validMatchId],
expiredCount: 1,
failedCount: 1,
});
expect(codeUpdate).toHaveBeenCalledTimes(1);
expect(codeUpdate.mock.calls[0][0]).toMatchObject({ _id: validCodeId });
expect(assignmentUpdate).toHaveBeenCalledWith(
{ _id: validAssignmentId, state: 'reserved' },
expect.any(Object),
expect.any(Object),
);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('used Competition assignment'),
);
errorLog.mockRestore();
});
it('leaves a foreign Competition assignment unchanged and reports the candidate failure', async () => {
const codeId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const foreignMatchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const code = { _id: codeId, state: 'reserved', matchId };
const codeUpdate = jest.fn();
const session = createSession();
const models = {
tournamentCode: {
find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])),
findOne: jest.fn().mockReturnValue(mongoQuery(code)),
findOneAndUpdate: codeUpdate,
},
tournamentCodeAssignment: {
find: jest.fn().mockReturnValue(
mongoQuery([
{
_id: new mongoose.Types.ObjectId(),
competitionId,
state: 'reserved',
},
]),
),
updateOne: jest.fn(),
},
competition: {
findById: jest
.fn()
.mockReturnValue(mongoQuery({ matchId: foreignMatchId })),
},
match: { updateOne: jest.fn() },
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const service = new TournamentCodeService(
{
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as never,
createAuctionRedisService() as never,
);
await expect(service.markExpired()).resolves.toEqual({
affectedMatchIds: [],
expiredCount: 0,
failedCount: 1,
});
expect(codeUpdate).not.toHaveBeenCalled();
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('ownership does not match'),
);
errorLog.mockRestore();
});
});
@@ -3,6 +3,7 @@ import {
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
@@ -43,8 +44,16 @@ const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000;
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
export interface TournamentCodeExpirationResult {
expiredCount: number;
failedCount: number;
affectedMatchIds: mongoose.Types.ObjectId[];
}
@Injectable()
export class TournamentCodeService {
private readonly logger = new Logger(TournamentCodeService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly auctionRedisService: AuctionRedisService,
@@ -216,9 +225,9 @@ export class TournamentCodeService {
const MatchModel = await this.connectionService.getModel('match');
const code = await TournamentCodeModel.findById(id);
if (!code) throw new NotFoundException('Tournament code not found.');
if (code.state !== 'released' && code.state !== 'reserved') {
if (code.state !== 'released') {
throw new BadRequestException(
'Only released or reserved tournament codes can be restored.',
'Only released tournament codes can be restored. Active Competition assignments must be reversed through Competition commands.',
);
}
const previousMatchId = code.matchId;
@@ -318,174 +327,6 @@ export class TournamentCodeService {
return match;
}
public async replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<TournamentCodeSlotView> {
return this.withLockedMatchTransaction(params.matchId, (session) =>
this.replaceForMatchGameInTransaction(params, session),
);
}
private async replaceForMatchGameInTransaction(
params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
},
session: mongoose.ClientSession,
): Promise<TournamentCodeSlotView> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const match = await this.execQuery<MatchDocument | null>(
this.withQuerySession(
MatchModel.findOne({
_id: params.matchId,
communityId: params.communityId,
}),
session,
),
);
if (!match) throw new NotFoundException('Match not found.');
if (match.status !== 'team-built' && match.status !== 'in-progress') {
throw new BadRequestException(
'Tournament codes can only be replaced while the match is ready or in progress.',
);
}
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match);
const doubleEliminationSlot =
(match.gameMode ?? 'pair') === 'double-elimination'
? this.resolveDoubleEliminationGameSlotByGameNumber(
match,
params.gameNumber,
)
: undefined;
const requiredSlots = this.resolveRequiredSlots(match);
if (
!Number.isInteger(params.gameNumber) ||
params.gameNumber < 1 ||
params.gameNumber > requiredSlots
) {
throw new BadRequestException('Invalid tournament code game number.');
}
if (
(match.result?.games ?? []).some(
(game) => game.gameNumber === params.gameNumber,
)
) {
throw new BadRequestException(
'This game already has a collected result and cannot be replaced.',
);
}
const currentCode = await this.execQuery<TournamentCodeDocument | null>(
this.withQuerySession(
TournamentCodeModel.findOne({
_id: { $in: match.tournamentCodeIds },
matchId: match._id,
...(doubleEliminationSlot
? {
gameNumber: params.gameNumber,
bracketMatchId:
doubleEliminationSlot.bracketMatch.bracketMatchId,
}
: { gameNumber: params.gameNumber }),
}),
session,
),
);
if (!currentCode) {
throw new NotFoundException('Assigned tournament code not found.');
}
if (currentCode.state === 'used' || currentCode.riotMatchId) {
throw new BadRequestException(
'Used tournament codes cannot be replaced.',
);
}
const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
await this.execQuery(
this.withQuerySession(
TournamentCodeModel.updateOne(
{ _id: currentCode._id },
{
$set: { state: 'released', releasedAt: new Date() },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
riotMatchId: 1,
},
},
),
session,
),
);
const replacement = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: params.gameNumber,
...(doubleEliminationSlot
? {
bracketMatchId:
doubleEliminationSlot.bracketMatch.bracketMatchId,
}
: {}),
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!replacement) {
throw new BadRequestException(
'No available tournament code to replace with.',
);
}
match.tournamentCodeIds = this.replaceTournamentCodeId(
match.tournamentCodeIds,
currentCode._id,
replacement._id,
);
await match.save({ session });
return {
gameNumber: params.gameNumber,
...(doubleEliminationSlot
? this.toDoubleEliminationSlotBase(doubleEliminationSlot)
: {}),
roundNumber: this.resolveRoundNumberForGameNumber(
match,
params.gameNumber,
),
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
code: replacement.code,
expiresAt: replacement.expiresAt.toISOString(),
state: replacement.state,
riotMatchId: replacement.riotMatchId ?? null,
};
}
public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> {
@@ -530,17 +371,153 @@ export class TournamentCodeService {
await match.save({ session });
}
public async markExpired(): Promise<number> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const result = await TournamentCodeModel.updateMany(
{
state: { $in: ['available', 'reserved', 'released'] },
expiresAt: { $lte: new Date() },
},
{ $set: { state: 'expired' } },
).exec();
return result.modifiedCount;
public async markExpired(): Promise<TournamentCodeExpirationResult> {
const [TournamentCodeModel, AssignmentModel, CompetitionModel, MatchModel] =
await Promise.all([
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('competition'),
this.connectionService.getModel('match'),
]);
const expiredAt = new Date();
const candidates = await TournamentCodeModel.find({
state: { $in: ['available', 'reserved', 'released'] },
expiresAt: { $lte: expiredAt },
})
.select({ _id: 1 })
.lean()
.exec();
const affectedMatchIds = new Map<string, mongoose.Types.ObjectId>();
let expiredCount = 0;
let failedCount = 0;
for (const candidate of candidates) {
try {
const expired = await this.runTransactionWithRetry(async (session) => {
const code = await TournamentCodeModel.findOne(
{
_id: candidate._id,
expiresAt: { $lte: expiredAt },
state: { $in: ['available', 'reserved', 'released'] },
},
null,
{ session },
)
.lean()
.exec();
if (!code) return null;
const activeAssignments = await AssignmentModel.find({
tournamentCodeId: code._id,
state: { $in: ['reserved', 'used'] },
})
.session(session)
.limit(2)
.lean()
.exec();
if (activeAssignments.length > 1) {
throw new Error(
`Tournament Code ${code._id.toString()} has multiple active Competition assignments.`,
);
}
const assignment = activeAssignments[0];
if (assignment?.state === 'used') {
throw new Error(
`Tournament Code ${code._id.toString()} has a used Competition assignment and cannot expire as reserved.`,
);
}
if (assignment) {
if (!code.matchId) {
throw new Error(
`Tournament Code ${code._id.toString()} has an active Competition assignment without a Match binding.`,
);
}
const competition = await CompetitionModel.findById(
assignment.competitionId,
)
.session(session)
.select({ matchId: 1 })
.lean()
.exec();
if (
!competition ||
competition.matchId.toString() !== code.matchId.toString()
) {
throw new Error(
`Tournament Code ${code._id.toString()} Competition ownership does not match its Match binding.`,
);
}
}
const expiredCode = await TournamentCodeModel.findOneAndUpdate(
{
_id: code._id,
expiresAt: { $lte: expiredAt },
state: code.state,
},
{
$set: { state: 'expired' },
$unset: {
bracketMatchId: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
},
},
{ returnDocument: 'before', session },
).exec();
if (!expiredCode) return null;
if (assignment) {
const assignmentResult = await AssignmentModel.updateOne(
{ _id: assignment._id, state: 'reserved' },
{ $set: { releasedAt: expiredAt, state: 'released' } },
{ session },
).exec();
if (assignmentResult.modifiedCount !== 1) {
throw new Error(
`Tournament Code ${code._id.toString()} assignment did not transition to released.`,
);
}
}
if (code.matchId) {
const matchResult = await MatchModel.updateOne(
{ _id: code.matchId },
{ $pull: { tournamentCodeIds: code._id } },
{ session },
).exec();
if (
assignment &&
(matchResult.matchedCount !== 1 ||
matchResult.modifiedCount !== 1)
) {
throw new Error(
`Tournament Code ${code._id.toString()} Match binding did not transition atomically.`,
);
}
}
return code;
});
if (!expired) continue;
expiredCount += 1;
if (expired.matchId) {
affectedMatchIds.set(expired.matchId.toString(), expired.matchId);
}
} catch (error) {
failedCount += 1;
this.logger.error(
`Failed to expire Tournament Code ${candidate._id.toString()}; candidate was left unchanged: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
return {
expiredCount,
failedCount,
affectedMatchIds: [...affectedMatchIds.values()],
};
}
public async attachPendingMatches(
@@ -610,7 +587,11 @@ export class TournamentCodeService {
: [];
const byGameNumber = new Map(
codes
.filter((code) => typeof code.gameNumber === 'number')
.filter(
(code) =>
typeof code.gameNumber === 'number' &&
(code.state === 'reserved' || code.state === 'used'),
)
.map((code) => [code.gameNumber as number, code]),
);
@@ -645,21 +626,6 @@ export class TournamentCodeService {
return (code ?? '').trim();
}
private replaceTournamentCodeId(
currentIds: mongoose.Types.ObjectId[],
oldId: mongoose.Types.ObjectId,
newId: mongoose.Types.ObjectId,
): mongoose.Types.ObjectId[] {
let replaced = false;
const next = currentIds.map((id) => {
if (id.toString() !== oldId.toString()) return id;
replaced = true;
return newId;
});
if (!replaced) next.push(newId);
return next;
}
private resolveMatchId(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): mongoose.Types.ObjectId {
@@ -991,7 +957,12 @@ export class TournamentCodeService {
.map((team) => team.teamIndex)
.sort((left, right) => left - right);
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
const seededTeamIndexes = this.configuredDoubleEliminationSeedOrder(
match,
teamIndexes,
);
const shuffledTeamIndexes =
seededTeamIndexes ?? this.shuffleTeamIndexes(teamIndexes);
match.doubleElimination = buildDoubleEliminationBracket(
shuffledTeamIndexes,
{
@@ -1003,6 +974,34 @@ export class TournamentCodeService {
match.markModified?.('doubleElimination');
}
private configuredDoubleEliminationSeedOrder(
match: MatchDocument,
teamIndexes: number[],
): number[] | undefined {
const seeds = match.doubleElimination?.seeds ?? [];
if (seeds.length !== teamIndexes.length) return undefined;
const validTeamIndexes = new Set(teamIndexes);
const seedNumbers = new Set<number>();
const seededTeamIndexes = new Set<number>();
for (const seed of seeds) {
if (
!Number.isInteger(seed.seedNumber) ||
seed.seedNumber < 1 ||
seed.seedNumber > teamIndexes.length ||
seedNumbers.has(seed.seedNumber) ||
!validTeamIndexes.has(seed.teamIndex) ||
seededTeamIndexes.has(seed.teamIndex)
) {
return undefined;
}
seedNumbers.add(seed.seedNumber);
seededTeamIndexes.add(seed.teamIndex);
}
return [...seeds]
.sort((left, right) => left.seedNumber - right.seedNumber)
.map(({ teamIndex }) => teamIndex);
}
private resolveDoubleEliminationGameSlotByGameNumber(
match: MatchDocument,
gameNumber: number,
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import { Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { ConnectionService } from '../global/database/connection.service';
@@ -7,6 +8,10 @@ import { CompetitionAssignmentProvisioner } from './competition-assignment.provi
import { CompetitionOutboxProcessor } from './competition-outbox.processor';
describe('CompetitionOutboxProcessor', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('leases a projection event and applies idempotent downstream effects', async () => {
const competitionId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
@@ -158,6 +163,59 @@ describe('CompetitionOutboxProcessor', () => {
},
);
});
it('dead-letters a poison event after the delivery attempt limit', async () => {
const event = {
_id: new mongoose.Types.ObjectId(),
competitionId: new mongoose.Types.ObjectId(),
revision: 2,
type: 'competition.projection-updated',
state: 'pending',
attemptCount: 10,
};
const updateOne = jest.fn(() => executable({ matchedCount: 1 }));
const models = {
competitionOutbox: {
findOneAndUpdate: jest
.fn()
.mockReturnValueOnce(leanExecutable(event))
.mockReturnValueOnce(leanExecutable(null)),
updateOne,
},
competition: {
findById: jest.fn(() => leanExecutable(null)),
},
match: {},
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const processor = new CompetitionOutboxProcessor(
{
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as unknown as ConnectionService,
{ provisionReadyAssignments: jest.fn() } as never,
{ buildAndUpsert: jest.fn() } as never,
{ invalidateCommunity: jest.fn() } as never,
);
await expect(processor.drainOnce()).resolves.toBe(1);
expect(updateOne).toHaveBeenCalledWith(
{ _id: event._id, state: 'pending', attemptCount: 10 },
{
$set: {
state: 'dead-letter',
lastError: 'Competition no longer exists.',
},
},
);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('moved to dead-letter after 10 attempts'),
);
});
});
function leanExecutable<T>(value: T) {
@@ -15,6 +15,7 @@ const DRAIN_INTERVAL_MS = 5_000;
const PROCESSING_LEASE_MS = 60_000;
const MAX_EVENTS_PER_DRAIN = 20;
const MAX_RETRY_DELAY_MS = 5 * 60_000;
const MAX_DELIVERY_ATTEMPTS = 10;
interface ClaimedOutboxEvent {
_id: mongoose.Types.ObjectId;
@@ -130,18 +131,33 @@ export class CompetitionOutboxProcessor
$unset: { lastError: 1 },
}).exec();
} catch (error) {
const lastError = errorMessage(error).slice(0, 2_000);
if (event.attemptCount >= MAX_DELIVERY_ATTEMPTS) {
const terminal = await OutboxModel.updateOne(leaseFilter(event), {
$set: {
state: 'dead-letter',
lastError,
},
}).exec();
if (terminal.matchedCount > 0) {
this.logger.error(
`Competition outbox event ${event._id.toString()} moved to dead-letter after ${event.attemptCount} attempts: ${lastError}`,
);
}
return;
}
const availableAt = new Date(
Date.now() + retryDelayMilliseconds(event.attemptCount),
);
await OutboxModel.updateOne(leaseFilter(event), {
$set: {
state: 'failed',
lastError: errorMessage(error).slice(0, 2_000),
lastError,
availableAt,
},
}).exec();
this.logger.warn(
`Competition outbox event ${event._id.toString()} failed: ${errorMessage(error)}`,
`Competition outbox event ${event._id.toString()} failed: ${lastError}`,
);
}
}