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

@@ -3,6 +3,7 @@ import {
ConflictException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
@@ -43,8 +44,16 @@ const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL';
const TOURNAMENT_CODE_MATCH_LOCK_TTL_MS = 30_000;
const TOURNAMENT_CODE_TRANSACTION_ATTEMPTS = 3;
export interface TournamentCodeExpirationResult {
expiredCount: number;
failedCount: number;
affectedMatchIds: mongoose.Types.ObjectId[];
}
@Injectable()
export class TournamentCodeService {
private readonly logger = new Logger(TournamentCodeService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly auctionRedisService: AuctionRedisService,
@@ -216,9 +225,9 @@ export class TournamentCodeService {
const MatchModel = await this.connectionService.getModel('match');
const code = await TournamentCodeModel.findById(id);
if (!code) throw new NotFoundException('Tournament code not found.');
if (code.state !== 'released' && code.state !== 'reserved') {
if (code.state !== 'released') {
throw new BadRequestException(
'Only released or reserved tournament codes can be restored.',
'Only released tournament codes can be restored. Active Competition assignments must be reversed through Competition commands.',
);
}
const previousMatchId = code.matchId;
@@ -318,174 +327,6 @@ export class TournamentCodeService {
return match;
}
public async replaceForMatchGame(params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
}): Promise<TournamentCodeSlotView> {
return this.withLockedMatchTransaction(params.matchId, (session) =>
this.replaceForMatchGameInTransaction(params, session),
);
}
private async replaceForMatchGameInTransaction(
params: {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
gameNumber: number;
},
session: mongoose.ClientSession,
): Promise<TournamentCodeSlotView> {
const MatchModel = await this.connectionService.getModel('match');
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const match = await this.execQuery<MatchDocument | null>(
this.withQuerySession(
MatchModel.findOne({
_id: params.matchId,
communityId: params.communityId,
}),
session,
),
);
if (!match) throw new NotFoundException('Match not found.');
if (match.status !== 'team-built' && match.status !== 'in-progress') {
throw new BadRequestException(
'Tournament codes can only be replaced while the match is ready or in progress.',
);
}
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
this.ensureGameSchedule(match);
const doubleEliminationSlot =
(match.gameMode ?? 'pair') === 'double-elimination'
? this.resolveDoubleEliminationGameSlotByGameNumber(
match,
params.gameNumber,
)
: undefined;
const requiredSlots = this.resolveRequiredSlots(match);
if (
!Number.isInteger(params.gameNumber) ||
params.gameNumber < 1 ||
params.gameNumber > requiredSlots
) {
throw new BadRequestException('Invalid tournament code game number.');
}
if (
(match.result?.games ?? []).some(
(game) => game.gameNumber === params.gameNumber,
)
) {
throw new BadRequestException(
'This game already has a collected result and cannot be replaced.',
);
}
const currentCode = await this.execQuery<TournamentCodeDocument | null>(
this.withQuerySession(
TournamentCodeModel.findOne({
_id: { $in: match.tournamentCodeIds },
matchId: match._id,
...(doubleEliminationSlot
? {
gameNumber: params.gameNumber,
bracketMatchId:
doubleEliminationSlot.bracketMatch.bracketMatchId,
}
: { gameNumber: params.gameNumber }),
}),
session,
),
);
if (!currentCode) {
throw new NotFoundException('Assigned tournament code not found.');
}
if (currentCode.state === 'used' || currentCode.riotMatchId) {
throw new BadRequestException(
'Used tournament codes cannot be replaced.',
);
}
const expiresAfter = new Date(
Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS,
);
await this.execQuery(
this.withQuerySession(
TournamentCodeModel.updateOne(
{ _id: currentCode._id },
{
$set: { state: 'released', releasedAt: new Date() },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
riotMatchId: 1,
},
},
),
session,
),
);
const replacement = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: DEFAULT_REGION,
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: params.gameNumber,
...(doubleEliminationSlot
? {
bracketMatchId:
doubleEliminationSlot.bracketMatch.bracketMatchId,
}
: {}),
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!replacement) {
throw new BadRequestException(
'No available tournament code to replace with.',
);
}
match.tournamentCodeIds = this.replaceTournamentCodeId(
match.tournamentCodeIds,
currentCode._id,
replacement._id,
);
await match.save({ session });
return {
gameNumber: params.gameNumber,
...(doubleEliminationSlot
? this.toDoubleEliminationSlotBase(doubleEliminationSlot)
: {}),
roundNumber: this.resolveRoundNumberForGameNumber(
match,
params.gameNumber,
),
...this.resolveSeriesRefForGameNumber(match, params.gameNumber),
code: replacement.code,
expiresAt: replacement.expiresAt.toISOString(),
state: replacement.state,
riotMatchId: replacement.riotMatchId ?? null,
};
}
public async releaseFromMatch(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): Promise<void> {
@@ -530,17 +371,153 @@ export class TournamentCodeService {
await match.save({ session });
}
public async markExpired(): Promise<number> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const result = await TournamentCodeModel.updateMany(
{
state: { $in: ['available', 'reserved', 'released'] },
expiresAt: { $lte: new Date() },
},
{ $set: { state: 'expired' } },
).exec();
return result.modifiedCount;
public async markExpired(): Promise<TournamentCodeExpirationResult> {
const [TournamentCodeModel, AssignmentModel, CompetitionModel, MatchModel] =
await Promise.all([
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('competition'),
this.connectionService.getModel('match'),
]);
const expiredAt = new Date();
const candidates = await TournamentCodeModel.find({
state: { $in: ['available', 'reserved', 'released'] },
expiresAt: { $lte: expiredAt },
})
.select({ _id: 1 })
.lean()
.exec();
const affectedMatchIds = new Map<string, mongoose.Types.ObjectId>();
let expiredCount = 0;
let failedCount = 0;
for (const candidate of candidates) {
try {
const expired = await this.runTransactionWithRetry(async (session) => {
const code = await TournamentCodeModel.findOne(
{
_id: candidate._id,
expiresAt: { $lte: expiredAt },
state: { $in: ['available', 'reserved', 'released'] },
},
null,
{ session },
)
.lean()
.exec();
if (!code) return null;
const activeAssignments = await AssignmentModel.find({
tournamentCodeId: code._id,
state: { $in: ['reserved', 'used'] },
})
.session(session)
.limit(2)
.lean()
.exec();
if (activeAssignments.length > 1) {
throw new Error(
`Tournament Code ${code._id.toString()} has multiple active Competition assignments.`,
);
}
const assignment = activeAssignments[0];
if (assignment?.state === 'used') {
throw new Error(
`Tournament Code ${code._id.toString()} has a used Competition assignment and cannot expire as reserved.`,
);
}
if (assignment) {
if (!code.matchId) {
throw new Error(
`Tournament Code ${code._id.toString()} has an active Competition assignment without a Match binding.`,
);
}
const competition = await CompetitionModel.findById(
assignment.competitionId,
)
.session(session)
.select({ matchId: 1 })
.lean()
.exec();
if (
!competition ||
competition.matchId.toString() !== code.matchId.toString()
) {
throw new Error(
`Tournament Code ${code._id.toString()} Competition ownership does not match its Match binding.`,
);
}
}
const expiredCode = await TournamentCodeModel.findOneAndUpdate(
{
_id: code._id,
expiresAt: { $lte: expiredAt },
state: code.state,
},
{
$set: { state: 'expired' },
$unset: {
bracketMatchId: 1,
gameNumber: 1,
matchId: 1,
reservedAt: 1,
},
},
{ returnDocument: 'before', session },
).exec();
if (!expiredCode) return null;
if (assignment) {
const assignmentResult = await AssignmentModel.updateOne(
{ _id: assignment._id, state: 'reserved' },
{ $set: { releasedAt: expiredAt, state: 'released' } },
{ session },
).exec();
if (assignmentResult.modifiedCount !== 1) {
throw new Error(
`Tournament Code ${code._id.toString()} assignment did not transition to released.`,
);
}
}
if (code.matchId) {
const matchResult = await MatchModel.updateOne(
{ _id: code.matchId },
{ $pull: { tournamentCodeIds: code._id } },
{ session },
).exec();
if (
assignment &&
(matchResult.matchedCount !== 1 ||
matchResult.modifiedCount !== 1)
) {
throw new Error(
`Tournament Code ${code._id.toString()} Match binding did not transition atomically.`,
);
}
}
return code;
});
if (!expired) continue;
expiredCount += 1;
if (expired.matchId) {
affectedMatchIds.set(expired.matchId.toString(), expired.matchId);
}
} catch (error) {
failedCount += 1;
this.logger.error(
`Failed to expire Tournament Code ${candidate._id.toString()}; candidate was left unchanged: ${
error instanceof Error ? error.message : String(error)
}`,
);
}
}
return {
expiredCount,
failedCount,
affectedMatchIds: [...affectedMatchIds.values()],
};
}
public async attachPendingMatches(
@@ -610,7 +587,11 @@ export class TournamentCodeService {
: [];
const byGameNumber = new Map(
codes
.filter((code) => typeof code.gameNumber === 'number')
.filter(
(code) =>
typeof code.gameNumber === 'number' &&
(code.state === 'reserved' || code.state === 'used'),
)
.map((code) => [code.gameNumber as number, code]),
);
@@ -645,21 +626,6 @@ export class TournamentCodeService {
return (code ?? '').trim();
}
private replaceTournamentCodeId(
currentIds: mongoose.Types.ObjectId[],
oldId: mongoose.Types.ObjectId,
newId: mongoose.Types.ObjectId,
): mongoose.Types.ObjectId[] {
let replaced = false;
const next = currentIds.map((id) => {
if (id.toString() !== oldId.toString()) return id;
replaced = true;
return newId;
});
if (!replaced) next.push(newId);
return next;
}
private resolveMatchId(
matchOrId: MatchDocument | mongoose.Types.ObjectId,
): mongoose.Types.ObjectId {
@@ -991,7 +957,12 @@ export class TournamentCodeService {
.map((team) => team.teamIndex)
.sort((left, right) => left - right);
if (teamIndexes.length !== 4 && teamIndexes.length !== 8) return;
const shuffledTeamIndexes = this.shuffleTeamIndexes(teamIndexes);
const seededTeamIndexes = this.configuredDoubleEliminationSeedOrder(
match,
teamIndexes,
);
const shuffledTeamIndexes =
seededTeamIndexes ?? this.shuffleTeamIndexes(teamIndexes);
match.doubleElimination = buildDoubleEliminationBracket(
shuffledTeamIndexes,
{
@@ -1003,6 +974,34 @@ export class TournamentCodeService {
match.markModified?.('doubleElimination');
}
private configuredDoubleEliminationSeedOrder(
match: MatchDocument,
teamIndexes: number[],
): number[] | undefined {
const seeds = match.doubleElimination?.seeds ?? [];
if (seeds.length !== teamIndexes.length) return undefined;
const validTeamIndexes = new Set(teamIndexes);
const seedNumbers = new Set<number>();
const seededTeamIndexes = new Set<number>();
for (const seed of seeds) {
if (
!Number.isInteger(seed.seedNumber) ||
seed.seedNumber < 1 ||
seed.seedNumber > teamIndexes.length ||
seedNumbers.has(seed.seedNumber) ||
!validTeamIndexes.has(seed.teamIndex) ||
seededTeamIndexes.has(seed.teamIndex)
) {
return undefined;
}
seedNumbers.add(seed.seedNumber);
seededTeamIndexes.add(seed.teamIndex);
}
return [...seeds]
.sort((left, right) => left.seedNumber - right.seedNumber)
.map(({ teamIndex }) => teamIndex);
}
private resolveDoubleEliminationGameSlotByGameNumber(
match: MatchDocument,
gameNumber: number,