fix: repair double-elimination tournament codes

This commit is contained in:
dahyeon committed 2026-07-10 08:44:42 -07:00
1 parent 2d1c33f1e9
commit 3357d4c9c8
2 files changed
+243 -14

No files matched your search

@@ -0,0 +1,94 @@
import mongoose from 'mongoose';
import { buildRepairPlan } from './repair-double-elimination-series-rules';
import type { MatchDocument, TournamentCodeDocument } from '../schema';
function createMatch(overrides: Partial<MatchDocument>): MatchDocument {
return {
_id: new mongoose.Types.ObjectId(),
gameCount: 3,
tournamentCodeIds: [],
doubleElimination: {
teamCount: 8,
resetFinalEnabled: false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [],
placements: {},
events: [],
},
...overrides,
} as unknown as MatchDocument;
}
function createCode(
overrides: Partial<TournamentCodeDocument>,
): TournamentCodeDocument {
return {
_id: new mongoose.Types.ObjectId(),
code: 'CODE',
state: 'reserved',
...overrides,
} as unknown as TournamentCodeDocument;
}
describe('repair-double-elimination-series-rules buildRepairPlan', () => {
it('plans missing ready series slots even when result games already exist', () => {
const match = createMatch({
result: {
riotMatchIds: ['KR_1'],
games: [
{
gameNumber: 1,
bracketMatchId: 'WB_R2_M1',
},
],
seriesResults: [],
},
doubleElimination: {
teamCount: 8,
resetFinalEnabled: false,
resetFinalCreated: false,
seeds: [],
bracketMatches: [
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 1,
gameCount: 3,
requiredWins: 2,
bracketSide: 'winner',
roundNumber: 2,
matchNumber: 1,
state: 'ready',
teamAIndex: 4,
teamBIndex: 6,
},
],
placements: {},
events: [],
},
});
const existingFirstSetCode = createCode({
bracketMatchId: 'WB_R2_M1',
gameNumber: 1,
});
const plan = buildRepairPlan(match, [existingFirstSetCode], 3);
expect(plan.ruleRepairSkippedReason).toBe('result-games-exist');
expect(plan.codeUpdates).toEqual([]);
expect(plan.missingReadySlots).toEqual([
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 2,
seriesGameNumber: 2,
seriesGameCount: 3,
},
{
bracketMatchId: 'WB_R2_M1',
gameNumber: 3,
seriesGameNumber: 3,
seriesGameCount: 3,
},
]);
});
});
@@ -9,6 +9,7 @@ import {
buildDoubleEliminationGameSlots, buildDoubleEliminationGameSlots,
type DoubleEliminationBracketMatch, type DoubleEliminationBracketMatch,
} from '../../../double-elimination/double-elimination.util'; } from '../../../double-elimination/double-elimination.util';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants';
import { ConnectionService } from '../connection.service'; import { ConnectionService } from '../connection.service';
import type { MatchDocument, TournamentCodeDocument } from '../schema'; import type { MatchDocument, TournamentCodeDocument } from '../schema';
import { SecretModule } from '../../secret/secret.module'; import { SecretModule } from '../../secret/secret.module';
@@ -28,12 +29,21 @@ interface CodeUpdatePlan {
nextGameNumber: number; nextGameNumber: number;
} }
interface MissingReadySlotPlan {
bracketMatchId: string;
gameNumber: number;
seriesGameNumber: number;
seriesGameCount: number;
}
interface MatchRepairPlan { interface MatchRepairPlan {
codeUpdates: CodeUpdatePlan[]; codeUpdates: CodeUpdatePlan[];
currentGameCount: number; currentGameCount: number;
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
missingReadySlots: MissingReadySlotPlan[];
nextGameCount: number; nextGameCount: number;
nextBracketMatches: DoubleEliminationBracketMatch[]; nextBracketMatches: DoubleEliminationBracketMatch[];
ruleRepairSkippedReason?: string;
skippedReason?: string; skippedReason?: string;
} }
@@ -173,27 +183,82 @@ function requiredWinsFor(gameCount: number): number {
return Math.floor(gameCount / 2) + 1; return Math.floor(gameCount / 2) + 1;
} }
function buildRepairPlan( function codeSlotKey(
bracketMatchId: string | undefined,
gameNumber: number | undefined,
): string | undefined {
if (!bracketMatchId || typeof gameNumber !== 'number') return undefined;
return `${bracketMatchId}:${gameNumber}`;
}
function buildActiveCodeSlotKeys(
codes: TournamentCodeDocument[],
codeUpdates: CodeUpdatePlan[] = [],
): Set<string> {
const updateByCodeId = new Map(
codeUpdates.map((update) => [update.codeId.toString(), update]),
);
const activeSlotKeys = new Set<string>();
for (const code of codes) {
if (code.state !== 'reserved' && code.state !== 'used') continue;
const update = updateByCodeId.get(code._id.toString());
const key = codeSlotKey(
update?.bracketMatchId ?? code.bracketMatchId,
update?.nextGameNumber ?? code.gameNumber,
);
if (key) activeSlotKeys.add(key);
}
return activeSlotKeys;
}
function buildMissingReadySlots(
bracketMatches: DoubleEliminationBracketMatch[],
codes: TournamentCodeDocument[],
codeUpdates: CodeUpdatePlan[] = [],
): MissingReadySlotPlan[] {
const activeSlotKeys = buildActiveCodeSlotKeys(codes, codeUpdates);
return buildDoubleEliminationGameSlots(bracketMatches)
.filter((slot) => slot.bracketMatch.state === 'ready')
.filter(
(slot) =>
!activeSlotKeys.has(
`${slot.bracketMatch.bracketMatchId}:${slot.gameNumber}`,
),
)
.map((slot) => ({
bracketMatchId: slot.bracketMatch.bracketMatchId,
gameNumber: slot.gameNumber,
seriesGameNumber: slot.seriesGameNumber,
seriesGameCount: slot.seriesGameCount,
}));
}
export function buildRepairPlan(
match: MatchDocument, match: MatchDocument,
codes: TournamentCodeDocument[], codes: TournamentCodeDocument[],
winnerGameCount: number, winnerGameCount: number,
): MatchRepairPlan { ): MatchRepairPlan {
const currentGameCount = match.gameCount; const currentGameCount = match.gameCount;
const resultGames = match.result?.games ?? []; const resultGames = match.result?.games ?? [];
const currentBracketMatches = [
...(match.doubleElimination?.bracketMatches ?? []),
];
if (resultGames.length > 0) { if (resultGames.length > 0) {
return { return {
codeUpdates: [], codeUpdates: [],
currentGameCount, currentGameCount,
matchId: match._id, matchId: match._id,
nextBracketMatches: [...(match.doubleElimination?.bracketMatches ?? [])], missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes),
nextBracketMatches: currentBracketMatches,
nextGameCount: currentGameCount, nextGameCount: currentGameCount,
skippedReason: 'result-games-exist', ruleRepairSkippedReason: 'result-games-exist',
}; };
} }
const nextBracketMatches = ( const nextBracketMatches = currentBracketMatches.map((bracketMatch) => {
match.doubleElimination?.bracketMatches ?? []
).map((bracketMatch) => {
const gameCount = const gameCount =
bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1; bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1;
return { return {
@@ -222,11 +287,17 @@ function buildRepairPlan(
} satisfies CodeUpdatePlan; } satisfies CodeUpdatePlan;
}) })
.filter((entry): entry is CodeUpdatePlan => Boolean(entry)); .filter((entry): entry is CodeUpdatePlan => Boolean(entry));
const missingReadySlots = buildMissingReadySlots(
nextBracketMatches,
codes,
codeUpdates,
);
return { return {
codeUpdates, codeUpdates,
currentGameCount, currentGameCount,
matchId: match._id, matchId: match._id,
missingReadySlots,
nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount), nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount),
nextBracketMatches, nextBracketMatches,
}; };
@@ -238,15 +309,26 @@ function printPlan(plan: MatchRepairPlan) {
console.log(` skipped=${plan.skippedReason}`); console.log(` skipped=${plan.skippedReason}`);
return; return;
} }
console.log(` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`); if (plan.ruleRepairSkippedReason) {
console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`);
} else {
console.log(
` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`,
);
}
console.log( console.log(
` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length}`, ` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`,
); );
for (const update of plan.codeUpdates) { for (const update of plan.codeUpdates) {
console.log( console.log(
` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`, ` code ${update.code} ${update.bracketMatchId}: ${update.currentGameNumber ?? 'unset'} -> ${update.nextGameNumber}`,
); );
} }
for (const slot of plan.missingReadySlots) {
console.log(
` missing ${slot.bracketMatchId}: game ${slot.gameNumber} (${slot.seriesGameNumber}/${slot.seriesGameCount})`,
);
}
} }
async function applyPlan( async function applyPlan(
@@ -259,21 +341,74 @@ async function applyPlan(
for (const update of plan.codeUpdates) { for (const update of plan.codeUpdates) {
await TournamentCodeModel.updateOne( await TournamentCodeModel.updateOne(
{ _id: update.codeId }, { _id: update.codeId },
{ $set: { gameNumber: update.nextGameNumber } }, {
$set: {
gameNumber: update.nextGameNumber,
bracketMatchId: update.bracketMatchId,
},
},
{ session }, { session },
).exec(); ).exec();
} }
match.gameCount = plan.nextGameCount; const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS);
if (match.doubleElimination) { const reservedIds: mongoose.Types.ObjectId[] = [];
match.doubleElimination.bracketMatches = plan.nextBracketMatches; for (const slot of plan.missingReadySlots) {
match.markModified('doubleElimination'); const existingSlotCode = await TournamentCodeModel.exists({
matchId: match._id,
gameNumber: slot.gameNumber,
bracketMatchId: slot.bracketMatchId,
state: { $in: ['reserved', 'used'] },
})
.session(session)
.exec();
if (existingSlotCode) continue;
const code = await TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: { $gt: expiresAfter },
},
{
$set: {
state: 'reserved',
matchId: match._id,
gameNumber: slot.gameNumber,
bracketMatchId: slot.bracketMatchId,
reservedAt: new Date(),
},
$unset: { releasedAt: 1 },
},
{ sort: { expiresAt: 1 }, returnDocument: 'after', session },
).exec();
if (!code) break;
reservedIds.push(code._id);
}
if (reservedIds.length > 0) {
match.tournamentCodeIds = match.tournamentCodeIds ?? [];
match.tournamentCodeIds.push(...reservedIds);
}
if (!plan.ruleRepairSkippedReason) {
match.gameCount = plan.nextGameCount;
if (match.doubleElimination) {
match.doubleElimination.bracketMatches = plan.nextBracketMatches;
match.markModified('doubleElimination');
}
}
if (reservedIds.length > 0 || !plan.ruleRepairSkippedReason) {
await match.save({ session });
} }
await match.save({ session });
} }
async function main() { async function main() {
const options = parseArgs(process.argv.slice(2)); const options = parseArgs(process.argv.slice(2));
process.env.NODE_ENV = options.nodeEnv; process.env.NODE_ENV = options.nodeEnv;
process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical';
await loadMachineEnvFile(); await loadMachineEnvFile();
const app = await NestFactory.createApplicationContext(RepairModule, { const app = await NestFactory.createApplicationContext(RepairModule, {