import { Injectable, Logger } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchDocument } from '../global/database/schema'; import { RiotMatchService } from '../riot/riot-match.service'; import { RIOT_REGIONAL_ROUTES, type RiotMatchDto, type RiotMatchTimelineDto, type RiotRegionalRoute, } from '../riot/riot.types'; import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; import { MatchStatsRepository } from './match-stats.repository'; import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; @Injectable() export class MatchStatsService { private readonly logger = new Logger(MatchStatsService.name); constructor( private readonly connectionService: ConnectionService, private readonly repository: MatchStatsRepository, private readonly builder: MatchStatsFragmentBuilder, private readonly riotMatchService: RiotMatchService, ) {} public async buildAndUpsert( matchId: mongoose.Types.ObjectId, options: { includeTimeline?: boolean; sourceRevision?: number } = {}, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const CompetitionModel = await this.connectionService.getModel('competition'); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const match = await MatchModel.findById(matchId).exec(); if (!match) return; const competition = await CompetitionModel.findOne({ matchId }) .lean() .exec(); if ( options.sourceRevision !== undefined && (!competition || competition.revision < options.sourceRevision) ) { return; } const competitionSource = competition ? competitionStatsSource(match, competition) : undefined; const sourceMatch = competitionSource?.match ?? match; if (!this.isEligible(sourceMatch)) { if (competitionSource) { await this.repository.deleteByMatch(matchId, { sourceCompetitionId: competitionSource.sourceCompetitionId, sourceRevision: competitionSource.sourceRevision, }); } else { await this.repository.deleteByMatch(matchId); } return; } const riotIds = competitionSource?.riotMatchIds ?? [ ...new Set( (match.result?.games ?? []) .map((game) => game.riotMatchId) .filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)), ), ]; const riotDocs = riotIds.length > 0 ? await RiotMatchModel.find({ matchId: { $in: riotIds } }) .lean() .exec() : []; const rawByRiotMatchId = new Map( riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), ); const timelineByRiotMatchId = new Map(); for (const doc of riotDocs) { if (isRiotMatchTimelineDto(doc.timeline)) { timelineByRiotMatchId.set(doc.matchId, doc.timeline); } } if ( options.includeTimeline && riotDocs.length > 0 && timelineByRiotMatchId.size < riotDocs.length ) { const region = await this.resolveRiotRegion(match.communityId); for (const doc of riotDocs) { if (timelineByRiotMatchId.has(doc.matchId)) continue; try { const timeline = await this.riotMatchService.getMatchTimeline( doc.matchId, { region }, ); await RiotMatchModel.updateOne( { matchId: doc.matchId }, { $set: { timeline: timeline as unknown as Record, timelineFetchedAt: new Date(), }, }, ).exec(); timelineByRiotMatchId.set(doc.matchId, timeline); } catch (error) { this.logger.warn( `Failed to fetch match timeline for ${doc.matchId}: ${ error instanceof Error ? error.message : error }`, ); } } } const fragment = this.builder.buildFragment({ match: sourceMatch, rawByRiotMatchId, timelineByRiotMatchId, timelineLoadAttempted: options.includeTimeline === true, }); await this.repository.upsert({ matchId: match._id, communityId: match.communityId, scheduledAt: match.scheduledAt, gameCreationMin: fragment.gameCreationMin, gameCreationMax: fragment.gameCreationMax, userIds: fragment.userIds, championIds: fragment.championIds, matchCard: fragment.matchCard as unknown as Record, records: fragment.records, gameDetails: fragment.gameDetails, builtAt: new Date(), builderVersion: MATCH_STATS_BUILDER_VERSION, ...(competitionSource ? { sourceCompetitionId: competitionSource.sourceCompetitionId, sourceRevision: competitionSource.sourceRevision, projectorVersion: competitionSource.projectorVersion, } : {}), }); // Source reads and the read-model write are intentionally separated by // Riot/timeline work. Revalidate after the write so a concurrent aggregate // deletion cannot resurrect MatchStats after the delete transaction. await this.removeFragmentIfSourceChanged(matchId, competitionSource); } public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise { await this.repository.deleteByMatch(matchId); } public async removeByMatches( matchIds: mongoose.Types.ObjectId[], ): Promise { await this.repository.deleteByMatches(matchIds); } public async backfillCommunity( communityId: mongoose.Types.ObjectId, ): Promise<{ processed: number; failed: number }> { const MatchModel = await this.connectionService.getModel('match'); const matches = await MatchModel.find({ communityId, status: { $in: ['finished', 'in-progress'] }, $or: [ { competitionId: { $exists: true } }, { 'result.games.0': { $exists: true } }, ], }) .sort({ scheduledAt: -1 }) .select({ _id: 1 }) .exec(); let processed = 0; let failed = 0; for (const match of matches) { try { await this.buildAndUpsert(match._id); processed += 1; } catch { failed += 1; } } return { processed, failed }; } private isEligible(match: MatchDocument): boolean { return ( (match.status === 'finished' || match.status === 'in-progress') && Boolean(match.result?.games?.length) ); } private async resolveRiotRegion( communityId: mongoose.Types.ObjectId, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(communityId) .select({ riotRegion: 1 }) .lean() .exec(); const region = community?.riotRegion; return RIOT_REGIONAL_ROUTES.includes(region as RiotRegionalRoute) ? (region as RiotRegionalRoute) : 'asia'; } private async removeFragmentIfSourceChanged( matchId: mongoose.Types.ObjectId, source: | { sourceCompetitionId: mongoose.Types.ObjectId; sourceRevision: number; } | undefined, ): Promise { const [MatchModel, CompetitionModel] = await Promise.all([ this.connectionService.getModel('match'), this.connectionService.getModel('competition'), ]); const [currentMatch, currentCompetition] = await Promise.all([ MatchModel.findById(matchId).exec(), CompetitionModel.findOne({ matchId, ...(source ? { _id: source.sourceCompetitionId, revision: source.sourceRevision, } : {}), }) .lean() .exec(), ]); if (source) { if (!currentMatch || !currentCompetition) { await this.repository.deleteByMatch(matchId, { sourceCompetitionId: source.sourceCompetitionId, sourceRevision: source.sourceRevision, }); } return; } if (!currentMatch || currentCompetition) { await this.repository.deleteLegacyByMatch(matchId); } } } function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto { if (!isRecord(value) || !isRecord(value.info)) return false; return Array.isArray(value.info.frames); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null; } function competitionStatsSource( match: MatchDocument, competition: { _id: mongoose.Types.ObjectId; revision: number; projectorVersion: number; teams: unknown[]; projection: Record; }, ): { match: MatchDocument; riotMatchIds: string[]; sourceCompetitionId: mongoose.Types.ObjectId; sourceRevision: number; projectorVersion: number; } { const teamIndexById = new Map(); for (const rawTeam of competition.teams) { if (!isRecord(rawTeam)) continue; const teamId = identifier(rawTeam.teamId); const legacyTeamIndex = finiteNumber(rawTeam.legacyTeamIndex); const displayOrder = finiteNumber(rawTeam.displayOrder); if (teamId && (legacyTeamIndex ?? displayOrder)) { teamIndexById.set(teamId, legacyTeamIndex ?? displayOrder!); } } const rawGames = Array.isArray(competition.projection.games) ? competition.projection.games : []; const riotMatchIds = new Set(); const games = rawGames.flatMap((rawGame, gameIndex) => { if (!isRecord(rawGame)) return []; const teams = isRecord(rawGame.teams) ? rawGame.teams : undefined; const blue = teams && isRecord(teams.blue) ? teams.blue : undefined; const red = teams && isRecord(teams.red) ? teams.red : undefined; const blueTeamId = identifier(blue?.teamId); const redTeamId = identifier(red?.teamId); const winnerTeamId = identifier(rawGame.winnerTeamId); const blueTeamIndex = blueTeamId ? teamIndexById.get(blueTeamId) : undefined; const redTeamIndex = redTeamId ? teamIndexById.get(redTeamId) : undefined; const winnerTeamIndex = winnerTeamId ? teamIndexById.get(winnerTeamId) : undefined; if (!blueTeamIndex || !redTeamIndex || !winnerTeamIndex) return []; const evidence = isRecord(rawGame.evidence) ? rawGame.evidence : undefined; const riotMatchId = evidence?.type === 'riot' && typeof evidence.riotMatchId === 'string' ? evidence.riotMatchId : typeof evidence?.legacyReference === 'string' ? evidence.legacyReference : `competition:${identifier(rawGame.id) ?? 'game'}`; if (evidence?.type === 'riot') riotMatchIds.add(riotMatchId); const participantValues = Array.isArray(rawGame.participants) ? rawGame.participants : []; const participants = participantValues.flatMap((rawParticipant) => { if (!isRecord(rawParticipant)) return []; const userId = identifier(rawParticipant.userId); const teamId = identifier(rawParticipant.teamId); const teamIndex = teamId ? teamIndexById.get(teamId) : undefined; const side = rawParticipant.side; if ( !userId || !mongoose.isValidObjectId(userId) || !teamIndex || (side !== 'blue' && side !== 'red') ) { return []; } return [ { userId: new mongoose.Types.ObjectId(userId), teamIndex, side, championId: finiteNumber(rawParticipant.championId) ?? 0, kills: finiteNumber(rawParticipant.kills) ?? 0, deaths: finiteNumber(rawParticipant.deaths) ?? 0, assists: finiteNumber(rawParticipant.assists) ?? 0, win: teamId === winnerTeamId, }, ]; }); const startedAt = dateFromUnknown(rawGame.startedAt); return [ { gameNumber: finiteNumber(rawGame.displayNumber) ?? gameIndex + 1, riotMatchId, blueTeamIndex, redTeamIndex, winnerTeamIndex, winnerSide: winnerTeamIndex === blueTeamIndex ? ('blue' as const) : ('red' as const), gameCreation: Number.isNaN(startedAt.getTime()) ? 0 : startedAt.getTime(), gameDuration: finiteNumber(rawGame.durationSeconds) ?? 0, participants, }, ]; }); const base = typeof match.toObject === 'function' ? match.toObject() : { ...match }; return { match: { ...base, status: competition.projection.phase === 'completed' ? 'finished' : games.length > 0 ? 'in-progress' : match.status, result: { riotMatchIds: games.map(({ riotMatchId }) => riotMatchId), games, seriesResults: [], }, } as unknown as MatchDocument, riotMatchIds: [...riotMatchIds], sourceCompetitionId: competition._id, sourceRevision: competition.revision, projectorVersion: competition.projectorVersion, }; } function identifier(value: unknown): string | undefined { if (typeof value === 'string' && value.length > 0) return value; if (value instanceof mongoose.Types.ObjectId) return value.toHexString(); return undefined; } function dateFromUnknown(value: unknown): Date { if (value instanceof Date) return new Date(value.getTime()); if (typeof value === 'string' || typeof value === 'number') { return new Date(value); } return new Date(Number.NaN); } function finiteNumber(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? value : undefined; }