From 1272c81fa9f49270bcd26ca6ba0e311fa1d1a261 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 19 Jun 2026 02:33:18 -0700 Subject: [PATCH] chore: add round-robin match repair script --- ...pair-limited-round-robin-finished-match.ts | 680 ++++++++++++++++++ 1 file changed, 680 insertions(+) create mode 100644 apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts diff --git a/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts new file mode 100644 index 00000000..24108c05 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts @@ -0,0 +1,680 @@ +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 { + ConnectionService, + resolveMongoDbName, +} from '../connection.service'; +import type { + MatchDocument, + MatchGameAssignment, + MatchGameResult, + MatchSeriesResult, + TournamentCodeDocument, +} from '../schema'; +import { SecretModule } from '../../secret/secret.module'; +import { MatchStatsFragmentBuilder } from '../../../community-stats/match-stats-fragment.builder'; +import { MatchStatsRepository } from '../../../community-stats/match-stats.repository'; +import { MatchStatsService } from '../../../community-stats/match-stats.service'; + +interface CliOptions { + dryRun: boolean; + matchId: mongoose.Types.ObjectId; + maxRounds: number; + nodeEnv: string; +} + +interface ResultGamePlan { + oldGameNumber: number; + newGameNumber: number; + roundNumber: number; + teamAIndex: number; + teamBIndex: number; + game: MatchGameResult; +} + +interface RepairPlan { + schedule: MatchGameAssignment[]; + gamePlans: ResultGamePlan[]; + seriesResults: MatchSeriesResult[]; + winnerTeamIndex?: number; + usedCodeByOldGameNumber: Map; + releasedCodes: TournamentCodeDocument[]; +} + +@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, + MatchStatsFragmentBuilder, + MatchStatsRepository, + MatchStatsService, + ], +}) +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 { + // 로컬 machine env 파일이 없으면 그냥 지나간다. + } +} + +function parseArgs(argv: string[]): CliOptions { + let dryRun = true; + let matchId: mongoose.Types.ObjectId | undefined; + let maxRounds = 3; + let nodeEnv = process.env.NODE_ENV ?? 'dev'; + + 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 === '--match-id') { + const value = argv[index + 1]; + if (!value || !mongoose.isValidObjectId(value)) { + throw new Error('--match-id requires a valid ObjectId.'); + } + matchId = new mongoose.Types.ObjectId(value); + index += 1; + continue; + } + if (arg.startsWith('--match-id=')) { + const value = arg.slice('--match-id='.length); + if (!mongoose.isValidObjectId(value)) { + throw new Error('--match-id requires a valid ObjectId.'); + } + matchId = new mongoose.Types.ObjectId(value); + continue; + } + if (arg === '--max-rounds') { + maxRounds = parsePositiveInteger(argv[index + 1], '--max-rounds'); + index += 1; + continue; + } + if (arg.startsWith('--max-rounds=')) { + maxRounds = parsePositiveInteger( + arg.slice('--max-rounds='.length), + '--max-rounds', + ); + 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 === '--help' || arg === '-h') { + printHelp(); + process.exit(0); + } + throw new Error(`Unknown argument: ${arg}`); + } + + if (!matchId) throw new Error('--match-id is required.'); + if (!['dev', 'staging', 'prod'].includes(nodeEnv)) { + throw new Error('--env must be dev, staging, or prod.'); + } + + return { dryRun, matchId, maxRounds, nodeEnv }; +} + +function parsePositiveInteger(value: string | undefined, label: string) { + const parsed = Number(value); + if (!Number.isInteger(parsed) || parsed < 1) { + throw new Error(`${label} requires a positive integer.`); + } + return parsed; +} + +function printHelp() { + console.log(`Usage: + pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts --match-id --max-rounds 3 --dry-run + pnpm --filter api exec ts-node src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts --match-id --max-rounds 3 --env prod --apply + +Options: + --match-id Match ObjectId to repair. + --max-rounds Number of round-robin rounds to keep. Default: 3. + --dry-run Print the repair plan without writing. Default. + --apply Apply match, tournament code, and stats updates. + --env dev | staging | prod. Default: NODE_ENV or dev. +`); +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + process.env.NODE_ENV = options.nodeEnv; + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(RepairModule, { + logger: ['log', 'warn', 'error'], + }); + + try { + const connectionService = app.get(ConnectionService); + const matchStatsService = app.get(MatchStatsService); + const MatchModel = await connectionService.getModel('match'); + const TournamentCodeModel = + await connectionService.getModel('tournamentCode'); + const match = await MatchModel.findById(options.matchId).exec(); + if (!match) { + throw new Error(`Match not found: ${options.matchId.toString()}`); + } + + const codes = await TournamentCodeModel.find({ + _id: { $in: match.tournamentCodeIds ?? [] }, + }) + .sort({ gameNumber: 1, reservedAt: 1, _id: 1 }) + .exec(); + const plan = buildRepairPlan(match, codes, options.maxRounds); + + printPlan(options, match, codes, plan); + + if (options.dryRun) { + console.log('No writes were made. Re-run with --apply to update MongoDB.'); + return; + } + + const now = new Date(); + const session = await (await connectionService.getConnection()).startSession(); + try { + await session.withTransaction(async () => { + await applyTournamentCodeUpdates(plan, now, session); + await MatchModel.updateOne( + { _id: match._id }, + { + $set: { + status: 'finished', + roundRobinMaxRounds: options.maxRounds, + gameSchedule: plan.schedule, + tournamentCodeIds: [ + ...plan.usedCodeByOldGameNumber.values(), + ].map((code) => code._id), + resultPollState: { + startedAt: match.resultPollState?.startedAt ?? now, + lastPolledAt: now, + lastPollOutcome: 'matched', + matchedCount: plan.gamePlans.length, + expandedToAllPuuids: true, + state: 'complete', + }, + result: { + winnerTeamIndex: plan.winnerTeamIndex, + mvpUserId: match.result?.mvpUserId, + riotMatchIds: plan.gamePlans.map( + (gamePlan) => gamePlan.game.riotMatchId, + ), + games: plan.gamePlans.map((gamePlan) => ({ + ...toPlainGame(gamePlan.game), + gameNumber: gamePlan.newGameNumber, + })), + seriesResults: plan.seriesResults, + }, + }, + }, + { session }, + ).exec(); + }); + } finally { + await session.endSession(); + } + + await matchStatsService.buildAndUpsert(match._id); + console.log('Repair applied and match stats rebuilt.'); + } finally { + await app.close(); + await mongoose.disconnect(); + } +} + +function buildRepairPlan( + match: MatchDocument, + codes: TournamentCodeDocument[], + maxRounds: number, +): RepairPlan { + if (match.gameMode !== 'round-robin') { + throw new Error(`Expected round-robin match, got ${match.gameMode}.`); + } + + const games = [...(match.result?.games ?? [])] + .map(toPlainGame) + .sort((left, right) => left.gameNumber - right.gameNumber); + if (games.length === 0) { + throw new Error('Match has no result games to preserve.'); + } + + const teamIndexes = [...new Set(match.teams.map((team) => team.teamIndex))] + .filter((teamIndex) => Number.isInteger(teamIndex) && teamIndex > 0) + .sort((left, right) => left - right); + if (teamIndexes.length < 2) { + throw new Error('Match needs at least two teams.'); + } + if (teamIndexes.length % 2 !== 0) { + throw new Error('This repair script currently expects an even team count.'); + } + + const gamesPerRound = teamIndexes.length / 2; + const requiredGames = gamesPerRound * maxRounds; + if (games.length !== requiredGames) { + throw new Error( + `Expected ${requiredGames} result games for ${maxRounds} rounds and ${teamIndexes.length} teams, got ${games.length}.`, + ); + } + + validateResultGames(games, teamIndexes); + const rounds = partitionIntoRounds(games, teamIndexes, maxRounds); + const gamePlans = rounds.flatMap((roundGames, roundIndex) => + sortRoundGames(roundGames).map((game, gameIndex) => ({ + oldGameNumber: game.gameNumber, + newGameNumber: roundIndex * gamesPerRound + gameIndex + 1, + roundNumber: roundIndex + 1, + teamAIndex: Math.min(game.blueTeamIndex, game.redTeamIndex), + teamBIndex: Math.max(game.blueTeamIndex, game.redTeamIndex), + game, + })), + ); + + const schedule = gamePlans.map( + ({ newGameNumber, roundNumber, teamAIndex, teamBIndex }) => ({ + gameNumber: newGameNumber, + roundNumber, + teamAIndex, + teamBIndex, + }), + ); + + const usedOldGameNumbers = new Set( + gamePlans.map((gamePlan) => gamePlan.oldGameNumber), + ); + const usedCodeByOldGameNumber = resolveUsedCodesByOldGameNumber( + codes, + gamePlans, + ); + const releasedCodes = codes.filter( + (code) => !usedOldGameNumbers.has(code.gameNumber ?? 0), + ); + const unsafeReleased = releasedCodes.filter((code) => code.state === 'used'); + if (unsafeReleased.length > 0) { + throw new Error( + `Refusing to release used tournament codes without matching result games: ${unsafeReleased + .map((code) => formatCode(code)) + .join(', ')}`, + ); + } + + const updatedGames = gamePlans.map((gamePlan) => ({ + ...toPlainGame(gamePlan.game), + gameNumber: gamePlan.newGameNumber, + })); + const seriesResults = buildSeriesResults(updatedGames); + + return { + schedule, + gamePlans, + seriesResults, + winnerTeamIndex: resolveMatchWinnerTeamIndex(seriesResults), + usedCodeByOldGameNumber, + releasedCodes, + }; +} + +function validateResultGames(games: MatchGameResult[], teamIndexes: number[]) { + const validTeamIndexes = new Set(teamIndexes); + const pairKeys = new Set(); + const gameNumbers = new Set(); + + for (const game of games) { + if (gameNumbers.has(game.gameNumber)) { + throw new Error(`Duplicate result gameNumber: ${game.gameNumber}.`); + } + gameNumbers.add(game.gameNumber); + + if (!validTeamIndexes.has(game.blueTeamIndex)) { + throw new Error(`Invalid blueTeamIndex ${game.blueTeamIndex}.`); + } + if (!validTeamIndexes.has(game.redTeamIndex)) { + throw new Error(`Invalid redTeamIndex ${game.redTeamIndex}.`); + } + if (game.blueTeamIndex === game.redTeamIndex) { + throw new Error(`Game ${game.gameNumber} has the same team twice.`); + } + + const key = pairKey(game); + if (pairKeys.has(key)) { + throw new Error(`Duplicate team pair in results: ${key}.`); + } + pairKeys.add(key); + } +} + +function partitionIntoRounds( + games: MatchGameResult[], + teamIndexes: number[], + maxRounds: number, +): MatchGameResult[][] { + const targetPerRound = teamIndexes.length / 2; + const unused = new Set(games.map((game) => game.gameNumber)); + const byGameNumber = new Map(games.map((game) => [game.gameNumber, game])); + const rounds: MatchGameResult[][] = []; + + function fillRound(roundIndex: number): boolean { + if (roundIndex === maxRounds) return unused.size === 0; + + const candidates = enumerateRoundCandidates( + [...unused] + .map((gameNumber) => byGameNumber.get(gameNumber)) + .filter((game): game is MatchGameResult => Boolean(game)), + teamIndexes, + targetPerRound, + ); + + for (const candidate of candidates) { + for (const game of candidate) unused.delete(game.gameNumber); + rounds[roundIndex] = candidate; + if (fillRound(roundIndex + 1)) return true; + for (const game of candidate) unused.add(game.gameNumber); + } + + rounds.length = roundIndex; + return false; + } + + if (!fillRound(0)) { + throw new Error('Could not partition result games into simultaneous rounds.'); + } + + return rounds; +} + +function enumerateRoundCandidates( + availableGames: MatchGameResult[], + teamIndexes: number[], + targetPerRound: number, +): MatchGameResult[][] { + const candidates: MatchGameResult[][] = []; + + function visit(usedTeams: Set, chosen: MatchGameResult[]) { + if (chosen.length === targetPerRound) { + candidates.push([...chosen]); + return; + } + + const nextTeam = teamIndexes.find((teamIndex) => !usedTeams.has(teamIndex)); + if (!nextTeam) return; + + const nextGames = availableGames + .filter((game) => { + if (!includesTeam(game, nextTeam)) return false; + return ( + !usedTeams.has(game.blueTeamIndex) && + !usedTeams.has(game.redTeamIndex) + ); + }) + .sort((left, right) => left.gameNumber - right.gameNumber); + + for (const game of nextGames) { + chosen.push(game); + usedTeams.add(game.blueTeamIndex); + usedTeams.add(game.redTeamIndex); + visit(usedTeams, chosen); + usedTeams.delete(game.blueTeamIndex); + usedTeams.delete(game.redTeamIndex); + chosen.pop(); + } + } + + visit(new Set(), []); + return candidates; +} + +function sortRoundGames(games: MatchGameResult[]) { + return [...games].sort( + (left, right) => + Math.min(left.blueTeamIndex, left.redTeamIndex) - + Math.min(right.blueTeamIndex, right.redTeamIndex) || + Math.max(left.blueTeamIndex, left.redTeamIndex) - + Math.max(right.blueTeamIndex, right.redTeamIndex), + ); +} + +function resolveUsedCodesByOldGameNumber( + codes: TournamentCodeDocument[], + gamePlans: ResultGamePlan[], +): Map { + const byGameNumber = new Map(); + for (const code of codes) { + if (!code.gameNumber) continue; + const existing = byGameNumber.get(code.gameNumber) ?? []; + existing.push(code); + byGameNumber.set(code.gameNumber, existing); + } + + const result = new Map(); + for (const gamePlan of gamePlans) { + const candidates = byGameNumber.get(gamePlan.oldGameNumber) ?? []; + if (candidates.length !== 1) { + throw new Error( + `Expected exactly one tournament code for old game ${gamePlan.oldGameNumber}, got ${candidates.length}.`, + ); + } + const [code] = candidates; + if (code.riotMatchId && code.riotMatchId !== gamePlan.game.riotMatchId) { + throw new Error( + `Tournament code ${formatCode(code)} has riotMatchId ${code.riotMatchId}, expected ${gamePlan.game.riotMatchId}.`, + ); + } + result.set(gamePlan.oldGameNumber, code); + } + + return result; +} + +async function applyTournamentCodeUpdates( + plan: RepairPlan, + now: Date, + session: mongoose.ClientSession, +) { + const usedOperations = plan.gamePlans.map((gamePlan) => { + const code = plan.usedCodeByOldGameNumber.get(gamePlan.oldGameNumber); + if (!code) { + throw new Error(`Missing tournament code for ${gamePlan.oldGameNumber}.`); + } + return code.updateOne( + { + $set: { + state: 'used', + gameNumber: gamePlan.newGameNumber, + riotMatchId: gamePlan.game.riotMatchId, + usedAt: resolveGameEndedAt(gamePlan.game), + }, + $unset: { + releasedAt: '', + }, + }, + { session }, + ); + }); + + const releasedOperations = plan.releasedCodes.map((code) => + code.updateOne( + { + $set: { + state: 'released', + releasedAt: now, + }, + $unset: { + matchId: '', + gameNumber: '', + reservedAt: '', + usedAt: '', + riotMatchId: '', + }, + }, + { session }, + ), + ); + + await Promise.all([...usedOperations, ...releasedOperations]); +} + +function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] { + const bySeries = new Map(); + for (const game of games) { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + const key = `${teamAIndex}:${teamBIndex}`; + const current = + bySeries.get(key) ?? + ({ + teamAIndex, + teamBIndex, + teamAWins: 0, + teamBWins: 0, + } satisfies MatchSeriesResult); + if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; + if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; + current.winnerTeamIndex = + current.teamAWins > current.teamBWins + ? teamAIndex + : current.teamBWins > current.teamAWins + ? teamBIndex + : undefined; + bySeries.set(key, current); + } + return [...bySeries.values()].sort( + (left, right) => + left.teamAIndex - right.teamAIndex || + left.teamBIndex - right.teamBIndex, + ); +} + +function resolveMatchWinnerTeamIndex(seriesResults: MatchSeriesResult[]) { + const winsByTeam = new Map(); + for (const series of seriesResults) { + if (!series.winnerTeamIndex) continue; + winsByTeam.set( + series.winnerTeamIndex, + (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, + ); + } + + const sorted = [...winsByTeam.entries()].sort( + (left, right) => right[1] - left[1], + ); + if (sorted.length === 0) return undefined; + if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; + return sorted[0][0]; +} + +function printPlan( + options: CliOptions, + match: MatchDocument, + codes: TournamentCodeDocument[], + plan: RepairPlan, +) { + console.log( + `[limited round-robin repair] mode=${options.dryRun ? 'dry-run' : 'apply'} env=${options.nodeEnv} db=${resolveMongoDbName(options.nodeEnv)}`, + ); + console.log( + `[limited round-robin repair] match=${match._id.toString()} title="${match.title}"`, + ); + console.log( + `[limited round-robin repair] status ${match.status} -> finished, maxRounds=${options.maxRounds}`, + ); + console.log( + `[limited round-robin repair] resultGames=${plan.gamePlans.length} codes kept=${plan.usedCodeByOldGameNumber.size} codes released=${plan.releasedCodes.length} previousCodeIds=${codes.length}`, + ); + console.log( + `[limited round-robin repair] winnerTeamIndex=${plan.winnerTeamIndex ?? '(tie)'}`, + ); + + for (const gamePlan of plan.gamePlans) { + console.log( + ` R${gamePlan.roundNumber} G${gamePlan.newGameNumber}: ${gamePlan.teamAIndex}팀 vs ${gamePlan.teamBIndex}팀 (old G${gamePlan.oldGameNumber}, riot=${gamePlan.game.riotMatchId})`, + ); + } +} + +function toPlainGame(game: MatchGameResult): MatchGameResult { + const maybeSubdocument = game as unknown as { + toObject?: () => MatchGameResult; + }; + const objectValue = + typeof maybeSubdocument.toObject === 'function' + ? maybeSubdocument.toObject() + : game; + return { + ...objectValue, + participants: [...(objectValue.participants ?? [])], + }; +} + +function includesTeam(game: MatchGameResult, teamIndex: number) { + return game.blueTeamIndex === teamIndex || game.redTeamIndex === teamIndex; +} + +function pairKey(game: MatchGameResult) { + const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); + const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); + return `${teamAIndex}:${teamBIndex}`; +} + +function resolveGameEndedAt(game: MatchGameResult) { + return new Date(game.gameCreation + game.gameDuration * 1000); +} + +function formatCode(code: TournamentCodeDocument) { + return `${code._id.toString()}(gameNumber=${code.gameNumber ?? 'none'}, state=${code.state})`; +} + +void main() + .then(() => { + process.exit(0); + }) + .catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); + });