import { BadRequestException, Injectable, Logger, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { completeDoubleEliminationBracketMatch, } from '../double-elimination/double-elimination.util'; import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import { DistributedLockService } from '../global/redis/distributed-lock.service'; import type { MatchDocument, MatchGameResult, MatchSeriesResult, RiotMatch as StoredRiotMatch, TournamentCodeDocument, } from '../global/database/schema'; import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; import { roundRobinGameSchedule, resolveRoundRobinTeamCount, } from '../tournament-code/round-robin.util'; import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants'; import { collectCaptainAndLimitedTeamMemberUserIds, collectCaptainUserIds, collectMatchUserIds, computeGameResult, type MatchPuuidLookup, } from './team-mapping.util'; import type { EnqueueTournamentResultPollResult, ManualTournamentResultCollectResponse, PollTournamentResultJob, } from './tournament-result.types'; const FIRST_HOUR_POLL_DELAY_MS = 2 * 60_000; const LATER_POLL_DELAY_MS = 60 * 60_000; const POLL_EXPIRY_MS = 24 * 60 * 60_000; const EXPAND_AFTER_MS = 60 * 60_000; const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 30 * 60_000; const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 5 * 60_000; const TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS = 5 * 60_000; interface ManualGameAssignment { gameNumber: number; bracketMatchId?: string; teamAIndex: number; teamBIndex: number; } @Injectable() export class TournamentResultService { private readonly logger = new Logger(TournamentResultService.name); constructor( private readonly connectionService: ConnectionService, private readonly riotMatchService: RiotMatchService, private readonly riotJobQueueService: RiotJobQueueService, private readonly communityStatsService: CommunityStatsService, private readonly matchStatsService: MatchStatsService, private readonly distributedLockService: DistributedLockService, ) {} public async scheduleInitialPoll( matchOrId: MatchDocument | mongoose.Types.ObjectId, priority: RiotJobPriority = 'high', ): Promise { const matchIdentifier = this.resolveMatchIdentifier(matchOrId); return this.distributedLockService.runWithLock( { lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier), lockExpirationDurationMilliseconds: TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockAcquireTimeoutMilliseconds: 1_000, lockRetryDelayMilliseconds: 100, }, async () => this.scheduleInitialPollWhileLockOwned(matchOrId, priority), ); } private async scheduleInitialPollWhileLockOwned( matchOrId: MatchDocument | mongoose.Types.ObjectId, priority: RiotJobPriority, ): Promise { const match = await this.loadMatch(matchOrId); if (match.status === 'finished') return null; if (!this.isReadyToPoll(match)) return null; match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: false, state: 'polling', }; await match.save(); return this.riotJobQueueService.enqueueTournamentResultPoll({ matchId: match._id.toString(), attempt: 1, expandedToAllPuuids: false, priority, }); } public async scheduleManualPoll(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; }): Promise { const match = await this.loadMatch(params.matchId); if (!match.communityId.equals(params.communityId)) { throw new BadRequestException('Match does not belong to this community.'); } if (!this.isReadyToPoll(match)) { throw new BadRequestException( 'Match needs built teams, teamBuiltAt, and tournament codes before polling.', ); } const result = await this.scheduleInitialPoll(match, 'high'); if (!result) { throw new BadRequestException( 'Tournament result polling is not available.', ); } return result; } public async collectManualByWindow(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; startTime: Date; endTime: Date; }): Promise { const match = await this.loadMatch(params.matchId); this.assertManualCollectionAllowed(match, params.communityId); if (params.startTime.getTime() > params.endTime.getTime()) { throw new BadRequestException( 'startTime must be less than or equal to endTime.', ); } const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); const puuids = this.collectPollingPuuids( collectMatchUserIds(match), lookup, ); const startTime = Math.floor(params.startTime.getTime() / 1000); const endTime = Math.floor(params.endTime.getTime() / 1000); const riotMatchIds = new Set(); for (const puuid of puuids) { try { const ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { region, startTime, endTime, count: 100, }); ids.forEach((id) => riotMatchIds.add(id)); } catch (error) { this.logger.warn( `Manual result match id lookup failed for ${puuid}: ${ error instanceof Error ? error.message : error }`, ); } } const details = await this.loadRiotMatchDetails( [...riotMatchIds], region, 'Manual result detail fetch failed', ); return this.applyManualRiotMatches(match, details, lookup); } public async collectManualByRiotMatch(params: { matchId: mongoose.Types.ObjectId; communityId: mongoose.Types.ObjectId; riotMatchId: string; }): Promise { const match = await this.loadMatch(params.matchId); this.assertManualCollectionAllowed(match, params.communityId); const normalizedRiotMatchId = params.riotMatchId.trim(); if (!normalizedRiotMatchId) { throw new BadRequestException('riotMatchId is required.'); } const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); const detail = await this.ensureRiotMatchPersisted( normalizedRiotMatchId, region, ); return this.applyManualRiotMatches(match, [detail], lookup); } public async cancelPolling( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { const match = await this.loadMatch(matchOrId); match.resultPollState = undefined; await match.save(); } public async processPollJob(job: PollTournamentResultJob): Promise { const didProcessPollJob = await this.distributedLockService.runWithRenewedLock( { lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), lockExpirationDurationMilliseconds: TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockRenewalIntervalMilliseconds: TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, }, async () => { await this.processPollJobWhileLockOwned(job); return true; }, ); if (didProcessPollJob) return; this.logger.debug( `Skipped tournament result poll job ${job.jobId}; another worker is processing match ${job.matchId}.`, ); } private async processPollJobWhileLockOwned( job: PollTournamentResultJob, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const CommunityModel = await this.connectionService.getModel('community'); const match = await MatchModel.findById(job.matchId); if (!match || match.status === 'finished') return; if (!this.isReadyToPoll(match)) { await this.updatePollState(match, 'failed', job.expandedToAllPuuids); return; } const codes = await TournamentCodeModel.find({ matchId: match._id }) .sort({ gameNumber: 1 }) .exec(); const unmatched = codes.filter( (code) => code.state === 'reserved' && !code.riotMatchId, ); if (unmatched.length === 0) { const completed = await this.advanceMatchIfReady(match, codes); if (!completed) { await this.reserveReadyDoubleEliminationCodes(match); await this.scheduleNextPoll(match, job); } return; } const community = await CommunityModel.findById(match.communityId) .select({ riotRegion: 1 }) .lean() .exec(); const region = community?.riotRegion ?? 'asia'; const lookup = await this.buildPuuidLookup(match); const puuids = job.expandedToAllPuuids ? this.collectPollingPuuids( collectCaptainAndLimitedTeamMemberUserIds( match, EXPANDED_MEMBER_LIMIT_PER_TEAM, ), lookup, ) : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); const matchedGameNumbers = new Set(); const checkedRiotMatchIds = new Set(); const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code])); for (const puuid of puuids) { let ids: string[]; try { ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { region, type: 'tourney', startTime: this.resolveStartTime(match), endTime: Math.floor(Date.now() / 1000), count: 100, }); } catch (error) { this.logger.warn( `Tournament result match id lookup failed for ${puuid}: ${ error instanceof Error ? error.message : error }`, ); continue; } for (const riotMatchId of ids) { if (checkedRiotMatchIds.has(riotMatchId)) continue; checkedRiotMatchIds.add(riotMatchId); const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId, }); if (alreadyMatched) continue; let detail: RiotMatchDto; try { detail = await this.ensureRiotMatchPersisted(riotMatchId, region); } catch (error) { this.logger.warn( `Tournament result detail fetch failed for ${riotMatchId}: ${ error instanceof Error ? error.message : error }`, ); continue; } const tournamentCode = detail.info.tournamentCode?.trim(); if (!tournamentCode) continue; const code = unmatchedByCode.get(tournamentCode); if (!code) continue; const applied = await this.applyMatchToGameSlot({ match, code, detail, lookup, }); if (applied) { matchedGameNumbers.add(code.gameNumber ?? 0); unmatchedByCode.delete(tournamentCode); } } } const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id }) .sort({ gameNumber: 1 }) .exec(); const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found'; await this.updatePollState(match, outcome, job.expandedToAllPuuids); const completed = await this.advanceMatchIfReady(match, reloadedCodes); if (!completed) { await this.scheduleNextPoll(match, job); } } private async applyMatchToGameSlot(params: { match: MatchDocument; code: TournamentCodeDocument; detail: RiotMatchDto; lookup: MatchPuuidLookup; }): Promise { const { match, code, detail, lookup } = params; if (code.state !== 'reserved' || code.riotMatchId) return false; if (!code.gameNumber) return false; const gameResult = computeGameResult({ match, detail, gameNumber: code.gameNumber, lookup, ...this.resolveSeriesRefForGameNumber(match, code.gameNumber), }); if (!gameResult) { this.logger.warn( `Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`, ); return false; } gameResult.bracketMatchId = code.bracketMatchId; code.state = 'used'; code.usedAt = new Date( detail.info.gameEndTimestamp ?? detail.info.gameCreation, ); code.riotMatchId = detail.metadata.matchId; await code.save(); this.upsertGameResult(match, gameResult); this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result'); if (match.status === 'team-built') { match.status = 'in-progress'; } await match.save(); await this.reserveReadyDoubleEliminationCodes(match); await this.rebuildMatchStatsSafe(match); return true; } private async applyManualRiotMatches( match: MatchDocument, details: RiotMatchDto[], lookup: MatchPuuidLookup, ): Promise { const sortedDetails = [...details].sort( (left, right) => left.info.gameCreation - right.info.gameCreation, ); const appliedRiotMatchIds: string[] = []; const appliedGameNumbers: number[] = []; let skipped = 0; for (const detail of sortedDetails) { if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) { skipped += 1; continue; } const gameResult = this.computeManualGameResult(match, detail, lookup); if (!gameResult) { skipped += 1; continue; } this.upsertGameResult(match, gameResult); this.advanceDoubleEliminationIfNeeded(match, gameResult, 'riot-result'); await this.markTournamentCodeUsedForManualResult( match, gameResult, detail, ); appliedRiotMatchIds.push(detail.metadata.matchId); appliedGameNumbers.push(gameResult.gameNumber); } if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') { match.status = 'in-progress'; } this.updateManualCollectionState(match, appliedRiotMatchIds.length); await match.save(); if (appliedRiotMatchIds.length > 0) { await this.reserveReadyDoubleEliminationCodes(match); } if (appliedRiotMatchIds.length > 0) { await this.rebuildMatchStatsSafe(match); } if (this.hasAllRequiredGameResults(match)) { await this.finishMatchFromManualResults(match); } return { scanned: sortedDetails.length, matched: appliedRiotMatchIds.length, skipped, riotMatchIds: appliedRiotMatchIds, gameNumbers: appliedGameNumbers, }; } private async advanceMatchIfReady( match: MatchDocument, codes: TournamentCodeDocument[], ): Promise { if ((match.gameMode ?? 'pair') === 'double-elimination') { if (!this.isDoubleEliminationComplete(match)) return false; match.status = 'finished'; if (match.result) { match.result.winnerTeamIndex = match.doubleElimination?.placements.firstTeamIndex; } match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, state: 'complete', }; await match.save(); await this.rebuildMatchStatsSafe(match); void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { this.logger.warn( `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ error instanceof Error ? error.message : error }`, ); }); return true; } if (codes.length < this.resolveRequiredGameSlots(match)) return false; if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { return false; } match.status = 'finished'; if (match.result) { match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( match.result.seriesResults ?? [], ); } match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, state: 'complete', }; await match.save(); await this.rebuildMatchStatsSafe(match); void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { this.logger.warn( `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ error instanceof Error ? error.message : error }`, ); }); return true; } private async scheduleNextPoll( match: MatchDocument, job: PollTournamentResultJob, ): Promise { const pollState = match.resultPollState; const startedAt = pollState?.startedAt ?? new Date(); const elapsedMs = Date.now() - startedAt.getTime(); const delayMs = this.nextPollDelayMs(elapsedMs); if (delayMs === null) { match.resultPollState = { startedAt, lastPolledAt: pollState?.lastPolledAt, lastPollOutcome: pollState?.lastPollOutcome, matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, state: 'expired', }; await match.save(); this.logger.warn( `Tournament result polling expired for match ${match._id.toString()}.`, ); return; } const expandedToAllPuuids = job.expandedToAllPuuids || (elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0); await this.riotJobQueueService.enqueueTournamentResultPoll({ matchId: match._id.toString(), attempt: job.attempt + 1, expandedToAllPuuids, priority: 'low', deferUntilMs: Date.now() + delayMs, }); } private async ensureRiotMatchPersisted( riotMatchId: string, region: RiotRegionalRoute, ): Promise { const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const stored = await RiotMatchModel.findOne({ matchId: riotMatchId, }).exec(); if (isRiotMatchDto(stored?.raw)) return stored.raw; const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); const payload: Partial = { matchId: dto.metadata.matchId, gameCreation: dto.info.gameCreation, gameDuration: dto.info.gameDuration, gameVersion: dto.info.gameVersion, queueId: dto.info.queueId, participantPuuids: dto.metadata.participants, raw: dto as unknown as Record, fetchedAt: new Date(), }; await RiotMatchModel.updateOne( { matchId: dto.metadata.matchId }, { $setOnInsert: payload }, { upsert: true }, ).exec(); return dto; } private async loadRiotMatchDetails( riotMatchIds: string[], region: RiotRegionalRoute, logPrefix: string, ): Promise { const details: RiotMatchDto[] = []; const checked = new Set(); for (const riotMatchId of riotMatchIds) { if (checked.has(riotMatchId)) continue; checked.add(riotMatchId); try { details.push(await this.ensureRiotMatchPersisted(riotMatchId, region)); } catch (error) { this.logger.warn( `${logPrefix} ${riotMatchId}: ${ error instanceof Error ? error.message : error }`, ); } } return details; } private async buildPuuidLookup( match: MatchDocument, ): Promise { const puuidByUserId = new Map(); const userIdByPuuid = new Map(); for (const participant of match.participants) { if (!participant.puuid) continue; const userId = participant.userId.toString(); puuidByUserId.set(userId, participant.puuid); userIdByPuuid.set(participant.puuid, participant.userId); } const missingUserIds = collectMatchUserIds(match).filter( (userId) => !puuidByUserId.has(userId.toString()), ); if (missingUserIds.length > 0) { const UserModel = await this.connectionService.getModel('user'); const users = await UserModel.find({ _id: { $in: missingUserIds } }) .select({ riotAccounts: 1 }) .exec(); for (const user of users) { const primary = user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0]; if (!primary) continue; puuidByUserId.set(user._id.toString(), primary.puuid); userIdByPuuid.set(primary.puuid, user._id); } } return { puuidByUserId, userIdByPuuid }; } private collectPollingPuuids( userIds: mongoose.Types.ObjectId[], lookup: MatchPuuidLookup, ): string[] { return [ ...new Set( userIds .map((userId) => lookup.puuidByUserId.get(userId.toString())) .filter((puuid): puuid is string => Boolean(puuid)), ), ]; } private upsertGameResult( match: MatchDocument, gameResult: MatchGameResult, ): void { const currentGames = match.result?.games ?? []; const games = [ ...currentGames.filter( (game) => game.gameNumber !== gameResult.gameNumber && game.riotMatchId !== gameResult.riotMatchId, ), gameResult, ].sort((left, right) => left.gameNumber - right.gameNumber); const seriesResults = this.buildSeriesResults(games); match.result = { winnerTeamIndex: (match.gameMode ?? 'pair') === 'double-elimination' ? match.doubleElimination?.placements.firstTeamIndex : this.resolveMatchWinnerTeamIndex(seriesResults), mvpUserId: match.result?.mvpUserId, riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], games, seriesResults, }; } private computeManualGameResult( match: MatchDocument, detail: RiotMatchDto, lookup: MatchPuuidLookup, ): MatchGameResult | null { for (const assignment of this.resolveOpenManualGameAssignments(match)) { const gameResult = computeGameResult({ match, detail, gameNumber: assignment.gameNumber, lookup, teamAIndex: assignment.teamAIndex, teamBIndex: assignment.teamBIndex, }); if (gameResult) { gameResult.bracketMatchId = assignment.bracketMatchId; return gameResult; } } return null; } private resolveOpenManualGameAssignments( match: MatchDocument, ): ManualGameAssignment[] { const usedGameNumbers = new Set( (match.result?.games ?? []).map((game) => game.gameNumber), ); const usedBracketMatchIds = new Set( (match.result?.games ?? []) .map((game) => game.bracketMatchId) .filter((id): id is string => Boolean(id)), ); const assignments: ManualGameAssignment[] = []; if ((match.gameMode ?? 'pair') === 'double-elimination') { for (const bracketMatch of match.doubleElimination?.bracketMatches ?? []) { if (bracketMatch.state !== 'ready') continue; if (usedBracketMatchIds.has(bracketMatch.bracketMatchId)) continue; if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue; assignments.push({ gameNumber: bracketMatch.gameNumber, bracketMatchId: bracketMatch.bracketMatchId, teamAIndex: bracketMatch.teamAIndex, teamBIndex: bracketMatch.teamBIndex, }); } return assignments; } const requiredSlots = this.resolveRequiredGameSlots(match); for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { if (usedGameNumbers.has(gameNumber)) continue; assignments.push({ gameNumber, ...this.resolveSeriesRefForGameNumber(match, gameNumber), }); } return assignments; } private hasResultForRiotMatch( match: MatchDocument, riotMatchId: string, ): boolean { return Boolean( match.result?.games?.some((game) => game.riotMatchId === riotMatchId), ); } private hasAllRequiredGameResults(match: MatchDocument): boolean { if ((match.gameMode ?? 'pair') === 'double-elimination') { return this.isDoubleEliminationComplete(match); } const requiredSlots = this.resolveRequiredGameSlots(match); if (requiredSlots <= 0) return false; const resultGameNumbers = new Set( (match.result?.games ?? []).map((game) => game.gameNumber), ); for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { if (!resultGameNumbers.has(gameNumber)) return false; } return true; } private updateManualCollectionState( match: MatchDocument, matchedCount: number, ): void { match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found', matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: true, state: 'polling', }; } private async finishMatchFromManualResults( match: MatchDocument, ): Promise { match.status = 'finished'; if (match.result) { match.result.winnerTeamIndex = (match.gameMode ?? 'pair') === 'double-elimination' ? match.doubleElimination?.placements.firstTeamIndex : this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []); } match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: 'matched', matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids: true, state: 'complete', }; await match.save(); await this.rebuildMatchStatsSafe(match); void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { this.logger.warn( `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ error instanceof Error ? error.message : error }`, ); }); } private async rebuildMatchStatsSafe(match: MatchDocument): Promise { try { await this.matchStatsService.buildAndUpsert(match._id); } catch (error) { this.logger.warn( `Failed to rebuild match stats for ${match._id.toString()}: ${ error instanceof Error ? error.message : error }`, ); } } private advanceDoubleEliminationIfNeeded( match: MatchDocument, gameResult: MatchGameResult, completedBy: 'riot-result' | 'walkover', ): void { if ((match.gameMode ?? 'pair') !== 'double-elimination') return; if (!match.doubleElimination || !gameResult.bracketMatchId) return; match.doubleElimination = completeDoubleEliminationBracketMatch( match.doubleElimination, { bracketMatchId: gameResult.bracketMatchId, winnerTeamIndex: gameResult.winnerTeamIndex, completedBy, completedAt: new Date(gameResult.gameCreation), }, ); if (match.result && this.isDoubleEliminationComplete(match)) { match.result.winnerTeamIndex = match.doubleElimination!.placements.firstTeamIndex; } match.markModified?.('doubleElimination'); } private isDoubleEliminationComplete(match: MatchDocument): boolean { const placements = match.doubleElimination?.placements; return Boolean( placements?.firstTeamIndex && placements.secondTeamIndex && placements.thirdTeamIndex, ); } private async reserveReadyDoubleEliminationCodes( match: MatchDocument, ): Promise { await this.distributedLockService.runWithLock( { lockKey: this.tournamentResultReadyCodeReservationLockKey( match._id.toString(), ), lockExpirationDurationMilliseconds: TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS, }, async () => this.reserveReadyDoubleEliminationCodesWhileLockOwned(match), ); } private async reserveReadyDoubleEliminationCodesWhileLockOwned( match: MatchDocument, ): Promise { if ((match.gameMode ?? 'pair') !== 'double-elimination') return; const readyBracketMatches = (match.doubleElimination?.bracketMatches ?? []) .filter((bracketMatch) => bracketMatch.state === 'ready'); if (readyBracketMatches.length === 0) return; const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const existingCodes = match.tournamentCodeIds.length > 0 ? await TournamentCodeModel.find({ _id: { $in: match.tournamentCodeIds }, }).exec() : []; const existingByBracketMatchId = new Map( existingCodes .filter( (code) => code.bracketMatchId && (code.state === 'reserved' || code.state === 'used'), ) .map((code) => [code.bracketMatchId as string, code]), ); const reservedIds: mongoose.Types.ObjectId[] = []; const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); for (const bracketMatch of readyBracketMatches) { if (existingByBracketMatchId.has(bracketMatch.bracketMatchId)) 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: bracketMatch.gameNumber, bracketMatchId: bracketMatch.bracketMatchId, reservedAt: new Date(), }, $unset: { releasedAt: 1 }, }, { sort: { expiresAt: 1 }, returnDocument: 'after' }, ).exec(); if (!code) break; reservedIds.push(code._id); } if (reservedIds.length === 0) return; await MatchModel.updateOne( { _id: match._id }, { $addToSet: { tournamentCodeIds: { $each: reservedIds } } }, ).exec(); const existingTournamentCodeIds = new Set( match.tournamentCodeIds.map((tournamentCodeId) => tournamentCodeId.toString(), ), ); for (const reservedId of reservedIds) { if (existingTournamentCodeIds.has(reservedId.toString())) continue; match.tournamentCodeIds.push(reservedId); } } private async markTournamentCodeUsedForManualResult( match: MatchDocument, gameResult: MatchGameResult, detail: RiotMatchDto, ): Promise { const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); await TournamentCodeModel.updateOne( { matchId: match._id, ...(gameResult.bracketMatchId ? { bracketMatchId: gameResult.bracketMatchId } : { gameNumber: gameResult.gameNumber }), state: { $in: ['reserved', 'released'] }, }, { $set: { state: 'used', usedAt: new Date( detail.info.gameEndTimestamp ?? detail.info.gameCreation, ), riotMatchId: detail.metadata.matchId, ...(gameResult.bracketMatchId ? { bracketMatchId: gameResult.bracketMatchId } : {}), }, }, ).exec(); } private buildSeriesResults( games: MatchGameResult[], ): NonNullable['seriesResults'] { 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 = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`; const current = bySeries.get(key) ?? { bracketMatchId: game.bracketMatchId, teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0, }; 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.bracketMatchId ?? '').localeCompare( right.bracketMatchId ?? '', ) || left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex, ); } private resolveSeriesRefForGameNumber( match: MatchDocument, gameNumber: number, ): { teamAIndex: number; teamBIndex: number } { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { const bracketMatch = match.doubleElimination?.bracketMatches.find( (entry) => entry.gameNumber === gameNumber, ); return bracketMatch ? { teamAIndex: bracketMatch.teamAIndex ?? 1, teamBIndex: bracketMatch.teamBIndex ?? 2, } : { teamAIndex: 1, teamBIndex: 2, }; } if (gameMode === 'round-robin') { const persisted = match.gameSchedule?.find( (entry) => entry.gameNumber === gameNumber, ); if (persisted) { return { teamAIndex: persisted.teamAIndex, teamBIndex: persisted.teamBIndex, }; } const fallback = this.buildRoundRobinGameSchedule(match).find( (entry) => entry.gameNumber === gameNumber, ); return fallback ? { teamAIndex: fallback.teamAIndex, teamBIndex: fallback.teamBIndex, } : { teamAIndex: 1, teamBIndex: 2, }; } const perSeries = match.gameCount || 1; const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); return { teamAIndex: (seriesIndex - 1) * 2 + 1, teamBIndex: (seriesIndex - 1) * 2 + 2, }; } private resolveRequiredGameSlots(match: MatchDocument): number { const gameMode = match.gameMode ?? 'pair'; if (gameMode === 'double-elimination') { return match.doubleElimination?.bracketMatches.length ?? 0; } if (gameMode === 'round-robin') { if ((match.gameSchedule?.length ?? 0) > 0) { return match.gameSchedule.length; } return this.buildRoundRobinGameSchedule(match).length; } const activeParticipantCount = match.participants.filter( (participant) => !participant.excluded, ).length; const participantSeriesCount = Math.floor(activeParticipantCount / 10); const teamSeriesCount = Math.ceil(match.teams.length / 2); const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount); return seriesCount * (match.gameCount || 1); } private buildRoundRobinGameSchedule(match: MatchDocument) { return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), { gamesPerPair: match.gameCount || 1, maxRounds: match.roundRobinMaxRounds, }); } private resolveMatchWinnerTeamIndex( seriesResults: NonNullable['seriesResults'], ): number | undefined { 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]; } private async updatePollState( match: MatchDocument, outcome: 'matched' | 'not-found' | 'failed', expandedToAllPuuids: boolean, ): Promise { match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: outcome, matchedCount: match.result?.games?.length ?? 0, expandedToAllPuuids, state: outcome === 'failed' ? 'failed' : 'polling', }; await match.save(); } private nextPollDelayMs(elapsedMs: number): number | null { if (elapsedMs >= POLL_EXPIRY_MS) return null; if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS; return LATER_POLL_DELAY_MS; } private resolveStartTime(match: MatchDocument): number { return Math.max( 0, Math.floor(match.teamBuiltAt!.getTime() / 1000) - TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, ); } private isReadyToPoll(match: MatchDocument): boolean { return Boolean( match.teamBuiltAt && match.tournamentCodeIds.length > 0 && match.teams.length >= 2 && match.teams.every((team) => team.members.length > 0), ); } private assertManualCollectionAllowed( match: MatchDocument, communityId: mongoose.Types.ObjectId, ): void { if (!match.communityId.equals(communityId)) { throw new BadRequestException('Match does not belong to this community.'); } if (!this.hasBuiltTeams(match)) { throw new BadRequestException( 'Match needs built teams before manual result collection.', ); } } private hasBuiltTeams(match: MatchDocument): boolean { return Boolean( match.teamBuiltAt && match.teams.length >= 2 && match.teams.every((team) => team.members.length > 0), ); } private async resolveRiotRegion( match: MatchDocument, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(match.communityId) .select({ riotRegion: 1 }) .lean() .exec(); return community?.riotRegion ?? 'asia'; } private async loadMatch( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = matchOrId instanceof mongoose.Types.ObjectId ? await MatchModel.findById(matchOrId) : await MatchModel.findById(matchOrId._id); if (!match) throw new NotFoundException('Match not found.'); return match; } private resolveMatchIdentifier( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): string { return matchOrId instanceof mongoose.Types.ObjectId ? matchOrId.toString() : matchOrId._id.toString(); } private tournamentResultPollProcessingLockKey(matchIdentifier: string): string { return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`; } private tournamentResultReadyCodeReservationLockKey( matchIdentifier: string, ): string { return `distributed-lock:tournament-result:reserve-ready-double-elimination-codes:match:${matchIdentifier}`; } } function isRiotMatchDto(value: unknown): value is RiotMatchDto { return Boolean( value && typeof value === 'object' && 'metadata' in value && 'info' in value, ); }