import { BadRequestException, Injectable, Logger, NotFoundException, } from '@nestjs/common'; import { createHash } from 'node:crypto'; import mongoose from 'mongoose'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { CompetitionBootstrapService, type CompetitionBootstrapMatch, } from '../competition/competition-bootstrap.service'; import { CompetitionCommandService } from '../competition/competition-command.service'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument, RiotMatch as StoredRiotMatch, TournamentCodeDocument, } from '../global/database/schema'; import { DistributedLockService } from '../global/redis/distributed-lock.service'; 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 { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; import { compareRiotGameChronology, hasAcceptedRiotMatch, mapRiotGameToCompetitionSlot, resolveReadyCompetitionSlot, type CompetitionResultGameSlotProjection, type CompetitionResultSnapshot, type MappedCompetitionRiotGame, } from './competition-result.adapter'; import { collectCaptainAndLimitedTeamMemberUserIds, collectCaptainUserIds, collectMatchUserIds, 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 RESULT_ACCEPT_ATTEMPTS = 2; 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_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 5 * 60_000; type CompetitionPersistenceDocument = { _id: mongoose.Types.ObjectId; revision: number; phase: string; teams: unknown[]; projection: Record; toObject?: () => unknown; }; type CodeAssignmentRecord = { competitionId: mongoose.Types.ObjectId; seriesId: mongoose.Types.ObjectId; gameSlotId: mongoose.Types.ObjectId; tournamentCodeId: mongoose.Types.ObjectId; state: 'reserved' | 'used' | 'released' | 'voided'; }; type AcceptanceOutcome = | { kind: 'accepted'; displayNumber: number; competition: CompetitionResultSnapshot; } | { kind: 'duplicate'; competition: CompetitionResultSnapshot } | { kind: 'unmatched'; competition: CompetitionResultSnapshot }; @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 distributedLockService: DistributedLockService, private readonly competitionBootstrapService: CompetitionBootstrapService, private readonly competitionCommandService: CompetitionCommandService, private readonly competitionAssignmentProvisioner: CompetitionAssignmentProvisioner, ) {} public async scheduleInitialPoll( matchOrId: MatchDocument | mongoose.Types.ObjectId, priority: RiotJobPriority = 'high', ): Promise { const matchIdentifier = this.resolveMatchIdentifier(matchOrId); const preparedMatchId = await this.distributedLockService.runWithLock( { lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier), lockExpirationDurationMilliseconds: TOURNAMENT_RESULT_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockAcquireTimeoutMilliseconds: 1_000, lockRetryDelayMilliseconds: 100, }, async () => this.prepareInitialPollWhileLockOwned(matchOrId), ); if (!preparedMatchId) return null; // A fast worker must not see the job while its preparation owns the same lock. return this.riotJobQueueService.enqueueTournamentResultPoll({ matchId: preparedMatchId, attempt: 1, expandedToAllPuuids: false, priority, }); } private async prepareInitialPollWhileLockOwned( matchOrId: MatchDocument | mongoose.Types.ObjectId, ): Promise { const match = await this.loadMatch(matchOrId); if (!this.isReadyToPoll(match)) return null; let competition = await this.ensureCompetition(match); competition = await this.provisionCompetitionAssignments( match, competition, ); if (competition.projection.phase === 'completed') return null; if (match.status === 'finished') match.status = 'in-progress'; match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, matchedCount: competition.projection.games.length, expandedToAllPuuids: false, state: 'polling', }; await match.save(); return match._id.toString(); } 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 and teamBuiltAt 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() / 1_000); const endTime = Math.floor(params.endTime.getTime() / 1_000); 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}: ${errorMessage(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 riotMatchId = params.riotMatchId.trim(); if (!riotMatchId) throw new BadRequestException('riotMatchId is required.'); const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); const detail = await this.ensureRiotMatchPersisted(riotMatchId, region); return this.applyManualRiotMatches(match, [detail], lookup); } public async cancelPolling( matchOrId: MatchDocument | mongoose.Types.ObjectId, session?: mongoose.ClientSession, ): Promise { const match = matchOrId instanceof mongoose.Types.ObjectId ? await this.loadMatch(matchOrId, session) : matchOrId; match.resultPollState = undefined; if (session) await match.save({ session }); else await match.save(); } public async processPollJob(job: PollTournamentResultJob): Promise { const didProcess = 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 (didProcess) return; throw new Error( `Tournament result poll job ${job.jobId} could not acquire the processing lock for match ${job.matchId}.`, ); } private async processPollJobWhileLockOwned( job: PollTournamentResultJob, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const match = await MatchModel.findById(job.matchId); if (!match) return; if (!this.isReadyToPoll(match)) { await this.updatePollState(match, 'failed', job.expandedToAllPuuids); return; } let competition = await this.ensureCompetition(match); competition = await this.provisionCompetitionAssignments( match, competition, ); const codes = await TournamentCodeModel.find({ matchId: match._id }) .sort({ gameNumber: 1 }) .exec(); const unmatchedCodes = codes.filter( (code) => code.state === 'reserved' && !code.riotMatchId, ); if (unmatchedCodes.length === 0) { await this.syncMatchLifecycle(match, competition); if (competition.projection.phase !== 'completed') { await this.scheduleNextPoll(match, competition, job); } return; } const region = await this.resolveRiotRegion(match); 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 checkedRiotMatchIds = new Set(); const unmatchedByCode = new Map( unmatchedCodes.map((code) => [code.code, code]), ); const collected: Array<{ detail: RiotMatchDto; code: TournamentCodeDocument; tournamentCode: string; }> = []; let matched = 0; for (const puuid of puuids) { let riotMatchIds: string[]; try { riotMatchIds = await this.riotMatchService.getMatchIdsByPuuid(puuid, { region, type: 'tourney', startTime: this.resolveStartTime(match), endTime: Math.floor(Date.now() / 1_000), count: 100, }); } catch (error) { this.logger.warn( `Tournament result match id lookup failed for ${puuid}: ${errorMessage(error)}`, ); continue; } for (const riotMatchId of riotMatchIds) { if (checkedRiotMatchIds.has(riotMatchId)) continue; checkedRiotMatchIds.add(riotMatchId); let detail: RiotMatchDto; try { detail = await this.ensureRiotMatchPersisted(riotMatchId, region); } catch (error) { this.logger.warn( `Tournament result detail fetch failed for ${riotMatchId}: ${errorMessage(error)}`, ); continue; } const tournamentCode = detail.info.tournamentCode?.trim(); if (!tournamentCode) continue; const code = unmatchedByCode.get(tournamentCode); if (!code) continue; collected.push({ detail, code, tournamentCode }); } } collected.sort((left, right) => compareRiotGameChronology(left.detail, right.detail), ); for (const candidate of collected) { if (unmatchedByCode.get(candidate.tournamentCode) !== candidate.code) { continue; } const outcome = await this.acceptRiotGame({ match, initialCompetition: competition, detail: candidate.detail, lookup, code: candidate.code, }); competition = outcome.competition; if (outcome.kind === 'accepted') matched += 1; if (outcome.kind !== 'unmatched') { unmatchedByCode.delete(candidate.tournamentCode); } } await this.updatePollState( match, matched > 0 ? 'matched' : 'not-found', job.expandedToAllPuuids, competition, ); await this.syncMatchLifecycle(match, competition); if (competition.projection.phase !== 'completed') { await this.scheduleNextPoll(match, competition, job); } } private async applyManualRiotMatches( match: MatchDocument, details: RiotMatchDto[], lookup: MatchPuuidLookup, ): Promise { const sortedDetails = [...details].sort(compareRiotGameChronology); let competition = await this.ensureCompetition(match); const riotMatchIds: string[] = []; const gameNumbers: number[] = []; let skipped = 0; for (const detail of sortedDetails) { const outcome = await this.acceptRiotGame({ match, initialCompetition: competition, detail, lookup, }); competition = outcome.competition; if (outcome.kind !== 'accepted') { skipped += 1; continue; } riotMatchIds.push(detail.metadata.matchId); gameNumbers.push(outcome.displayNumber); } match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: riotMatchIds.length > 0 ? 'matched' : 'not-found', matchedCount: competition.projection.games.length, expandedToAllPuuids: true, state: competition.projection.phase === 'completed' ? 'complete' : 'polling', }; await this.syncMatchLifecycle(match, competition); return { scanned: sortedDetails.length, matched: riotMatchIds.length, skipped, riotMatchIds, gameNumbers, }; } private async acceptRiotGame(params: { match: MatchDocument; initialCompetition: CompetitionResultSnapshot; detail: RiotMatchDto; lookup: MatchPuuidLookup; code?: TournamentCodeDocument; }): Promise { let competition = params.initialCompetition; for (let attempt = 1; attempt <= RESULT_ACCEPT_ATTEMPTS; attempt += 1) { if (hasAcceptedRiotMatch(competition, params.detail.metadata.matchId)) { return { kind: 'duplicate', competition }; } const declaredCode = params.code ?? (await this.findDeclaredTournamentCode(params.match, params.detail)); const target = declaredCode ? await this.resolveCodeTarget(competition, declaredCode) : undefined; const mapped = target ? mapRiotGameToCompetitionSlot({ competition, target, detail: params.detail, lookup: params.lookup, }) : declaredCode ? null : resolveReadyCompetitionSlot({ competition, detail: params.detail, lookup: params.lookup, }); if (!mapped) return { kind: 'unmatched', competition }; const manualCode = declaredCode ?? (await this.findCodeForMappedSlot(params.match, mapped)); if (manualCode && !params.code) { await this.ensureCodeAssignment(competition, manualCode, { id: mapped.gameSlotId, seriesId: mapped.seriesId, ordinal: mapped.ordinal, displayNumber: mapped.displayNumber, }); } try { const result = await this.competitionCommandService.acceptGame({ competitionId: objectId(competition.competitionId, 'Competition'), expectedRevision: competition.revision, idempotencyKey: `riot-result:${params.detail.metadata.matchId}`, actor: { type: 'system' }, occurredAt: mapped.occurredAt, gameId: objectId(mapped.gameId, 'Game'), seriesId: objectId(mapped.seriesId, 'Series'), gameSlotId: objectId(mapped.gameSlotId, 'GameSlot'), ordinal: mapped.ordinal, evidence: mapped.evidence, mapping: mapped.mapping, startedAt: mapped.startedAt, durationSeconds: mapped.durationSeconds, participants: mapped.normalizedParticipants, ...(manualCode ? { tournamentCode: { tournamentCodeId: manualCode._id, riotMatchId: params.detail.metadata.matchId, }, } : {}), }); competition = competitionSnapshot(result.competition); competition = await this.provisionCompetitionAssignments( params.match, competition, ); // acceptGame commits the stats rebuild to the durable Competition outbox. return { kind: 'accepted', displayNumber: mapped.displayNumber, competition, }; } catch (error) { if (attempt < RESULT_ACCEPT_ATTEMPTS && isStaleRevision(error)) { competition = await this.loadCompetition(competition.competitionId); continue; } throw error; } } return { kind: 'unmatched', competition }; } private async resolveCodeTarget( competition: CompetitionResultSnapshot, code: TournamentCodeDocument, ): Promise { const AssignmentModel = await this.connectionService.getModel( 'tournamentCodeAssignment', ); const existing = (await AssignmentModel.findOne({ competitionId: objectId(competition.competitionId, 'Competition'), tournamentCodeId: code._id, }) .lean() .exec()) as CodeAssignmentRecord | null; if (existing) { if (existing.state !== 'reserved') return undefined; return competition.projection.gameSlots.find( (slot) => slot.id === existing.gameSlotId.toString() && slot.status === 'ready', ); } if (!code.gameNumber) return undefined; const target = competition.projection.gameSlots.find( (slot) => slot.displayNumber === code.gameNumber && slot.status === 'ready', ); if (!target) return undefined; await this.ensureCodeAssignment(competition, code, target); return target; } private async ensureCodeAssignment( competition: CompetitionResultSnapshot, code: TournamentCodeDocument, target: Pick< CompetitionResultGameSlotProjection, 'id' | 'seriesId' | 'ordinal' | 'displayNumber' >, ): Promise { const AssignmentModel = await this.connectionService.getModel( 'tournamentCodeAssignment', ); const competitionId = objectId(competition.competitionId, 'Competition'); const seriesId = objectId(target.seriesId, 'Series'); const gameSlotId = objectId(target.id, 'GameSlot'); const commandId = `cutover-assignment:${code._id.toString()}:${target.id}:${competition.revision}`; await AssignmentModel.updateOne( { competitionId, tournamentCodeId: code._id, state: { $in: ['reserved', 'used'] }, }, { $setOnInsert: { _id: deterministicObjectId(commandId), competitionId, seriesId, gameSlotId, tournamentCodeId: code._id, state: 'reserved', reservedAt: code.reservedAt ?? new Date(), commandId, }, }, { upsert: true }, ).exec(); } private async findDeclaredTournamentCode( match: MatchDocument, detail: RiotMatchDto, ): Promise { const tournamentCode = detail.info.tournamentCode?.trim(); if (!tournamentCode) return undefined; const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const code = await TournamentCodeModel.findOne({ matchId: match._id, state: 'reserved', code: tournamentCode, }).exec(); return code ?? undefined; } private async findCodeForMappedSlot( match: MatchDocument, mapped: MappedCompetitionRiotGame, ): Promise { if (match.tournamentCodeIds.length === 0) return undefined; const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const code = await TournamentCodeModel.findOne({ _id: { $in: match.tournamentCodeIds }, matchId: match._id, state: 'reserved', gameNumber: mapped.displayNumber, }).exec(); return code ?? undefined; } private async ensureCompetition( match: MatchDocument, ): Promise { const document = await this.competitionBootstrapService.bootstrap( match as unknown as CompetitionBootstrapMatch, ); const snapshot = competitionSnapshot(document); match.competitionId = objectId(snapshot.competitionId, 'Competition'); return snapshot; } private async provisionCompetitionAssignments( match: MatchDocument, competition: CompetitionResultSnapshot, ): Promise { try { await this.competitionAssignmentProvisioner.provisionReadyAssignments({ matchId: match._id, competition, }); return competition; } catch (error) { if (!isAssignmentStaleRevision(error)) throw error; const current = await this.loadCompetition(competition.competitionId); await this.competitionAssignmentProvisioner.provisionReadyAssignments({ matchId: match._id, competition: current, }); return current; } } private async loadCompetition( competitionId: string, ): Promise { const CompetitionModel = await this.connectionService.getModel('competition'); const competition = await CompetitionModel.findById(competitionId) .lean() .exec(); if (!competition) throw new NotFoundException('Competition not found.'); return competitionSnapshot(competition); } private async syncMatchLifecycle( match: MatchDocument, competition: CompetitionResultSnapshot, ): Promise { if (competition.projection.phase === 'completed') { match.status = 'finished'; if (match.resultPollState) match.resultPollState.state = 'complete'; } else if ( (competition.projection.phase === 'running' && match.status === 'team-built') || match.status === 'finished' ) { match.status = 'in-progress'; } if (match.resultPollState) { match.resultPollState.matchedCount = competition.projection.games.length; } await match.save(); if (competition.projection.phase === 'completed') { void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { this.logger.warn( `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${errorMessage(error)}`, ); }); } } 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 }, { $set: payload }, { upsert: true }, ).exec(); await this.communityStatsService .refreshForRiotMatches([dto.metadata.matchId]) .catch((error: unknown) => { this.logger.warn( `Stats recovery failed after saving ${dto.metadata.matchId}: ${errorMessage(error)}`, ); }); 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}: ${errorMessage(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; puuidByUserId.set(participant.userId.toString(), 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.flatMap((userId) => { const puuid = lookup.puuidByUserId.get(userId.toString()); return puuid ? [puuid] : []; }), ), ]; } private async updatePollState( match: MatchDocument, outcome: 'matched' | 'not-found' | 'failed', expandedToAllPuuids: boolean, competition?: CompetitionResultSnapshot, ): Promise { match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: outcome, matchedCount: competition?.projection.games.length ?? match.resultPollState?.matchedCount ?? 0, expandedToAllPuuids, state: outcome === 'failed' ? 'failed' : 'polling', }; await match.save(); } private async scheduleNextPoll( match: MatchDocument, competition: CompetitionResultSnapshot, 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: competition.projection.games.length, 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 && competition.projection.games.length === 0); await this.riotJobQueueService.enqueueTournamentResultPoll({ matchId: match._id.toString(), attempt: job.attempt + 1, expandedToAllPuuids, priority: 'low', deferUntilMs: Date.now() + delayMs, }); } 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() / 1_000) - TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, ); } private isReadyToPoll(match: MatchDocument): boolean { return this.hasBuiltTeams(match); } 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, session?: mongoose.ClientSession, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const query = matchOrId instanceof mongoose.Types.ObjectId ? MatchModel.findById(matchOrId) : MatchModel.findById(matchOrId._id); const match = await (session ? query.session(session) : query); 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}`; } } function competitionSnapshot(value: unknown): CompetitionResultSnapshot { const raw = value && typeof value === 'object' && 'toObject' in value ? ((value as CompetitionPersistenceDocument).toObject?.() ?? value) : value; if (!isRecord(raw)) throw new Error('Competition snapshot is missing.'); const projection = raw.projection; if (!isRecord(projection)) throw new Error('Competition projection is missing.'); const competitionId = idString(raw._id); const revision = raw.revision; if (!competitionId || typeof revision !== 'number') { throw new Error('Competition identity or revision is invalid.'); } return { competitionId, revision, phase: String(raw.phase) as CompetitionResultSnapshot['phase'], teams: asArray(raw.teams).map((team) => ({ teamId: idString(asRecord(team).teamId), members: asArray(asRecord(team).members).map((member) => ({ userId: idString(asRecord(member).userId), })), })), projection: { phase: String( projection.phase, ) as CompetitionResultSnapshot['projection']['phase'], series: asArray(projection.series).map((series) => { const record = asRecord(series); return { seriesId: idString(record.seriesId), status: String( record.status, ) as CompetitionResultSnapshot['projection']['series'][number]['status'], entries: asArray(record.entries).map((entry) => { const row = asRecord(entry); return { slot: String(row.slot) as 'A' | 'B', teamId: row.teamId == null ? null : idString(row.teamId), gameWins: typeof row.gameWins === 'number' ? row.gameWins : 0, }; }), }; }), gameSlots: asArray(projection.gameSlots).map((slot) => { const record = asRecord(slot); return { id: idString(record.id), seriesId: idString(record.seriesId), ordinal: Number(record.ordinal), displayNumber: Number(record.displayNumber), status: String( record.status, ) as CompetitionResultGameSlotProjection['status'], }; }), games: asArray(projection.games).map((game) => { const evidence = asRecord(asRecord(game).evidence); return { evidence: { type: typeof evidence.type === 'string' ? evidence.type : undefined, riotMatchId: typeof evidence.riotMatchId === 'string' ? evidence.riotMatchId : undefined, }, }; }), }, }; } function objectId(value: string, label: string): mongoose.Types.ObjectId { if (!mongoose.Types.ObjectId.isValid(value)) { throw new Error(`${label} id is not a valid ObjectId.`); } return new mongoose.Types.ObjectId(value); } function deterministicObjectId(key: string): mongoose.Types.ObjectId { return new mongoose.Types.ObjectId( createHash('sha256').update(key).digest('hex').slice(0, 24), ); } function isStaleRevision(error: unknown): boolean { return isRecord(error) && error.code === 'STALE_COMPETITION_REVISION'; } function isAssignmentStaleRevision(error: unknown): boolean { return ( isRecord(error) && error.code === 'COMPETITION_ASSIGNMENT_STALE_REVISION' ); } function isRiotMatchDto(value: unknown): value is RiotMatchDto { return Boolean( value && typeof value === 'object' && 'metadata' in value && 'info' in value, ); } function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } function asRecord(value: unknown): Record { return isRecord(value) ? value : {}; } function asArray(value: unknown): unknown[] { return Array.isArray(value) ? value : []; } function idString(value: unknown): string { if (value instanceof mongoose.Types.ObjectId) return value.toString(); if (typeof value === 'string') return value; if (typeof value === 'number' || typeof value === 'bigint') { return String(value); } return ''; } function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); }