import type { CompetitionGameView, GameAnalysisAvailability, InternalMatchCompetition, InternalMatchResultPresentation, } from '@lolympus/contracts'; import { BadRequestException, Injectable, Logger, NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { presentCompetitionDetail } from '../competition/competition.presenter'; import type { Competition } from '../competition/competition.schema'; import { ConnectionService } from '../global/database/connection.service'; import type { CommunityDocument, MatchStatsDocument, RiotLane, } from '../global/database/schema'; import type { HistorySeasonDto, RecentMatchView, } from '../match-history/match-history.types'; import { CommunityStatsCacheKey, CommunityStatsCacheService, } from './community-stats-cache.service'; import type { CommunityStatsFilters, InternalMatchCardView, InternalMatchDetailResponse, InternalMatchListResponse, LeaderboardChampionStats, LeaderboardResponse, LeaderboardRow, LeaderHighlight, TeamInsightsResponse, UserInternalHistoryResponse, } from './community-stats.types'; import { MatchStatsDetailFragment, MatchStatsRepository, MatchStatsUserRecordFragment, } from './match-stats.repository'; import { MatchStatsService } from './match-stats.service'; import { presentStatsCard, statsDate } from './internal-stats-presentation'; import { InternalGameDetail, InternalRecord, MATCH_STATS_BUILDER_VERSION, } from './match-stats.types'; const DEFAULT_LIST_LIMIT = 20; const MAX_LIST_LIMIT = 50; const MAX_MATCH_SCAN = 300; const MIN_HIGHLIGHT_GAMES = 5; const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 9; const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60; interface CommunityStatsContext { community: CommunityDocument; season: HistorySeasonDto; from: Date | null; to: Date | null; } interface BaseDataset { season: HistorySeasonDto; matches: InternalMatchCardView[]; records: InternalRecord[]; detailsByMatchId: Map; competition?: InternalMatchCompetition; } interface CachedMatchPage extends Omit { cards: Array<{ card: InternalMatchCardView; sourceCompetitionId?: string; sourceRevision?: number; }>; } @Injectable() export class CommunityStatsService { private readonly logger = new Logger(CommunityStatsService.name); private readonly matchDetailInFlight = new Map< string, Promise >(); private readonly userInternalHistoryInFlight = new Map< string, Promise >(); private readonly fragmentRepairs = new Map>(); private readonly rawRecoveryRetryAfter = new Map(); constructor( private readonly connectionService: ConnectionService, private readonly cacheService: CommunityStatsCacheService, private readonly matchStatsRepository: MatchStatsRepository, private readonly matchStatsService: MatchStatsService, ) {} public async getMatches(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey('matches', params.communityId, params.filters); const cached = await this.cacheService.get(key); const page = cached ?? (await this.loadMatchPage(params.communityId, params.filters)); if (!cached) await this.cacheService.set(key, page); const { cards, ...pagination } = page; if (cards.length === 0) return { ...pagination, matches: [] }; const matchIds = cards.map( ({ card }) => new mongoose.Types.ObjectId(card.matchId), ); const CompetitionModel = await this.connectionService.getModel('competition'); const competitions = await CompetitionModel.find({ communityId: params.communityId, matchId: { $in: matchIds }, }) .select({ matchId: 1, communityId: 1, schemaVersion: 1, revision: 1, phase: 1, format: 1, createdAt: 1, updatedAt: 1, 'teams.teamId': 1, 'teams.name': 1, 'teams.displayOrder': 1, 'projection.phase': 1, 'projection.formatType': 1, 'projection.outcome': 1, 'projection.series': 1, 'projection.games': 1, }) .lean() .exec(); const official = new Map( competitions.map((competition) => [ competition.matchId.toString(), this.presentOfficialResult(competition), ]), ); const sources = new Map( competitions.map((source) => [source.matchId.toString(), source]), ); return { ...pagination, matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => { const resultPresentation = official.get(card.matchId) ?? { type: sourceCompetitionId ? ('unavailable' as const) : ('legacy' as const), }; const canUseGames = resultPresentation.type === 'legacy' || (resultPresentation.type === 'official' && sourceCompetitionId === resultPresentation.competitionId && sourceRevision === resultPresentation.sourceRevision); const presented = { ...(canUseGames ? card : this.adjustCardForRange(card, [])), resultPresentation, }; const source = sources.get(card.matchId); return source && canUseGames ? presentStatsCard( presented, presentCompetitionDetail({ ...source, teams: source.teams.map((team) => ({ ...team, members: [] })), }), ) : presented; }), }; } private async loadMatchPage( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): Promise { const limit = this.clampLimit( filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT, ); const context = await this.resolveContext(communityId, filters); await this.repairCommunityFragments(communityId); const page = await this.matchStatsRepository.findMatchPage({ ...filters, communityId, from: context.from?.getTime(), to: context.to?.getTime(), limit: limit + 1, }); const visible = page.slice(0, limit); const last = page.length > limit ? visible.at(-1) : undefined; return { cards: visible.map((fragment) => ({ card: this.adjustCardForRange( { ...(fragment.matchCard as unknown as InternalMatchCardView), games: ( fragment.matchCard as unknown as InternalMatchCardView ).games.map((game) => { const detail = fragment.gameDetails?.find( (item) => item.gameNumber === game.gameNumber, ); return { ...game, analysisAvailability: !detail ? ('pending' as const) : detail.rawAvailable === false ? ('missing' as const) : ('available' as const), }; }), }, (fragment.gameDetails ?? []).filter((game) => this.isGameInRange(game.gameCreation, context), ), ), sourceCompetitionId: fragment.sourceCompetitionId?.toString(), sourceRevision: fragment.sourceRevision, })), nextCursor: last?.scheduledAt.getTime() ?? null, nextCursorMatchId: last?.matchId.toString(), season: context.season, }; } public async getSeasons(communityId: mongoose.Types.ObjectId) { const { community } = await this.resolveContext(communityId, {}); return { seasons: this.resolveSeasons(community) }; } public async getLeaderboard(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const { query, ...filters } = params.filters; const key = this.cacheKey('leaderboard', params.communityId, filters); let response = await this.cacheService.get(key); if (!response) { const dataset = await this.buildSeasonDataset( params.communityId, filters, ); const records = this.applyChampionFilter(dataset.records, filters); response = { rows: this.buildLeaderboardRows(records), lane: filters.lane, season: dataset.season, }; await this.cacheService.set(key, response); } const keyword = query?.toLocaleLowerCase('ko-KR'); if (!keyword) return response; return { ...response, matchedUserIds: response.rows .filter(({ summonerName, tagLine }) => (tagLine ? summonerName + '#' + tagLine : summonerName) .toLocaleLowerCase('ko-KR') .includes(keyword), ) .map(({ userId }) => userId), }; } public async getTeamInsights(params: { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( 'teamInsights', params.communityId, params.filters, ); const cached = await this.cacheService.get(key); if (cached) return cached; const dataset = await this.buildSeasonDataset( params.communityId, params.filters, ); const records = this.applyChampionFilter(dataset.records, params.filters); const rows = this.buildLeaderboardRows(records); const gameDetails = dataset.gameDetails; const blueGames = gameDetails.length; const redGames = gameDetails.length; const blueWins = gameDetails.filter( (game) => game.winnerSide === 'blue', ).length; const redWins = gameDetails.filter( (game) => game.winnerSide === 'red', ).length; const confirmedGames = blueWins + redWins; const response: TeamInsightsResponse = { season: dataset.season, totals: dataset.totals, sideWinRate: { blue: this.percent(blueWins, blueGames), red: this.percent(redWins, redGames), bluePicks: blueGames, redPicks: redGames, confirmed: { sampleSize: confirmedGames, blue: this.percent(blueWins, confirmedGames), red: this.percent(redWins, confirmedGames), }, }, topKda: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort((left, right) => right.kda - left.kda)[0], 'kda', ), mostKills: this.toHighlight( rows.sort((left, right) => right.totalKills - left.totalKills)[0], 'totalKills', ), topTeamGpm: this.toSingleGameHighlight( records.sort((left, right) => right.gpm - left.gpm)[0], 'gpm', ), topKillParticipation: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort( (left, right) => right.avgKillParticipation - left.avgKillParticipation, )[0], 'avgKillParticipation', ), bestFarm: this.toHighlight( rows .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) .sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0], 'avgCsPerMin', ), minGamesThreshold: MIN_HIGHLIGHT_GAMES, }; await this.cacheService.set(key, response); return response; } public async getMatchDetail(params: { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }): Promise { const revision = await this.getDetailRevision( params.communityId, params.matchId, ); const key = new CommunityStatsCacheKey( params.communityId.toString(), 'matchDetail', `v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}:${revision}`, ); const cached = await this.cacheService.get(key); if ( cached && isCompleteMatchDetailResponse(cached) && (!this.canRetryRawRecovery(key) || !(await this.hasArchivedMissingRaw(cached.games, cached.competition))) ) { return cached; } const identity = key.identity; const inFlight = this.matchDetailInFlight.get(identity); if (inFlight) return inFlight; const promise = this.buildMatchDetailResponse(params, key); this.matchDetailInFlight.set(identity, promise); try { return await promise; } finally { if (this.matchDetailInFlight.get(identity) === promise) { this.matchDetailInFlight.delete(identity); } } } private async getDetailRevision( communityId: mongoose.Types.ObjectId, matchId: mongoose.Types.ObjectId, ): Promise { const CompetitionModel = await this.connectionService.getModel('competition'); const source = await CompetitionModel.findOne({ communityId, matchId }) .select({ _id: 1, revision: 1, projectorVersion: 1 }) .lean() .exec(); return source ? `${source._id.toString()}:${source.revision}:${source.projectorVersion}` : 'legacy'; } private async buildMatchDetailResponse( params: { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; }, key: CommunityStatsCacheKey, ): Promise { let dataset = await this.buildBaseDataset( params.communityId, { seasonId: 'all', }, params.matchId, ); let match = dataset.matches.find( (item) => item.matchId === params.matchId.toString(), ); if (!match) throw new NotFoundException('Internal match not found.'); let games = linkDetailGames(dataset, match.matchId); const missingBefore = new Set( games .filter( ({ analysisAvailability }) => analysisAvailability === 'missing', ) .map(({ game }) => game.riotMatchId), ); const rawRestored = this.canRetryRawRecovery(key) && (await this.hasArchivedMissingRaw( games.map(({ game, official, analysisAvailability }) => ({ riotMatchId: game.riotMatchId, gameId: official?.id, analysisAvailability, })), dataset.competition, )); let canCacheResponse = true; if (rawRestored || games.some(needsDetailHydration)) { if (rawRestored) this.deferRawRecovery(key); await this.matchStatsService.buildAndUpsert(params.matchId, { includeTimeline: true, }); const refreshedDataset = await this.buildBaseDataset( params.communityId, { seasonId: 'all', }, params.matchId, ); const refreshedMatch = refreshedDataset.matches.find( (item) => item.matchId === params.matchId.toString(), ); if (!refreshedMatch) throw new NotFoundException('Internal match not found.'); dataset = refreshedDataset; match = refreshedMatch; games = linkDetailGames(dataset, match.matchId); const rawImproved = games.some( ({ game, analysisAvailability }) => missingBefore.has(game.riotMatchId) && analysisAvailability === 'available', ); if (rawImproved) { canCacheResponse = await this.cacheService.invalidateCommunityWithRetry( params.communityId.toString(), ); if (canCacheResponse) { try { // Read the new generation before caching the rebuilt response. await this.cacheService.get(key); } catch (error) { canCacheResponse = false; this.logger.warn( `Stats detail cache refresh failed: ${String(error)}`, ); } } } if ( !games.some( ({ game, analysisAvailability }) => missingBefore.has(game.riotMatchId) && analysisAvailability === 'missing', ) ) { this.rawRecoveryRetryAfter.delete(key.field); } } const response: InternalMatchDetailResponse = { match: presentStatsCard( { ...match, games: (match.games ?? []).map((game) => ({ ...game, analysisAvailability: games.find((linked) => linked.game.gameNumber === game.gameNumber) ?.analysisAvailability ?? 'pending', })), }, dataset.competition, ), competition: dataset.competition, games: games.map(({ game, official, analysisAvailability }) => ({ gameNumber: game.gameNumber, analysisAvailability, ...(official ? { gameId: official.id, gameSlotId: official.gameSlotId, seriesId: official.seriesId, ordinal: official.ordinal, } : {}), riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, gameVersion: game.gameVersion, timeline: game.timeline ?? [], objectiveEvents: game.objectiveEvents ?? [], timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [], teams: game.teams.map((team) => ({ teamIndex: team.teamIndex, side: team.side, win: team.win, objectives: team.objectives, bans: team.bans ?? [], participants: team.participants.map((record) => ({ participantId: record.participantId, checkpoints: record.checkpoints, userId: record.userId, summonerName: record.summonerName, tagLine: record.tagLine, teamIndex: record.teamIndex, side: record.side, teamPosition: record.teamPosition, championId: record.championId, championLevel: record.championLevel, kills: record.kills, deaths: record.deaths, assists: record.assists, cs: record.cs, csPerMin: record.csPerMin, gold: record.gold, gpm: record.gpm, damageDealtToChampions: record.damageDealtToChampions, damageTaken: record.damageTaken, damageShare: record.damageShare, killParticipation: record.killParticipation, visionScore: record.visionScore, wardsPlaced: record.wardsPlaced, wardsKilled: record.wardsKilled, controlWardsBought: record.controlWardsBought, firstBloodKill: record.firstBloodKill ?? false, firstBloodAssist: record.firstBloodAssist ?? false, items: record.items, trinket: record.trinket, summonerSpells: record.summonerSpells, perks: record.perks, itemBuild: record.itemBuild ?? [], skillBuild: record.skillBuild ?? [], win: record.win, })), })), })), }; if (!canCacheResponse) return response; if ( !games.some(needsDetailHydration) && (!dataset.competition || response.games.length === dataset.competition.projection.games.length) ) { await this.cacheService.setDetail(key, response); } else { await this.cacheService.set( key, response, INCOMPLETE_MATCH_DETAIL_TTL_SECONDS, ); } return response; } public async getUserInternalHistory(params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { const key = this.cacheKey( `userInternal:v3:${params.userId.toString()}`, params.communityId, params.filters, ); const cached = await this.cacheService.get(key); if (cached) return cached; // Auction viewers can all request the same next player's internal history // at once. Coalesce local cache misses so one player change does one DB read. const inFlight = this.userInternalHistoryInFlight.get(key.identity); if (inFlight) return inFlight; const promise = this.buildUserInternalHistoryResponse(params, key); this.userInternalHistoryInFlight.set(key.identity, promise); try { return await promise; } finally { if (this.userInternalHistoryInFlight.get(key.identity) === promise) { this.userInternalHistoryInFlight.delete(key.identity); } } } public async refreshForRiotMatches(riotMatchIds: string[]): Promise { if (riotMatchIds.length === 0) return; const RiotMatchModel = await this.connectionService.getModel('riotMatch'); const archived = await RiotMatchModel.find({ matchId: { $in: [...new Set(riotMatchIds)] }, 'raw.info': { $exists: true }, }) .select({ matchId: 1 }) .lean() .exec(); const ids = new Set(archived.map((match) => match.matchId)); if (ids.size === 0) return; const fragments = await this.matchStatsRepository.findByRiotMatchIds([ ...ids, ]); const communityIds = new Map(); for (const fragment of fragments) { const missingIds = new Set( fragment.gameDetails .filter( (game) => ids.has(game.riotMatchId) && game.rawAvailable === false, ) .map((game) => game.riotMatchId), ); if (missingIds.size === 0) continue; try { // Raw enrichment must run even when the Competition revision is current. await this.matchStatsService.buildAndUpsert(fragment.matchId); } catch (error) { this.logger.warn( `Stats recovery failed for ${fragment.matchId.toString()}: ${String(error)}`, ); } try { // A builder can return without writing, or fail during post-write checks. // Only actual enrichment should cause a community-wide invalidation. const updated = await this.matchStatsRepository.findByMatch( fragment.matchId, ); if ( updated?.gameDetails.some( (game) => missingIds.has(game.riotMatchId) && game.rawAvailable === true, ) ) { communityIds.set( fragment.communityId.toString(), fragment.communityId, ); } } catch (error) { this.logger.warn( `Could not verify stats recovery for ${fragment.matchId.toString()}: ${String(error)}`, ); } } for (const communityId of communityIds.values()) { await this.cacheService.invalidateCommunityWithRetry( communityId.toString(), ); } } private canRetryRawRecovery(key: CommunityStatsCacheKey): boolean { return (this.rawRecoveryRetryAfter.get(key.field) ?? 0) <= Date.now(); } private deferRawRecovery(key: CommunityStatsCacheKey): void { const now = Date.now(); for (const [field, retryAt] of this.rawRecoveryRetryAfter) { if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field); } if (this.rawRecoveryRetryAfter.size >= 1000) { const oldest = this.rawRecoveryRetryAfter.keys().next(); if (!oldest.done) this.rawRecoveryRetryAfter.delete(oldest.value); } this.rawRecoveryRetryAfter.set( key.field, now + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS * 1000, ); } private async hasArchivedMissingRaw( games: Array< Pick< InternalMatchDetailResponse['games'][number], 'riotMatchId' | 'gameId' | 'analysisAvailability' > >, competition?: InternalMatchCompetition, ): Promise { const officialById = new Map( competition?.projection.games.map((game) => [game.id, game]), ); const ids = games .filter( (game) => game.analysisAvailability === 'missing' && (!competition || (game.gameId && officialById.get(game.gameId)?.evidence.type === 'riot')), ) .map((game) => game.riotMatchId); if (ids.length === 0) return false; const RiotMatchModel = await this.connectionService.getModel('riotMatch'); return Boolean( await RiotMatchModel.exists({ matchId: { $in: ids }, 'raw.info': { $exists: true }, }).exec(), ); } public invalidateCommunity( communityId: mongoose.Types.ObjectId, ): Promise { return this.cacheService.invalidateCommunity(communityId.toString()); } private async buildSeasonDataset( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ) { const context = await this.resolveContext(communityId, filters); await this.repairCommunityFragments(communityId); const fragments = await this.matchStatsRepository.findSeasonStats({ communityId, from: context.from?.getTime(), to: context.to?.getTime(), }); const gameDetails: Array> = []; const records: InternalRecord[] = []; const participants = new Set(); let matches = 0, analyzedGames = 0; for (const fragment of fragments) { const games = fragment.gameDetails.filter((game) => this.isGameInRange(game.gameCreation, context), ); if (games.length) matches += 1; const gameNumbers = new Set( games .filter((game) => game.rawAvailable !== false) .map(({ gameNumber }) => gameNumber), ); analyzedGames += gameNumbers.size; const allNumbers = new Set(games.map((game) => game.gameNumber)); fragment.records .filter((record) => allNumbers.has(record.gameNumber)) .forEach((record) => participants.add(record.userId)); gameDetails.push(...games); records.push( ...fragment.records.filter(({ gameNumber }) => gameNumbers.has(gameNumber), ), ); } return { season: context.season, records, gameDetails, totals: { matches, games: gameDetails.length, analyzedGames, players: participants.size, }, }; } private async buildBaseDataset( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, matchId: mongoose.Types.ObjectId, ): Promise { const context = await this.resolveContext(communityId, filters); const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findOne({ _id: matchId, communityId }) .lean() .exec(); if (!match) throw new NotFoundException('Internal match not found.'); const CompetitionModel = await this.connectionService.getModel('competition'); const [source, stored] = await Promise.all([ CompetitionModel.findOne({ matchId, communityId }).lean().exec(), this.matchStatsRepository.findByMatch(matchId), ]); const isCurrent = (fragment: MatchStatsDocument | null) => Boolean( fragment?.communityId.equals(communityId) && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION && (source ? fragment.sourceCompetitionId?.equals(source._id) && fragment.sourceRevision === source.revision && fragment.projectorVersion === source.projectorVersion : !fragment.sourceCompetitionId && !match.competitionId), ); let fragment = stored; if (!isCurrent(fragment) && (source || match.result?.games.length)) { await this.matchStatsService.buildAndUpsert(matchId); fragment = await this.matchStatsRepository.findByMatch(matchId); } if (!isCurrent(fragment)) fragment = null; if (!fragment && !source && !match.competitionId) { throw new NotFoundException('Internal match not found.'); } const competition = source && presentCompetitionDetail({ ...source, teams: source.teams.map((team) => ({ ...team, members: team.members.map((member) => ({ ...member })), })), }); const resultPresentation: InternalMatchResultPresentation = source ? this.presentOfficialResult(source) : { type: match.competitionId ? 'unavailable' : 'legacy' }; const card = (fragment?.matchCard as unknown as | InternalMatchCardView | undefined) ?? { matchId: matchId.toString(), title: match.title, scheduledAt: match.scheduledAt.toISOString(), status: match.status === 'finished' ? 'finished' : 'in-progress', gameCount: match.gameCount, seriesResults: [], games: [], teams: match.teams.map(({ teamIndex, name }) => ({ teamIndex, name, members: [], })), }; return { season: context.season, matches: [{ ...card, resultPresentation }], records: fragment?.records ?? [], detailsByMatchId: new Map([ [matchId.toString(), fragment?.gameDetails ?? []], ]), competition: competition ? { id: competition.id, revision: competition.revision, teams: competition.teams, projection: competition.projection, } : undefined, }; } private presentOfficialResult( source: Competition & { _id: mongoose.Types.ObjectId }, ): InternalMatchResultPresentation { const competition = presentCompetitionDetail({ ...source, teams: source.teams.map((team) => ({ ...team, members: [] })), }); const { projection } = competition; return { type: 'official', competitionId: competition.id, sourceRevision: competition.revision, phase: projection.phase, formatType: projection.formatType, teams: competition.teams.map(({ teamId, name }) => ({ teamId, name })), completedSeriesCount: projection.series.filter( ({ status }) => status === 'completed', ).length, outcome: projection.outcome, singleSeries: projection.formatType === 'paired-series' && projection.series.length === 1 ? projection.series[0] : undefined, }; } private async buildUserInternalHistoryResponse( params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }, cacheKey: CommunityStatsCacheKey, ): Promise { const context = await this.resolveContext( params.communityId, params.filters, ); const userId = params.userId.toString(); const fragmentQuery = { communityId: params.communityId, userId: params.userId, fromGameCreation: context.from?.getTime(), toGameCreation: context.to?.getTime(), // The inspector needs the latest 20 of each lane, even in older events. limit: params.filters.includePositionCounts ? 0 : MAX_MATCH_SCAN, }; let fragments = await this.matchStatsRepository.findUserRecordFragments(fragmentQuery); const stale = fragments.filter( (fragment) => fragment.builderVersion < MATCH_STATS_BUILDER_VERSION, ); if (stale.length > 0) { for (const { matchId } of stale) { await this.matchStatsService.buildAndUpsert(matchId); } fragments = await this.matchStatsRepository.findUserRecordFragments(fragmentQuery); } const allUserRecords = this.extractUserRecords(fragments, userId, context); const records = this.applyChampionFilter(allUserRecords, params.filters); const limit = this.clampLimit(params.filters.limit, 30, 50); const cursor = params.filters.cursor; const page = records .filter((record) => !cursor || record.gameCreation < cursor) .slice(0, limit + 1); const visible = page.slice(0, limit); const detailsByMatchId = await this.loadVisibleDetails( params.communityId, visible, context, ); const dataset: BaseDataset = { season: context.season, matches: [], records: allUserRecords, detailsByMatchId, }; const response: UserInternalHistoryResponse = { season: context.season, ...(params.filters.includePositionCounts ? { positionCounts: Object.fromEntries( ['ALL', 'TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].map( (lane) => [ lane, Math.min( 20, this.applyChampionFilter(allUserRecords, { championId: params.filters.championId, }).filter( (record) => lane === 'ALL' || record.teamPosition === lane, ).length, ), ], ), ), } : {}), playerStats: records.length ? this.toLeaderboardRow(userId, records) : null, championStats: this.buildUserChampionStats( this.applyChampionFilter(allUserRecords, { lane: params.filters.lane }), context.season, ), summary: this.buildUserSummary(records, visible.length || limit), matches: visible.map((record) => this.toRecentMatchView(record, dataset)), nextCursor: page.length > limit ? (visible[visible.length - 1]?.gameCreation ?? null) : null, lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, }; await this.cacheService.set(cacheKey, response); return response; } private extractUserRecords( fragments: MatchStatsUserRecordFragment[], userId: string, context: CommunityStatsContext, ): InternalRecord[] { return fragments .flatMap((fragment) => fragment.records.filter( (record) => record.userId === userId && !fragment.gameDetails?.some( (game) => game.gameNumber === record.gameNumber && game.rawAvailable === false, ) && this.isGameInRange(record.gameCreation, context), ), ) .sort((left, right) => right.gameCreation - left.gameCreation); } private async loadVisibleDetails( communityId: mongoose.Types.ObjectId, visible: InternalRecord[], context: CommunityStatsContext, ): Promise> { const matchIds = [ ...new Set( visible .map((record) => record.matchId) .filter((matchId) => mongoose.isValidObjectId(matchId)), ), ].map((matchId) => new mongoose.Types.ObjectId(matchId)); const fragments = await this.matchStatsRepository.findDetailsByMatches({ communityId, matchIds, }); return this.toDetailsByMatchId(fragments, context); } private toDetailsByMatchId( fragments: MatchStatsDetailFragment[], context: CommunityStatsContext, ): Map { const detailsByMatchId = new Map(); for (const fragment of fragments) { detailsByMatchId.set( fragment.matchId.toString(), fragment.gameDetails.filter((game) => this.isGameInRange(game.gameCreation, context), ), ); } return detailsByMatchId; } private async rebuildMissingOrStaleFragments( communityId: mongoose.Types.ObjectId, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const [matches, fragments] = await Promise.all([ MatchModel.find({ communityId, status: { $in: ['finished', 'in-progress'] }, $or: [ { competitionId: { $exists: true } }, { 'result.games.0': { $exists: true } }, ], }) .sort({ scheduledAt: -1 }) .limit(MAX_MATCH_SCAN) .select({ _id: 1, competitionId: 1 }) .exec(), this.matchStatsRepository.findByCommunity({ communityId, limit: MAX_MATCH_SCAN, }), ]); const fragmentByMatchId = new Map( fragments.map((fragment) => [fragment.matchId.toString(), fragment]), ); const competitionIds = matches.flatMap((match) => match.competitionId ? [match.competitionId] : [], ); const CompetitionModel = await this.connectionService.getModel('competition'); const competitions = competitionIds.length > 0 ? await CompetitionModel.find({ _id: { $in: competitionIds } }) .select({ _id: 1, revision: 1, projectorVersion: 1 }) .lean() .exec() : []; const competitionById = new Map( competitions.map((competition) => [ competition._id.toString(), competition, ]), ); let rebuilt = 0; for (const match of matches) { const fragment = fragmentByMatchId.get(match._id.toString()); const competition = match.competitionId ? competitionById.get(match.competitionId.toString()) : undefined; const sourceIsCurrent = match.competitionId ? Boolean( competition && fragment?.sourceCompetitionId?.toString() === competition._id.toString() && (fragment.sourceRevision ?? -1) >= competition.revision && (fragment.projectorVersion ?? -1) >= competition.projectorVersion, ) : true; if ( fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION && sourceIsCurrent ) { continue; } try { await this.matchStatsService.buildAndUpsert(match._id); rebuilt += 1; } catch (error) { this.logger.warn( `Failed to build match stats fragment for ${match._id.toString()}: ${ error instanceof Error ? error.message : error }`, ); } } return rebuilt; } private repairCommunityFragments(communityId: mongoose.Types.ObjectId) { const key = communityId.toString(); const inFlight = this.fragmentRepairs.get(key); if (inFlight) return inFlight; const repair = this.rebuildMissingOrStaleFragments(communityId).finally( () => { this.fragmentRepairs.delete(key); }, ); this.fragmentRepairs.set(key, repair); return repair; } private adjustCardForRange( card: InternalMatchCardView, filteredGames: Pick[], ): InternalMatchCardView { const allowedGameNumbers = new Set( filteredGames.map((game) => game.gameNumber), ); const games = card.games.filter((game) => allowedGameNumbers.has(game.gameNumber), ); const seriesResults = this.rebuildSeriesResults(games); return { ...card, games, seriesResults, winnerTeamIndex: this.resolveWinnerTeamIndex(seriesResults), }; } private rebuildSeriesResults( games: InternalMatchCardView['games'], ): InternalMatchCardView['seriesResults'] { const bySeries = new Map< string, InternalMatchCardView['seriesResults'][number] >(); for (const game of games) { if (game.winnerTeamIndex === null) continue; 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, }; 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, ); } private resolveWinnerTeamIndex( seriesResults: InternalMatchCardView['seriesResults'], ): number | undefined { const wins = new Map(); for (const series of seriesResults) { if (!series.winnerTeamIndex) continue; wins.set( series.winnerTeamIndex, (wins.get(series.winnerTeamIndex) ?? 0) + 1, ); } return [...wins.entries()].sort( (left, right) => right[1] - left[1] || left[0] - right[0], )[0]?.[0]; } private async resolveContext( communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): Promise { const CommunityModel = await this.connectionService.getModel('community'); const community = await CommunityModel.findById(communityId).exec(); if (!community) throw new NotFoundException('Community not found.'); const season = this.resolveSeason(community, filters.seasonId); let from = filters.from ? statsDate(filters.from, false) : season.startedAt ? new Date(season.startedAt) : null; let to = filters.to ? statsDate(filters.to, true) : season.endedAt ? new Date(season.endedAt) : null; if (from && Number.isNaN(from.getTime())) { throw new BadRequestException('Invalid from date.'); } if (to && Number.isNaN(to.getTime())) { throw new BadRequestException('Invalid to date.'); } if (from && to && from.getTime() > to.getTime()) { throw new BadRequestException('Invalid date range.'); } // A date filter narrows the selected season; it never escapes it. if (season.startedAt && (!from || from < new Date(season.startedAt))) from = new Date(season.startedAt); if (season.endedAt && (!to || to > new Date(season.endedAt))) to = new Date(season.endedAt); return { community, season, from, to }; } private resolveSeason( community: CommunityDocument, seasonId?: string, ): HistorySeasonDto { const seasons = this.resolveSeasons(community); if (seasonId === 'all') { return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null }; } if (seasonId && seasonId !== 'current') { const selected = seasons.find((season) => season.id === seasonId); if (!selected) throw new BadRequestException('Invalid seasonId.'); return selected; } return ( seasons.find((season) => !season.endedAt) ?? seasons[0] ?? { id: 'current', label: '현재 시즌', startedAt: community.seasonStartedAt?.toISOString() ?? null, endedAt: null, } ); } private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { const configured = community.seasons?.map((season) => ({ id: season.id, label: season.label, startedAt: season.startedAt.toISOString(), endedAt: season.endedAt?.toISOString() ?? null, })); if (configured?.length) return configured; return [ { id: 'current', label: '현재 시즌', startedAt: community.seasonStartedAt?.toISOString() ?? null, endedAt: null, }, ]; } private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { const byUser = new Map(); for (const record of records) { const rows = byUser.get(record.userId); if (rows) rows.push(record); else byUser.set(record.userId, [record]); } return [...byUser.entries()] .map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ); } private toLeaderboardRow( userId: string, records: InternalRecord[], ): LeaderboardRow { const first = records[0]; const wins = records.filter((record) => record.win).length; const kills = this.sum(records, 'kills'); const deaths = this.sum(records, 'deaths'); const assists = this.sum(records, 'assists'); const byLane: LeaderboardRow['byLane'] = {}; for (const lane of [ 'TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY', ] as RiotLane[]) { const laneRecords = records.filter( (record) => record.teamPosition === lane, ); if (laneRecords.length === 0) continue; byLane[lane] = { games: laneRecords.length, wins: laneRecords.filter((record) => record.win).length, kda: this.kda( this.sum(laneRecords, 'kills'), this.sum(laneRecords, 'deaths'), this.sum(laneRecords, 'assists'), ), }; } const championCounts = new Map(); for (const record of records) { const current = championCounts.get(record.championId) ?? { games: 0, wins: 0, }; current.games += 1; current.wins += record.win ? 1 : 0; championCounts.set(record.championId, current); } return { userId, summonerName: first?.summonerName ?? 'Unknown', tagLine: first?.tagLine || undefined, profileIconId: first?.profileIconId ?? 0, games: records.length, wins, losses: records.length - wins, winRate: this.percent(wins, records.length), totalKills: kills, totalDeaths: deaths, totalAssists: assists, kda: this.kda(kills, deaths, assists), avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length), avgKillParticipation: this.average( this.sum(records, 'killParticipation'), records.length, ), avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length), avgDamageShare: this.average( this.sum(records, 'damageShare'), records.length, ), avgVisionScore: this.average( this.sum(records, 'visionScore'), records.length, ), byLane, topChampions: [...championCounts.entries()] .map(([championId, stat]) => ({ championId, games: stat.games, winRate: this.percent(stat.wins, stat.games), })) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ) .slice(0, 3), }; } private buildUserChampionStats( records: InternalRecord[], season: HistorySeasonDto, ): LeaderboardChampionStats { const byChampion = new Map(); for (const record of records) { byChampion.set(record.championId, [ ...(byChampion.get(record.championId) ?? []), record, ]); } const champions = [...byChampion.entries()] .map(([championId, rows]) => this.toChampionRow(championId, rows)) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ); const totals = this.toChampionRow(0, records); return { queueGroup: 'internal', rank: 'all', queueIds: [], season, lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, champions, totals, }; } private toChampionRow(championId: number, rows: InternalRecord[]) { const wins = rows.filter((record) => record.win).length; const kills = this.sum(rows, 'kills'); const deaths = this.sum(rows, 'deaths'); const assists = this.sum(rows, 'assists'); const gameMinutes = rows.reduce( (sum, record) => sum + Math.max(record.gameDuration / 60, 1), 0, ); return { championId, games: rows.length, wins, losses: rows.length - wins, winRate: this.percent(wins, rows.length), avgKills: this.average(kills, rows.length), avgDeaths: this.average(deaths, rows.length), avgAssists: this.average(assists, rows.length), kda: this.kda(kills, deaths, assists), totalKills: kills, totalDeaths: deaths, totalAssists: assists, doubleKills: rows.reduce( (sum, row) => sum + (row.multiKills?.doubleKills ?? 0), 0, ), tripleKills: rows.reduce( (sum, row) => sum + (row.multiKills?.tripleKills ?? 0), 0, ), quadraKills: rows.reduce( (sum, row) => sum + (row.multiKills?.quadraKills ?? 0), 0, ), pentaKills: rows.reduce( (sum, row) => sum + (row.multiKills?.pentaKills ?? 0), 0, ), avgCs: this.average(this.sum(rows, 'cs'), rows.length), avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes), }; } private buildUserSummary( records: InternalRecord[], requestedLimit: number, ): UserInternalHistoryResponse['summary'] { const views = records.slice(0, requestedLimit); const wins = views.filter((record) => record.win).length; const kills = this.sum(views, 'kills'); const deaths = this.sum(views, 'deaths'); const assists = this.sum(views, 'assists'); const best = views.reduce((bestRecord, record) => { if (!bestRecord) return record; return record.deaths === 0 || record.rating > bestRecord.rating ? record : bestRecord; }, null); return { windowSize: views.length, winRate: this.percent(wins, views.length), wins, losses: views.length - wins, streak: this.resolveStreak(views), kda: this.kda(kills, deaths, assists), avgKills: this.average(kills, views.length), avgDeaths: this.average(deaths, views.length), avgAssists: this.average(assists, views.length), bestRating: best ? { rating: best.deaths === 0 ? 'Perfect' : best.rating, kills: best.kills, deaths: best.deaths, assists: best.assists, matchId: best.riotMatchId, } : null, positionRates: this.resolvePositionRates(views), topChampions: this.resolveTopChampions(views), lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null, }; } private toRecentMatchView( record: InternalRecord, dataset: BaseDataset, ): RecentMatchView { const detail = dataset.detailsByMatchId .get(record.matchId) ?.find((game) => game.riotMatchId === record.riotMatchId); return { matchId: record.riotMatchId, internalMatchId: record.matchId, internalMatchTitle: record.title, gameNumber: record.gameNumber, queueId: 0, queueLabel: '내전', gameCreation: record.gameCreation, gameDuration: record.gameDuration, win: record.win, remake: false, championId: record.championId, championLevel: record.championLevel, teamPosition: record.teamPosition, kills: record.kills, largestMultiKill: record.multiKills?.largestMultiKill, deaths: record.deaths, assists: record.assists, kda: this.kda(record.kills, record.deaths, record.assists), rating: record.rating, totalCs: record.cs, csPerMin: record.csPerMin, killParticipation: record.killParticipation, visionScore: record.visionScore, controlWardsBought: record.controlWardsBought, wardsPlaced: record.wardsPlaced, wardsKilled: record.wardsKilled, damageDealtToChampions: record.damageDealtToChampions, damageShare: record.damageShare, damageTaken: record.damageTaken, goldEarned: record.gold, items: record.items, trinket: record.trinket, summonerSpells: record.summonerSpells, perks: record.perks, teams: (detail?.teams ?? []).map((team) => ({ side: team.side === 'blue' ? 100 : 200, win: team.win, objectives: team.objectives, participants: team.participants.map((participant) => ({ puuid: participant.userId, gameName: participant.summonerName, tagLine: '', tier: participant.tier ? { tier: participant.tier.tier, rank: participant.tier.rank, leaguePoints: participant.tier.leaguePoints, fetchedAt: new Date(participant.tier.fetchedAt).toISOString(), } : undefined, championId: participant.championId, championLevel: participant.championLevel, teamPosition: participant.teamPosition, kills: participant.kills, deaths: participant.deaths, assists: participant.assists, items: participant.items, trinket: participant.trinket, summonerSpells: participant.summonerSpells, perks: participant.perks, totalCs: participant.cs, csPerMin: participant.csPerMin, goldEarned: participant.gold, damageDealtToChampions: participant.damageDealtToChampions, damageTaken: participant.damageTaken, visionScore: participant.visionScore, wardsPlaced: participant.wardsPlaced, wardsKilled: participant.wardsKilled, controlWardsBought: participant.controlWardsBought, })), })), }; } private applyChampionFilter( records: InternalRecord[], filters: CommunityStatsFilters, ): InternalRecord[] { return records.filter( (record) => (!filters.championId || record.championId === filters.championId) && (!filters.lane || record.teamPosition === filters.lane), ); } private isGameInRange( gameCreation: number, context: CommunityStatsContext, ): boolean { if (context.from && gameCreation < context.from.getTime()) return false; if (context.to && gameCreation > context.to.getTime()) return false; return true; } private toHighlight( row: LeaderboardRow | undefined, field: keyof Pick< LeaderboardRow, 'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin' >, ): LeaderHighlight | null { if (!row) return null; return { metric: Number(row[field]), userId: row.userId, summonerName: row.summonerName, isSingleGame: false, }; } private toSingleGameHighlight( record: InternalRecord | undefined, field: keyof Pick, ): LeaderHighlight | null { if (!record) return null; return { metric: record[field], userId: record.userId, summonerName: record.summonerName, championId: record.championId, matchId: record.riotMatchId, internalMatchId: record.matchId, gameNumber: record.gameNumber, isSingleGame: true, }; } private resolveStreak( records: InternalRecord[], ): UserInternalHistoryResponse['summary']['streak'] { if (records.length === 0) return null; const firstWin = records[0].win; let count = 0; for (const record of records) { if (record.win !== firstWin) break; count += 1; } return { type: firstWin ? 'win' : 'loss', count }; } private resolvePositionRates( records: InternalRecord[], ): Partial> { const counts = new Map(); for (const record of records) { if (!record.teamPosition) continue; counts.set( record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1, ); } return Object.fromEntries( [...counts.entries()].map(([lane, count]) => [ lane, this.percent(count, records.length), ]), ) as Partial>; } private resolveTopChampions(records: InternalRecord[]) { const byChampion = new Map< number, { games: number; wins: number; rating: number } >(); for (const record of records) { const current = byChampion.get(record.championId) ?? { games: 0, wins: 0, rating: 0, }; current.games += 1; current.wins += record.win ? 1 : 0; current.rating += record.rating; byChampion.set(record.championId, current); } return [...byChampion.entries()] .map(([championId, stat]) => ({ championId, games: stat.games, winRate: this.percent(stat.wins, stat.games), pickRate: this.percent(stat.games, records.length), avgRating: this.average(stat.rating, stat.games), })) .sort( (left, right) => right.games - left.games || right.winRate - left.winRate, ) .slice(0, 3); } private cacheKey( scope: string, communityId: mongoose.Types.ObjectId, filters: CommunityStatsFilters, ): CommunityStatsCacheKey { const cacheScope = scope.startsWith('userInternal:') ? 'userInternal' : scope; if ( cacheScope !== 'matches' && cacheScope !== 'leaderboard' && cacheScope !== 'teamInsights' && cacheScope !== 'userInternal' ) { throw new Error(`Unsupported community stats cache scope: ${scope}`); } return new CommunityStatsCacheKey( communityId.toString(), cacheScope, JSON.stringify([ MATCH_STATS_BUILDER_VERSION, `${scope}:presentation-v2`, filters.seasonId ?? 'current', filters.from ?? '', filters.to ?? '', filters.championId ?? '', filters.cursor ?? '', filters.limit ?? '', filters.query ?? '', filters.format ?? '', filters.playerId ?? '', filters.cursorMatchId ?? '', filters.lane ?? '', ...(filters.includePositionCounts ? ['position-windows-v1'] : []), ]), ); } private clampLimit( value: number | undefined, fallback: number, max: number, ): number { if (!value || !Number.isFinite(value)) return fallback; return Math.max(1, Math.min(Math.floor(value), max)); } private sum( records: InternalRecord[], field: T, ): number { return records.reduce((total, record) => { const value = record[field]; return total + (typeof value === 'number' ? value : 0); }, 0); } private kda(kills: number, deaths: number, assists: number): number { return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); } private percent(value: number, total: number): number { return total > 0 ? Math.round((value / total) * 100) : 0; } private average(value: number, total: number): number { return total > 0 ? this.round(value / total) : 0; } private round(value: number): number { return Math.round(value * 10) / 10; } } interface LinkedDetailGame { game: InternalGameDetail; official?: CompetitionGameView; analysisAvailability: GameAnalysisAvailability; } function linkDetailGames( dataset: BaseDataset, matchId: string, ): LinkedDetailGame[] { const officialByEvidence = new Map(); for (const game of dataset.competition?.projection.games ?? []) { const evidence = game.evidence.type === 'riot' ? game.evidence.riotMatchId : game.evidence.legacyReference; const key = JSON.stringify([game.displayNumber, evidence]); officialByEvidence.set(key, officialByEvidence.has(key) ? null : game); } return (dataset.detailsByMatchId.get(matchId) ?? []).flatMap((game) => { const official = officialByEvidence.get( JSON.stringify([game.gameNumber, game.riotMatchId]), ); if (dataset.competition && !official) return []; // A Riot ID is evidence, not a pending raw fetch. Detail hydration only // fetches timelines for matches whose raw data is already archived. const analysisAvailability: GameAnalysisAvailability = game.rawAvailable === false ? 'missing' : 'available'; return [{ game, official: official ?? undefined, analysisAvailability }]; }); } function needsDetailHydration({ game, analysisAvailability, }: LinkedDetailGame) { return analysisAvailability === 'available' && game.timelineLoaded !== true; } function isCompleteMatchDetailResponse( response: InternalMatchDetailResponse, ): boolean { return response.games.every( (game) => Array.isArray(game.timeline) && Array.isArray(game.objectiveEvents) && Array.isArray(game.timelineEvents) && game.teams.every( (team) => Array.isArray(team.bans) && team.participants.every( (participant) => typeof participant.tagLine === 'string' && Array.isArray(participant.itemBuild) && Array.isArray(participant.skillBuild) && isOptionalFiniteNumber(participant.participantId) && isCompleteParticipantCheckpoints(participant.checkpoints), ), ), ); } function isCompleteParticipantCheckpoints(value: unknown): boolean { if (value === undefined) return true; if (!isRecord(value)) return false; return ['at10', 'at15'].every((key) => { const checkpoint = value[key]; if (checkpoint === undefined) return true; if (!isRecord(checkpoint)) return false; return [ 'timestamp', 'gold', 'cs', 'xp', 'kills', 'deaths', 'assists', ].every((field) => isFiniteNumber(checkpoint[field])); }); } function isOptionalFiniteNumber(value: unknown): boolean { return value === undefined || isFiniteNumber(value); } function isFiniteNumber(value: unknown): value is number { return typeof value === 'number' && Number.isFinite(value); } function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); }