import 'reflect-metadata'; import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { NestFactory } from '@nestjs/core'; import mongoose from 'mongoose'; import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import { buildDoubleEliminationGameSlots, type DoubleEliminationBracketMatch, } from '../../../double-elimination/double-elimination.util'; import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../../../tournament-code/tournament-code.constants'; import { ConnectionService } from '../connection.service'; import type { MatchDocument, TournamentCodeDocument } from '../schema'; import { SecretModule } from '../../secret/secret.module'; interface CliOptions { dryRun: boolean; matchId?: mongoose.Types.ObjectId; nodeEnv: string; winnerGameCount: number; } interface CodeUpdatePlan { codeId: mongoose.Types.ObjectId; code: string; bracketMatchId: string; currentGameNumber: number | undefined; nextGameNumber: number; } interface MissingReadySlotPlan { bracketMatchId: string; gameNumber: number; seriesGameNumber: number; seriesGameCount: number; } interface MatchRepairPlan { codeUpdates: CodeUpdatePlan[]; currentGameCount: number; matchId: mongoose.Types.ObjectId; missingReadySlots: MissingReadySlotPlan[]; nextGameCount: number; nextBracketMatches: DoubleEliminationBracketMatch[]; ruleRepairSkippedReason?: string; skippedReason?: string; } @Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: [ resolve(__dirname, '../../../../../../project.env'), resolve(process.cwd(), '../project.env'), resolve(process.cwd(), 'apps/project.env'), resolve(process.cwd(), 'project.env'), ], }), SecretModule, ], providers: [ConnectionService], }) class RepairModule {} async function loadMachineEnvFile() { const homeDir = process.env.HOME ?? process.env.USERPROFILE; if (!homeDir) return; const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); try { const file = await readFile(machineEnvFile, 'utf8'); for (const rawLine of file.split(/\r?\n/)) { const line = rawLine.trim(); if (!line || line.startsWith('#')) continue; const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); if (!matched) continue; const [, key, rawValue] = matched; process.env[key] = rawValue.replace(/^["']|["']$/g, ''); } } catch { // Local machine env is optional for one-off migrations. } } function parseArgs(argv: string[]): CliOptions { let dryRun = true; let matchId: mongoose.Types.ObjectId | undefined; let nodeEnv = process.env.NODE_ENV ?? 'dev'; let winnerGameCount = 3; for (let index = 0; index < argv.length; index += 1) { const arg = argv[index]; if (arg === '--apply') { dryRun = false; continue; } if (arg === '--dry-run') { dryRun = true; continue; } if (arg === '--env') { const value = argv[index + 1]; if (!value) throw new Error('--env requires dev, staging, or prod.'); nodeEnv = value; index += 1; continue; } if (arg.startsWith('--env=')) { nodeEnv = arg.slice('--env='.length); continue; } if (arg === '--match-id') { matchId = parseObjectId(argv[index + 1], '--match-id'); index += 1; continue; } if (arg.startsWith('--match-id=')) { matchId = parseObjectId(arg.slice('--match-id='.length), '--match-id'); continue; } if (arg === '--winner-game-count') { winnerGameCount = parseOddPositiveInteger( argv[index + 1], '--winner-game-count', ); index += 1; continue; } if (arg.startsWith('--winner-game-count=')) { winnerGameCount = parseOddPositiveInteger( arg.slice('--winner-game-count='.length), '--winner-game-count', ); continue; } if (arg === '--help' || arg === '-h') { printHelp(); process.exit(0); } throw new Error(`Unknown argument: ${arg}`); } if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { throw new Error('--env must be dev, staging, or prod.'); } return { dryRun, matchId, nodeEnv, winnerGameCount }; } function parseObjectId(value: string | undefined, label: string) { if (!value || !mongoose.isValidObjectId(value)) { throw new Error(`${label} requires a valid ObjectId.`); } return new mongoose.Types.ObjectId(value); } function parseOddPositiveInteger(value: string | undefined, label: string) { const parsed = Number(value); if (!Number.isInteger(parsed) || parsed < 1 || parsed % 2 === 0) { throw new Error(`${label} requires a positive odd integer.`); } return parsed; } function printHelp() { console.log(`Usage: pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id --dry-run pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-double-elimination-series-rules.ts --match-id --env prod --apply Options: --match-id Optional match ObjectId. If omitted, scans all double-elimination matches. --winner-game-count Winner-bracket series size. Must be odd. Default: 3. --dry-run Print the repair plan without writing. Default. --apply Apply match and tournament code updates. --env dev | staging | prod. Default: NODE_ENV or dev. `); } function requiredWinsFor(gameCount: number): number { return Math.floor(gameCount / 2) + 1; } 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 { const updateByCodeId = new Map( codeUpdates.map((update) => [update.codeId.toString(), update]), ); const activeSlotKeys = new Set(); 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, codes: TournamentCodeDocument[], winnerGameCount: number, ): MatchRepairPlan { const currentGameCount = match.gameCount; const resultGames = match.result?.games ?? []; const currentBracketMatches = [ ...(match.doubleElimination?.bracketMatches ?? []), ]; if (resultGames.length > 0) { return { codeUpdates: [], currentGameCount, matchId: match._id, missingReadySlots: buildMissingReadySlots(currentBracketMatches, codes), nextBracketMatches: currentBracketMatches, nextGameCount: currentGameCount, ruleRepairSkippedReason: 'result-games-exist', }; } const nextBracketMatches = currentBracketMatches.map((bracketMatch) => { const gameCount = bracketMatch.bracketSide === 'winner' ? winnerGameCount : 1; return { ...bracketMatch, gameCount, requiredWins: requiredWinsFor(gameCount), }; }); const firstSlotByBracketMatchId = new Map( buildDoubleEliminationGameSlots(nextBracketMatches) .filter((slot) => slot.seriesGameNumber === 1) .map((slot) => [slot.bracketMatch.bracketMatchId, slot]), ); const codeUpdates = codes .filter((code) => code.bracketMatchId) .map((code) => { const slot = firstSlotByBracketMatchId.get(code.bracketMatchId!); if (!slot) return null; if (code.gameNumber === slot.gameNumber) return null; return { codeId: code._id, code: code.code, bracketMatchId: code.bracketMatchId!, currentGameNumber: code.gameNumber, nextGameNumber: slot.gameNumber, } satisfies CodeUpdatePlan; }) .filter((entry): entry is CodeUpdatePlan => Boolean(entry)); const missingReadySlots = buildMissingReadySlots( nextBracketMatches, codes, codeUpdates, ); return { codeUpdates, currentGameCount, matchId: match._id, missingReadySlots, nextGameCount: Math.max(currentGameCount ?? 1, winnerGameCount), nextBracketMatches, }; } function printPlan(plan: MatchRepairPlan) { console.log(`match=${plan.matchId.toString()}`); if (plan.skippedReason) { console.log(` skipped=${plan.skippedReason}`); return; } if (plan.ruleRepairSkippedReason) { console.log(` ruleRepairSkipped=${plan.ruleRepairSkippedReason}`); } else { console.log( ` gameCount: ${plan.currentGameCount} -> ${plan.nextGameCount}`, ); } console.log( ` bracketMatches=${plan.nextBracketMatches.length} codeUpdates=${plan.codeUpdates.length} missingReadySlots=${plan.missingReadySlots.length}`, ); for (const update of plan.codeUpdates) { console.log( ` 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( match: MatchDocument, plan: MatchRepairPlan, TournamentCodeModel: mongoose.Model, session: mongoose.ClientSession, ) { if (plan.skippedReason) return; for (const update of plan.codeUpdates) { await TournamentCodeModel.updateOne( { _id: update.codeId }, { $set: { gameNumber: update.nextGameNumber, bracketMatchId: update.bracketMatchId, }, }, { session }, ).exec(); } const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); const reservedIds: mongoose.Types.ObjectId[] = []; for (const slot of plan.missingReadySlots) { 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 }); } } async function main() { const options = parseArgs(process.argv.slice(2)); process.env.NODE_ENV = options.nodeEnv; process.env.SECRET_SOURCE = process.env.SECRET_SOURCE || 'infisical'; await loadMachineEnvFile(); const app = await NestFactory.createApplicationContext(RepairModule, { logger: ['log', 'warn', 'error'], }); try { const connectionService = app.get(ConnectionService); const MatchModel = await connectionService.getModel('match'); const TournamentCodeModel = await connectionService.getModel('tournamentCode'); const matches = await MatchModel.find({ gameMode: 'double-elimination', ...(options.matchId ? { _id: options.matchId } : {}), }).exec(); const plans: Array<{ match: MatchDocument; plan: MatchRepairPlan }> = []; for (const match of matches) { const codes = await TournamentCodeModel.find({ _id: { $in: match.tournamentCodeIds ?? [] }, }).exec(); const plan = buildRepairPlan(match, codes, options.winnerGameCount); plans.push({ match, plan }); printPlan(plan); } if (options.dryRun) { console.log( 'No writes were made. Re-run with --apply to update MongoDB.', ); return; } const session = await ( await connectionService.getConnection() ).startSession(); try { await session.withTransaction(async () => { for (const { match, plan } of plans) { await applyPlan(match, plan, TournamentCodeModel, session); } }); } finally { await session.endSession(); } console.log( `Applied ${plans.filter(({ plan }) => !plan.skippedReason).length} match repairs.`, ); } finally { await app.close(); } } if (require.main === module) { main().catch((error) => { console.error(error); process.exit(1); }); }