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({ const sideEffectUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }), 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 scheduleInitialPoll = jest.fn().mockResolvedValue(null);
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true); const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
const broadcastMatchSideEffect = jest.fn(); const broadcastMatchSideEffect = jest.fn();
@@ -1010,7 +1013,7 @@ describe('auction durability projection helpers', () => {
teamIndex: 1, teamIndex: 1,
}, },
]); ]);
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(2);
expect(reserveForMatch).toHaveBeenCalledWith(match); expect(reserveForMatch).toHaveBeenCalledWith(match);
expect(scheduleInitialPoll).toHaveBeenCalledWith(match); expect(scheduleInitialPoll).toHaveBeenCalledWith(match);
expect(sideEffectUpdateOne).toHaveBeenCalledWith( expect(sideEffectUpdateOne).toHaveBeenCalledWith(
@@ -80,6 +80,7 @@ type ParsedMatchSideEffectMutation =
| { type: typeof UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE }; | { type: typeof UNDO_COMPLETED_MATCH_SIDE_EFFECT_TYPE };
interface CleanupSideEffectMatchDocument { interface CleanupSideEffectMatchDocument {
competitionId?: unknown;
gameSchedule?: unknown[]; gameSchedule?: unknown[];
participants: Array<{ excluded?: boolean }>; participants: Array<{ excluded?: boolean }>;
result?: unknown; result?: unknown;
@@ -420,13 +421,14 @@ export class AuctionDurabilityScheduler
}, },
); );
if (!processingDelta) return; if (!processingDelta) return;
let expectedMatchSideEffectRevision = const expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision; processingDelta.matchSideEffectRevision;
try { try {
const match = (await execMaybe( const match = (await execMaybe(
MatchModel.findById(payload.matchId) as never, MatchModel.findById(payload.matchId) as never,
)) as { )) as {
competitionId?: unknown;
participants: Array<{ participants: Array<{
preferredPositions?: Array<{ position?: Position }>; preferredPositions?: Array<{ position?: Position }>;
userId: { toString(): string }; userId: { toString(): string };
@@ -438,39 +440,50 @@ export class AuctionDurabilityScheduler
} | null; } | null;
if (!match) if (!match)
throw new Error(`Match not found: ${String(payload.matchId)}`); throw new Error(`Match not found: ${String(payload.matchId)}`);
const matchTeams = buildMatchTeamsFromProjection( if (match.competitionId) {
payload.afterAuctionMongoProjection, await this.tournamentResultService.scheduleInitialPoll(match as never);
match, } else {
); const matchTeams = buildMatchTeamsFromProjection(
// [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사 payload.afterAuctionMongoProjection,
// (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다). match,
const allMemberUserIds = matchTeams.flatMap((team) => );
team.members.map((member) => member.userId.toString()), // [AUCTION-DEBUG] 제거 대상. 최종 팀에 같은 유저가 2번 들어갔는지 무조건 검사
); // (출처가 markSold든 undo 복원이든 projection이든 여기서 결정적으로 잡힌다).
const distinctMemberCount = new Set(allMemberUserIds).size; const allMemberUserIds = matchTeams.flatMap((team) =>
recordNewRelicCustomEvent('AuctionServerTeamBuild', { team.members.map((member) => member.userId.toString()),
matchId: typeof payload.matchId === 'string' ? payload.matchId : '', );
auctionStateTransitionId: payload.auctionStateTransitionId, const distinctMemberCount = new Set(allMemberUserIds).size;
teamCount: matchTeams.length, recordNewRelicCustomEvent('AuctionServerTeamBuild', {
totalMemberCount: allMemberUserIds.length, matchId: typeof payload.matchId === 'string' ? payload.matchId : '',
distinctMemberCount, auctionStateTransitionId: payload.auctionStateTransitionId,
hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount, teamCount: matchTeams.length,
duplicateUserId: totalMemberCount: allMemberUserIds.length,
allMemberUserIds.find( distinctMemberCount,
(id, idx) => allMemberUserIds.indexOf(id) !== idx, hasDuplicateMember: allMemberUserIds.length !== distinctMemberCount,
) ?? null, duplicateUserId:
}); allMemberUserIds.find(
if (matchTeams.length === 0) { (id, idx) => allMemberUserIds.indexOf(id) !== idx,
throw new Error( ) ?? null,
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`, });
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 = const completedAtTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS(); await this.auctionRedisService.getCurrentRedisTimestampMS();
@@ -543,7 +556,9 @@ export class AuctionDurabilityScheduler
await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params); await this.isAppendHistoryInvalidatedByLaterDestructiveMutation(params);
if (invalidated) return; if (invalidated) return;
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne; const historyOperation = buildAuctionHistoryUpsert(
params.payload,
).updateOne;
await execMaybe( await execMaybe(
params.AuctionHistoryModel.updateOne( params.AuctionHistoryModel.updateOne(
historyOperation.filter as never, historyOperation.filter as never,
@@ -700,7 +715,7 @@ export class AuctionDurabilityScheduler
}, },
); );
if (!processingDelta) return; if (!processingDelta) return;
let expectedMatchSideEffectRevision = const expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision; processingDelta.matchSideEffectRevision;
try { try {
@@ -710,6 +725,11 @@ export class AuctionDurabilityScheduler
if (!match) { if (!match) {
throw new Error(`Match not found: ${String(params.payload.matchId)}`); 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); await params.updateMatch(match);
const completedAtTimestampMS = const completedAtTimestampMS =
@@ -2072,13 +2072,17 @@ describe('AuctionService', () => {
findById: jest.fn().mockResolvedValue(match), findById: jest.fn().mockResolvedValue(match),
}, },
}); });
tournamentCodeService.reserveForMatch.mockImplementation((candidate) => {
expect(candidate.teamBuiltAt).toBeUndefined();
return Promise.resolve(candidate);
});
await service.next(matchId); await service.next(matchId);
expect(auction.phase).toBe('complete'); expect(auction.phase).toBe('complete');
expect(auction.completedAt).toBeInstanceOf(Date); expect(auction.completedAt).toBeInstanceOf(Date);
expect(auction.save).toHaveBeenCalledTimes(1); expect(auction.save).toHaveBeenCalledTimes(1);
expect(match.save).toHaveBeenCalledTimes(1); expect(match.save).toHaveBeenCalledTimes(2);
expect(match.teams).toEqual([ expect(match.teams).toEqual([
{ {
teamIndex: 1, teamIndex: 1,
@@ -2174,6 +2178,55 @@ describe('AuctionService', () => {
expect(session.commitTransaction).toHaveBeenCalledTimes(1); 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 () => { it('fully deletes redis-v1 auction data when cancelling an auction', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
+59 -20
View File
@@ -1,5 +1,6 @@
import { import {
BadRequestException, BadRequestException,
ConflictException,
Injectable, Injectable,
InternalServerErrorException, InternalServerErrorException,
Logger, Logger,
@@ -471,7 +472,7 @@ export class AuctionService {
? auction.toObject({ depopulate: true }) ? auction.toObject({ depopulate: true })
: auction; : auction;
return { return {
...JSON.parse(JSON.stringify(mongoState)), ...this.cloneJson(mongoState),
...redisState, ...redisState,
chatMessages: auction.chatMessages ?? [], chatMessages: auction.chatMessages ?? [],
}; };
@@ -1061,8 +1062,8 @@ export class AuctionService {
return this.resolveReplayedRedisActionRequest(matchId, actionRequest); return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
} }
const passedPlayer = { const passedPlayer: AuctionPlayerSnapshot = {
...JSON.parse(JSON.stringify(currentPlayer)), ...this.cloneAuctionPlayerSnapshot(currentPlayer),
passCount: this.numberFromState(currentPlayer.passCount) + 1, passCount: this.numberFromState(currentPlayer.passCount) + 1,
}; };
structureInput.auctionPlayerOrder[ structureInput.auctionPlayerOrder[
@@ -1157,8 +1158,8 @@ export class AuctionService {
]; ];
if (!currentPlayer) throw new BadRequestException('No current player.'); if (!currentPlayer) throw new BadRequestException('No current player.');
const passedPlayer = { const passedPlayer: AuctionPlayerSnapshot = {
...JSON.parse(JSON.stringify(currentPlayer)), ...this.cloneAuctionPlayerSnapshot(currentPlayer),
passCount: this.numberFromState(currentPlayer.passCount) + 1, passCount: this.numberFromState(currentPlayer.passCount) + 1,
}; };
structureInput.auctionPlayerOrder[ structureInput.auctionPlayerOrder[
@@ -1210,7 +1211,7 @@ export class AuctionService {
structureInput.auctionPlayerOrder = [ structureInput.auctionPlayerOrder = [
...structureInput.auctionPlayerOrder, ...structureInput.auctionPlayerOrder,
...structureInput.passedAuctionPlayerQueue.map((player) => ...structureInput.passedAuctionPlayerQueue.map((player) =>
JSON.parse(JSON.stringify(player)), this.cloneAuctionPlayerSnapshot(player),
), ),
]; ];
structureInput.passedAuctionPlayerQueue = []; structureInput.passedAuctionPlayerQueue = [];
@@ -1434,6 +1435,7 @@ export class AuctionService {
if (!match.communityId.equals(params.communityId)) { if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Community mismatch.'); throw new BadRequestException('Community mismatch.');
} }
this.assertCompetitionLifecycleMutable(match, 'reset the auction');
if (this.isRedisV1Auction(auction)) { if (this.isRedisV1Auction(auction)) {
redisRuntimeToClear = { redisRuntimeToClear = {
@@ -1543,11 +1545,17 @@ export class AuctionService {
const undoingCompletedAuction = const undoingCompletedAuction =
Boolean(auction.completedAt) && !('completedAt' in snapshot); Boolean(auction.completedAt) && !('completedAt' in snapshot);
if (undoingCompletedAuction) {
this.assertCompetitionLifecycleMutable(
match,
'undo a completed auction',
);
}
if (this.isRedisV1Auction(auction)) { if (this.isRedisV1Auction(auction)) {
redisUndoContext = { redisUndoContext = {
auction, auction,
actionRequestParams: params, actionRequestParams: params,
snapshot: snapshot as Record<string, unknown>, snapshot: snapshot,
targetHistorySequence: params.sequence, targetHistorySequence: params.sequence,
undoingCompletedAuction, undoingCompletedAuction,
}; };
@@ -2111,7 +2119,7 @@ export class AuctionService {
? (auction.toObject({ depopulate: true }) as Record<string, unknown>) ? (auction.toObject({ depopulate: true }) as Record<string, unknown>)
: (auction as unknown as Record<string, unknown>); : (auction as unknown as Record<string, unknown>);
return { return {
...JSON.parse(JSON.stringify(base)), ...this.cloneJson(base),
...this.buildAuctionMongoProjectionFromState(auction, state), ...this.buildAuctionMongoProjectionFromState(auction, state),
_id: auction._id, _id: auction._id,
matchId: auction.matchId, matchId: auction.matchId,
@@ -2220,11 +2228,11 @@ export class AuctionService {
>[0]['auctionTeams'], >[0]['auctionTeams'],
): AuctionTeam[] { ): AuctionTeam[] {
return auctionTeams.map((team) => ({ return auctionTeams.map((team) => ({
captainUserId: team.captainUserId as mongoose.Types.ObjectId, captainUserId: team.captainUserId,
members: (team.members ?? []).map((member) => ({ members: (team.members ?? []).map((member) => ({
assignedPosition: member.assignedPosition, assignedPosition: member.assignedPosition,
cost: member.memberAcquisitionBidPointAmount, cost: member.memberAcquisitionBidPointAmount,
userId: member.userId as mongoose.Types.ObjectId, userId: member.userId,
})), })),
points: team.remainingBidPointAmount, points: team.remainingBidPointAmount,
teamIndex: team.teamIndex, teamIndex: team.teamIndex,
@@ -2247,7 +2255,11 @@ export class AuctionService {
// 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다. // 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다.
// structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로 // structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로
// JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다. // 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 { private numberFromState(value: unknown, fallback = 0): number {
@@ -2455,7 +2467,7 @@ export class AuctionService {
sequence: (latest?.sequence ?? 0) + 1, sequence: (latest?.sequence ?? 0) + 1,
action, action,
actorUserId, actorUserId,
snapshotBefore: JSON.parse(JSON.stringify(snapshotBefore)), snapshotBefore: this.cloneJson(snapshotBefore),
takenAt: new Date(), takenAt: new Date(),
}); });
} }
@@ -2612,6 +2624,17 @@ export class AuctionService {
return auction.auctionEngineVersion === 'redis-v1'; 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 { private isRestartableResetRedisAuction(auction: AuctionDocument): boolean {
return ( return (
this.isRedisV1Auction(auction) && this.isRedisV1Auction(auction) &&
@@ -2661,6 +2684,10 @@ export class AuctionService {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(auction.matchId); const match = await MatchModel.findById(auction.matchId);
if (!match) throw new NotFoundException('Match not found.'); if (!match) throw new NotFoundException('Match not found.');
if (match.competitionId) {
await this.tournamentResultService.scheduleInitialPoll(match);
return;
}
const participantByUserId = new Map( const participantByUserId = new Map(
match.participants.map((participant) => [ match.participants.map((participant) => [
@@ -2698,12 +2725,16 @@ export class AuctionService {
`Auction completed without teams for match ${match._id.toString()}.`, `Auction completed without teams for match ${match._id.toString()}.`,
); );
} }
const finalizedAt = match.teamBuiltAt ?? new Date();
match.teams = matchTeams; match.teams = matchTeams;
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = undefined;
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match); const preparedMatch =
await this.tournamentResultService.scheduleInitialPoll(match); (await this.tournamentCodeService.reserveForMatch(match)) ?? match;
preparedMatch.teamBuiltAt = finalizedAt;
await preparedMatch.save();
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
} }
private async syncMatchTeamsFromRedisAuctionState( private async syncMatchTeamsFromRedisAuctionState(
@@ -2713,6 +2744,10 @@ export class AuctionService {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findById(auction.matchId); const match = await MatchModel.findById(auction.matchId);
if (!match) throw new NotFoundException('Match not found.'); if (!match) throw new NotFoundException('Match not found.');
if (match.competitionId) {
await this.tournamentResultService.scheduleInitialPoll(match);
return;
}
const participantByUserId = new Map( const participantByUserId = new Map(
match.participants.map((participant) => [ match.participants.map((participant) => [
@@ -2757,12 +2792,16 @@ export class AuctionService {
`Redis auction completed without teams for match ${match._id.toString()}.`, `Redis auction completed without teams for match ${match._id.toString()}.`,
); );
} }
const finalizedAt = match.teamBuiltAt ?? new Date();
match.teams = matchTeams; match.teams = matchTeams;
match.status = 'team-built'; match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date(); match.teamBuiltAt = undefined;
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match); const preparedMatch =
await this.tournamentResultService.scheduleInitialPoll(match); (await this.tournamentCodeService.reserveForMatch(match)) ?? match;
preparedMatch.teamBuiltAt = finalizedAt;
await preparedMatch.save();
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
} }
private async hydrateRedisStateFromAuctionDocument( private async hydrateRedisStateFromAuctionDocument(
@@ -2948,7 +2987,7 @@ export class AuctionService {
void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => { void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => {
this.logger.warn( this.logger.warn(
`Auction background Riot refresh failed for ${params.auctionId.toString()}: ${ `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) { } catch (error: unknown) {
this.logger.warn( this.logger.warn(
`Failed to refresh auction Riot snapshot for ${target.puuid}: ${ `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'; } from './community-stats.types';
import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsRepository } from './match-stats.repository';
import { MatchStatsService } from './match-stats.service'; 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() { function objectives() {
return { return {
@@ -219,8 +223,9 @@ describe('CommunityStatsService', () => {
matchStatsRepository, matchStatsRepository,
{} as MatchStatsService, {} as MatchStatsService,
); );
(service as unknown as { resolveContext: jest.Mock }).resolveContext = (service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
jest.fn().mockResolvedValue({ .fn()
.mockResolvedValue({
community: {}, community: {},
season: { season: {
id: 'all', id: 'all',
@@ -275,7 +280,12 @@ describe('CommunityStatsService', () => {
participant.userId = userId.toString(); participant.userId = userId.toString();
let resolveFragments: let resolveFragments:
| ((fragments: Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>) => void) | ((
fragments: Array<{
matchId: mongoose.Types.ObjectId;
records: InternalRecord[];
}>,
) => void)
| undefined; | undefined;
const fragmentsPromise = new Promise< const fragmentsPromise = new Promise<
Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }> Array<{ matchId: mongoose.Types.ObjectId; records: InternalRecord[] }>
@@ -296,8 +306,9 @@ describe('CommunityStatsService', () => {
matchStatsRepository, matchStatsRepository,
{} as MatchStatsService, {} as MatchStatsService,
); );
(service as unknown as { resolveContext: jest.Mock }).resolveContext = (service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
jest.fn().mockResolvedValue({ .fn()
.mockResolvedValue({
community: {}, community: {},
season: { season: {
id: 'all', id: 'all',
@@ -329,4 +340,83 @@ describe('CommunityStatsService', () => {
); );
expect(cacheService.set).toHaveBeenCalledTimes(1); 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 = { const response: InternalMatchDetailResponse = {
match, match,
games: gameDetails.map( games: gameDetails.map((game) => ({
(game) => ({ gameNumber: game.gameNumber,
gameNumber: game.gameNumber, riotMatchId: game.riotMatchId,
riotMatchId: game.riotMatchId, gameCreation: game.gameCreation,
gameCreation: game.gameCreation, gameDuration: game.gameDuration,
gameDuration: game.gameDuration, gameVersion: game.gameVersion,
gameVersion: game.gameVersion, timeline: game.timeline ?? [],
timeline: game.timeline ?? [], objectiveEvents: game.objectiveEvents ?? [],
objectiveEvents: game.objectiveEvents ?? [], teams: game.teams.map((team) => ({
teams: game.teams.map((team) => ({ teamIndex: team.teamIndex,
teamIndex: team.teamIndex, side: team.side,
side: team.side, win: team.win,
win: team.win, objectives: team.objectives,
objectives: team.objectives, bans: team.bans ?? [],
bans: team.bans ?? [], participants: team.participants.map((record) => ({
participants: team.participants.map((record) => ({ userId: record.userId,
userId: record.userId, summonerName: record.summonerName,
summonerName: record.summonerName, tagLine: record.tagLine,
tagLine: record.tagLine, teamIndex: record.teamIndex,
teamIndex: record.teamIndex, side: record.side,
side: record.side, teamPosition: record.teamPosition,
teamPosition: record.teamPosition, championId: record.championId,
championId: record.championId, championLevel: record.championLevel,
championLevel: record.championLevel, kills: record.kills,
kills: record.kills, deaths: record.deaths,
deaths: record.deaths, assists: record.assists,
assists: record.assists, cs: record.cs,
cs: record.cs, csPerMin: record.csPerMin,
csPerMin: record.csPerMin, gold: record.gold,
gold: record.gold, gpm: record.gpm,
gpm: record.gpm, damageDealtToChampions: record.damageDealtToChampions,
damageDealtToChampions: record.damageDealtToChampions, damageTaken: record.damageTaken,
damageTaken: record.damageTaken, damageShare: record.damageShare,
damageShare: record.damageShare, killParticipation: record.killParticipation,
killParticipation: record.killParticipation, visionScore: record.visionScore,
visionScore: record.visionScore, wardsPlaced: record.wardsPlaced,
wardsPlaced: record.wardsPlaced, wardsKilled: record.wardsKilled,
wardsKilled: record.wardsKilled, controlWardsBought: record.controlWardsBought,
controlWardsBought: record.controlWardsBought, firstBloodKill: record.firstBloodKill ?? false,
firstBloodKill: record.firstBloodKill ?? false, firstBloodAssist: record.firstBloodAssist ?? false,
firstBloodAssist: record.firstBloodAssist ?? false, items: record.items,
items: record.items, trinket: record.trinket,
trinket: record.trinket, summonerSpells: record.summonerSpells,
summonerSpells: record.summonerSpells, perks: record.perks,
perks: record.perks, itemBuild: record.itemBuild ?? [],
itemBuild: record.itemBuild ?? [], skillBuild: record.skillBuild ?? [],
skillBuild: record.skillBuild ?? [], win: record.win,
win: record.win,
})),
})), })),
}), })),
), })),
}; };
await this.cacheService.setDetail(key, response); await this.cacheService.setDetail(key, response);
return response; return response;
@@ -357,7 +355,7 @@ export class CommunityStatsService {
const detailsByMatchId = new Map<string, InternalGameDetail[]>(); const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) { for (const fragment of fragments) {
const filteredGames = (fragment.gameDetails as InternalGameDetail[]) const filteredGames = fragment.gameDetails
.filter((game) => this.isGameInRange(game.gameCreation, context)) .filter((game) => this.isGameInRange(game.gameCreation, context))
.sort((left, right) => left.gameNumber - right.gameNumber); .sort((left, right) => left.gameNumber - right.gameNumber);
if (filteredGames.length === 0) continue; if (filteredGames.length === 0) continue;
@@ -373,7 +371,7 @@ export class CommunityStatsService {
filteredGames.map((game) => game.gameNumber), filteredGames.map((game) => game.gameNumber),
); );
records.push( records.push(
...(fragment.records as InternalRecord[]).filter((record) => ...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber), allowedGameNumbers.has(record.gameNumber),
), ),
); );
@@ -407,11 +405,7 @@ export class CommunityStatsService {
toGameCreation: context.to?.getTime(), toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN, limit: MAX_MATCH_SCAN,
}); });
const allUserRecords = this.extractUserRecords( const allUserRecords = this.extractUserRecords(fragments, userId, context);
fragments,
userId,
context,
);
const records = this.applyChampionFilter(allUserRecords, params.filters); const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50); const limit = this.clampLimit(params.filters.limit, 30, 50);
const cursor = params.filters.cursor; const cursor = params.filters.cursor;
@@ -457,7 +451,7 @@ export class CommunityStatsService {
): InternalRecord[] { ): InternalRecord[] {
return fragments return fragments
.flatMap((fragment) => .flatMap((fragment) =>
(fragment.records as InternalRecord[]).filter( fragment.records.filter(
(record) => (record) =>
record.userId === userId && record.userId === userId &&
this.isGameInRange(record.gameCreation, context), this.isGameInRange(record.gameCreation, context),
@@ -493,7 +487,7 @@ export class CommunityStatsService {
for (const fragment of fragments) { for (const fragment of fragments) {
detailsByMatchId.set( detailsByMatchId.set(
fragment.matchId.toString(), fragment.matchId.toString(),
(fragment.gameDetails as InternalGameDetail[]).filter((game) => fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context), this.isGameInRange(game.gameCreation, context),
), ),
); );
@@ -509,11 +503,14 @@ export class CommunityStatsService {
MatchModel.find({ MatchModel.find({
communityId, communityId,
status: { $in: ['finished', 'in-progress'] }, status: { $in: ['finished', 'in-progress'] },
'result.games.0': { $exists: true }, $or: [
{ competitionId: { $exists: true } },
{ 'result.games.0': { $exists: true } },
],
}) })
.sort({ scheduledAt: -1 }) .sort({ scheduledAt: -1 })
.limit(MAX_MATCH_SCAN) .limit(MAX_MATCH_SCAN)
.select({ _id: 1 }) .select({ _id: 1, competitionId: 1 })
.exec(), .exec(),
this.matchStatsRepository.findByCommunity({ this.matchStatsRepository.findByCommunity({
communityId, communityId,
@@ -523,11 +520,45 @@ export class CommunityStatsService {
const fragmentByMatchId = new Map( const fragmentByMatchId = new Map(
fragments.map((fragment) => [fragment.matchId.toString(), fragment]), 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; let rebuilt = 0;
for (const match of matches) { for (const match of matches) {
const fragment = fragmentByMatchId.get(match._id.toString()); 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; continue;
} }
@@ -4,6 +4,47 @@ import type { MatchStats } from '../global/database/schema';
import { MatchStatsRepository } from './match-stats.repository'; import { MatchStatsRepository } from './match-stats.repository';
describe('MatchStatsRepository', () => { 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 () => { it('only updates a Competition projection when its revision is not stale', async () => {
const updateOne = jest.fn().mockReturnValue({ const updateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }), exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }),
@@ -36,6 +77,122 @@ describe('MatchStatsRepository', () => {
{ upsert: false }, { 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) { function statsFragment(sourceRevision: number) {
@@ -13,6 +13,11 @@ export type MatchStatsDetailFragment = Pick<
'matchId' | 'gameDetails' 'matchId' | 'gameDetails'
>; >;
export interface MatchStatsDeleteGuard {
sourceCompetitionId: mongoose.Types.ObjectId;
sourceRevision: number;
}
@Injectable() @Injectable()
export class MatchStatsRepository { export class MatchStatsRepository {
constructor(private readonly connectionService: ConnectionService) {} constructor(private readonly connectionService: ConnectionService) {}
@@ -25,30 +30,33 @@ export class MatchStatsRepository {
!fragment.sourceCompetitionId || !fragment.sourceCompetitionId ||
fragment.sourceRevision === undefined fragment.sourceRevision === undefined
) { ) {
await MatchStatsModel.updateOne( const updated = await MatchStatsModel.updateOne(
{ matchId: fragment.matchId }, {
matchId: fragment.matchId,
sourceCompetitionId: { $exists: false },
},
{ $set: fragment }, { $set: fragment },
{ upsert: true }, { upsert: false },
).exec(); ).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; return;
} }
const revisionGuard = competitionRevisionGuard(fragment);
const updated = await MatchStatsModel.updateOne( const updated = await MatchStatsModel.updateOne(
{ revisionGuard,
matchId: fragment.matchId,
$or: [
{ sourceCompetitionId: { $exists: false } },
{ sourceCompetitionId: fragment.sourceCompetitionId },
],
$and: [
{
$or: [
{ sourceRevision: { $exists: false } },
{ sourceRevision: { $lte: fragment.sourceRevision } },
],
},
],
},
{ $set: fragment }, { $set: fragment },
{ upsert: false }, { upsert: false },
).exec(); ).exec();
@@ -56,16 +64,48 @@ export class MatchStatsRepository {
// If no read model exists, insert it. If a newer revision won the race, // If no read model exists, insert it. If a newer revision won the race,
// this filter matches it and $setOnInsert intentionally changes nothing. // 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( await MatchStatsModel.updateOne(
{ matchId: fragment.matchId }, revisionGuard,
{ $setOnInsert: fragment }, { $set: fragment },
{ upsert: true }, { upsert: false },
).exec(); ).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'); 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( public async deleteByMatches(
@@ -76,6 +116,16 @@ export class MatchStatsRepository {
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec(); 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( public async findByMatch(
matchId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId,
): Promise<MatchStatsDocument | null> { ): Promise<MatchStatsDocument | null> {
@@ -173,3 +223,32 @@ export class MatchStatsRepository {
return filter; 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(); 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 () => { it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const communityId = 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 () => { it('does not rebuild before the requested Competition revision is visible', async () => {
const matchId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId();
const riotFind = jest.fn(); const riotFind = jest.fn();
@@ -48,7 +48,14 @@ export class MatchStatsService {
: undefined; : undefined;
const sourceMatch = competitionSource?.match ?? match; const sourceMatch = competitionSource?.match ?? match;
if (!this.isEligible(sourceMatch)) { 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; 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> { public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
@@ -196,6 +208,49 @@ export class MatchStatsService {
? (region as RiotRegionalRoute) ? (region as RiotRegionalRoute)
: 'asia'; : '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 { 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 () => { it('rejects incomplete and duplicate team assignments before opening a transaction', async () => {
const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [ const cases: Array<[string, (match: CompetitionBootstrapMatch) => void]> = [
[
'the Match lifecycle is still recruiting',
(match) => {
match.status = 'recruiting';
},
],
[ [
'an active participant is not assigned', 'an active participant is not assigned',
(match) => { (match) => {
@@ -288,6 +317,8 @@ describe('CompetitionBootstrapService', () => {
expect(harness.matchModel.updateOne).toHaveBeenCalledWith( expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ {
_id: MATCH_ID, _id: MATCH_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
$or: [ $or: [
{ competitionId: { $exists: false } }, { competitionId: { $exists: false } },
{ competitionId: null }, { competitionId: null },
@@ -404,6 +435,8 @@ function matchSnapshot(params: {
return { return {
_id: MATCH_ID, _id: MATCH_ID,
communityId: COMMUNITY_ID, communityId: COMMUNITY_ID,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T00:05:00.000Z'),
gameCount: params.gameCount ?? 3, gameCount: params.gameCount ?? 3,
gameMode: params.gameMode, gameMode: params.gameMode,
...(params.roundRobinMaxRounds === undefined ...(params.roundRobinMaxRounds === undefined
@@ -5,6 +5,7 @@ import { ConnectionService } from '../global/database/connection.service';
import type { import type {
MatchGameMode, MatchGameMode,
MatchParticipant, MatchParticipant,
MatchStatus,
MatchTeam, MatchTeam,
} from '../global/database/schema'; } from '../global/database/schema';
import type { import type {
@@ -30,6 +31,8 @@ export interface CompetitionBootstrapMatch {
_id: Types.ObjectId; _id: Types.ObjectId;
communityId: Types.ObjectId; communityId: Types.ObjectId;
competitionId?: Types.ObjectId; competitionId?: Types.ObjectId;
status: MatchStatus;
teamBuiltAt: Date;
gameCount: number; gameCount: number;
gameMode: MatchGameMode; gameMode: MatchGameMode;
roundRobinMaxRounds?: number; roundRobinMaxRounds?: number;
@@ -142,6 +145,8 @@ export class CompetitionBootstrapService {
const linkResult = await MatchModel.updateOne( const linkResult = await MatchModel.updateOne(
{ {
_id: match._id, _id: match._id,
status: match.status,
teamBuiltAt: match.teamBuiltAt,
$or: [ $or: [
{ competitionId: { $exists: false } }, { competitionId: { $exists: false } },
{ competitionId: null }, { competitionId: null },
@@ -206,6 +211,13 @@ function buildCompetitionInsertPayload(
): CompetitionInsertPayload { ): CompetitionInsertPayload {
assertObjectId(match._id, 'Match ID'); assertObjectId(match._id, 'Match ID');
assertObjectId(match.communityId, 'Community 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'); assertPositiveInteger(match.gameCount, 'Match game count');
const competitionId = stableObjectId(match._id, 'competition'); const competitionId = stableObjectId(match._id, 'competition');
@@ -405,7 +417,11 @@ function applySeeds(
): void { ): void {
if (match.gameMode !== 'double-elimination') return; if (match.gameMode !== 'double-elimination') return;
const configuredSeeds = match.doubleElimination?.seeds ?? []; 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) { if (configuredSeeds.length !== teams.length) {
throw invalidTeamSnapshot( throw invalidTeamSnapshot(
'Double-elimination seeds must include every built team exactly once.', 'Double-elimination seeds must include every built team exactly once.',
@@ -106,6 +106,49 @@ describe('CompetitionCommandService', () => {
expect(harness.session.abortTransaction).not.toHaveBeenCalled(); 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 () => { it('rejects the same Idempotency-Key when its payload hash differs', async () => {
const harness = createHarness(); const harness = createHarness();
harness.outboxModel.findOne.mockReturnValue( harness.outboxModel.findOne.mockReturnValue(
@@ -382,6 +425,39 @@ describe('CompetitionCommandService', () => {
{ session: harness.session }, { session: harness.session },
); );
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled(); 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( expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: COMPETITION_ID, revision: 7 }, { _id: COMPETITION_ID, revision: 7 },
expect.objectContaining({ $inc: { revision: 1 } }), expect.objectContaining({ $inc: { revision: 1 } }),
@@ -390,6 +466,50 @@ describe('CompetitionCommandService', () => {
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1); expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).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'); const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
@@ -496,12 +616,18 @@ function createHarness(
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }), updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }), updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
}; };
const matchModel = {
updateOne: jest
.fn()
.mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
};
const models: Record<string, unknown> = { const models: Record<string, unknown> = {
competition: competitionModel, competition: competitionModel,
competitionFact: factModel, competitionFact: factModel,
competitionOutbox: outboxModel, competitionOutbox: outboxModel,
tournamentCodeAssignment: assignmentModel, tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel, tournamentCode: tournamentCodeModel,
match: matchModel,
}; };
const connectionService = { const connectionService = {
createSession: jest.fn().mockResolvedValue(session), createSession: jest.fn().mockResolvedValue(session),
@@ -515,6 +641,7 @@ function createHarness(
outboxModel, outboxModel,
assignmentModel, assignmentModel,
tournamentCodeModel, tournamentCodeModel,
matchModel,
connectionService, connectionService,
}; };
} }
@@ -612,6 +739,8 @@ function reversalFixture() {
childFactId, childFactId,
parentGameSlotId, parentGameSlotId,
childGameSlotId, childGameSlotId,
parentCodeId,
childCodeId,
competition: { competition: {
...competitionDocument(7), ...competitionDocument(7),
seriesGraph: [ seriesGraph: [
@@ -14,6 +14,7 @@ import {
} from './domain/competition-reversal'; } from './domain/competition-reversal';
type PersistenceId = string | mongoose.Types.ObjectId; type PersistenceId = string | mongoose.Types.ObjectId;
const COMMAND_TRANSACTION_ATTEMPTS = 3;
export type CompetitionCommandActor = export type CompetitionCommandActor =
| { type: 'system' } | { type: 'system' }
@@ -211,283 +212,316 @@ export class CompetitionCommandService {
throw invalidCommandError(); throw invalidCommandError();
} }
const session = await this.connectionService.createSession(); let lastRetryableError: unknown;
if (!session) { for (
throw new CompetitionCommandError( let attempt = 1;
'COMPETITION_TRANSACTION_UNAVAILABLE', attempt <= COMMAND_TRANSACTION_ATTEMPTS;
'A MongoDB transaction is required for Competition commands.', attempt += 1
500, ) {
); const session = await this.connectionService.createSession();
} if (!session) {
throw new CompetitionCommandError(
try { 'COMPETITION_TRANSACTION_UNAVAILABLE',
session.startTransaction(); 'A MongoDB transaction is required for Competition commands.',
const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] = 500,
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,
); );
await session.commitTransaction();
return replay;
} }
const competition = await CompetitionModel.findById(command.competitionId) try {
.session(session) session.startTransaction();
.lean() const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] =
.exec(); await Promise.all([
if (!competition) throw competitionNotFound(command.competitionId); this.connectionService.getModel('competition'),
assertExpectedRevision(competition.revision, command.expectedRevision); this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
const [existingFacts, assignments] = await Promise.all([ this.connectionService.getModel('tournamentCodeAssignment'),
FactModel.find({ competitionId: command.competitionId }) ]);
.sort({ revision: 1, ordinalWithinRevision: 1 }) const requestHash = requestHashFor(envelope);
const commandId = commandIdFor(envelope);
const receipt = await OutboxModel.findOne({
competitionId: command.competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session) .session(session)
.lean() .lean()
.exec(), .exec();
AssignmentModel.find({ competitionId: command.competitionId }) if (receipt) {
.session(session) const replay = await this.replay(
.lean() CompetitionModel,
.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(
command.competitionId, command.competitionId,
envelope,
commandId,
requestHash, requestHash,
nextRevision, receipt,
reversalFacts, session,
projection, );
updated, await session.commitTransaction();
recordedAt, return replay;
), }
],
{ session }, const competition = await CompetitionModel.findById(
); command.competitionId,
await session.commitTransaction(); )
return { .session(session)
competition: updated, .lean()
commandId, .exec();
revision: nextRevision, if (!competition) throw competitionNotFound(command.competitionId);
replayed: false, assertExpectedRevision(competition.revision, command.expectedRevision);
};
} catch (error) { const [existingFacts, assignments] = await Promise.all([
await session.abortTransaction().catch(() => undefined); FactModel.find({ competitionId: command.competitionId })
throw error; .sort({ revision: 1, ordinalWithinRevision: 1 })
} finally { .session(session)
await session.endSession(); .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( private async runCommand(
command: CommandEnvelope, command: CommandEnvelope,
): Promise<CompetitionCommandResult> { ): Promise<CompetitionCommandResult> {
validateEnvelope(command); validateEnvelope(command);
const session = await this.connectionService.createSession(); let lastRetryableError: unknown;
if (!session) { for (
throw new CompetitionCommandError( let attempt = 1;
'COMPETITION_TRANSACTION_UNAVAILABLE', attempt <= COMMAND_TRANSACTION_ATTEMPTS;
'A MongoDB transaction is required for Competition commands.', attempt += 1
500, ) {
); const session = await this.connectionService.createSession();
} if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
}
try { try {
session.startTransaction(); session.startTransaction();
const CompetitionModel = const CompetitionModel =
await this.connectionService.getModel('competition'); await this.connectionService.getModel('competition');
const FactModel = const FactModel =
await this.connectionService.getModel('competitionFact'); await this.connectionService.getModel('competitionFact');
const OutboxModel = const OutboxModel =
await this.connectionService.getModel('competitionOutbox'); await this.connectionService.getModel('competitionOutbox');
const requestHash = requestHashFor(command); const requestHash = requestHashFor(command);
const commandId = commandIdFor(command); const commandId = commandIdFor(command);
const competitionId = command.competitionId; const competitionId = command.competitionId;
const receipt = await OutboxModel.findOne({ const receipt = await OutboxModel.findOne({
competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
competitionId, 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, requestHash,
receipt, nextRevision,
session, 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(); 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( private async replay(
@@ -595,6 +629,7 @@ export class CompetitionCommandService {
private async applyReversalAssignments( private async applyReversalAssignments(
competitionId: PersistenceId, competitionId: PersistenceId,
matchId: PersistenceId,
preview: SeriesReversalPreview, preview: SeriesReversalPreview,
assignments: AssignmentRecord[], assignments: AssignmentRecord[],
commandId: string, commandId: string,
@@ -638,6 +673,14 @@ export class CompetitionCommandService {
tournamentCodeReversalStatePipeline(recordedAt), tournamentCodeReversalStatePipeline(recordedAt),
{ session }, { 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: { releasedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$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; : 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( function competitionNotFound(
competitionId: PersistenceId, competitionId: PersistenceId,
): CompetitionCommandError { ): CompetitionCommandError {
@@ -1,29 +1,24 @@
import { ForbiddenException } from '@nestjs/common'; import { ConflictException, ForbiddenException } from '@nestjs/common';
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
import { CompetitionQueryService } from './competition-query.service'; import { CompetitionQueryService } from './competition-query.service';
describe('CompetitionQueryService', () => { 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 harness = createHarness({ competition: null });
const bootstrapped = competitionDocument();
harness.bootstrapService.bootstrap.mockResolvedValue(bootstrapped);
const service = createService(harness); const service = createService(harness);
const result = await service.getCompetition({ await expect(
communityId: COMMUNITY_ID, service.getCompetition({
matchId: MATCH_ID, communityId: COMMUNITY_ID,
}); matchId: MATCH_ID,
}),
).rejects.toBeInstanceOf(ConflictException);
expect(harness.matchModel.findOne).toHaveBeenCalledWith({ expect(harness.matchModel.findOne).toHaveBeenCalledWith({
_id: MATCH_ID, _id: MATCH_ID,
communityId: COMMUNITY_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 () => { 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(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({ expect(harness.tournamentCodeModel.find).toHaveBeenCalledWith({
_id: { $in: [TEAM_A_CODE_ID] }, _id: { $in: [TEAM_A_CODE_ID] },
state: { $in: ['reserved', 'used'] },
}); });
}); });
@@ -71,6 +67,20 @@ describe('CompetitionQueryService', () => {
).rejects.toBeInstanceOf(ForbiddenException); ).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 () => { it('pages facts in immutable revision order using an opaque cursor', async () => {
const harness = createHarness(); const harness = createHarness();
harness.factModel.find.mockReturnValueOnce( harness.factModel.find.mockReturnValueOnce(
@@ -116,7 +126,6 @@ const GAME_SLOT_ID = 'slot-1';
function createService(harness: ReturnType<typeof createHarness>) { function createService(harness: ReturnType<typeof createHarness>) {
return new CompetitionQueryService( return new CompetitionQueryService(
harness.connectionService as ConnectionService, harness.connectionService as ConnectionService,
harness.bootstrapService as unknown as CompetitionBootstrapService,
); );
} }
@@ -167,11 +176,15 @@ function createHarness(options: { competition?: unknown } = {}) {
{ {
_id: TEAM_A_CODE_ID, _id: TEAM_A_CODE_ID,
code: 'TEAM-A-SECRET-CODE', code: 'TEAM-A-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'), expiresAt: new Date('2026-07-13T00:00:00.000Z'),
}, },
{ {
_id: TEAM_B_CODE_ID, _id: TEAM_B_CODE_ID,
code: 'OPPONENT-SECRET-CODE', code: 'OPPONENT-SECRET-CODE',
state: 'reserved',
matchId: MATCH_ID,
expiresAt: new Date('2026-07-13T00:00:00.000Z'), expiresAt: new Date('2026-07-13T00:00:00.000Z'),
}, },
]), ]),
@@ -196,7 +209,6 @@ function createHarness(options: { competition?: unknown } = {}) {
connectionService: { connectionService: {
getModel: jest.fn((name: string) => Promise.resolve(models[name])), getModel: jest.fn((name: string) => Promise.resolve(models[name])),
}, },
bootstrapService: { bootstrap: jest.fn() },
}; };
} }
@@ -13,7 +13,6 @@ import {
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
import type { Competition, CompetitionFact } from './competition.schema'; import type { Competition, CompetitionFact } from './competition.schema';
import { CompetitionBootstrapService } from './competition-bootstrap.service';
type PersistenceId = string | mongoose.Types.ObjectId; type PersistenceId = string | mongoose.Types.ObjectId;
type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId }; type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId };
@@ -30,25 +29,12 @@ interface CompetitionProjectionSource {
@Injectable() @Injectable()
export class CompetitionQueryService { export class CompetitionQueryService {
constructor( constructor(private readonly connectionService: ConnectionService) {}
private readonly connectionService: ConnectionService,
private readonly bootstrapService: CompetitionBootstrapService,
) {}
/** 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( public async getCompetition(
scope: CompetitionScope, scope: CompetitionScope,
): Promise<CompetitionRecord> { ): 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 MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({ const match = await MatchModel.findOne({
_id: scope.matchId, _id: scope.matchId,
@@ -66,7 +52,19 @@ export class CompetitionQueryService {
'Competition is unavailable until team building is complete.', '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( public async getTeamView(
@@ -126,7 +124,10 @@ export class CompetitionQueryService {
const TournamentCodeModel = const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode'); await this.connectionService.getModel('tournamentCode');
const codes = codeIds.length const codes = codeIds.length
? await TournamentCodeModel.find({ _id: { $in: codeIds } }) ? await TournamentCodeModel.find({
_id: { $in: codeIds },
state: { $in: ['reserved', 'used'] },
})
.lean() .lean()
.exec() .exec()
: []; : [];
@@ -150,6 +151,17 @@ export class CompetitionQueryService {
const code = assignment const code = assignment
? codeById.get(idString(assignment.tournamentCodeId)) ? codeById.get(idString(assignment.tournamentCodeId))
: undefined; : 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 { return {
gameSlotId: gameSlotId as never, gameSlotId: gameSlotId as never,
seriesId: idString(slot.seriesId as PersistenceId) as never, seriesId: idString(slot.seriesId as PersistenceId) as never,
@@ -1,4 +1,5 @@
import { import {
COMPETITION_OUTBOX_STATES,
CompetitionFactSchema, CompetitionFactSchema,
CompetitionOutboxSchema, CompetitionOutboxSchema,
CompetitionSchema, 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', () => { it('allows only one active assignment for a code or GameSlot', () => {
expectIndexes(TournamentCodeAssignmentSchema, [ expectIndexes(TournamentCodeAssignmentSchema, [
{ {
@@ -20,6 +20,7 @@ export const COMPETITION_OUTBOX_STATES = [
'pending', 'pending',
'published', 'published',
'failed', 'failed',
'dead-letter',
] as const; ] as const;
export type CompetitionOutboxState = (typeof COMPETITION_OUTBOX_STATES)[number]; export type CompetitionOutboxState = (typeof COMPETITION_OUTBOX_STATES)[number];
@@ -32,6 +33,110 @@ export const TOURNAMENT_CODE_ASSIGNMENT_STATES = [
export type TournamentCodeAssignmentState = export type TournamentCodeAssignmentState =
(typeof TOURNAMENT_CODE_ASSIGNMENT_STATES)[number]; (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 { export interface CompetitionTeamMemberSnapshot {
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
displayName: string; displayName: string;
@@ -200,7 +305,7 @@ export const CompetitionSchema: mongoose.Schema<Competition> =
{ timestamps: true, collection: 'competition' }, { timestamps: true, collection: 'competition' },
); );
CompetitionSchema.index({ matchId: 1 }, { unique: true }); applyCompetitionDomainInvariantIndexes(CompetitionSchema, 'competition');
CompetitionSchema.index({ communityId: 1, phase: 1, updatedAt: -1 }); CompetitionSchema.index({ communityId: 1, phase: 1, updatedAt: -1 });
export const CompetitionFactSchema = new Schema<CompetitionFact>( export const CompetitionFactSchema = new Schema<CompetitionFact>(
@@ -238,23 +343,9 @@ export const CompetitionFactSchema = new Schema<CompetitionFact>(
{ timestamps: true, collection: 'competition_fact' }, { timestamps: true, collection: 'competition_fact' },
); );
CompetitionFactSchema.index( applyCompetitionDomainInvariantIndexes(
{ competitionId: 1, revision: 1, ordinalWithinRevision: 1 }, CompetitionFactSchema,
{ unique: true }, 'competition_fact',
);
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' },
},
},
); );
CompetitionFactSchema.index({ competitionId: 1, seriesId: 1, recordedAt: 1 }); CompetitionFactSchema.index({ competitionId: 1, seriesId: 1, recordedAt: 1 });
@@ -286,12 +377,11 @@ export const CompetitionOutboxSchema = new Schema<CompetitionOutbox>(
{ timestamps: true, collection: 'competition_outbox' }, { timestamps: true, collection: 'competition_outbox' },
); );
CompetitionOutboxSchema.index({ eventId: 1 }, { unique: true }); applyCompetitionDomainInvariantIndexes(
CompetitionOutboxSchema.index({ state: 1, availableAt: 1 }); CompetitionOutboxSchema,
CompetitionOutboxSchema.index( 'competition_outbox',
{ competitionId: 1, idempotencyKey: 1 },
{ unique: true },
); );
CompetitionOutboxSchema.index({ state: 1, availableAt: 1 });
export const TournamentCodeAssignmentSchema = export const TournamentCodeAssignmentSchema =
new Schema<TournamentCodeAssignment>( new Schema<TournamentCodeAssignment>(
@@ -323,30 +413,22 @@ export const TournamentCodeAssignmentSchema =
{ timestamps: true, collection: 'tournament_code_assignment' }, { timestamps: true, collection: 'tournament_code_assignment' },
); );
const activeAssignmentFilter = { state: { $in: ['reserved', 'used'] } }; applyCompetitionDomainInvariantIndexes(
TournamentCodeAssignmentSchema.index( TournamentCodeAssignmentSchema,
{ gameSlotId: 1 }, 'tournament_code_assignment',
{
unique: true,
partialFilterExpression: activeAssignmentFilter,
},
);
TournamentCodeAssignmentSchema.index(
{ tournamentCodeId: 1 },
{
unique: true,
partialFilterExpression: activeAssignmentFilter,
},
);
TournamentCodeAssignmentSchema.index(
{ riotMatchId: 1 },
{
unique: true,
partialFilterExpression: { riotMatchId: { $type: 'string' } },
},
); );
TournamentCodeAssignmentSchema.index({ competitionId: 1, state: 1 }); 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<{ export const competitionModelDefinitions: Array<{
name: string; name: string;
schema: mongoose.Schema; schema: mongoose.Schema;
@@ -307,6 +307,114 @@ describe('projectCompetition', () => {
expect(projection.games).toEqual([]); 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', () => { it('completes an eight-team double elimination with shared elimination-round placements', () => {
const competitionId = 'competition-eight-team-completion'; const competitionId = 'competition-eight-team-completion';
const teams = Array.from({ length: 8 }, (_, index) => const teams = Array.from({ length: 8 }, (_, index) =>
@@ -1,3 +1,4 @@
import { assertCompetitionInvariant } from './domain-error';
import type { import type {
CompetitionGraphFormat, CompetitionGraphFormat,
CompetitionGraphTeam, CompetitionGraphTeam,
@@ -130,6 +131,7 @@ export interface CompetitionProjection {
export function projectCompetition( export function projectCompetition(
input: ProjectCompetitionInput, input: ProjectCompetitionInput,
): CompetitionProjection { ): CompetitionProjection {
assertPrimaryFactTargetsGraph(input.seriesGraph, input.facts);
const teamBySeed = new Map<number, string>(); const teamBySeed = new Map<number, string>();
const knownTeams = new Set<string>(); const knownTeams = new Set<string>();
for (const team of input.teams) { 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( function asProjectorDefinition(
definition: SeriesDefinition, definition: SeriesDefinition,
): SeriesDefinitionLike { ): SeriesDefinitionLike {
@@ -36,6 +36,7 @@ describe('migrateCompetitionDomain', () => {
expect(startSession).not.toHaveBeenCalled(); expect(startSession).not.toHaveBeenCalled();
expect(db.writeCount).toBe(0); expect(db.writeCount).toBe(0);
expect(db.docs('competition')).toHaveLength(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 () => { it('applies one Match atomically and converges on an already-applied replay', async () => {
@@ -181,6 +182,309 @@ describe('migrateCompetitionDomain', () => {
}); });
expect(db.writeCount).toBe(0); 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 { class FakeSession implements CompetitionDomainMigrationSession {
@@ -211,6 +515,13 @@ type AnyDoc = Record<string, any> & { _id: unknown };
class MemoryMigrationDb implements CompetitionDomainMigrationDb { class MemoryMigrationDb implements CompetitionDomainMigrationDb {
private readonly collections = new Map<string, AnyDoc[]>(); private readonly collections = new Map<string, AnyDoc[]>();
public writeCount = 0; 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[]> = {}) { constructor(seed: Record<string, AnyDoc[]> = {}) {
for (const [name, docs] of Object.entries(seed)) { for (const [name, docs] of Object.entries(seed)) {
@@ -227,6 +538,23 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
collection(name: string) { collection(name: string) {
const owner = this; const owner = this;
return { 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>) { find(filter: Record<string, unknown>) {
return new MemoryCursor(() => return new MemoryCursor(() =>
owner.docs(name).filter((doc) => matches(doc, filter)), owner.docs(name).filter((doc) => matches(doc, filter)),
@@ -240,6 +568,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
update: Record<string, Record<string, unknown>>, update: Record<string, Record<string, unknown>>,
options: { upsert?: boolean } = {}, options: { upsert?: boolean } = {},
) { ) {
owner.operations.push('write');
owner.writeCount += 1; owner.writeCount += 1;
const docs = owner.docs(name); const docs = owner.docs(name);
let doc = docs.find((candidate) => matches(candidate, filter)); let doc = docs.find((candidate) => matches(candidate, filter));
@@ -251,6 +580,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
if (!doc) return { matchedCount: 0, modifiedCount: 0 }; if (!doc) return { matchedCount: 0, modifiedCount: 0 };
if (inserted) Object.assign(doc, update.$setOnInsert ?? {}); if (inserted) Object.assign(doc, update.$setOnInsert ?? {});
Object.assign(doc, update.$set ?? {}); Object.assign(doc, update.$set ?? {});
for (const field of Object.keys(update.$unset ?? {})) delete doc[field];
return { return {
matchedCount: inserted ? 0 : 1, matchedCount: inserted ? 0 : 1,
modifiedCount: 1, modifiedCount: 1,
@@ -258,6 +588,7 @@ class MemoryMigrationDb implements CompetitionDomainMigrationDb {
}; };
}, },
async deleteOne(filter: Record<string, unknown>) { async deleteOne(filter: Record<string, unknown>) {
owner.operations.push('write');
owner.writeCount += 1; owner.writeCount += 1;
const docs = owner.docs(name); const docs = owner.docs(name);
const index = docs.findIndex((doc) => matches(doc, filter)); const index = docs.findIndex((doc) => matches(doc, filter));
@@ -318,6 +649,9 @@ function matches(doc: AnyDoc, filter: Record<string, unknown>): boolean {
sameValue(actual, candidate), sameValue(actual, candidate),
); );
} }
if ('$gt' in expected) {
return String(actual) > String(expected.$gt);
}
} }
return sameValue(actual, expected); 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); return value !== null && typeof value === 'object' && !Array.isArray(value);
} }
function readyMatch(): AnyDoc { function readyMatch(riotMatchId = 'KR_MIGRATION_1'): AnyDoc {
const matchId = objectId(); const matchId = objectId();
const codeId = objectId(); const codeId = objectId();
return { return {
@@ -362,11 +696,11 @@ function readyMatch(): AnyDoc {
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
tournamentCodeIds: [codeId], tournamentCodeIds: [codeId],
result: { result: {
riotMatchIds: ['KR_MIGRATION_1'], riotMatchIds: [riotMatchId],
games: [ games: [
{ {
gameNumber: 1, gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1', riotMatchId,
blueTeamIndex: 1, blueTeamIndex: 1,
redTeamIndex: 2, redTeamIndex: 2,
winnerTeamIndex: 1, winnerTeamIndex: 1,
@@ -383,23 +717,26 @@ function readyMatch(): AnyDoc {
}; };
} }
function usedTournamentCode(match = readyMatch()): AnyDoc { function usedTournamentCode(
match = readyMatch(),
riotMatchId = 'KR_MIGRATION_1',
): AnyDoc {
return { return {
_id: match.tournamentCodeIds[0], _id: match.tournamentCodeIds[0],
matchId: match._id, matchId: match._id,
state: 'used', state: 'used',
gameNumber: 1, gameNumber: 1,
riotMatchId: 'KR_MIGRATION_1', riotMatchId,
reservedAt: new Date('2026-07-01T00:30:00.000Z'), reservedAt: new Date('2026-07-01T00:30:00.000Z'),
usedAt: new Date('2026-07-01T01:00:00.000Z'), usedAt: new Date('2026-07-01T01:00:00.000Z'),
}; };
} }
function riotArchive(): AnyDoc { function riotArchive(matchId = 'KR_MIGRATION_1'): AnyDoc {
return { return {
_id: objectId(), _id: objectId(),
matchId: 'KR_MIGRATION_1', matchId,
raw: { metadata: { matchId: 'KR_MIGRATION_1' } }, raw: { metadata: { matchId } },
}; };
} }
@@ -1,6 +1,10 @@
import { createHash } from 'node:crypto'; import { createHash } from 'node:crypto';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { projectCompetition } from '../../../competition/domain/competition-projector'; import { projectCompetition } from '../../../competition/domain/competition-projector';
import {
COMPETITION_DOMAIN_INVARIANT_INDEXES,
type CompetitionDomainInvariantIndex,
} from '../../../competition/competition.schema';
import { import {
planCompetitionMigration, planCompetitionMigration,
type CompetitionMigrationAssignment, type CompetitionMigrationAssignment,
@@ -21,6 +25,10 @@ export interface CompetitionDomainMigrationCursor extends AsyncIterable<AnyDocum
} }
export interface CompetitionDomainMigrationCollection { export interface CompetitionDomainMigrationCollection {
createIndex(
key: mongoose.IndexDefinition,
options: mongoose.IndexOptions,
): Promise<string>;
find( find(
filter: Record<string, unknown>, filter: Record<string, unknown>,
options?: { session?: CompetitionDomainMigrationSession }, options?: { session?: CompetitionDomainMigrationSession },
@@ -34,6 +42,7 @@ export interface CompetitionDomainMigrationCollection {
update: { update: {
$set?: Record<string, unknown>; $set?: Record<string, unknown>;
$setOnInsert?: Record<string, unknown>; $setOnInsert?: Record<string, unknown>;
$unset?: Record<string, unknown>;
}, },
options?: { options?: {
session?: CompetitionDomainMigrationSession; session?: CompetitionDomainMigrationSession;
@@ -64,6 +73,7 @@ export interface CompetitionDomainMigrationSession {
export interface CompetitionDomainMigrationOptions { export interface CompetitionDomainMigrationOptions {
dryRun?: boolean; dryRun?: boolean;
limit?: number; limit?: number;
afterMatchId?: string;
migrationRunId?: string; migrationRunId?: string;
now?: Date; now?: Date;
startSession?: () => Promise<CompetitionDomainMigrationSession | undefined>; startSession?: () => Promise<CompetitionDomainMigrationSession | undefined>;
@@ -118,10 +128,37 @@ export interface CompetitionDomainMigrationSummary {
export interface CompetitionDomainMigrationResult { export interface CompetitionDomainMigrationResult {
migrationRunId: string; migrationRunId: string;
mode: 'dry-run' | 'apply'; mode: 'dry-run' | 'apply';
indexPreflight: CompetitionDomainIndexPreflight;
resume: CompetitionDomainMigrationResume;
summary: CompetitionDomainMigrationSummary; summary: CompetitionDomainMigrationSummary;
matches: CompetitionDomainMigrationMatchResult[]; 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 * 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. * 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; options.migrationRunId?.trim() || DEFAULT_MIGRATION_RUN_ID;
assertOptions(options); 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[] = []; 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 const result = dryRun
? await inspectMatch(db, scannedMatch, migrationRunId) ? await inspectMatch(db, scannedMatch, migrationRunId)
: await applyMatch(db, scannedMatch, migrationRunId, options); : await applyMatch(db, scannedMatch, migrationRunId, options);
@@ -146,29 +217,216 @@ export async function migrateCompetitionDomain(
index: index + 1, index: index + 1,
matchId: result.matchId, matchId: result.matchId,
status: result.status, 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 { return {
migrationRunId, migrationRunId,
mode: dryRun ? 'dry-run' : 'apply', mode: dryRun ? 'dry-run' : 'apply',
indexPreflight,
resume: resumeReport(
resumeStart,
checkpointAfterMatchId,
hasMore,
completed,
),
summary: summarize(matches), summary: summarize(matches),
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( async function scanMatches(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
limit: number | undefined, limit: number | undefined,
): Promise<AnyDocument[]> { afterMatchId: string | undefined,
return readCursor( ): Promise<{ matches: AnyDocument[]; hasMore: boolean }> {
const scanned = await readCursor(
db db
.collection('match') .collection('match')
.find(MATCH_SCAN_FILTER) .find({
...MATCH_SCAN_FILTER,
...(afterMatchId ? { _id: { $gt: persistenceId(afterMatchId) } } : {}),
})
.sort({ _id: 1 }) .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( 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 upsertReadyPlan(db, plan, session);
await verifyReadyPlan(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( async function hydrateLegacyMatch(
db: CompetitionDomainMigrationDb, db: CompetitionDomainMigrationDb,
match: AnyDocument, match: AnyDocument,
@@ -819,6 +1218,17 @@ function assertOptions(options: CompetitionDomainMigrationOptions): void {
if (options.dryRun === false && !options.startSession) { if (options.dryRun === false && !options.startSession) {
throw new Error('Apply mode requires a transaction session factory.'); 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( async function readCursor(
@@ -31,4 +31,22 @@ describe('competition domain migration CLI', () => {
nodeEnv: 'dev', 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; dryRun: boolean;
help: boolean; help: boolean;
limit?: number; limit?: number;
afterMatchId?: string;
nodeEnv: string; nodeEnv: string;
} }
@@ -60,6 +61,7 @@ export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
let dryRun = true; let dryRun = true;
let help = false; let help = false;
let limit: number | undefined; let limit: number | undefined;
let afterMatchId: string | undefined;
let nodeEnv = process.env.NODE_ENV ?? 'dev'; let nodeEnv = process.env.NODE_ENV ?? 'dev';
for (let index = 0; index < argv.length; index += 1) { 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'); limit = positiveInteger(argument.slice('--limit='.length), '--limit');
continue; 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') { if (argument === '--help' || argument === '-h') {
help = true; help = true;
continue; continue;
@@ -105,7 +116,7 @@ export function parseCliOptions(argv: string[]): CompetitionDomainCliOptions {
if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { if (!['dev', 'staging', 'prod'].includes(nodeEnv)) {
throw new Error('--env must be dev, staging, or prod.'); 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 { function positiveInteger(value: string | undefined, label: string): number {
@@ -116,6 +127,15 @@ function positiveInteger(value: string | undefined, label: string): number {
return parsed; 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 { function printHelp(): void {
process.stdout.write(`Usage: process.stdout.write(`Usage:
pnpm --silent --filter api competition:migrate pnpm --silent --filter api competition:migrate
@@ -125,7 +145,8 @@ Options:
--dry-run Plan and report without writes. Default. --dry-run Plan and report without writes. Default.
--apply Apply one transaction per Match. --apply Apply one transaction per Match.
--env <env> dev | staging | prod. Default: NODE_ENV or dev. --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. 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, dryRun: options.dryRun,
limit: options.limit, limit: options.limit,
afterMatchId: options.afterMatchId,
startSession: options.dryRun startSession: options.dryRun
? undefined ? undefined
: async () => connection.startSession(), : async () => connection.startSession(),
@@ -164,11 +186,15 @@ async function main(): Promise<void> {
`db=${resolveMongoDbName(options.nodeEnv)} scanned=${summary.scanned} ` + `db=${resolveMongoDbName(options.nodeEnv)} scanned=${summary.scanned} ` +
`ready=${summary.ready} applied=${summary.applied} ` + `ready=${summary.ready} applied=${summary.applied} ` +
`alreadyApplied=${summary.alreadyApplied} quarantined=${summary.quarantined} ` + `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`); 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; else if (summary.quarantined > 0) process.exitCode = 2;
} finally { } finally {
await app.close().catch((error: unknown) => { await app.close().catch((error: unknown) => {
@@ -8,6 +8,7 @@ import {
CompetitionFact, CompetitionFact,
CompetitionOutbox, CompetitionOutbox,
TournamentCodeAssignment, TournamentCodeAssignment,
applyCompetitionDomainInvariantIndexes,
competitionModelDefinitions, competitionModelDefinitions,
} from '../../competition/competition.schema'; } from '../../competition/competition.schema';
import { ModelDefinition } from './types'; import { ModelDefinition } from './types';
@@ -465,6 +466,7 @@ export interface TournamentCode extends MongooseTimestamps {
reservedAt?: Date; reservedAt?: Date;
usedAt?: Date; usedAt?: Date;
releasedAt?: Date; releasedAt?: Date;
voidedAt?: Date;
riotMatchId?: string; riotMatchId?: string;
uploadedBy: mongoose.Types.ObjectId; uploadedBy: mongoose.Types.ObjectId;
uploadedAt: Date; uploadedAt: Date;
@@ -1501,6 +1503,7 @@ export const TournamentCodeSchema = new Schema<TournamentCode>(
reservedAt: { type: Date }, reservedAt: { type: Date },
usedAt: { type: Date }, usedAt: { type: Date },
releasedAt: { type: Date }, releasedAt: { type: Date },
voidedAt: { type: Date },
riotMatchId: { type: String }, riotMatchId: { type: String },
uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true }, uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
uploadedAt: { type: Date, required: true, default: Date.now }, 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({ communityId: 1, scheduledAt: -1 });
MatchSchema.index( applyCompetitionDomainInvariantIndexes(MatchSchema, 'match');
{ competitionId: 1 },
{
unique: true,
partialFilterExpression: { competitionId: { $type: 'objectId' } },
},
);
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 }); MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index( MatchSchema.index(
{ communityId: 1, shortCode: 1 }, { 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 () => { it('cascades admin deletion through Competition facts and read models', async () => {
const fixture = createImportFixture(); 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 competitionFactModel = deleteManyModel();
const competitionOutboxModel = 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 = { const competitionModel = {
...deleteManyModel(), ...deleteManyModel(),
find: jest.fn().mockReturnValue({ find: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({ select: jest.fn().mockReturnValue({
lean: jest session: jest.fn().mockReturnValue({
.fn() lean: jest
.mockReturnValue(execResult([{ _id: fixture.competition._id }])), .fn()
.mockReturnValue(execResult([{ _id: fixture.competition._id }])),
}),
}), }),
}), }),
}; };
@@ -311,11 +335,44 @@ describe('Legacy import Competition result cutover', () => {
find: jest.fn().mockReturnValue({ find: jest.fn().mockReturnValue({
select: jest select: jest
.fn() .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 = { const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getConnection: jest.fn().mockResolvedValue({
collection: jest.fn().mockReturnValue(quarantineCollection),
}),
getModel: jest.fn((name: string) => { getModel: jest.fn((name: string) => {
const models: Record<string, unknown> = { const models: Record<string, unknown> = {
match: matchModel, match: matchModel,
@@ -323,6 +380,8 @@ describe('Legacy import Competition result cutover', () => {
competitionFact: competitionFactModel, competitionFact: competitionFactModel,
competitionOutbox: competitionOutboxModel, competitionOutbox: competitionOutboxModel,
tournamentCodeAssignment: assignmentModel, tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
matchStats: matchStatsModel,
}; };
const model = models[name]; const model = models[name];
return model return model
@@ -330,15 +389,11 @@ describe('Legacy import Competition result cutover', () => {
: Promise.reject(new Error(`Unexpected model ${name}`)); : Promise.reject(new Error(`Unexpected model ${name}`));
}), }),
} as unknown as ConnectionService; } as unknown as ConnectionService;
const matchStatsService = {
removeByMatches: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<MatchStatsService>;
const communityStatsService = { const communityStatsService = {
invalidateCommunity: jest.fn().mockResolvedValue(undefined), invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as unknown as jest.Mocked<CommunityStatsService>; } as unknown as jest.Mocked<CommunityStatsService>;
const service = createService({ const service = createService({
connectionService, connectionService,
matchStatsService,
communityStatsService, communityStatsService,
}); });
@@ -360,9 +415,98 @@ describe('Legacy import Competition result cutover', () => {
expect(competitionModel.deleteMany).toHaveBeenCalledWith({ expect(competitionModel.deleteMany).toHaveBeenCalledWith({
_id: { $in: [fixture.competition._id] }, _id: { $in: [fixture.competition._id] },
}); });
expect(matchStatsService.removeByMatches).toHaveBeenCalledWith([ expect(tournamentCodeModel.updateMany).toHaveBeenCalledTimes(2);
fixture.match._id, 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 () => { 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) }; 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() { function deleteManyModel() {
return { return {
deleteMany: jest deleteMany: jest
.fn() .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, BadRequestException,
ConflictException, ConflictException,
Injectable, Injectable,
InternalServerErrorException,
Logger, Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
@@ -381,60 +382,194 @@ export class LegacyImportService {
.filter((id) => mongoose.isValidObjectId(id)) .filter((id) => mongoose.isValidObjectId(id))
.map((id) => new mongoose.Types.ObjectId(id)); .map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 }; 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 [ const [
MatchModel,
CompetitionModel, CompetitionModel,
CompetitionFactModel, CompetitionFactModel,
CompetitionOutboxModel, CompetitionOutboxModel,
AssignmentModel, AssignmentModel,
TournamentCodeModel,
MatchStatsModel,
connection,
] = await Promise.all([ ] = await Promise.all([
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'), this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'), this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'), this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'), this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('matchStats'),
this.connectionService.getConnection(),
]); ]);
const competitions = await CompetitionModel.find({ const session = await this.connectionService.createSession();
matchId: { $in: targetIds }, if (!session) {
}) throw new InternalServerErrorException(
.select({ _id: 1 }) 'A MongoDB transaction is required to delete legacy Matches.',
.lean() );
.exec(); }
const competitionIds = competitions.map(({ _id }) => _id);
if (competitionIds.length > 0) { let deleted = 0;
await Promise.all([ try {
CompetitionFactModel.deleteMany({ session.startTransaction();
competitionId: { $in: competitionIds }, const targets = await MatchModel.find({
}).exec(), _id: { $in: ids },
CompetitionOutboxModel.deleteMany({ communityId: params.communityId,
competitionId: { $in: competitionIds }, legacyImported: true,
}).exec(), })
AssignmentModel.deleteMany({ .select({ _id: 1 })
competitionId: { $in: competitionIds }, .session(session)
}).exec(), .exec();
]); const targetIds = targets.map((match) => match._id);
await CompetitionModel.deleteMany({ if (targetIds.length === 0) {
_id: { $in: competitionIds }, await session.commitTransaction();
}).exec(); } 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); await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted: result.deletedCount ?? 0 }; return { deleted };
} }
public async rebuildLegacyMatches(params: { public async rebuildLegacyMatches(params: {
@@ -1322,6 +1457,29 @@ function optionalNumber(value: unknown): number | undefined {
: 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 { function deterministicObjectId(key: string): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId( return new mongoose.Types.ObjectId(
createHash('sha256').update(key).digest('hex').slice(0, 24), createHash('sha256').update(key).digest('hex').slice(0, 24),
@@ -1,7 +1,9 @@
import 'reflect-metadata'; import 'reflect-metadata';
import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { plainToInstance } from 'class-transformer'; import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator'; 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', () => { describe('CreateMatchDto game mode cutover', () => {
it('rejects the removed live bracket mode', () => { 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 }) @ValidateNested({ each: true })
@Type(() => PositionPreferenceDto) @Type(() => PositionPreferenceDto)
preferredPositions!: PositionPreferenceDto[]; preferredPositions!: PositionPreferenceDto[];
@IsOptional()
@IsString()
userId?: string;
} }
export class AddParticipantDto { export class AddParticipantDto {
@@ -234,13 +230,3 @@ export class AddParticipantDto {
@IsString() @IsString()
riotPuuid?: string; riotPuuid?: string;
} }
export class SwapDoubleEliminationSeedsDto {
@IsInt()
@Min(1)
leftSeedNumber!: number;
@IsInt()
@Min(1)
rightSeedNumber!: number;
}
@@ -9,6 +9,7 @@ describe('presentPublicMatch', () => {
competitionId: oid('3'), competitionId: oid('3'),
shortCode: '33NW', shortCode: '33NW',
title: '내전', title: '내전',
joined: false,
description: '설명', description: '설명',
mapId: 11, mapId: 11,
status: 'in-progress', status: 'in-progress',
@@ -25,6 +26,16 @@ describe('presentPublicMatch', () => {
gameName: '선수', gameName: '선수',
tagLine: 'KR1', tagLine: 'KR1',
profileIconId: 1, 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: [ preferredPositions: [
{ position: 'MID', priority: 1 }, { position: 'MID', priority: 1 },
{ position: 'SUP', priority: 2 }, { position: 'SUP', priority: 2 },
@@ -65,6 +76,15 @@ describe('presentPublicMatch', () => {
expect.objectContaining({ expect.objectContaining({
userId: oid('5').toString(), userId: oid('5').toString(),
joinedAt: '2026-07-01T00:00:00.000Z', 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: [ teams: [
@@ -89,6 +109,7 @@ describe('presentPublicMatch', () => {
expect(response).not.toHaveProperty('resultPollState'); expect(response).not.toHaveProperty('resultPollState');
expect(response).not.toHaveProperty('legacyImportSource'); expect(response).not.toHaveProperty('legacyImportSource');
expect(response.participants[0]).not.toHaveProperty('puuid'); 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 { import type {
MatchGameMode, MatchGameMode,
MatchStatus, MatchStatus,
@@ -57,12 +58,12 @@ interface PublicMatchSource {
export function presentPublicMatch( export function presentPublicMatch(
source: PublicMatchSource, source: PublicMatchSource,
options: { joined?: boolean } = {}, options: { joined?: boolean } = {},
) { ): MatchDetailResponse {
return { return {
_id: source._id.toString(), _id: source._id.toString() as never,
communityId: source.communityId.toString(), communityId: source.communityId.toString() as never,
...(source.competitionId ...(source.competitionId
? { competitionId: source.competitionId.toString() } ? { competitionId: source.competitionId.toString() as never }
: {}), : {}),
...(source.shortCode ? { shortCode: source.shortCode } : {}), ...(source.shortCode ? { shortCode: source.shortCode } : {}),
title: source.title, title: source.title,
@@ -82,32 +83,37 @@ export function presentPublicMatch(
source.doubleElimination?.resetFinalEnabled ?? false, source.doubleElimination?.resetFinalEnabled ?? false,
} }
: {}), : {}),
...(source.hostUserId ? { hostUserId: source.hostUserId.toString() } : {}), ...(source.hostUserId
participants: source.participants.map((participant) => ({ ? { hostUserId: source.hostUserId.toString() as never }
userId: participant.userId.toString(), : {}),
...(participant.gameName ? { gameName: participant.gameName } : {}), participants: source.participants.map((participant) => {
...(participant.tagLine ? { tagLine: participant.tagLine } : {}), const tier = toPublicTier(participant.tier);
...(participant.profileIconId === undefined return {
? {} userId: participant.userId.toString() as never,
: { profileIconId: participant.profileIconId }), ...(participant.gameName ? { gameName: participant.gameName } : {}),
...(participant.tier === undefined ...(participant.tagLine ? { tagLine: participant.tagLine } : {}),
? {} ...(participant.profileIconId === undefined
: { tier: toWireValue(participant.tier) }), ? {}
preferredPositions: participant.preferredPositions.map((preference) => ({ : { profileIconId: participant.profileIconId }),
position: preference.position, ...(tier ? { tier } : {}),
priority: preference.priority, preferredPositions: participant.preferredPositions.map(
})), (preference) => ({
joinedAt: asIso(participant.joinedAt), position: preference.position,
excluded: participant.excluded ?? false, priority: preference.priority,
})), }),
),
joinedAt: asIso(participant.joinedAt),
excluded: participant.excluded ?? false,
};
}),
teams: source.teams.map((team) => ({ teams: source.teams.map((team) => ({
teamIndex: team.teamIndex, teamIndex: team.teamIndex,
name: team.name, name: team.name,
...(team.captainUserId ...(team.captainUserId
? { captainUserId: team.captainUserId.toString() } ? { captainUserId: team.captainUserId.toString() as never }
: {}), : {}),
members: team.members.map((member) => ({ members: team.members.map((member) => ({
userId: member.userId.toString(), userId: member.userId.toString() as never,
assignedPosition: member.assignedPosition, assignedPosition: member.assignedPosition,
...(member.cost === undefined ? {} : { cost: member.cost }), ...(member.cost === undefined ? {} : { cost: member.cost }),
})), })),
@@ -115,7 +121,7 @@ export function presentPublicMatch(
prizes: [...source.prizes], prizes: [...source.prizes],
notices: [...source.notices], notices: [...source.notices],
schedule: source.schedule.map(({ time, label }) => ({ time, label })), schedule: source.schedule.map(({ time, label }) => ({ time, label })),
...(options.joined === undefined ? {} : { joined: options.joined }), joined: options.joined ?? false,
createdAt: asIso(source.createdAt), createdAt: asIso(source.createdAt),
updatedAt: asIso(source.updatedAt), updatedAt: asIso(source.updatedAt),
}; };
@@ -125,13 +131,29 @@ function asIso(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value; return value instanceof Date ? value.toISOString() : value;
} }
function toWireValue(value: unknown): unknown { function toPublicTier(value: unknown): MatchTierView | undefined {
if (value instanceof Date) return value.toISOString(); if (typeof value !== 'object' || value === null || Array.isArray(value)) {
if (Array.isArray(value)) return value.map(toWireValue); return undefined;
if (typeof value === 'object' && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key, child]) => [key, toWireValue(child)]),
);
} }
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 { import {
BadRequestException, BadRequestException,
Body, Body,
@@ -23,7 +27,6 @@ import {
AddParticipantDto, AddParticipantDto,
CreateMatchDto, CreateMatchDto,
JoinMatchDto, JoinMatchDto,
SwapDoubleEliminationSeedsDto,
UpdateMatchDto, UpdateMatchDto,
UpdateParticipantDto, UpdateParticipantDto,
} from './dto/create-match.dto'; } from './dto/create-match.dto';
@@ -41,9 +44,9 @@ export class MatchController {
@Param('communityId', ParseObjectIdPipe) @Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
@Body() body: CreateMatchDto, @Body() body: CreateMatchDto,
) { ): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId); this.assertSameCommunity(currentUser, communityId);
return this.matchService.create({ const match = await this.matchService.create({
communityId, communityId,
hostUserId: currentUser._id, hostUserId: currentUser._id,
data: { data: {
@@ -62,6 +65,7 @@ export class MatchController {
schedule: body.schedule ?? [], schedule: body.schedule ?? [],
}, },
}); });
return this.matchService.serialize(match, { joined: false });
} }
// 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환.
@@ -78,7 +82,7 @@ export class MatchController {
@Query('scheduledFrom') scheduledFrom?: string, @Query('scheduledFrom') scheduledFrom?: string,
@Query('scheduledTo') scheduledTo?: string, @Query('scheduledTo') scheduledTo?: string,
@Query('sort') sort?: 'asc' | 'desc', @Query('sort') sort?: 'asc' | 'desc',
) { ): Promise<MatchListResponse> {
const result = await this.matchService.listPage({ const result = await this.matchService.listPage({
communityId, communityId,
status, status,
@@ -108,10 +112,20 @@ export class MatchController {
@Get(':matchId') @Get(':matchId')
@AllowPublicAccess() @AllowPublicAccess()
public async getMatch( public async getMatch(
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
) { ): Promise<MatchDetailResponse> {
const match = await this.matchService.getById(matchId); const match = await this.matchService.getById(matchId, communityId);
return this.matchService.serialize(match); return this.matchService.serialize(match, {
joined: Boolean(
currentUser &&
match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
),
),
});
} }
@Patch(':matchId') @Patch(':matchId')
@@ -123,48 +137,18 @@ export class MatchController {
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: UpdateMatchDto, @Body() body: UpdateMatchDto,
) { ): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId); this.assertSameCommunity(currentUser, communityId);
return this.matchService.update({ matchId, communityId, patch: body }); const match = await this.matchService.update({
}
@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({
matchId, matchId,
communityId, communityId,
actorUserId: currentUser._id, patch: body,
}); });
return this.matchService.serialize(match); return this.matchService.serialize(match, {
} joined: match.participants.some((participant) =>
participant.userId.equals(currentUser._id),
@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);
} }
@Delete(':matchId') @Delete(':matchId')
@@ -181,20 +165,25 @@ export class MatchController {
await this.matchService.remove({ matchId, communityId }); await this.matchService.remove({ matchId, communityId });
} }
// 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용). // 커뮤니티 멤버 본인 참여. 다른 유저 추가는 관리자 전용 경로를 사용한다.
@Post(':matchId/participants') @Post(':matchId/participants')
@AllowPublicAccess() @Roles('owner', 'admin', 'member')
@UseGuards(RolesGuard)
public async joinMatch( public async joinMatch(
@CurrentUser() currentUser: UserDocument | undefined, @CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Body() body: JoinMatchDto, @Body() body: JoinMatchDto,
) { ): Promise<MatchDetailResponse> {
const userId = this.resolveJoinerUserId(currentUser, body.userId); this.assertSameCommunity(currentUser, communityId);
return this.matchService.join({ const match = await this.matchService.join({
matchId, matchId,
userId, communityId,
userId: currentUser._id,
preferredPositions: body.preferredPositions, 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('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: AddParticipantDto | undefined, @Body() body: AddParticipantDto | undefined,
) { ): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId); this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.join({ const match = await this.matchService.join({
matchId, matchId,
communityId,
userId, userId,
preferredPositions: body?.preferredPositions, preferredPositions: body?.preferredPositions,
riotPuuid: body?.riotPuuid, 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('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
@Body() body: UpdateParticipantDto, @Body() body: UpdateParticipantDto,
) { ): Promise<MatchDetailResponse> {
this.assertSameCommunity(currentUser, communityId); this.assertSameCommunity(currentUser, communityId);
const match = await this.matchService.updateParticipantPositions({ const match = await this.matchService.updateParticipantPositions({
matchId, matchId,
@@ -239,7 +233,11 @@ export class MatchController {
mainPosition: body.mainPosition, mainPosition: body.mainPosition,
subPosition: body.subPosition, 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( private assertSameCommunity(
user: UserDocument, user: UserDocument,
communityId: mongoose.Types.ObjectId, communityId: mongoose.Types.ObjectId,
+140 -24
View File
@@ -57,6 +57,7 @@ describe('MatchService', () => {
) { ) {
const MatchModel = { const MatchModel = {
findById: jest.fn().mockResolvedValue(match), findById: jest.fn().mockResolvedValue(match),
findOne: jest.fn().mockResolvedValue(match),
findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch), findOneAndUpdate: jest.fn().mockResolvedValue(updatedMatch),
}; };
const connectionService = { 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 () => { it('applies offset before page-based pagination', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const { service, skip } = createServiceWithListModel(); const { service, skip } = createServiceWithListModel();
@@ -344,6 +358,36 @@ describe('MatchService', () => {
expect(match.save).not.toHaveBeenCalled(); 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 () => { it('cancels a join with an atomic participant pull', async () => {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const userId = new mongoose.Types.ObjectId(); const userId = new mongoose.Types.ObjectId();
@@ -525,7 +569,7 @@ describe('MatchService', () => {
expect(MatchModel.create).not.toHaveBeenCalled(); 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 communityId = new mongoose.Types.ObjectId();
const match = { const match = {
communityId, communityId,
@@ -547,20 +591,23 @@ describe('MatchService', () => {
const { service, tournamentCodeService, matchStatsService } = const { service, tournamentCodeService, matchStatsService } =
createService(match); createService(match);
await service.update({ await expect(
matchId: new mongoose.Types.ObjectId(), service.update({
communityId, matchId: new mongoose.Types.ObjectId(),
patch: { status: 'recruiting' }, communityId,
}); patch: { status: 'recruiting' },
}),
).rejects.toThrow('cannot return to recruiting');
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled(); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.tournamentCodeIds).toEqual([]); expect(match.tournamentCodeIds).toEqual([]);
expect(match.gameSchedule).toEqual([]); expect(match.gameSchedule).toEqual([
expect(match.teamBuiltAt).toBeUndefined(); { gameNumber: 1, teamAIndex: 2, teamBIndex: 4 },
expect(match.result).toBeUndefined(); ]);
expect(match.resultPollState).toBeUndefined(); expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.save).toHaveBeenCalledTimes(1); expect(match.result).toEqual({ games: [] });
expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); 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 () => { it('rejects round-robin max round changes after recruiting', async () => {
@@ -581,12 +628,77 @@ describe('MatchService', () => {
patch: { roundRobinMaxRounds: 3 }, patch: { roundRobinMaxRounds: 3 },
}), }),
).rejects.toThrow( ).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(); 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 communityId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId(); const codeId = new mongoose.Types.ObjectId();
const match = { const match = {
@@ -604,14 +716,18 @@ describe('MatchService', () => {
}; };
const { service, tournamentCodeService } = createService(match); const { service, tournamentCodeService } = createService(match);
await service.update({ await expect(
matchId: new mongoose.Types.ObjectId(), service.update({
communityId, matchId: new mongoose.Types.ObjectId(),
patch: { status: 'recruiting' }, communityId,
}); patch: { status: 'recruiting' },
}),
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(match); ).rejects.toThrow('cannot return to recruiting');
expect(match.tournamentCodeIds).toEqual([]); expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
expect(match.gameSchedule).toEqual([]); 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 { import {
BadRequestException, BadRequestException,
ConflictException,
Injectable, Injectable,
InternalServerErrorException, InternalServerErrorException,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import {
reshuffleDoubleEliminationSeeds,
swapDoubleEliminationSeeds,
} from '../double-elimination/double-elimination.util';
import { MatchStatsService } from '../community-stats/match-stats.service'; import { MatchStatsService } from '../community-stats/match-stats.service';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
@@ -76,6 +73,7 @@ interface MatchListFilter {
interface JoinMatchParams { interface JoinMatchParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
communityId?: mongoose.Types.ObjectId;
userId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId;
preferredPositions?: PositionPreference[]; preferredPositions?: PositionPreference[];
// 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용.
@@ -101,17 +99,6 @@ interface UpdateParticipantPositionsParams {
subPosition: Position; 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() @Injectable()
export class MatchService { export class MatchService {
constructor( constructor(
@@ -197,9 +184,10 @@ export class MatchService {
public async getById( public async getById(
matchId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId,
communityId: mongoose.Types.ObjectId,
): Promise<MatchDocument> { ): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match'); 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.'); if (!match) throw new NotFoundException('Match not found.');
return match; return match;
} }
@@ -224,15 +212,24 @@ export class MatchService {
throw new BadRequestException('Match does not belong to this community.'); throw new BadRequestException('Match does not belong to this community.');
} }
const previousStatus = match.status; 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 ( if (
previousStatus !== 'recruiting' && previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || ('maxParticipants' in params.patch ||
'gameCount' in params.patch ||
'gameMode' in params.patch || 'gameMode' in params.patch ||
'roundRobinMaxRounds' in params.patch || 'roundRobinMaxRounds' in params.patch ||
'doubleEliminationResetFinalEnabled' in params.patch) 'doubleEliminationResetFinalEnabled' in params.patch)
) { ) {
throw new BadRequestException( 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 = const patchToSet =
@@ -252,21 +249,8 @@ export class MatchService {
}) })
: this.stripMatchConfigInput(params.patch); : this.stripMatchConfigInput(params.patch);
match.set(patchToSet); 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(); await match.save();
if (previousStatus !== 'recruiting' && match.status === 'recruiting') { if (match.result?.games?.length) {
await this.matchStatsService.removeByMatch(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId);
} else if (match.result?.games?.length) {
await this.matchStatsService.buildAndUpsert(match._id); await this.matchStatsService.buildAndUpsert(match._id);
await this.communityStatsService.invalidateCommunity(params.communityId); await this.communityStatsService.invalidateCommunity(params.communityId);
} }
@@ -283,62 +267,31 @@ export class MatchService {
if (!match.communityId.equals(params.communityId)) { if (!match.communityId.equals(params.communityId)) {
throw new BadRequestException('Match does not belong to this community.'); 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.tournamentCodeService.releaseFromMatch(match);
await this.matchStatsService.removeByMatch(match._id); await this.matchStatsService.removeByMatch(match._id);
await match.deleteOne(); await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId); 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> { public async join(params: JoinMatchParams): Promise<MatchDocument> {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const UserModel = await this.connectionService.getModel('user'); const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId); const user = await UserModel.findById(params.userId);
if (!user) throw new NotFoundException('User not found.'); 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 const selectedRiot = params.riotPuuid
? user.riotAccounts.find((a) => a.puuid === params.riotPuuid) ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid)
@@ -362,7 +315,7 @@ export class MatchService {
const updatedMatch = await MatchModel.findOneAndUpdate( const updatedMatch = await MatchModel.findOneAndUpdate(
{ {
_id: params.matchId, _id: params.matchId,
communityId: user.communityId, communityId: params.communityId ?? user.communityId,
status: 'recruiting', status: 'recruiting',
'participants.userId': { $ne: user._id }, 'participants.userId': { $ne: user._id },
$expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] }, $expr: { $lt: [{ $size: '$participants' }, '$maxParticipants'] },
@@ -438,85 +391,6 @@ export class MatchService {
return gameCount % 2 === 0 ? gameCount + 1 : gameCount; 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( public async cancelJoin(
params: CancelMatchJoinParams, params: CancelMatchJoinParams,
): Promise<MatchDocument> { ): 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 { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { TournamentCodeController } from './tournament-code.controller'; import { TournamentCodeController } from './tournament-code.controller';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
import { TournamentCodeReplacementController } from './tournament-code-replacement.controller';
import { TournamentCodeScheduler } from './tournament-code.scheduler'; import { TournamentCodeScheduler } from './tournament-code.scheduler';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
import { TournamentCodeVendorService } from './tournament-code-vendor.service'; import { TournamentCodeVendorService } from './tournament-code-vendor.service';
@Module({ @Module({
imports: [TournamentResultModule, AuctionRedisModule], imports: [TournamentResultModule, AuctionRedisModule],
controllers: [TournamentCodeController, TournamentCodeReplacementController], controllers: [TournamentCodeController],
providers: [ providers: [
TournamentCodeService, TournamentCodeService,
TournamentCodeVendorService, TournamentCodeVendorService,
@@ -1,16 +1,28 @@
import mongoose from 'mongoose';
import { DistributedLockService } from '../global/redis/distributed-lock.service'; import { DistributedLockService } from '../global/redis/distributed-lock.service';
import { TournamentCodeScheduler } from './tournament-code.scheduler'; import { TournamentCodeScheduler } from './tournament-code.scheduler';
describe('TournamentCodeScheduler', () => { describe('TournamentCodeScheduler', () => {
function createScheduler(params?: { function createScheduler(params?: {
attachedMatches?: unknown[]; attachedMatches?: unknown[];
expirationResult?: {
affectedMatchIds: unknown[];
expiredCount: number;
failedCount: number;
};
scheduleInitialPoll?: jest.Mock; scheduleInitialPoll?: jest.Mock;
}) { }) {
const tournamentCodeService = { const tournamentCodeService = {
attachPendingMatchDocuments: jest attachPendingMatchDocuments: jest
.fn() .fn()
.mockResolvedValue(params?.attachedMatches ?? []), .mockResolvedValue(params?.attachedMatches ?? []),
markExpired: jest.fn().mockResolvedValue(0), markExpired: jest.fn().mockResolvedValue(
params?.expirationResult ?? {
affectedMatchIds: [],
expiredCount: 0,
failedCount: 0,
},
),
}; };
const autoProvisionService = { const autoProvisionService = {
ensurePool: jest.fn().mockResolvedValue(undefined), ensurePool: jest.fn().mockResolvedValue(undefined),
@@ -20,21 +32,26 @@ describe('TournamentCodeScheduler', () => {
params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null), params?.scheduleInitialPoll ?? jest.fn().mockResolvedValue(null),
}; };
const distributedLockService = { const distributedLockService = {
runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) => runWithRenewedLock: jest
operation({ .fn()
lockKey: options.lockKey, .mockImplementation(async (options, operation) =>
lockOwnershipToken: 'lock-owner', operation({
lockExpirationDurationMilliseconds: lockKey: options.lockKey,
options.lockExpirationDurationMilliseconds, lockOwnershipToken: 'lock-owner',
}), lockExpirationDurationMilliseconds:
), options.lockExpirationDurationMilliseconds,
}),
),
} as unknown as jest.Mocked<DistributedLockService>; } as unknown as jest.Mocked<DistributedLockService>;
const scheduler = new TournamentCodeScheduler( const scheduler = new TournamentCodeScheduler(
tournamentCodeService as never, tournamentCodeService as never,
autoProvisionService as never, autoProvisionService as never,
tournamentResultService as never, tournamentResultService as never,
distributedLockService as never, distributedLockService as never,
) as unknown as { attachPending(): Promise<void> }; ) as unknown as {
attachPending(): Promise<void>;
markExpired(): Promise<void>;
};
return { return {
scheduler, scheduler,
@@ -84,4 +101,21 @@ describe('TournamentCodeScheduler', () => {
tournamentCodeService.attachPendingMatchDocuments, tournamentCodeService.attachPendingMatchDocuments,
).not.toHaveBeenCalled(); ).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 { DistributedLockService } from '../global/redis/distributed-lock.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service';
import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service'; import { TournamentCodeAutoProvisionService } from './tournament-code-auto-provision.service';
@@ -31,13 +36,19 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
this.attachTimer = setInterval(() => { this.attachTimer = setInterval(() => {
void this.attachPending(); void this.attachPending();
}, 30_000); }, 30_000);
this.expireTimer = setInterval(() => { this.expireTimer = setInterval(
void this.markExpired(); () => {
}, 60 * 60 * 1000); void this.markExpired();
},
60 * 60 * 1000,
);
if (isAutoProvisionEnabled()) { if (isAutoProvisionEnabled()) {
this.refillTimer = setInterval(() => { this.refillTimer = setInterval(
void this.ensureVendorPool(); () => {
}, 5 * 60 * 1000); void this.ensureVendorPool();
},
5 * 60 * 1000,
);
} }
this.attachTimer.unref?.(); this.attachTimer.unref?.();
this.expireTimer.unref?.(); this.expireTimer.unref?.();
@@ -99,7 +110,18 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS, SCHEDULER_LOCK_RENEWAL_INTERVAL_MILLISECONDS,
}, },
async () => { 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) { } catch (error) {
@@ -136,8 +158,7 @@ export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy {
} }
function isAutoProvisionEnabled(): boolean { function isAutoProvisionEnabled(): boolean {
const raw = process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED const raw =
?.trim() process.env.TOURNAMENT_CODE_AUTO_PROVISION_ENABLED?.trim().toLowerCase();
.toLowerCase();
return raw !== 'false' && raw !== '0' && raw !== 'off'; return raw !== 'false' && raw !== '0' && raw !== 'off';
} }
@@ -2,6 +2,7 @@ import {
TournamentCodeSchema, TournamentCodeSchema,
type MatchDocument, type MatchDocument,
} from '../global/database/schema'; } from '../global/database/schema';
import { Logger } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { TournamentCodeService } from './tournament-code.service'; import { TournamentCodeService } from './tournament-code.service';
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
@@ -13,11 +14,6 @@ type TournamentCodeServiceInternals = TournamentCodeService & {
gameNumber: number, gameNumber: number,
): { teamAIndex: number; teamBIndex: number }; ): { teamAIndex: number; teamBIndex: number };
ensureGameSchedule(match: MatchDocument): void; 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>; 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() { function createService() {
return new TournamentCodeService( return new TournamentCodeService(
{} as never, {} as never,
@@ -51,6 +62,7 @@ interface MatchOverrides {
participants?: Array<{ excluded?: boolean }>; participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>; teams?: Array<{ teamIndex: number }>;
doubleElimination?: MatchDocument['doubleElimination']; doubleElimination?: MatchDocument['doubleElimination'];
tournamentCodeIds?: mongoose.Types.ObjectId[];
gameSchedule?: Array<{ gameSchedule?: Array<{
gameNumber: number; gameNumber: number;
roundNumber?: number; roundNumber?: number;
@@ -261,6 +273,43 @@ describe('TournamentCodeService round-robin scheduling', () => {
).toMatchObject({ gameCount: 3, requiredWins: 2 }); ).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 () => { it('expands double-elimination winner bracket series into code slots', async () => {
const TournamentCodeModel = { const TournamentCodeModel = {
find: jest.fn().mockReturnValue({ find: jest.fn().mockReturnValue({
@@ -437,6 +486,50 @@ describe('TournamentCodeService round-robin scheduling', () => {
expect(slots).toEqual([]); 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', () => { describe('TournamentCodeService bulk upload', () => {
@@ -639,228 +732,278 @@ describe('TournamentCodeService pending match attachment', () => {
}); });
}); });
describe('TournamentCodeService code replacement', () => { describe('TournamentCodeService Competition assignment safety', () => {
function queryResult<T>(value: T) { it('does not restore an actively reserved code outside Competition commands', async () => {
return { exec: jest.fn().mockResolvedValue(value) }; const code = {
}
function createCode(overrides: Record<string, unknown>) {
return {
_id: new mongoose.Types.ObjectId(), _id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved', state: 'reserved',
expiresAt: new Date(Date.now() + 60 * 60 * 1000), save: jest.fn(),
matchId: new mongoose.Types.ObjectId(),
gameNumber: 1,
reservedAt: new Date(),
releasedAt: undefined,
riotMatchId: undefined,
save: jest.fn().mockResolvedValue(undefined),
...overrides,
}; };
}
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 = { const connectionService = {
createSession: jest.fn().mockResolvedValue(session), getModel: jest.fn().mockImplementation((name: string) => {
getModel: jest.fn().mockImplementation((modelName: string) => { if (name === 'tournamentCode') {
if (modelName === 'match') return Promise.resolve(MatchModel); return Promise.resolve({
if (modelName === 'tournamentCode') { findById: jest.fn().mockResolvedValue(code),
return Promise.resolve(TournamentCodeModel); });
} }
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( const service = new TournamentCodeService(
connectionService as never, connectionService as never,
auctionRedisService as never, createAuctionRedisService() as never,
) as unknown as TournamentCodeServiceInternals; );
return { await expect(service.restoreToAvailable(code._id)).rejects.toThrow(
match, 'Active Competition assignments',
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',
}),
); );
expect(MatchModel.findOne).toHaveBeenCalledWith({ expect(code.save).not.toHaveBeenCalled();
_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();
}); });
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 matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId();
const fixture = createReplacementFixture({ const assignmentId = new mongoose.Types.ObjectId();
match: createMatch({ const session = createSession();
_id: matchId, const code = { _id: codeId, state: 'reserved', matchId };
communityId, const codeUpdate = jest.fn().mockReturnValue(mongoQuery(code));
status: 'in-progress', const assignmentUpdate = jest
gameCount: 1, .fn()
participants: Array.from({ length: 10 }, () => ({})), .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
teams: [{ teamIndex: 1 }, { teamIndex: 2 }], const matchUpdate = jest
tournamentCodeIds: [new mongoose.Types.ObjectId()], .fn()
result: { .mockReturnValue(mongoQuery({ matchedCount: 1, modifiedCount: 1 }));
riotMatchIds: ['KR_1'], const models = {
games: [{ gameNumber: 1 }], tournamentCode: {
seriesResults: [], find: jest.fn().mockReturnValue(mongoQuery([{ _id: codeId }])),
}, findOne: jest.fn().mockReturnValue(mongoQuery(code)),
} as unknown as MatchOverrides), 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( expect(codeUpdate).toHaveBeenCalledWith(
fixture.service.replaceForMatchGame({ {
communityId, _id: codeId,
matchId, expiresAt: { $lte: expect.any(Date) as Date },
gameNumber: 1, state: 'reserved',
}), },
).rejects.toThrow('already has a collected result'); {
expect(fixture.TournamentCodeModel.findOne).not.toHaveBeenCalled(); $set: { state: 'expired' },
expect(fixture.TournamentCodeModel.findOneAndUpdate).not.toHaveBeenCalled(); $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 () => { it('isolates a used-assignment corruption and still expires the next valid candidate', async () => {
const { match, communityId, matchId, currentCode, session, service } = const corruptCodeId = new mongoose.Types.ObjectId();
createReplacementFixture({ const validCodeId = new mongoose.Types.ObjectId();
replacementCode: null, 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( await expect(service.markExpired()).resolves.toEqual({
service.replaceForMatchGame({ communityId, matchId, gameNumber: 1 }), affectedMatchIds: [validMatchId],
).rejects.toThrow('No available tournament code'); expiredCount: 1,
expect(currentCode?.save).not.toHaveBeenCalled(); failedCount: 1,
expect(match.save).not.toHaveBeenCalled(); });
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(session.abortTransaction).toHaveBeenCalledTimes(1);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('ownership does not match'),
);
errorLog.mockRestore();
}); });
}); });
@@ -3,6 +3,7 @@ import {
ConflictException, ConflictException,
Injectable, Injectable,
InternalServerErrorException, InternalServerErrorException,
Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { randomUUID } from 'crypto'; 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_MATCH_LOCK_TTL_MS = 30_000;
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3; const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
export interface TournamentCodeExpirationResult {
expiredCount: number;
failedCount: number;
affectedMatchIds: mongoose.Types.ObjectId[];
}
@Injectable() @Injectable()
export class TournamentCodeService { export class TournamentCodeService {
private readonly logger = new Logger(TournamentCodeService.name);
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly auctionRedisService: AuctionRedisService, private readonly auctionRedisService: AuctionRedisService,
@@ -216,9 +225,9 @@ export class TournamentCodeService {
const MatchModel = await this.connectionService.getModel('match'); const MatchModel = await this.connectionService.getModel('match');
const code = await TournamentCodeModel.findById(id); const code = await TournamentCodeModel.findById(id);
if (!code) throw new NotFoundException('Tournament code not found.'); if (!code) throw new NotFoundException('Tournament code not found.');
if (code.state !== 'released' && code.state !== 'reserved') { if (code.state !== 'released') {
throw new BadRequestException( 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; const previousMatchId = code.matchId;
@@ -318,174 +327,6 @@ export class TournamentCodeService {
return match; 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( public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId, matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> { ): Promise<void> {
@@ -530,17 +371,153 @@ export class TournamentCodeService {
await match.save({ session }); await match.save({ session });
} }
public async markExpired(): Promise<number> { public async markExpired(): Promise<TournamentCodeExpirationResult> {
const TournamentCodeModel = const [TournamentCodeModel, AssignmentModel, CompetitionModel, MatchModel] =
await this.connectionService.getModel('tournamentCode'); await Promise.all([
const result = await TournamentCodeModel.updateMany( this.connectionService.getModel('tournamentCode'),
{ this.connectionService.getModel('tournamentCodeAssignment'),
state: { $in: ['available', 'reserved', 'released'] }, this.connectionService.getModel('competition'),
expiresAt: { $lte: new Date() }, this.connectionService.getModel('match'),
}, ]);
{ $set: { state: 'expired' } }, const expiredAt = new Date();
).exec(); const candidates = await TournamentCodeModel.find({
return result.modifiedCount; 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( public async attachPendingMatches(
@@ -610,7 +587,11 @@ export class TournamentCodeService {
: []; : [];
const byGameNumber = new Map( const byGameNumber = new Map(
codes 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]), .map((code) => [code.gameNumber as number, code]),
); );
@@ -645,21 +626,6 @@ export class TournamentCodeService {
return (code ?? '').trim(); 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( private resolveMatchId(
matchOrId: MatchDocument | mongoose.Types.ObjectId, matchOrId: MatchDocument | mongoose.Types.ObjectId,
): mongoose.Types.ObjectId { ): mongoose.Types.ObjectId {
@@ -991,7 +957,12 @@ export class TournamentCodeService {
.map((team) => team.teamIndex) .map((team) => team.teamIndex)
.sort((left, right) => left - right); .sort((left, right) => left - right);
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return; 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( match.doubleElimination = buildDoubleEliminationBracket(
shuffledTeamIndexes, shuffledTeamIndexes,
{ {
@@ -1003,6 +974,34 @@ export class TournamentCodeService {
match.markModified?.('doubleElimination'); 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( private resolveDoubleEliminationGameSlotByGameNumber(
match: MatchDocument, match: MatchDocument,
gameNumber: number, gameNumber: number,
@@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */ /* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service';
import { MatchStatsService } from '../community-stats/match-stats.service'; import { MatchStatsService } from '../community-stats/match-stats.service';
import { ConnectionService } from '../global/database/connection.service'; import { ConnectionService } from '../global/database/connection.service';
@@ -7,6 +8,10 @@ import { CompetitionAssignmentProvisioner } from './competition-assignment.provi
import { CompetitionOutboxProcessor } from './competition-outbox.processor'; import { CompetitionOutboxProcessor } from './competition-outbox.processor';
describe('CompetitionOutboxProcessor', () => { describe('CompetitionOutboxProcessor', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('leases a projection event and applies idempotent downstream effects', async () => { it('leases a projection event and applies idempotent downstream effects', async () => {
const competitionId = new mongoose.Types.ObjectId(); const competitionId = new mongoose.Types.ObjectId();
const matchId = 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) { function leanExecutable<T>(value: T) {
@@ -15,6 +15,7 @@ const DRAIN_INTERVAL_MS = 5_000;
const PROCESSING_LEASE_MS = 60_000; const PROCESSING_LEASE_MS = 60_000;
const MAX_EVENTS_PER_DRAIN = 20; const MAX_EVENTS_PER_DRAIN = 20;
const MAX_RETRY_DELAY_MS = 5 * 60_000; const MAX_RETRY_DELAY_MS = 5 * 60_000;
const MAX_DELIVERY_ATTEMPTS = 10;
interface ClaimedOutboxEvent { interface ClaimedOutboxEvent {
_id: mongoose.Types.ObjectId; _id: mongoose.Types.ObjectId;
@@ -130,18 +131,33 @@ export class CompetitionOutboxProcessor
$unset: { lastError: 1 }, $unset: { lastError: 1 },
}).exec(); }).exec();
} catch (error) { } 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( const availableAt = new Date(
Date.now() + retryDelayMilliseconds(event.attemptCount), Date.now() + retryDelayMilliseconds(event.attemptCount),
); );
await OutboxModel.updateOne(leaseFilter(event), { await OutboxModel.updateOne(leaseFilter(event), {
$set: { $set: {
state: 'failed', state: 'failed',
lastError: errorMessage(error).slice(0, 2_000), lastError,
availableAt, availableAt,
}, },
}).exec(); }).exec();
this.logger.warn( this.logger.warn(
`Competition outbox event ${event._id.toString()} failed: ${errorMessage(error)}`, `Competition outbox event ${event._id.toString()} failed: ${lastError}`,
); );
} }
} }
+1
View File
@@ -7,6 +7,7 @@
"dev": "vite", "dev": "vite",
"start:dev": "vite --mode development", "start:dev": "vite --mode development",
"start:staging": "vite --mode staging", "start:staging": "vite --mode staging",
"test": "node --test --experimental-strip-types test/*.test.ts",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"build:staging": "tsc -b && vite build --mode staging", "build:staging": "tsc -b && vite build --mode staging",
"build:prod": "tsc -b && vite build --mode production", "build:prod": "tsc -b && vite build --mode production",
+35
View File
@@ -0,0 +1,35 @@
export interface AuthQueryScopeInput {
authUserId: string | null;
accountKey: string | null;
msalConfigured: boolean;
msalReady: boolean;
}
interface ExecuteAuthScopedQueryInput<T> {
accountKey: string | null;
acquireAccessToken: () => Promise<string>;
request: (authorizationHeader: string | null) => Promise<T>;
}
export function resolveAuthQueryScope({
authUserId,
accountKey,
msalConfigured,
msalReady,
}: AuthQueryScopeInput) {
return {
cacheKey: [authUserId, accountKey] as const,
ready: Boolean(authUserId || !msalConfigured || msalReady),
};
}
export async function executeAuthScopedQuery<T>({
accountKey,
acquireAccessToken,
request,
}: ExecuteAuthScopedQueryInput<T>): Promise<T> {
if (!accountKey) return request(null);
const accessToken = await acquireAccessToken();
return request(`Bearer ${accessToken}`);
}
+87 -48
View File
@@ -5,6 +5,9 @@ import type {
CompetitionCommandResponse, CompetitionCommandResponse,
CompetitionDetailResponse, CompetitionDetailResponse,
CreateSeriesAdjudicationRequest, CreateSeriesAdjudicationRequest,
MatchDetailResponse,
MatchLifecycleStatus,
MatchListResponse,
ReverseSeriesResultRequest, ReverseSeriesResultRequest,
SeriesId, SeriesId,
SeriesReversalPreviewRequest, SeriesReversalPreviewRequest,
@@ -18,6 +21,10 @@ import {
MSAL_API_SCOPE, MSAL_API_SCOPE,
MSAL_SILENT_REDIRECT_URI, MSAL_SILENT_REDIRECT_URI,
} from '../lib/auth/msal.config'; } from '../lib/auth/msal.config';
import {
executeAuthScopedQuery,
resolveAuthQueryScope,
} from './auth-query-scope';
import type { import type {
ApiAuction, ApiAuction,
ApiAuctionHistoryEntry, ApiAuctionHistoryEntry,
@@ -31,7 +38,6 @@ import type {
LegacyImportJobsResponse, LegacyImportJobsResponse,
LegacyImportMembersResponse, LegacyImportMembersResponse,
LegacyMatchListResponse, LegacyMatchListResponse,
ApiMatch,
ApiRecentMatchesResponse, ApiRecentMatchesResponse,
ApiRecentSummaryResponse, ApiRecentSummaryResponse,
ApiTeamInsightsResponse, ApiTeamInsightsResponse,
@@ -41,9 +47,7 @@ import type {
DdragonManifest, DdragonManifest,
StartLegacyImportRequest, StartLegacyImportRequest,
StartLegacyImportResponse, StartLegacyImportResponse,
MatchStatus,
MatchMutationRequest, MatchMutationRequest,
MatchesResponse,
ManualTournamentResultCollectResponse, ManualTournamentResultCollectResponse,
MeResponse, MeResponse,
RiotQueueGroup, RiotQueueGroup,
@@ -59,7 +63,7 @@ import type {
const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000;
interface MatchesQueryOptions { interface MatchesQueryOptions {
status?: MatchStatus; status?: MatchLifecycleStatus;
limit?: number; limit?: number;
page?: number; page?: number;
offset?: number; offset?: number;
@@ -101,6 +105,45 @@ function createMatchesPath(
return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`; return `/communities/${communityId}/matches${queryString ? `?${queryString}` : ''}`;
} }
function useOptionalAuthQueryScope() {
const authUserId = useAuthUserId();
const { accounts, inProgress, instance } = useMsal();
const account = isMsalConfigured
? (instance.getActiveAccount() ?? accounts[0] ?? null)
: null;
const scope = resolveAuthQueryScope({
authUserId,
accountKey: account?.homeAccountId ?? null,
msalConfigured: isMsalConfigured,
msalReady: inProgress === InteractionStatus.None,
});
const fetch = <T>(path: string) =>
executeAuthScopedQuery({
accountKey: account?.homeAccountId ?? null,
acquireAccessToken: async () => {
if (!account) {
throw new Error('MSAL account is unavailable.');
}
const response = await instance.acquireTokenSilent({
account,
scopes: [MSAL_API_SCOPE],
redirectUri: MSAL_SILENT_REDIRECT_URI,
});
return response.accessToken;
},
request: (authorizationHeader) =>
apiFetch<T>(
path,
authorizationHeader
? { headers: { Authorization: authorizationHeader } }
: undefined,
),
});
return { ...scope, fetch };
}
export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) { export function useCommunity(communityId = DEFAULT_COMMUNITY_ID) {
return useQuery({ return useQuery({
queryKey: ['community', communityId], queryKey: ['community', communityId],
@@ -114,10 +157,13 @@ export function useMatches(
options: MatchesQueryOptions, options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
) { ) {
const authScope = useOptionalAuthQueryScope();
return useQuery({ return useQuery({
queryKey: [ queryKey: [
'matches', 'matches',
communityId, communityId,
...authScope.cacheKey,
options.status ?? null, options.status ?? null,
options.limit ?? null, options.limit ?? null,
options.page ?? null, options.page ?? null,
@@ -127,13 +173,12 @@ export function useMatches(
options.sort ?? null, options.sort ?? null,
], ],
queryFn: async () => { queryFn: async () => {
const response = await apiFetch<MatchesResponse>( const response = await authScope.fetch<MatchListResponse>(
createMatchesPath(communityId, options), createMatchesPath(communityId, options),
{ auth: 'none' },
); );
return response.matches; return response.matches;
}, },
enabled: Boolean(communityId), enabled: Boolean(communityId && authScope.ready),
}); });
} }
@@ -141,10 +186,13 @@ export function useMatchesPage(
options: MatchesQueryOptions, options: MatchesQueryOptions,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
) { ) {
const authScope = useOptionalAuthQueryScope();
return useQuery({ return useQuery({
queryKey: [ queryKey: [
'matches-page', 'matches-page',
communityId, communityId,
...authScope.cacheKey,
options.status ?? null, options.status ?? null,
options.limit ?? null, options.limit ?? null,
options.page ?? null, options.page ?? null,
@@ -154,10 +202,10 @@ export function useMatchesPage(
options.sort ?? null, options.sort ?? null,
], ],
queryFn: () => queryFn: () =>
apiFetch<MatchesResponse>(createMatchesPath(communityId, options), { authScope.fetch<MatchListResponse>(
auth: 'none', createMatchesPath(communityId, options),
}), ),
enabled: Boolean(communityId), enabled: Boolean(communityId && authScope.ready),
placeholderData: (previousData) => previousData, placeholderData: (previousData) => previousData,
}); });
} }
@@ -166,15 +214,25 @@ export function useMatch(
matchId: string | undefined, matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
) { ) {
return useQuery({ const authScope = useOptionalAuthQueryScope();
queryKey: ['match', communityId, matchId ?? null], const queryKey = [
'match',
communityId,
matchId ?? null,
...authScope.cacheKey,
] as const;
const query = useQuery({
queryKey,
queryFn: () => queryFn: () =>
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, { authScope.fetch<MatchDetailResponse>(
auth: 'none', `/communities/${communityId}/matches/${matchId}`,
}), ),
enabled: Boolean(communityId && matchId), enabled: Boolean(communityId && matchId && authScope.ready),
retry: false, retry: false,
}); });
return { ...query, queryKey };
} }
export function useCompetition( export function useCompetition(
@@ -426,7 +484,7 @@ export function useResetAuction(communityId = DEFAULT_COMMUNITY_ID) {
export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) { export function useCreateMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({ return useMutation({
mutationFn: (body: MatchMutationRequest) => mutationFn: (body: MatchMutationRequest) =>
apiFetch<ApiMatch>(`/communities/${communityId}/matches`, { apiFetch<MatchDetailResponse>(`/communities/${communityId}/matches`, {
method: 'POST', method: 'POST',
body: JSON.stringify(body), body: JSON.stringify(body),
}), }),
@@ -442,10 +500,13 @@ export function useUpdateMatch(communityId = DEFAULT_COMMUNITY_ID) {
matchId: string; matchId: string;
body: Partial<MatchMutationRequest>; body: Partial<MatchMutationRequest>;
}) => }) =>
apiFetch<ApiMatch>(`/communities/${communityId}/matches/${matchId}`, { apiFetch<MatchDetailResponse>(
method: 'PATCH', `/communities/${communityId}/matches/${matchId}`,
body: JSON.stringify(body), {
}), method: 'PATCH',
body: JSON.stringify(body),
},
),
}); });
} }
@@ -1028,34 +1089,12 @@ export function useRebuildLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) {
} }
export function useMe() { export function useMe() {
const authUserId = useAuthUserId(); const authScope = useOptionalAuthQueryScope();
const { accounts, inProgress, instance } = useMsal();
const account = isMsalConfigured
? (instance.getActiveAccount() ?? accounts[0] ?? null)
: null;
const accountKey = account?.homeAccountId ?? null;
const isMsalReady =
!isMsalConfigured || inProgress === InteractionStatus.None;
return useQuery({ return useQuery({
queryKey: ['me', authUserId, accountKey], queryKey: ['me', ...authScope.cacheKey],
queryFn: async () => { queryFn: () => authScope.fetch<MeResponse>('/me'),
if (!account) { enabled: authScope.ready,
return apiFetch<MeResponse>('/me');
}
const response = await instance.acquireTokenSilent({
account,
scopes: [MSAL_API_SCOPE],
redirectUri: MSAL_SILENT_REDIRECT_URI,
});
return apiFetch<MeResponse>('/me', {
headers: {
Authorization: `Bearer ${response.accessToken}`,
},
});
},
enabled: Boolean(authUserId || isMsalReady),
retry: false, retry: false,
}); });
} }
+11 -7
View File
@@ -1,15 +1,17 @@
import type {
MatchDetailResponse,
MatchLifecycleStatus,
MatchParticipantView,
} from "@lolympus/contracts";
import type { import type {
ApiAuction, ApiAuction,
ApiAuctionPlayerSnapshot, ApiAuctionPlayerSnapshot,
ApiAuctionTeam, ApiAuctionTeam,
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference, ApiPositionPreference,
ApiRiotLaneStats, ApiRiotLaneStats,
ApiRiotRecentStatsSummary, ApiRiotRecentStatsSummary,
ApiTierHistoryEntry, ApiTierHistoryEntry,
ApiTierInfo, ApiTierInfo,
MatchStatus,
Position, Position,
RiotLane, RiotLane,
} from "./types"; } from "./types";
@@ -46,7 +48,7 @@ export interface MatchDetailView {
title: string; title: string;
date: string; date: string;
time: string; time: string;
status: MatchStatus; status: MatchLifecycleStatus;
description: string; description: string;
map: string; map: string;
maxParticipants: number; maxParticipants: number;
@@ -180,7 +182,7 @@ function resolveMainAndSubPosition(
} }
function mapMatchParticipantToView( function mapMatchParticipantToView(
participant: ApiMatchParticipant, participant: MatchParticipantView,
): ParticipantView { ): ParticipantView {
const { mainPosition, subPosition } = resolveMainAndSubPosition( const { mainPosition, subPosition } = resolveMainAndSubPosition(
participant.preferredPositions, participant.preferredPositions,
@@ -383,7 +385,9 @@ export function buildDefaultPreferredPositions() {
})); }));
} }
export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView { export function mapApiMatchToMatchDetail(
match: MatchDetailResponse,
): MatchDetailView {
const formattedDate = formatKoreanDate(match.scheduledAt); const formattedDate = formatKoreanDate(match.scheduledAt);
const participants = match.participants.map(mapMatchParticipantToView); const participants = match.participants.map(mapMatchParticipantToView);
const participantLookup = new Map( const participantLookup = new Map(
@@ -439,7 +443,7 @@ export function mapApiMatchToMatchDetail(match: ApiMatch): MatchDetailView {
export function mapApiAuctionToAuctionState( export function mapApiAuctionToAuctionState(
auction: ApiAuction, auction: ApiAuction,
match: ApiMatch, match: MatchDetailResponse,
now = new Date(), now = new Date(),
): AuctionStateView { ): AuctionStateView {
const participantLookup = new Map( const participantLookup = new Map(
+12 -87
View File
@@ -1,15 +1,14 @@
export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; import type {
MatchGameMode,
MatchPosition,
MatchPositionPreferenceView,
MatchScheduleItemView,
MatchTierView,
} from '@lolympus/contracts';
export type Position = MatchPosition;
export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY';
export type TeamSide = 'blue' | 'red'; export type TeamSide = 'blue' | 'red';
export type MatchGameMode =
| 'pair'
| 'round-robin'
| 'double-elimination';
export type MatchStatus =
| 'recruiting'
| 'team-built'
| 'in-progress'
| 'finished';
export type AuctionPhase = export type AuctionPhase =
| 'waiting' | 'waiting'
| 'presenting' | 'presenting'
@@ -25,20 +24,8 @@ export type AuctionTopTierThreshold =
| 'MANUAL'; | 'MANUAL';
export type CommunityRole = 'owner' | 'admin' | 'member'; export type CommunityRole = 'owner' | 'admin' | 'member';
export interface ApiPositionPreference { export type ApiPositionPreference = MatchPositionPreferenceView;
position: Position; export type ApiTierInfo = MatchTierView;
priority: number;
}
export interface ApiTierInfo {
queueType: string;
tier: string;
rank: string;
leaguePoints: number;
wins: number;
losses: number;
fetchedAt: string;
}
export interface ApiChampionMasteryEntry { export interface ApiChampionMasteryEntry {
puuid?: string; puuid?: string;
@@ -142,36 +129,6 @@ export type TournamentCodeState =
| 'released' | 'released'
| 'voided'; | 'voided';
export interface ApiMatchParticipant {
userId: string;
puuid?: string;
gameName?: string;
tagLine?: string;
profileIconId?: number;
tier?: ApiTierInfo;
preferredPositions: ApiPositionPreference[];
joinedAt: string;
excluded?: boolean;
}
export interface ApiMatchTeamMember {
userId: string;
assignedPosition: Position;
cost?: number;
}
export interface ApiMatchTeam {
teamIndex: number;
name: string;
captainUserId?: string;
members: ApiMatchTeamMember[];
}
export interface ApiMatchScheduleItem {
time: string;
label: string;
}
export interface ManualTournamentResultCollectResponse { export interface ManualTournamentResultCollectResponse {
scanned: number; scanned: number;
matched: number; matched: number;
@@ -180,31 +137,6 @@ export interface ManualTournamentResultCollectResponse {
gameNumbers: number[]; gameNumbers: number[];
} }
export interface ApiMatch {
_id: string;
communityId: string;
shortCode?: string;
title: string;
description: string;
mapId: number;
status: MatchStatus;
scheduledAt: string;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleEliminationResetFinalEnabled?: boolean;
hostUserId?: string;
participants: ApiMatchParticipant[];
teams: ApiMatchTeam[];
prizes: string[];
notices: string[];
schedule: ApiMatchScheduleItem[];
joined?: boolean;
createdAt: string;
updatedAt: string;
}
export interface ApiAuctionPlayerSnapshot { export interface ApiAuctionPlayerSnapshot {
userId: string; userId: string;
puuid: string; puuid: string;
@@ -336,13 +268,6 @@ export interface MeResponse {
memberships: ApiMembership[]; memberships: ApiMembership[];
} }
export interface MatchesResponse {
matches: ApiMatch[];
total: number;
page: number;
limit: number;
}
export interface MatchMutationRequest { export interface MatchMutationRequest {
title: string; title: string;
description?: string; description?: string;
@@ -355,7 +280,7 @@ export interface MatchMutationRequest {
doubleEliminationResetFinalEnabled?: boolean; doubleEliminationResetFinalEnabled?: boolean;
prizes?: string[]; prizes?: string[];
notices?: string[]; notices?: string[];
schedule?: ApiMatchScheduleItem[]; schedule?: MatchScheduleItemView[];
} }
export interface DdragonChampionEntry { export interface DdragonChampionEntry {
+15 -11
View File
@@ -1,5 +1,9 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQueryClient } from "@tanstack/react-query";
import type {
MatchDetailResponse,
MatchParticipantView,
} from "@lolympus/contracts";
import { ChevronLeft, Search, X } from "lucide-react"; import { ChevronLeft, Search, X } from "lucide-react";
import { Link, useLocation, useNavigate, useParams } from "react-router"; import { Link, useLocation, useNavigate, useParams } from "react-router";
import { import {
@@ -37,8 +41,6 @@ import type {
AuctionTopTierThreshold, AuctionTopTierThreshold,
ApiCommunityUserSearchCandidate, ApiCommunityUserSearchCandidate,
ApiCommunityUserSearchRiotAccount, ApiCommunityUserSearchRiotAccount,
ApiMatch,
ApiMatchParticipant,
ApiPositionPreference, ApiPositionPreference,
ApiTierInfo, ApiTierInfo,
ManualTournamentResultCollectResponse, ManualTournamentResultCollectResponse,
@@ -138,7 +140,7 @@ function parseAuctionSecondsInput(value: string, min: number) {
return seconds; return seconds;
} }
function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) { function buildAuctionParticipantPool(participants: MatchParticipantView[]) {
const ordered = [...participants].sort( const ordered = [...participants].sort(
(left, right) => (left, right) =>
new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(), new Date(left.joinedAt).getTime() - new Date(right.joinedAt).getTime(),
@@ -148,7 +150,7 @@ function buildAuctionParticipantPool(participants: ApiMatchParticipant[]) {
} }
function buildCaptainSlots( function buildCaptainSlots(
participants: ApiMatchParticipant[], participants: MatchParticipantView[],
): CaptainSelectionSlot[] { ): CaptainSelectionSlot[] {
const teamCount = Math.floor( const teamCount = Math.floor(
buildAuctionParticipantPool(participants).length / 5, buildAuctionParticipantPool(participants).length / 5,
@@ -1451,7 +1453,7 @@ export default function MatchDetailPage() {
}, },
}); });
const matchQueryKey = ["match", DEFAULT_COMMUNITY_ID, id ?? null]; const matchQueryKey = matchQuery.queryKey;
const addParticipantMutation = useMutation({ const addParticipantMutation = useMutation({
mutationFn: ({ mutationFn: ({
@@ -1463,7 +1465,7 @@ export default function MatchDetailPage() {
preferredPositions: ApiPositionPreference[]; preferredPositions: ApiPositionPreference[];
riotPuuid?: string; riotPuuid?: string;
}) => }) =>
apiFetch<ApiMatch>( apiFetch<MatchDetailResponse>(
`/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`, `/communities/${DEFAULT_COMMUNITY_ID}/matches/${id}/participants/${userId}`,
{ {
method: "POST", method: "POST",
@@ -1488,9 +1490,10 @@ export default function MatchDetailPage() {
), ),
onMutate: async (userId: string) => { onMutate: async (userId: string) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey }); await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey); const previous =
queryClient.getQueryData<MatchDetailResponse>(matchQueryKey);
if (previous) { if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, { queryClient.setQueryData<MatchDetailResponse>(matchQueryKey, {
...previous, ...previous,
participants: previous.participants.filter( participants: previous.participants.filter(
(participant) => participant.userId !== userId, (participant) => participant.userId !== userId,
@@ -1531,9 +1534,10 @@ export default function MatchDetailPage() {
), ),
onMutate: async ({ userId, mainPosition, subPosition }) => { onMutate: async ({ userId, mainPosition, subPosition }) => {
await queryClient.cancelQueries({ queryKey: matchQueryKey }); await queryClient.cancelQueries({ queryKey: matchQueryKey });
const previous = queryClient.getQueryData<ApiMatch>(matchQueryKey); const previous =
queryClient.getQueryData<MatchDetailResponse>(matchQueryKey);
if (previous) { if (previous) {
queryClient.setQueryData<ApiMatch>(matchQueryKey, { queryClient.setQueryData<MatchDetailResponse>(matchQueryKey, {
...previous, ...previous,
participants: previous.participants.map((participant) => participants: previous.participants.map((participant) =>
participant.userId === userId participant.userId === userId
@@ -1759,7 +1763,7 @@ export default function MatchDetailPage() {
const manualPriorityCandidates = auctionParticipantPool.filter( const manualPriorityCandidates = auctionParticipantPool.filter(
(participant) => !selectedCaptainIds.includes(participant.userId), (participant) => !selectedCaptainIds.includes(participant.userId),
); );
const manualPriorityCandidateIds = new Set( const manualPriorityCandidateIds = new Set<string>(
manualPriorityCandidates.map((participant) => participant.userId), manualPriorityCandidates.map((participant) => participant.userId),
); );
const selectedManualTopTierUserIds = const selectedManualTopTierUserIds =
+144 -20
View File
@@ -1,41 +1,112 @@
import { useState } from "react"; import { useEffect, useRef, useState } from "react";
import { Link, useParams } from "react-router"; import { Link, useParams } from "react-router";
import { useCompetition, useTeamCompetition } from "../api/hooks"; import { useCompetition, useTeamCompetition } from "../api/hooks";
import { SeriesScoreCard } from "../components/competition/SeriesScoreCard"; import { SeriesScoreCard } from "../components/competition/SeriesScoreCard";
import { DEFAULT_COMMUNITY_ID } from "../config"; import { DEFAULT_COMMUNITY_ID } from "../config";
import {
getTeamProgressErrorContent,
isConsistentTeamProgressSnapshot,
type TeamProgressErrorContent,
} from "./match-team-progress-state";
export default function MatchTeamProgressPage() { export default function MatchTeamProgressPage() {
const { id } = useParams(); const { id } = useParams();
const competitionQuery = useCompetition(id, DEFAULT_COMMUNITY_ID); const competitionQuery = useCompetition(id, DEFAULT_COMMUNITY_ID);
const teamQuery = useTeamCompetition(id, DEFAULT_COMMUNITY_ID); const teamQuery = useTeamCompetition(id, DEFAULT_COMMUNITY_ID);
const refetchCompetition = competitionQuery.refetch;
const refetchTeam = teamQuery.refetch;
const [copiedSlotId, setCopiedSlotId] = useState<string | null>(null); const [copiedSlotId, setCopiedSlotId] = useState<string | null>(null);
const lastAutoRefetchedMismatchRef = useRef<string | null>(null);
const competition = competitionQuery.data;
const teamView = teamQuery.data;
const hasQueryError = Boolean(
competitionQuery.error || teamQuery.error,
);
const isRefetching = competitionQuery.isFetching || teamQuery.isFetching;
const revisionsMatch = isConsistentTeamProgressSnapshot(
competition,
teamView,
);
const revisionMismatchKey =
competition && teamView && !revisionsMatch
? `${competition.revision}:${teamView.revision}`
: null;
useEffect(() => {
if (!revisionMismatchKey) {
lastAutoRefetchedMismatchRef.current = null;
return;
}
if (
hasQueryError ||
isRefetching ||
lastAutoRefetchedMismatchRef.current === revisionMismatchKey
) {
return;
}
lastAutoRefetchedMismatchRef.current = revisionMismatchKey;
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
() => undefined,
);
}, [
hasQueryError,
isRefetching,
refetchCompetition,
refetchTeam,
revisionMismatchKey,
]);
function retryBoth() {
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
() => undefined,
);
}
if (competitionQuery.isLoading || teamQuery.isLoading) { if (competitionQuery.isLoading || teamQuery.isLoading) {
return <TeamProgressLoadingState />;
}
if (hasQueryError) {
return ( return (
<main <TeamProgressProblemState
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6" content={getTeamProgressErrorContent(
aria-busy="true" [competitionQuery.error, teamQuery.error].filter(Boolean),
aria-label="팀 진행 정보를 불러오는 중" )}
> isRetrying={isRefetching}
<div className="h-7 w-48 animate-pulse bg-base-200" /> matchId={id}
<div className="h-32 animate-pulse bg-base-200/70" /> onRetry={retryBoth}
</main> />
); );
} }
const competition = competitionQuery.data;
const teamView = teamQuery.data;
if (!competition || !teamView) { if (!competition || !teamView) {
return ( return (
<main className="mx-auto max-w-5xl px-4 py-20 text-center"> <TeamProgressProblemState
<h1 className="text-lg font-bold">팀 진행 정보를 볼 수 없습니다</h1> content={getTeamProgressErrorContent([])}
<p className="mt-2 text-sm text-base-content/45"> isRetrying={isRefetching}
이 내전에 참여한 계정으로 로그인했는지 확인해주세요. matchId={id}
</p> onRetry={retryBoth}
<Link to={`/match/${id}`} className="btn btn-primary btn-sm mt-5"> />
내전 상세로 );
</Link> }
</main>
if (!revisionsMatch) {
return (
<TeamProgressProblemState
content={{
kind: "unknown",
title: isRefetching
? "최신 경기 정보를 맞추는 중입니다"
: "경기 정보의 revision이 일치하지 않습니다",
description: isRefetching
? "Competition과 팀 정보를 함께 다시 불러오고 있습니다."
: "일관된 경기 정보를 표시할 수 없어 두 응답을 다시 확인해야 합니다.",
}}
isRetrying={isRefetching}
matchId={id}
onRetry={retryBoth}
/>
); );
} }
@@ -208,6 +279,59 @@ export default function MatchTeamProgressPage() {
); );
} }
function TeamProgressLoadingState() {
return (
<main
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
aria-busy="true"
aria-label="팀 진행 정보를 불러오는 중"
>
<div className="h-7 w-48 animate-pulse bg-base-200" />
<div className="h-32 animate-pulse bg-base-200/70" />
</main>
);
}
function TeamProgressProblemState({
content,
isRetrying,
matchId,
onRetry,
}: {
content: TeamProgressErrorContent;
isRetrying: boolean;
matchId: string | undefined;
onRetry: () => void;
}) {
return (
<main className="mx-auto max-w-5xl px-4 py-20 sm:px-6">
<section
role="alert"
aria-busy={isRetrying}
className="border border-base-content/10 bg-base-100 px-5 py-8 text-center"
>
<h1 className="text-lg font-bold">{content.title}</h1>
<p className="mt-2 text-sm text-base-content/45">
{content.description}
</p>
<div className="mt-5 flex flex-wrap justify-center gap-2">
<button
type="button"
className="btn btn-primary btn-sm"
disabled={isRetrying}
onClick={onRetry}
>
{isRetrying ? "다시 불러오는 중..." : "다시 시도"}
</button>
<Link to={`/match/${matchId}`} className="btn btn-ghost btn-sm">
내전 상세로
</Link>
</div>
</section>
</main>
);
}
function EmptyState({ message }: { message: string }) { function EmptyState({ message }: { message: string }) {
return ( return (
<p <p
+20 -12
View File
@@ -1,5 +1,10 @@
import { useMemo, useState } from 'react'; import { useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query'; import { useQueryClient } from '@tanstack/react-query';
import type {
MatchDetailResponse,
MatchGameMode,
MatchScheduleItemView,
} from '@lolympus/contracts';
import { Link, useParams } from 'react-router'; import { Link, useParams } from 'react-router';
import { import {
useCreateMatch, useCreateMatch,
@@ -8,12 +13,7 @@ import {
useMe, useMe,
useUpdateMatch, useUpdateMatch,
} from '../../api/hooks'; } from '../../api/hooks';
import type { import type { MatchMutationRequest } from '../../api/types';
ApiMatch,
ApiMatchScheduleItem,
MatchGameMode,
MatchMutationRequest,
} from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config'; import { DEFAULT_COMMUNITY_ID } from '../../config';
const DEFAULT_FORM: MatchMutationRequest = { const DEFAULT_FORM: MatchMutationRequest = {
@@ -92,7 +92,7 @@ function parseLines(value: string) {
.filter(Boolean); .filter(Boolean);
} }
function parseSchedule(value: string): ApiMatchScheduleItem[] { function parseSchedule(value: string): MatchScheduleItemView[] {
return parseLines(value).map((line) => { return parseLines(value).map((line) => {
const [time, ...labelParts] = line.split('|').map((part) => part.trim()); const [time, ...labelParts] = line.split('|').map((part) => part.trim());
return { return {
@@ -102,11 +102,11 @@ function parseSchedule(value: string): ApiMatchScheduleItem[] {
}); });
} }
function scheduleToText(schedule: ApiMatchScheduleItem[] = []) { function scheduleToText(schedule: MatchScheduleItemView[] = []) {
return schedule.map((item) => `${item.time}|${item.label}`).join('\n'); return schedule.map((item) => `${item.time}|${item.label}`).join('\n');
} }
function makeForm(match?: ApiMatch): MatchMutationRequest & { function makeForm(match?: MatchDetailResponse): MatchMutationRequest & {
prizesText: string; prizesText: string;
noticesText: string; noticesText: string;
scheduleText: string; scheduleText: string;
@@ -149,7 +149,7 @@ export default function MatchAdminPage() {
const createMutation = useCreateMatch(communityId); const createMutation = useCreateMatch(communityId);
const updateMutation = useUpdateMatch(communityId); const updateMutation = useUpdateMatch(communityId);
const deleteMutation = useDeleteMatch(communityId); const deleteMutation = useDeleteMatch(communityId);
const [editing, setEditing] = useState<ApiMatch | null>(null); const [editing, setEditing] = useState<MatchDetailResponse | null>(null);
const [showForm, setShowForm] = useState(false); const [showForm, setShowForm] = useState(false);
const [form, setForm] = useState(makeForm()); const [form, setForm] = useState(makeForm());
const [message, setMessage] = useState<string | null>(null); const [message, setMessage] = useState<string | null>(null);
@@ -181,7 +181,7 @@ export default function MatchAdminPage() {
setMessage(null); setMessage(null);
} }
function openEdit(match: ApiMatch) { function openEdit(match: MatchDetailResponse) {
setEditing(match); setEditing(match);
setForm(makeForm(match)); setForm(makeForm(match));
setShowForm(true); setShowForm(true);
@@ -550,7 +550,15 @@ export default function MatchAdminPage() {
<button <button
type="button" type="button"
className="text-xs px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10" className="text-xs px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
disabled={deleteMutation.isPending} disabled={
deleteMutation.isPending ||
match.status !== 'recruiting'
}
title={
match.status === 'recruiting'
? '내전 삭제'
: '팀 구성이 확정된 내전 기록은 삭제할 수 없습니다.'
}
onClick={() => { onClick={() => {
if (!window.confirm('이 내전을 삭제할까요?')) return; if (!window.confirm('이 내전을 삭제할까요?')) return;
deleteMutation.mutate(match._id, { deleteMutation.mutate(match._id, {
@@ -0,0 +1,94 @@
interface RevisionedSnapshot {
revision: number;
}
export type TeamProgressErrorContent = {
kind:
| "unauthorized"
| "forbidden"
| "not-found"
| "not-ready"
| "server"
| "network"
| "unknown";
title: string;
description: string;
};
export function isConsistentTeamProgressSnapshot(
competition: RevisionedSnapshot | null | undefined,
teamView: RevisionedSnapshot | null | undefined,
): boolean {
return Boolean(
competition &&
teamView &&
competition.revision === teamView.revision,
);
}
export function getTeamProgressErrorContent(
errors: readonly unknown[],
): TeamProgressErrorContent {
const statuses = errors.flatMap((error) => {
if (typeof error !== "object" || error === null || !("status" in error)) {
return [];
}
return typeof error.status === "number" ? [error.status] : [];
});
if (statuses.includes(401)) {
return {
kind: "unauthorized",
title: "로그인이 필요합니다",
description: "팀 진행 정보를 보려면 로그인한 뒤 다시 시도해 주세요.",
};
}
if (statuses.includes(403)) {
return {
kind: "forbidden",
title: "팀 진행 정보를 볼 권한이 없습니다",
description:
"이 내전에 참여한 팀원 계정으로 로그인했는지 확인해 주세요.",
};
}
if (statuses.includes(404)) {
return {
kind: "not-found",
title: "팀 진행 정보를 찾을 수 없습니다",
description: "내전이 삭제되었거나 Competition이 아직 준비되지 않았습니다.",
};
}
if (statuses.includes(409)) {
return {
kind: "not-ready",
title: "Competition이 아직 준비되지 않았습니다",
description: "팀 구성이 완료된 뒤 다시 시도해 주세요.",
};
}
if (statuses.some((status) => status >= 500 && status <= 599)) {
return {
kind: "server",
title: "서버에서 팀 진행 정보를 불러오지 못했습니다",
description: "잠시 후 다시 시도해 주세요.",
};
}
if (errors.some(isNetworkError)) {
return {
kind: "network",
title: "네트워크에 연결할 수 없습니다",
description: "인터넷 연결을 확인한 뒤 다시 시도해 주세요.",
};
}
return {
kind: "unknown",
title: "팀 진행 정보를 불러오지 못했습니다",
description: "일시적인 오류일 수 있습니다. 다시 시도해 주세요.",
};
}
function isNetworkError(error: unknown): boolean {
return (
error instanceof TypeError ||
(error instanceof Error && error.name === "TypeError")
);
}
+108
View File
@@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
executeAuthScopedQuery,
resolveAuthQueryScope,
} from "../src/api/auth-query-scope.ts";
test("waits for MSAL before an anonymous optional-auth query starts", () => {
const scope = resolveAuthQueryScope({
authUserId: null,
accountKey: null,
msalConfigured: true,
msalReady: false,
});
assert.equal(scope.ready, false);
assert.deepEqual(scope.cacheKey, [null, null]);
});
test("allows an anonymous query once MSAL initialization finishes", () => {
const scope = resolveAuthQueryScope({
authUserId: null,
accountKey: null,
msalConfigured: true,
msalReady: true,
});
assert.equal(scope.ready, true);
});
test("allows dev auth during MSAL startup and scopes its cache by user", () => {
const first = resolveAuthQueryScope({
authUserId: "dev-user-1",
accountKey: null,
msalConfigured: true,
msalReady: false,
});
const second = resolveAuthQueryScope({
authUserId: "dev-user-2",
accountKey: null,
msalConfigured: true,
msalReady: false,
});
assert.equal(first.ready, true);
assert.notDeepEqual(first.cacheKey, second.cacheKey);
});
test("separates optional-auth query caches by MSAL account", () => {
const first = resolveAuthQueryScope({
authUserId: null,
accountKey: "account-1",
msalConfigured: true,
msalReady: true,
});
const second = resolveAuthQueryScope({
authUserId: null,
accountKey: "account-2",
msalConfigured: true,
msalReady: true,
});
assert.notDeepEqual(first.cacheKey, second.cacheKey);
});
test("keeps the existing dev or anonymous request path when no account exists", async () => {
let tokenAcquisitions = 0;
const result = await executeAuthScopedQuery({
accountKey: null,
acquireAccessToken: () => {
tokenAcquisitions += 1;
return Promise.resolve("unused-token");
},
request: (authorizationHeader) =>
Promise.resolve(authorizationHeader ?? "dev-or-anonymous"),
});
assert.equal(result, "dev-or-anonymous");
assert.equal(tokenAcquisitions, 0);
});
test("does not run an anonymous request when account token acquisition fails", async () => {
let requests = 0;
await assert.rejects(
executeAuthScopedQuery({
accountKey: "account-1",
acquireAccessToken: () => Promise.reject(new Error("token failed")),
request: () => {
requests += 1;
return Promise.resolve("must-not-run");
},
}),
/token failed/,
);
assert.equal(requests, 0);
});
test("sends an explicit bearer token for an authenticated account", async () => {
const authorizationHeader = await executeAuthScopedQuery({
accountKey: "account-1",
acquireAccessToken: () => Promise.resolve("access-token"),
request: (header) => Promise.resolve(header),
});
assert.equal(authorizationHeader, "Bearer access-token");
});
@@ -0,0 +1,57 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
getTeamProgressErrorContent,
isConsistentTeamProgressSnapshot,
} from "../src/pages/match-team-progress-state.ts";
test("only accepts Competition and team snapshots with the same revision", () => {
assert.equal(
isConsistentTeamProgressSnapshot({ revision: 7 }, { revision: 7 }),
true,
);
assert.equal(
isConsistentTeamProgressSnapshot({ revision: 7 }, { revision: 8 }),
false,
);
assert.equal(isConsistentTeamProgressSnapshot(undefined, { revision: 7 }), false);
});
test("describes a 401 response as an authentication error", () => {
assert.equal(
getTeamProgressErrorContent([{ status: 401 }]).kind,
"unauthorized",
);
});
test("describes a 403 response as a team access error", () => {
assert.equal(
getTeamProgressErrorContent([{ status: 403 }]).kind,
"forbidden",
);
});
test("describes a 404 response as missing Competition data", () => {
assert.equal(getTeamProgressErrorContent([{ status: 404 }]).kind, "not-found");
});
test("describes a 5xx response as a server error", () => {
assert.equal(getTeamProgressErrorContent([{ status: 503 }]).kind, "server");
});
test("describes a failed fetch as a network error", () => {
assert.equal(
getTeamProgressErrorContent([new TypeError("Failed to fetch")]).kind,
"network",
);
});
test("prioritizes authentication and authorization errors from either query", () => {
assert.equal(
getTeamProgressErrorContent([
new TypeError("Failed to fetch"),
{ status: 403 },
]).kind,
"forbidden",
);
});
+55 -3
View File
@@ -44,7 +44,7 @@ causing team 3 to advance despite team 8 winning two games.
## Commands ## Commands
- API unit/integration tests: `pnpm --filter api test` - API unit/integration tests: `pnpm --filter api test`
- Focused API test: `pnpm --filter api test -- --runInBand <test-path>` - Focused API test: `pnpm --filter api exec jest --runInBand <test-path>`
- API build: `pnpm --filter api build` - API build: `pnpm --filter api build`
- Web build/typecheck: `pnpm --filter web build` - Web build/typecheck: `pnpm --filter web build`
- Migration dry-run: `pnpm --filter api competition:migrate -- --dry-run` - Migration dry-run: `pnpm --filter api competition:migrate -- --dry-run`
@@ -80,6 +80,22 @@ and scheduling metadata. It receives a unique optional `competitionId`.
Exactly one Competition may reference a Match. Exactly one Competition may reference a Match.
Competition creation is an explicit side effect of the finalized team-building
workflow. Read endpoints never create state. If a finalized Match is observed before
its Competition has been linked, the API reports that initialization is still in
progress instead of attempting a lazy bootstrap.
After `competitionId` is linked, the Match cannot return to recruiting, change its
game count, reset or undo its auction, or be hard-deleted through ordinary Match
operations. Corrections happen through Competition facts and reversals; replacing the
event requires a new Match. The legacy-import bulk-delete operation is the one
explicit destructive exception and removes the whole aggregate and its dependent
read models transactionally.
Joining a Match is an authenticated self-service action. The normal participant
endpoint always derives the participant from the authenticated user; only the
administrator endpoint may add another community member.
### Identifiers ### Identifiers
- `CompetitionId`, `TeamId`, `SeriesId`, `GameSlotId`, `GameId`, and `FactId` are - `CompetitionId`, `TeamId`, `SeriesId`, `GameSlotId`, `GameId`, and `FactId` are
@@ -188,6 +204,13 @@ history. Active code and active GameSlot assignments are uniquely indexed.
Accepting a code-backed Riot game atomically commits the accepted fact, assignment Accepting a code-backed Riot game atomically commits the accepted fact, assignment
use, code consumption, Competition revision/projection, and outbox events. use, code consumption, Competition revision/projection, and outbox events.
Reversal releases only codes that are in a releasable terminal state and removes all
obsolete Match code bindings in the same transaction. Public/team reads validate the
active assignment, code state, and Match binding instead of returning stale codes.
Expired reserved codes also terminate their active assignment and Match binding
atomically so the slot can be provisioned again without an administrative replacement
endpoint.
## Command Semantics ## Command Semantics
All Competition mutations require an idempotency key and expected revision. All Competition mutations require an idempotency key and expected revision.
@@ -202,6 +225,11 @@ Within a MongoDB transaction, the shared command runner:
6. inserts outbox records; 6. inserts outbox records;
7. commits atomically. 7. commits atomically.
Transient transaction/write-conflict failures use a bounded retry. Idempotency is
rechecked on every attempt, so a concurrent successful command is replayed rather
than duplicated. Outbox delivery uses bounded attempts and moves permanently failing
events to an explicit `dead-letter` state for operator recovery.
External Riot fetches occur before the transaction. A stale revision returns HTTP 412, External Riot fetches occur before the transaction. A stale revision returns HTTP 412,
a valid-state conflict returns 409, and invalid input returns 422. a valid-state conflict returns 409, and invalid input returns 422.
@@ -214,6 +242,9 @@ individual reversal facts joined by one causation ID.
- Public Match and Competition responses are explicit DTOs, never spread Mongoose - Public Match and Competition responses are explicit DTOs, never spread Mongoose
documents. documents.
- The shared Match contract is the single wire definition used by API presenters and
web consumers. Authentication is optional on public Match reads solely to compute
the required `joined` flag; anonymous reads receive `joined: false`.
- Public responses exclude tournament codes, audit actors, and internal fact payloads. - Public responses exclude tournament codes, audit actors, and internal fact payloads.
- Team view exposes only the authenticated user's team slots and code assignments. - Team view exposes only the authenticated user's team slots and code assignments.
- Administrator fact view exposes the audit ledger. - Administrator fact view exposes the audit ledger.
@@ -241,6 +272,19 @@ Migration builds new collections without dual canonical writes.
- Dry-run is the default and emits machine-readable and human-readable reports. - Dry-run is the default and emits machine-readable and human-readable reports.
- Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact - Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact
replay equality after every write. replay equality after every write.
- Apply explicitly creates or verifies every Competition unique/partial index before
migrating a Match. Existing target-data/index-definition conflicts block apply with
a machine-readable preflight report; source Matches that collide with an already
accepted global identity are quarantined rather than guessed or partially written.
- Limited apply runs persist the last terminal Match `_id` in a migration checkpoint.
The next run resumes strictly after that cursor; a failed Match does not advance the
cursor, and an explicit `--after` cursor may override the checkpoint for recovery.
- An explicit limited-apply `--after` cursor durably replaces an older checkpoint
before scanning, so a failure on the first overridden Match is retried by the next
ordinary limited apply.
- Dry-run never creates indexes, uses a persisted resume checkpoint, or updates
checkpoints; it always audits the requested source range from the beginning unless
an explicit `--after` cursor is supplied.
Legacy Match fields remain untouched for rollback until the new runtime is verified, Legacy Match fields remain untouched for rollback until the new runtime is verified,
then a separate cleanup migration removes them. then a separate cleanup migration removes them.
@@ -263,9 +307,9 @@ Prefer explicit discriminated unions and pure functions:
```ts ```ts
switch (series.rule.type) { switch (series.rule.type) {
case 'first-to': case "first-to":
return projectFirstToSeries(series, facts); return projectFirstToSeries(series, facts);
case 'fixed-games': case "fixed-games":
return projectFixedGamesSeries(series, facts); return projectFixedGamesSeries(series, facts);
} }
``` ```
@@ -298,6 +342,8 @@ its `teamId` in the same object.
- Delete facts to implement correction. - Delete facts to implement correction.
- Fabricate Riot evidence for legacy results. - Fabricate Riot evidence for legacy results.
- Expose tournament codes on a public endpoint. - Expose tournament codes on a public endpoint.
- Reintroduce legacy seed reshuffling, positional bracket mutation, or unauthenticated
tournament-code replacement endpoints.
## Success Criteria ## Success Criteria
@@ -310,7 +356,13 @@ its `teamId` in the same object.
- Pair, round-robin, and double-elimination flows complete end to end. - Pair, round-robin, and double-elimination flows complete end to end.
- Reversal preview/cascade is revision- and hash-protected. - Reversal preview/cascade is revision- and hash-protected.
- Statistics cannot regress to an older source revision. - Statistics cannot regress to an older source revision.
- A legacy stats builder cannot overwrite a Competition-backed fragment, and a late
builder cannot resurrect stats after its Match/Competition has been deleted.
- Double-elimination seeds are persisted before the finalized team-build timestamp is
exposed, and an expired reserved code can be provisioned again automatically.
- Migration dry-run reports zero unclassified documents before apply. - Migration dry-run reports zero unclassified documents before apply.
- Competition unique/partial indexes are verified before the first apply write, and
repeated limited apply runs advance without rescanning the first page.
- API tests and API/web production builds pass. - API tests and API/web production builds pass.
- Legacy result writers, serializers, and frontend code are removed after cutover. - Legacy result writers, serializers, and frontend code are removed after cutover.
+63 -28
View File
@@ -1,4 +1,4 @@
import type { CompetitionDetailResponse, CompetitionPhase } from "./competition.js"; import type { CompetitionPhase } from "./competition.js";
import type { CompetitionFormatType } from "./format.js"; import type { CompetitionFormatType } from "./format.js";
import type { import type {
CommunityId, CommunityId,
@@ -13,11 +13,16 @@ import type { IsoDateTime, SeriesProjection } from "./series.js";
export type MatchLifecycleStatus = export type MatchLifecycleStatus =
| "recruiting" | "recruiting"
| "team-building" | "team-built"
| "ready" | "in-progress"
| "running" | "finished";
| "completed"
| "cancelled"; export type MatchGameMode =
| "pair"
| "round-robin"
| "double-elimination";
export type MatchPosition = "TOP" | "JGL" | "MID" | "ADC" | "SUP";
export interface MatchCompetitionSummaryView { export interface MatchCompetitionSummaryView {
id: CompetitionId; id: CompetitionId;
@@ -25,48 +30,79 @@ export interface MatchCompetitionSummaryView {
formatType: CompetitionFormatType; formatType: CompetitionFormatType;
} }
export interface MatchSummaryResponse { export interface MatchPositionPreferenceView {
id: MatchId; position: MatchPosition;
communityId: CommunityId; priority: number;
shortCode?: string; }
title: string;
description: string; export interface MatchTierView {
scheduledAt: IsoDateTime; queueType: string;
status: MatchLifecycleStatus; tier: string;
maxParticipants: number; rank: string;
participantCount: number; leaguePoints: number;
joined: boolean; wins: number;
competition?: MatchCompetitionSummaryView; losses: number;
createdAt: IsoDateTime; fetchedAt: IsoDateTime;
updatedAt: IsoDateTime;
} }
export interface MatchParticipantView { export interface MatchParticipantView {
userId: UserId; userId: UserId;
displayName: string;
gameName?: string; gameName?: string;
tagLine?: string; tagLine?: string;
profileIconId?: number; profileIconId?: number;
tier?: MatchTierView;
preferredPositions: MatchPositionPreferenceView[];
joinedAt: IsoDateTime; joinedAt: IsoDateTime;
excluded: boolean; excluded: boolean;
} }
export interface MatchTeamMemberView {
userId: UserId;
assignedPosition: MatchPosition;
cost?: number;
}
export interface MatchTeamView {
teamIndex: number;
name: string;
captainUserId?: UserId;
members: MatchTeamMemberView[];
}
export interface MatchScheduleItemView { export interface MatchScheduleItemView {
time: string; time: string;
label: string; label: string;
} }
export interface MatchDetailResponse /** Canonical wire DTO returned by both Match list and detail endpoints. */
extends Omit<MatchSummaryResponse, "competition"> { export interface MatchDetailResponse {
_id: MatchId;
communityId: CommunityId;
competitionId?: CompetitionId;
shortCode?: string;
title: string;
description: string;
mapId: number; mapId: number;
status: MatchLifecycleStatus;
scheduledAt: IsoDateTime;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
roundRobinMaxRounds?: number;
doubleEliminationResetFinalEnabled?: boolean;
hostUserId?: UserId; hostUserId?: UserId;
participants: MatchParticipantView[]; participants: MatchParticipantView[];
teams: MatchTeamView[];
prizes: string[]; prizes: string[];
notices: string[]; notices: string[];
schedule: MatchScheduleItemView[]; schedule: MatchScheduleItemView[];
competition?: CompetitionDetailResponse; joined: boolean;
createdAt: IsoDateTime;
updatedAt: IsoDateTime;
} }
export type MatchSummaryResponse = MatchDetailResponse;
export interface TeamTournamentCodeView { export interface TeamTournamentCodeView {
gameSlotId: GameSlotId; gameSlotId: GameSlotId;
seriesId: SeriesId; seriesId: SeriesId;
@@ -87,9 +123,8 @@ export interface TeamCompetitionViewResponse {
} }
export interface MatchListResponse { export interface MatchListResponse {
matches: MatchSummaryResponse[]; matches: MatchDetailResponse[];
total: number;
page: number; page: number;
pageSize: number; limit: number;
totalItems: number;
totalPages: number;
} }