From 00448c94f39c1ccb0a2a416fb8e50aa8c05ac2b2 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 3 May 2026 20:42:26 -0700 Subject: [PATCH] . --- .../community-stats-cache.service.ts | 2 +- .../community-stats/community-stats.module.ts | 13 +- .../community-stats.service.ts | 785 ++++++++---------- .../match-stats-fragment.builder.spec.ts | 98 +++ .../match-stats-fragment.builder.ts | 367 ++++++++ .../community-stats/match-stats.repository.ts | 84 ++ .../match-stats.service.spec.ts | 104 +++ .../community-stats/match-stats.service.ts | 104 +++ .../community-stats/match-stats.types.ts | 20 + .../dev-seeds/backfill-match-stats.ts | 102 +++ .../api/src/modules/global/database/schema.ts | 140 +++- .../legacy-import/legacy-import.service.ts | 101 ++- .../src/modules/match/match.service.spec.ts | 10 +- apps/api/src/modules/match/match.service.ts | 10 + .../tournament-result.service.spec.ts | 2 + .../tournament-result.service.ts | 97 ++- 16 files changed, 1529 insertions(+), 510 deletions(-) create mode 100644 apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts create mode 100644 apps/api/src/modules/community-stats/match-stats-fragment.builder.ts create mode 100644 apps/api/src/modules/community-stats/match-stats.repository.ts create mode 100644 apps/api/src/modules/community-stats/match-stats.service.spec.ts create mode 100644 apps/api/src/modules/community-stats/match-stats.service.ts create mode 100644 apps/api/src/modules/community-stats/match-stats.types.ts create mode 100644 apps/api/src/modules/global/database/dev-seeds/backfill-match-stats.ts diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts index 4d6abeb7..6f3c26f2 100644 --- a/apps/api/src/modules/community-stats/community-stats-cache.service.ts +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -1,7 +1,7 @@ import { Injectable, Logger } from '@nestjs/common'; import { GarnetService } from '../global/garnet/garnet.service'; -const COMMUNITY_STATS_TTL_SECONDS = 60 * 60; +const COMMUNITY_STATS_TTL_SECONDS = 5 * 60; const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; @Injectable() diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts index c52af44c..4be3ae42 100644 --- a/apps/api/src/modules/community-stats/community-stats.module.ts +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -2,10 +2,19 @@ import { Module } from '@nestjs/common'; import { CommunityStatsCacheService } from './community-stats-cache.service'; import { CommunityStatsController } from './community-stats.controller'; import { CommunityStatsService } from './community-stats.service'; +import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; +import { MatchStatsRepository } from './match-stats.repository'; +import { MatchStatsService } from './match-stats.service'; @Module({ controllers: [CommunityStatsController], - providers: [CommunityStatsService, CommunityStatsCacheService], - exports: [CommunityStatsService], + providers: [ + CommunityStatsService, + CommunityStatsCacheService, + MatchStatsFragmentBuilder, + MatchStatsRepository, + MatchStatsService, + ], + exports: [CommunityStatsService, MatchStatsService], }) export class CommunityStatsModule {} diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts index 53fc3fa8..df89ea56 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -1,15 +1,16 @@ -import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + Logger, + NotFoundException, +} from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; +import type { CommunityDocument, RiotLane } from '../global/database/schema'; import type { - CommunityDocument, - MatchDocument, - MatchGameResultParticipant, - RiotLane, - TeamSide, -} from '../global/database/schema'; -import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; -import type { HistorySeasonDto, RecentMatchView } from '../match-history/match-history.types'; + HistorySeasonDto, + RecentMatchView, +} from '../match-history/match-history.types'; import { CommunityStatsCacheService } from './community-stats-cache.service'; import type { CommunityStatsFilters, @@ -23,6 +24,13 @@ import type { TeamInsightsResponse, UserInternalHistoryResponse, } from './community-stats.types'; +import { MatchStatsRepository } from './match-stats.repository'; +import { MatchStatsService } from './match-stats.service'; +import { + InternalGameDetail, + InternalRecord, + MATCH_STATS_BUILDER_VERSION, +} from './match-stats.types'; const DEFAULT_LIST_LIMIT = 20; const MAX_LIST_LIMIT = 50; @@ -36,60 +44,6 @@ interface CommunityStatsContext { to: Date | null; } -interface InternalRecord { - matchId: string; - title: string; - scheduledAt: Date; - gameNumber: number; - riotMatchId: string; - gameCreation: number; - gameDuration: number; - userId: string; - summonerName: string; - profileIconId: number; - teamIndex: number; - side: TeamSide; - championId: number; - championLevel: number; - teamPosition: string; - kills: number; - deaths: number; - assists: number; - win: boolean; - cs: number; - csPerMin: number; - gold: number; - gpm: number; - damageDealtToChampions: number; - damageTaken: number; - damageShare: number; - killParticipation: number; - visionScore: number; - controlWardsBought: number; - wardsPlaced: number; - wardsKilled: number; - items: number[]; - trinket: number; - summonerSpells: [number, number]; - perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; - rating: number; -} - -interface InternalGameDetail { - gameNumber: number; - riotMatchId: string; - gameCreation: number; - gameDuration: number; - winnerSide: TeamSide; - teams: Array<{ - teamIndex: number; - side: TeamSide; - win: boolean; - objectives: { baron: number; dragon: number; tower: number }; - participants: InternalRecord[]; - }>; -} - interface BaseDataset { season: HistorySeasonDto; matches: InternalMatchCardView[]; @@ -99,9 +53,13 @@ interface BaseDataset { @Injectable() export class CommunityStatsService { + private readonly logger = new Logger(CommunityStatsService.name); + constructor( private readonly connectionService: ConnectionService, private readonly cacheService: CommunityStatsCacheService, + private readonly matchStatsRepository: MatchStatsRepository, + private readonly matchStatsService: MatchStatsService, ) {} public async getMatches(params: { @@ -112,8 +70,15 @@ export class CommunityStatsService { const cached = await this.cacheService.get(key); if (cached) return cached; - const limit = this.clampLimit(params.filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT); - const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const limit = this.clampLimit( + params.filters.limit, + DEFAULT_LIST_LIMIT, + MAX_LIST_LIMIT, + ); + const dataset = await this.buildBaseDataset( + params.communityId, + params.filters, + ); const filtered = params.filters.championId ? dataset.matches.filter((match) => dataset.records.some( @@ -125,7 +90,9 @@ export class CommunityStatsService { : dataset.matches; const cursor = params.filters.cursor; const page = filtered - .filter((match) => !cursor || new Date(match.scheduledAt).getTime() < cursor) + .filter( + (match) => !cursor || new Date(match.scheduledAt).getTime() < cursor, + ) .slice(0, limit + 1); const visible = page.slice(0, limit); const response: InternalMatchListResponse = { @@ -144,11 +111,18 @@ export class CommunityStatsService { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { - const key = this.cacheKey('leaderboard', params.communityId, params.filters); + const key = this.cacheKey( + 'leaderboard', + params.communityId, + params.filters, + ); const cached = await this.cacheService.get(key); if (cached) return cached; - const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const dataset = await this.buildBaseDataset( + params.communityId, + params.filters, + ); const records = this.applyChampionFilter(dataset.records, params.filters); const rows = this.buildLeaderboardRows(records); const response = { rows, season: dataset.season }; @@ -160,18 +134,29 @@ export class CommunityStatsService { communityId: mongoose.Types.ObjectId; filters: CommunityStatsFilters; }): Promise { - const key = this.cacheKey('teamInsights', params.communityId, params.filters); + const key = this.cacheKey( + 'teamInsights', + params.communityId, + params.filters, + ); const cached = await this.cacheService.get(key); if (cached) return cached; - const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const dataset = await this.buildBaseDataset( + params.communityId, + params.filters, + ); const records = this.applyChampionFilter(dataset.records, params.filters); const rows = this.buildLeaderboardRows(records); const gameDetails = [...dataset.detailsByMatchId.values()].flat(); 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 blueWins = gameDetails.filter( + (game) => game.winnerSide === 'blue', + ).length; + const redWins = gameDetails.filter( + (game) => game.winnerSide === 'red', + ).length; const response: TeamInsightsResponse = { season: dataset.season, @@ -221,7 +206,8 @@ export class CommunityStatsService { matchId: mongoose.Types.ObjectId; }): Promise { const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; - const cached = await this.cacheService.get(key); + const cached = + await this.cacheService.get(key); if (cached) return cached; const dataset = await this.buildBaseDataset(params.communityId, { @@ -233,42 +219,44 @@ export class CommunityStatsService { if (!match) throw new NotFoundException('Internal match not found.'); const response: InternalMatchDetailResponse = { match, - games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map((game) => ({ - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId, - gameCreation: game.gameCreation, - gameDuration: game.gameDuration, - teams: game.teams.map((team) => ({ - teamIndex: team.teamIndex, - side: team.side, - win: team.win, - objectives: team.objectives, - participants: team.participants.map((record) => ({ - userId: record.userId, - summonerName: record.summonerName, - teamIndex: record.teamIndex, - side: record.side, - teamPosition: record.teamPosition, - championId: record.championId, - kills: record.kills, - deaths: record.deaths, - assists: record.assists, - cs: record.cs, - csPerMin: record.csPerMin, - gold: record.gold, - gpm: record.gpm, - damageDealtToChampions: record.damageDealtToChampions, - damageShare: record.damageShare, - killParticipation: record.killParticipation, - visionScore: record.visionScore, - items: record.items, - trinket: record.trinket, - summonerSpells: record.summonerSpells, - perks: record.perks, - win: record.win, + games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map( + (game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + teams: game.teams.map((team) => ({ + teamIndex: team.teamIndex, + side: team.side, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((record) => ({ + userId: record.userId, + summonerName: record.summonerName, + teamIndex: record.teamIndex, + side: record.side, + teamPosition: record.teamPosition, + championId: record.championId, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + cs: record.cs, + csPerMin: record.csPerMin, + gold: record.gold, + gpm: record.gpm, + damageDealtToChampions: record.damageDealtToChampions, + damageShare: record.damageShare, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + win: record.win, + })), })), - })), - })), + }), + ), }; await this.cacheService.setDetail(key, response); return response; @@ -284,10 +272,14 @@ export class CommunityStatsService { params.communityId, params.filters, ); - const cached = await this.cacheService.get(key); + const cached = + await this.cacheService.get(key); if (cached) return cached; - const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const dataset = await this.buildBaseDataset( + params.communityId, + params.filters, + ); const allUserRecords = dataset.records .filter((record) => record.userId === params.userId.toString()) .sort((left, right) => right.gameCreation - left.gameCreation); @@ -300,20 +292,27 @@ export class CommunityStatsService { const visible = page.slice(0, limit); const response: UserInternalHistoryResponse = { season: dataset.season, - championStats: this.buildUserChampionStats(allUserRecords, dataset.season), + championStats: this.buildUserChampionStats( + allUserRecords, + dataset.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 + ? (visible[visible.length - 1]?.gameCreation ?? null) : null, - lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, + lastFetchedAt: records[0] + ? new Date(records[0].gameCreation).toISOString() + : null, }; await this.cacheService.set(key, response); return response; } - public invalidateCommunity(communityId: mongoose.Types.ObjectId): Promise { + public invalidateCommunity( + communityId: mongoose.Types.ObjectId, + ): Promise { return this.cacheService.invalidateCommunity(communityId.toString()); } @@ -322,52 +321,47 @@ export class CommunityStatsService { filters: CommunityStatsFilters, ): Promise { const context = await this.resolveContext(communityId, filters); - const MatchModel = await this.connectionService.getModel('match'); - const RiotMatchModel = await this.connectionService.getModel('riotMatch'); - const matches = await MatchModel.find({ + let fragments = await this.matchStatsRepository.findByCommunity({ communityId, - status: { $in: ['finished', 'in-progress'] }, - 'result.games.0': { $exists: true }, - }) - .sort({ scheduledAt: -1 }) - .limit(MAX_MATCH_SCAN) - .exec(); - const riotMatchIds = [ - ...new Set( - matches.flatMap((match) => - (match.result?.games ?? []).map((game) => game.riotMatchId), - ), - ), - ]; - const riotDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) - .lean() - .exec(); - const rawByMatchId = new Map( - riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), - ); + fromGameCreation: context.from?.getTime(), + toGameCreation: context.to?.getTime(), + limit: MAX_MATCH_SCAN, + }); + const rebuilt = await this.rebuildMissingOrStaleFragments(communityId); + if (rebuilt > 0) { + fragments = await this.matchStatsRepository.findByCommunity({ + communityId, + fromGameCreation: context.from?.getTime(), + toGameCreation: context.to?.getTime(), + limit: MAX_MATCH_SCAN, + }); + } const cards: InternalMatchCardView[] = []; const records: InternalRecord[] = []; const detailsByMatchId = new Map(); - for (const match of matches) { - const games = (match.result?.games ?? []) + for (const fragment of fragments) { + const filteredGames = (fragment.gameDetails as InternalGameDetail[]) .filter((game) => this.isGameInRange(game.gameCreation, context)) .sort((left, right) => left.gameNumber - right.gameNumber); - if (games.length === 0) continue; - cards.push(this.toMatchCard(match, games)); + if (filteredGames.length === 0) continue; - for (const game of games) { - const raw = rawByMatchId.get(game.riotMatchId); - const detail = raw - ? this.toGameDetail(match, game, raw) - : this.toFallbackGameDetail(match, game); - detailsByMatchId.set(match._id.toString(), [ - ...(detailsByMatchId.get(match._id.toString()) ?? []), - detail, - ]); - records.push(...detail.teams.flatMap((team) => team.participants)); - } + const card = this.adjustCardForRange( + fragment.matchCard as unknown as InternalMatchCardView, + filteredGames, + ); + cards.push(card); + detailsByMatchId.set(fragment.matchId.toString(), filteredGames); + + const allowedGameNumbers = new Set( + filteredGames.map((game) => game.gameNumber), + ); + records.push( + ...(fragment.records as InternalRecord[]).filter((record) => + allowedGameNumbers.has(record.gameNumber), + ), + ); } return { @@ -378,6 +372,123 @@ export class CommunityStatsService { }; } + 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'] }, + 'result.games.0': { $exists: true }, + }) + .sort({ scheduledAt: -1 }) + .limit(MAX_MATCH_SCAN) + .select({ _id: 1 }) + .exec(), + this.matchStatsRepository.findByCommunity({ + communityId, + limit: MAX_MATCH_SCAN, + }), + ]); + const fragmentByMatchId = new Map( + fragments.map((fragment) => [fragment.matchId.toString(), fragment]), + ); + let rebuilt = 0; + + for (const match of matches) { + const fragment = fragmentByMatchId.get(match._id.toString()); + if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) { + 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 adjustCardForRange( + card: InternalMatchCardView, + filteredGames: InternalGameDetail[], + ): 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, @@ -386,10 +497,11 @@ export class CommunityStatsService { const community = await CommunityModel.findById(communityId).exec(); if (!community) throw new NotFoundException('Community not found.'); const season = this.resolveSeason(community, filters.seasonId); - const from = - filters.from ? new Date(filters.from) : - season.startedAt ? new Date(season.startedAt) : - null; + const from = filters.from + ? new Date(filters.from) + : season.startedAt + ? new Date(season.startedAt) + : null; const to = filters.to ? new Date(filters.to) : null; if (from && Number.isNaN(from.getTime())) { throw new BadRequestException('Invalid from date.'); @@ -442,235 +554,6 @@ export class CommunityStatsService { ]; } - private toMatchCard( - match: MatchDocument, - games: NonNullable['games'], - ): InternalMatchCardView { - const participantById = new Map( - match.participants.map((participant) => [ - participant.userId.toString(), - participant, - ]), - ); - return { - matchId: match._id.toString(), - title: match.title, - scheduledAt: match.scheduledAt.toISOString(), - status: match.status === 'finished' ? 'finished' : 'in-progress', - gameCount: match.gameCount, - winnerTeamIndex: match.result?.winnerTeamIndex, - seriesResults: match.result?.seriesResults ?? [], - games: games.map((game) => ({ - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId ?? null, - blueTeamIndex: game.blueTeamIndex, - redTeamIndex: game.redTeamIndex, - winnerTeamIndex: game.winnerTeamIndex ?? null, - winnerSide: game.winnerSide ?? null, - gameDuration: game.gameDuration, - })), - teams: match.teams.map((team) => ({ - teamIndex: team.teamIndex, - name: team.name, - members: team.members.map((member) => { - const participant = participantById.get(member.userId.toString()); - return { - userId: member.userId.toString(), - summonerName: participant?.gameName ?? 'Unknown', - profileIconId: participant?.profileIconId ?? 0, - }; - }), - })), - }; - } - - private toGameDetail( - match: MatchDocument, - game: NonNullable['games'][number], - raw: RiotMatchDto, - ): InternalGameDetail { - const puuidByUserId = new Map( - match.participants - .filter((participant) => participant.puuid) - .map((participant) => [ - participant.userId.toString(), - participant.puuid as string, - ]), - ); - const rawByPuuid = new Map( - raw.info.participants.map((participant) => [participant.puuid, participant]), - ); - const rawTeamIdBySide = new Map(); - for (const participant of game.participants) { - const puuid = puuidByUserId.get(participant.userId.toString()); - const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined; - if (rawParticipant) rawTeamIdBySide.set(participant.side, rawParticipant.teamId); - } - - return { - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId, - gameCreation: game.gameCreation, - gameDuration: game.gameDuration, - winnerSide: game.winnerSide, - teams: (['blue', 'red'] as TeamSide[]).map((side) => { - const teamIndex = - side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; - const rawTeamId = rawTeamIdBySide.get(side); - const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId); - const teamRawParticipants = raw.info.participants.filter( - (participant) => participant.teamId === rawTeamId, - ); - const teamKills = teamRawParticipants.reduce( - (sum, participant) => sum + participant.kills, - 0, - ); - const teamDamage = teamRawParticipants.reduce( - (sum, participant) => sum + participant.totalDamageDealtToChampions, - 0, - ); - return { - teamIndex, - side, - win: game.winnerSide === side, - objectives: { - baron: rawTeam?.objectives?.baron?.kills ?? 0, - dragon: rawTeam?.objectives?.dragon?.kills ?? 0, - tower: rawTeam?.objectives?.tower?.kills ?? 0, - }, - participants: game.participants - .filter((participant) => participant.side === side) - .map((participant) => - this.toRecord({ - match, - game, - participant, - rawParticipant: rawByPuuid.get( - puuidByUserId.get(participant.userId.toString()) ?? '', - ), - teamKills, - teamDamage, - }), - ), - }; - }), - }; - } - - private toFallbackGameDetail( - match: MatchDocument, - game: NonNullable['games'][number], - ): InternalGameDetail { - return { - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId, - gameCreation: game.gameCreation, - gameDuration: game.gameDuration, - winnerSide: game.winnerSide, - teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ - teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, - side, - win: game.winnerSide === side, - objectives: { baron: 0, dragon: 0, tower: 0 }, - participants: game.participants - .filter((participant) => participant.side === side) - .map((participant) => - this.toRecord({ match, game, participant, teamKills: 0, teamDamage: 0 }), - ), - })), - }; - } - - private toRecord(params: { - match: MatchDocument; - game: NonNullable['games'][number]; - participant: MatchGameResultParticipant; - rawParticipant?: RiotMatchParticipantDto; - teamKills: number; - teamDamage: number; - }): InternalRecord { - const { match, game, participant, rawParticipant, teamKills, teamDamage } = params; - const snapshot = match.participants.find((item) => - item.userId.equals(participant.userId), - ); - const minutes = Math.max( - (rawParticipant?.timePlayed ?? game.gameDuration) / 60, - 1, - ); - const cs = rawParticipant - ? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled - : 0; - const damage = rawParticipant?.totalDamageDealtToChampions ?? 0; - const killParticipation = this.percent( - participant.kills + participant.assists, - teamKills, - ); - const damageShare = this.percent(damage, teamDamage); - const rating = this.resolveRating({ - kills: participant.kills, - deaths: participant.deaths, - assists: participant.assists, - killParticipation, - csPerMin: this.average(cs, minutes), - damageShare, - visionPerMin: this.average(rawParticipant?.visionScore ?? 0, minutes), - }); - - return { - matchId: match._id.toString(), - title: match.title, - scheduledAt: match.scheduledAt, - gameNumber: game.gameNumber, - riotMatchId: game.riotMatchId, - gameCreation: game.gameCreation, - gameDuration: game.gameDuration, - userId: participant.userId.toString(), - summonerName: - snapshot?.gameName ?? - rawParticipant?.riotIdGameName ?? - rawParticipant?.summonerName ?? - 'Unknown', - profileIconId: snapshot?.profileIconId ?? 0, - teamIndex: participant.teamIndex, - side: participant.side, - championId: participant.championId, - championLevel: rawParticipant?.champLevel ?? 0, - teamPosition: - rawParticipant?.teamPosition || rawParticipant?.individualPosition || '', - kills: participant.kills, - deaths: participant.deaths, - assists: participant.assists, - win: participant.win, - cs, - csPerMin: this.average(cs, minutes), - gold: rawParticipant?.goldEarned ?? 0, - gpm: this.average(rawParticipant?.goldEarned ?? 0, minutes), - damageDealtToChampions: damage, - damageTaken: rawParticipant?.totalDamageTaken ?? 0, - damageShare, - killParticipation, - visionScore: rawParticipant?.visionScore ?? 0, - controlWardsBought: this.numberField(rawParticipant, 'visionWardsBoughtInGame'), - wardsPlaced: rawParticipant?.wardsPlaced ?? 0, - wardsKilled: rawParticipant?.wardsKilled ?? 0, - items: [ - rawParticipant?.item0 ?? 0, - rawParticipant?.item1 ?? 0, - rawParticipant?.item2 ?? 0, - rawParticipant?.item3 ?? 0, - rawParticipant?.item4 ?? 0, - rawParticipant?.item5 ?? 0, - ], - trinket: rawParticipant?.item6 ?? 0, - summonerSpells: [ - rawParticipant?.summoner1Id ?? 0, - rawParticipant?.summoner2Id ?? 0, - ], - perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, - rating, - }; - } - private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { const byUser = new Map(); for (const record of records) { @@ -678,18 +561,32 @@ export class CommunityStatsService { } return [...byUser.entries()] .map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) - .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + .sort( + (left, right) => + right.games - left.games || right.winRate - left.winRate, + ); } - private toLeaderboardRow(userId: string, records: InternalRecord[]): LeaderboardRow { + 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); + 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, @@ -703,8 +600,10 @@ export class CommunityStatsService { } const championCounts = new Map(); for (const record of records) { - const current = - championCounts.get(record.championId) ?? { games: 0, wins: 0 }; + const current = championCounts.get(record.championId) ?? { + games: 0, + wins: 0, + }; current.games += 1; current.wins += record.win ? 1 : 0; championCounts.set(record.championId, current); @@ -728,8 +627,14 @@ export class CommunityStatsService { 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), + 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]) => ({ @@ -737,7 +642,10 @@ export class CommunityStatsService { games: stat.games, winRate: this.percent(stat.wins, stat.games), })) - .sort((left, right) => right.games - left.games || right.winRate - left.winRate) + .sort( + (left, right) => + right.games - left.games || right.winRate - left.winRate, + ) .slice(0, 3), }; } @@ -755,14 +663,19 @@ export class CommunityStatsService { } const champions = [...byChampion.entries()] .map(([championId, rows]) => this.toChampionRow(championId, rows)) - .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + .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, + lastFetchedAt: records[0] + ? new Date(records[0].gameCreation).toISOString() + : null, champions, totals, }; @@ -836,11 +749,16 @@ export class CommunityStatsService { : null, positionRates: this.resolvePositionRates(views), topChampions: this.resolveTopChampions(views), - lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null, + lastFetchedAt: views[0] + ? new Date(views[0].gameCreation).toISOString() + : null, }; } - private toRecentMatchView(record: InternalRecord, dataset: BaseDataset): RecentMatchView { + private toRecentMatchView( + record: InternalRecord, + dataset: BaseDataset, + ): RecentMatchView { const detail = dataset.detailsByMatchId .get(record.matchId) ?.find((game) => game.riotMatchId === record.riotMatchId); @@ -973,7 +891,10 @@ export class CommunityStatsService { const counts = new Map(); for (const record of records) { if (!record.teamPosition) continue; - counts.set(record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1); + counts.set( + record.teamPosition, + (counts.get(record.teamPosition) ?? 0) + 1, + ); } return Object.fromEntries( [...counts.entries()].map(([lane, count]) => [ @@ -984,10 +905,16 @@ export class CommunityStatsService { } private resolveTopChampions(records: InternalRecord[]) { - const byChampion = new Map(); + 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 }; + 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; @@ -1001,43 +928,13 @@ export class CommunityStatsService { 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) + .sort( + (left, right) => + right.games - left.games || right.winRate - left.winRate, + ) .slice(0, 3); } - private resolvePerks(participant: RiotMatchParticipantDto) { - const primary = participant.perks.styles.find( - (style) => style.description === 'primaryStyle', - ); - const sub = participant.perks.styles.find( - (style) => style.description === 'subStyle', - ); - return { - primaryStyle: primary?.style, - subStyle: sub?.style, - keystone: primary?.selections[0]?.perk, - }; - } - - private resolveRating(params: { - kills: number; - deaths: number; - assists: number; - killParticipation: number; - csPerMin: number; - damageShare: number; - visionPerMin: number; - }): number { - const kda = this.kda(params.kills, params.deaths, params.assists); - const score = - Math.min(kda / 6, 1) * 4 + - Math.min(params.killParticipation / 100, 1) * 2 + - Math.min(params.csPerMin / 9, 1) * 2 + - Math.min(params.damageShare / 35, 1) + - Math.min(params.visionPerMin / 2, 1); - return this.round(score); - } - private cacheKey( scope: string, communityId: mongoose.Types.ObjectId, @@ -1056,7 +953,11 @@ export class CommunityStatsService { ].join(':'); } - private clampLimit(value: number | undefined, fallback: number, max: number): number { + 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)); } @@ -1072,7 +973,9 @@ export class CommunityStatsService { } private kda(kills: number, deaths: number, assists: number): number { - return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); + return deaths === 0 + ? kills + assists + : this.round((kills + assists) / deaths); } private percent(value: number, total: number): number { @@ -1086,12 +989,4 @@ export class CommunityStatsService { private round(value: number): number { return Math.round(value * 10) / 10; } - - private numberField( - participant: RiotMatchParticipantDto | undefined, - key: string, - ): number { - const value = participant?.[key]; - return typeof value === 'number' && Number.isFinite(value) ? value : 0; - } } diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts new file mode 100644 index 00000000..3f5c9b1f --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts @@ -0,0 +1,98 @@ +import mongoose from 'mongoose'; +import type { MatchDocument } from '../global/database/schema'; +import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; + +function makeMatch(): MatchDocument { + const userId = new mongoose.Types.ObjectId(); + return { + _id: new mongoose.Types.ObjectId(), + communityId: new mongoose.Types.ObjectId(), + title: '내전', + scheduledAt: new Date('2026-05-03T00:00:00.000Z'), + status: 'finished', + gameCount: 1, + participants: [ + { + userId, + puuid: 'puuid-1', + gameName: 'Player', + profileIconId: 7, + }, + ], + teams: [ + { + teamIndex: 1, + name: 'A', + members: [{ userId, assignedPosition: 'TOP' }], + }, + { teamIndex: 2, name: 'B', members: [] }, + ], + result: { + winnerTeamIndex: 1, + riotMatchIds: ['KR_1'], + games: [ + { + gameNumber: 1, + riotMatchId: 'KR_1', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + winnerSide: 'blue', + gameCreation: 1_000, + gameDuration: 1_800, + participants: [ + { + userId, + teamIndex: 1, + side: 'blue', + championId: 266, + kills: 5, + deaths: 1, + assists: 7, + win: true, + }, + ], + }, + ], + seriesResults: [ + { + teamAIndex: 1, + teamBIndex: 2, + teamAWins: 1, + teamBWins: 0, + winnerTeamIndex: 1, + }, + ], + }, + } as unknown as MatchDocument; +} + +describe('MatchStatsFragmentBuilder', () => { + it('builds a fallback fragment without raw Riot match data', () => { + const builder = new MatchStatsFragmentBuilder(); + const match = makeMatch(); + + const fragment = builder.buildFragment({ + match, + rawByRiotMatchId: new Map(), + }); + + expect(fragment.matchCard.matchId).toBe(match._id.toString()); + expect(fragment.gameCreationMin).toBe(1_000); + expect(fragment.gameCreationMax).toBe(1_000); + expect(fragment.userIds.map((id) => id.toString())).toEqual([ + match.participants[0].userId.toString(), + ]); + expect(fragment.championIds).toEqual([266]); + expect(fragment.records).toHaveLength(1); + expect(fragment.records[0]).toMatchObject({ + summonerName: 'Player', + championId: 266, + kills: 5, + deaths: 1, + assists: 7, + win: true, + }); + expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1); + }); +}); diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts new file mode 100644 index 00000000..b4a10c0d --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -0,0 +1,367 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import type { + MatchDocument, + MatchGameResultParticipant, + TeamSide, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; +import type { InternalMatchCardView } from './community-stats.types'; +import type { + InternalGameDetail, + InternalRecord, + MatchStatsFragment, +} from './match-stats.types'; + +@Injectable() +export class MatchStatsFragmentBuilder { + public buildFragment(params: { + match: MatchDocument; + rawByRiotMatchId: Map; + }): MatchStatsFragment { + const games = [...(params.match.result?.games ?? [])].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + const matchCard = this.toMatchCard(params.match, games); + const gameDetails = games.map((game) => { + const raw = params.rawByRiotMatchId.get(game.riotMatchId); + return raw + ? this.toGameDetail(params.match, game, raw) + : this.toFallbackGameDetail(params.match, game); + }); + const records = gameDetails.flatMap((detail) => + detail.teams.flatMap((team) => team.participants), + ); + const gameCreations = gameDetails.map((detail) => detail.gameCreation); + + return { + matchCard, + records, + gameDetails, + userIds: [ + ...new Map( + records + .filter((record) => mongoose.isValidObjectId(record.userId)) + .map((record) => [ + record.userId, + new mongoose.Types.ObjectId(record.userId), + ]), + ).values(), + ], + championIds: [...new Set(records.map((record) => record.championId))], + gameCreationMin: + gameCreations.length > 0 + ? Math.min(...gameCreations) + : params.match.scheduledAt.getTime(), + gameCreationMax: + gameCreations.length > 0 + ? Math.max(...gameCreations) + : params.match.scheduledAt.getTime(), + }; + } + + private toMatchCard( + match: MatchDocument, + games: NonNullable['games'], + ): InternalMatchCardView { + const participantById = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt.toISOString(), + status: match.status === 'finished' ? 'finished' : 'in-progress', + gameCount: match.gameCount, + winnerTeamIndex: match.result?.winnerTeamIndex, + seriesResults: match.result?.seriesResults ?? [], + games: games.map((game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId ?? null, + blueTeamIndex: game.blueTeamIndex, + redTeamIndex: game.redTeamIndex, + winnerTeamIndex: game.winnerTeamIndex ?? null, + winnerSide: game.winnerSide ?? null, + gameDuration: game.gameDuration, + })), + teams: match.teams.map((team) => ({ + teamIndex: team.teamIndex, + name: team.name, + members: team.members.map((member) => { + const participant = participantById.get(member.userId.toString()); + return { + userId: member.userId.toString(), + summonerName: participant?.gameName ?? 'Unknown', + profileIconId: participant?.profileIconId ?? 0, + }; + }), + })), + }; + } + + private toGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + raw: RiotMatchDto, + ): InternalGameDetail { + const puuidByUserId = new Map( + match.participants + .filter((participant) => participant.puuid) + .map((participant) => [ + participant.userId.toString(), + participant.puuid as string, + ]), + ); + const rawByPuuid = new Map( + raw.info.participants.map((participant) => [ + participant.puuid, + participant, + ]), + ); + const rawTeamIdBySide = new Map(); + for (const participant of game.participants) { + const puuid = puuidByUserId.get(participant.userId.toString()); + const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined; + if (rawParticipant) { + rawTeamIdBySide.set(participant.side, rawParticipant.teamId); + } + } + + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => { + const teamIndex = + side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; + const rawTeamId = rawTeamIdBySide.get(side); + const rawTeam = raw.info.teams.find( + (team) => team.teamId === rawTeamId, + ); + const teamRawParticipants = raw.info.participants.filter( + (participant) => participant.teamId === rawTeamId, + ); + const teamKills = teamRawParticipants.reduce( + (sum, participant) => sum + participant.kills, + 0, + ); + const teamDamage = teamRawParticipants.reduce( + (sum, participant) => sum + participant.totalDamageDealtToChampions, + 0, + ); + return { + teamIndex, + side, + win: game.winnerSide === side, + objectives: { + baron: rawTeam?.objectives?.baron?.kills ?? 0, + dragon: rawTeam?.objectives?.dragon?.kills ?? 0, + tower: rawTeam?.objectives?.tower?.kills ?? 0, + }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ + match, + game, + participant, + rawParticipant: rawByPuuid.get( + puuidByUserId.get(participant.userId.toString()) ?? '', + ), + teamKills, + teamDamage, + }), + ), + }; + }), + }; + } + + private toFallbackGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + ): InternalGameDetail { + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ + teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, + side, + win: game.winnerSide === side, + objectives: { baron: 0, dragon: 0, tower: 0 }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ + match, + game, + participant, + teamKills: 0, + teamDamage: 0, + }), + ), + })), + }; + } + + private toRecord(params: { + match: MatchDocument; + game: NonNullable['games'][number]; + participant: MatchGameResultParticipant; + rawParticipant?: RiotMatchParticipantDto; + teamKills: number; + teamDamage: number; + }): InternalRecord { + const { match, game, participant, rawParticipant, teamKills, teamDamage } = + params; + const snapshot = match.participants.find((item) => + item.userId.equals(participant.userId), + ); + const minutes = Math.max( + (rawParticipant?.timePlayed ?? game.gameDuration) / 60, + 1, + ); + const cs = rawParticipant + ? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled + : 0; + const damage = rawParticipant?.totalDamageDealtToChampions ?? 0; + const killParticipation = percent( + participant.kills + participant.assists, + teamKills, + ); + const damageShare = percent(damage, teamDamage); + const rating = this.resolveRating({ + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + killParticipation, + csPerMin: average(cs, minutes), + damageShare, + visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes), + }); + + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt, + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + userId: participant.userId.toString(), + summonerName: + snapshot?.gameName ?? + rawParticipant?.riotIdGameName ?? + rawParticipant?.summonerName ?? + 'Unknown', + profileIconId: snapshot?.profileIconId ?? 0, + teamIndex: participant.teamIndex, + side: participant.side, + championId: participant.championId, + championLevel: rawParticipant?.champLevel ?? 0, + teamPosition: + rawParticipant?.teamPosition || + rawParticipant?.individualPosition || + '', + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + cs, + csPerMin: average(cs, minutes), + gold: rawParticipant?.goldEarned ?? 0, + gpm: average(rawParticipant?.goldEarned ?? 0, minutes), + damageDealtToChampions: damage, + damageTaken: rawParticipant?.totalDamageTaken ?? 0, + damageShare, + killParticipation, + visionScore: rawParticipant?.visionScore ?? 0, + controlWardsBought: numberField( + rawParticipant, + 'visionWardsBoughtInGame', + ), + wardsPlaced: rawParticipant?.wardsPlaced ?? 0, + wardsKilled: rawParticipant?.wardsKilled ?? 0, + items: [ + rawParticipant?.item0 ?? 0, + rawParticipant?.item1 ?? 0, + rawParticipant?.item2 ?? 0, + rawParticipant?.item3 ?? 0, + rawParticipant?.item4 ?? 0, + rawParticipant?.item5 ?? 0, + ], + trinket: rawParticipant?.item6 ?? 0, + summonerSpells: [ + rawParticipant?.summoner1Id ?? 0, + rawParticipant?.summoner2Id ?? 0, + ], + perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, + rating, + }; + } + + private resolvePerks(participant: RiotMatchParticipantDto) { + const primary = participant.perks.styles.find( + (style) => style.description === 'primaryStyle', + ); + const sub = participant.perks.styles.find( + (style) => style.description === 'subStyle', + ); + return { + primaryStyle: primary?.style, + subStyle: sub?.style, + keystone: primary?.selections[0]?.perk, + }; + } + + private resolveRating(params: { + kills: number; + deaths: number; + assists: number; + killParticipation: number; + csPerMin: number; + damageShare: number; + visionPerMin: number; + }): number { + const kdaScore = kda(params.kills, params.deaths, params.assists); + const score = + Math.min(kdaScore / 6, 1) * 4 + + Math.min(params.killParticipation / 100, 1) * 2 + + Math.min(params.csPerMin / 9, 1) * 2 + + Math.min(params.damageShare / 35, 1) + + Math.min(params.visionPerMin / 2, 1); + return round(score); + } +} + +function kda(kills: number, deaths: number, assists: number): number { + return deaths === 0 ? kills + assists : round((kills + assists) / deaths); +} + +function percent(value: number, total: number): number { + return total > 0 ? Math.round((value / total) * 100) : 0; +} + +function average(value: number, total: number): number { + return total > 0 ? round(value / total) : 0; +} + +function round(value: number): number { + return Math.round(value * 10) / 10; +} + +function numberField( + participant: RiotMatchParticipantDto | undefined, + key: string, +): number { + const value = participant?.[key]; + return typeof value === 'number' && Number.isFinite(value) ? value : 0; +} diff --git a/apps/api/src/modules/community-stats/match-stats.repository.ts b/apps/api/src/modules/community-stats/match-stats.repository.ts new file mode 100644 index 00000000..21b35acf --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.repository.ts @@ -0,0 +1,84 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { MatchStats, MatchStatsDocument } from '../global/database/schema'; + +@Injectable() +export class MatchStatsRepository { + constructor(private readonly connectionService: ConnectionService) {} + + public async upsert( + fragment: Omit, + ): Promise { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + await MatchStatsModel.updateOne( + { matchId: fragment.matchId }, + { $set: fragment }, + { upsert: true }, + ).exec(); + } + + public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + await MatchStatsModel.deleteOne({ matchId }).exec(); + } + + public async deleteByMatches( + matchIds: mongoose.Types.ObjectId[], + ): Promise { + if (matchIds.length === 0) return; + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec(); + } + + public async findByMatch( + matchId: mongoose.Types.ObjectId, + ): Promise { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + return MatchStatsModel.findOne({ matchId }).exec(); + } + + public async findByCommunity(params: { + communityId: mongoose.Types.ObjectId; + fromGameCreation?: number; + toGameCreation?: number; + limit?: number; + }): Promise { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + const filter: Record = { + communityId: params.communityId, + }; + if (params.fromGameCreation !== undefined) { + filter.gameCreationMax = { $gte: params.fromGameCreation }; + } + if (params.toGameCreation !== undefined) { + filter.gameCreationMin = { $lte: params.toGameCreation }; + } + + return MatchStatsModel.find(filter) + .sort({ scheduledAt: -1 }) + .limit(params.limit ?? 300) + .exec(); + } + + public async findByUser(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + fromGameCreation?: number; + toGameCreation?: number; + }): Promise { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + const filter: Record = { + communityId: params.communityId, + userIds: params.userId, + }; + if (params.fromGameCreation !== undefined) { + filter.gameCreationMax = { $gte: params.fromGameCreation }; + } + if (params.toGameCreation !== undefined) { + filter.gameCreationMin = { $lte: params.toGameCreation }; + } + + return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec(); + } +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.spec.ts b/apps/api/src/modules/community-stats/match-stats.service.spec.ts new file mode 100644 index 00000000..552cca15 --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.service.spec.ts @@ -0,0 +1,104 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder'; +import { MatchStatsRepository } from './match-stats.repository'; +import { MatchStatsService } from './match-stats.service'; + +describe('MatchStatsService', () => { + it('deletes an existing fragment when the match is no longer eligible', async () => { + const matchId = new mongoose.Types.ObjectId(); + const findById = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + _id: matchId, + status: 'recruiting', + result: undefined, + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'match') return { findById }; + if (name === 'riotMatch') return {}; + throw new Error(`Unexpected model: ${name}`); + }), + } as unknown as ConnectionService; + const repository = { + deleteByMatch: jest.fn().mockResolvedValue(undefined), + upsert: jest.fn(), + } as unknown as jest.Mocked; + const service = new MatchStatsService( + connectionService, + repository, + {} as MatchStatsFragmentBuilder, + ); + + await service.buildAndUpsert(matchId); + + expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId); + expect(repository.upsert).not.toHaveBeenCalled(); + }); + + it('upserts a fragment for eligible matches', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const scheduledAt = new Date('2026-05-03T00:00:00.000Z'); + const match = { + _id: matchId, + communityId, + scheduledAt, + status: 'finished', + result: { games: [{ riotMatchId: 'KR_1' }] }, + }; + const findById = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(match), + }); + const riotFind = jest.fn().mockReturnValue({ + lean: () => ({ + exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]), + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'match') return { findById }; + if (name === 'riotMatch') return { find: riotFind }; + throw new Error(`Unexpected model: ${name}`); + }), + } as unknown as ConnectionService; + const repository = { + upsert: jest.fn().mockResolvedValue(undefined), + deleteByMatch: jest.fn(), + } as unknown as jest.Mocked; + const builder = { + buildFragment: jest.fn().mockReturnValue({ + matchCard: { matchId: matchId.toString() }, + records: [], + gameDetails: [], + userIds: [], + championIds: [], + gameCreationMin: 1_000, + gameCreationMax: 2_000, + }), + } as unknown as jest.Mocked; + const service = new MatchStatsService( + connectionService, + repository, + builder, + ); + + await service.buildAndUpsert(matchId); + + expect(builder.buildFragment).toHaveBeenCalledWith({ + match, + rawByRiotMatchId: expect.any(Map), + }); + expect(repository.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + matchId, + communityId, + scheduledAt, + gameCreationMin: 1_000, + gameCreationMax: 2_000, + builderVersion: 1, + }), + ); + }); +}); diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts new file mode 100644 index 00000000..00381a9d --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -0,0 +1,104 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto } 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 { + constructor( + private readonly connectionService: ConnectionService, + private readonly repository: MatchStatsRepository, + private readonly builder: MatchStatsFragmentBuilder, + ) {} + + public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const match = await MatchModel.findById(matchId).exec(); + if (!match) return; + if (!this.isEligible(match)) { + await this.repository.deleteByMatch(matchId); + return; + } + + const riotIds = [ + ...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 fragment = this.builder.buildFragment({ match, rawByRiotMatchId }); + + 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, + }); + } + + 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'] }, + '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) + ); + } +} diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts new file mode 100644 index 00000000..ed0901e3 --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -0,0 +1,20 @@ +import type { + MatchStatsGameDetail, + MatchStatsRecord, +} from '../global/database/schema'; +import type { InternalMatchCardView } from './community-stats.types'; + +export const MATCH_STATS_BUILDER_VERSION = 1; + +export type InternalRecord = MatchStatsRecord; +export type InternalGameDetail = MatchStatsGameDetail; + +export interface MatchStatsFragment { + matchCard: InternalMatchCardView; + records: InternalRecord[]; + gameDetails: InternalGameDetail[]; + userIds: import('mongoose').Types.ObjectId[]; + championIds: number[]; + gameCreationMin: number; + gameCreationMax: number; +} diff --git a/apps/api/src/modules/global/database/dev-seeds/backfill-match-stats.ts b/apps/api/src/modules/global/database/dev-seeds/backfill-match-stats.ts new file mode 100644 index 00000000..f186f2fa --- /dev/null +++ b/apps/api/src/modules/global/database/dev-seeds/backfill-match-stats.ts @@ -0,0 +1,102 @@ +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { AppModule } from '../../../../app.module'; +import { ConnectionService } from '../connection.service'; +import { MatchStatsService } from '../../../community-stats/match-stats.service'; + +interface Options { + communityId?: mongoose.Types.ObjectId; + dryRun: boolean; + force: boolean; +} + +async function main() { + const options = parseArgs(process.argv.slice(2)); + const app = await NestFactory.createApplicationContext(AppModule, { + logger: ['log', 'warn', 'error'], + }); + + try { + const connectionService = app.get(ConnectionService); + const matchStatsService = app.get(MatchStatsService); + const MatchModel = await connectionService.getModel('match'); + const MatchStatsModel = await connectionService.getModel('matchStats'); + + const filter: Record = { + status: { $in: ['finished', 'in-progress'] }, + 'result.games.0': { $exists: true }, + }; + if (options.communityId) filter.communityId = options.communityId; + + const matches = await MatchModel.find(filter) + .sort({ scheduledAt: -1 }) + .select({ _id: 1 }) + .exec(); + console.log(`match_stats backfill target=${matches.length}`); + + let processed = 0; + let skipped = 0; + let failed = 0; + + for (const match of matches) { + if (!options.force) { + const existing = await MatchStatsModel.exists({ matchId: match._id }); + if (existing) { + skipped += 1; + continue; + } + } + if (options.dryRun) { + processed += 1; + continue; + } + + try { + await matchStatsService.buildAndUpsert(match._id); + processed += 1; + } catch (error) { + failed += 1; + console.warn( + `failed ${match._id.toString()}: ${ + error instanceof Error ? error.message : error + }`, + ); + } + + if ((processed + skipped + failed) % 50 === 0) { + console.log( + `progress processed=${processed} skipped=${skipped} failed=${failed}`, + ); + } + } + + console.log( + `done processed=${processed} skipped=${skipped} failed=${failed}`, + ); + } finally { + await app.close(); + } +} + +function parseArgs(args: string[]): Options { + const options: Options = { dryRun: false, force: false }; + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (arg === '--dry-run') options.dryRun = true; + if (arg === '--force') options.force = true; + if (arg === '--community-id') { + const value = args[index + 1]; + if (!value || !mongoose.isValidObjectId(value)) { + throw new Error('--community-id requires a valid ObjectId'); + } + options.communityId = new mongoose.Types.ObjectId(value); + index += 1; + } + } + return options; +} + +void main().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index 5855880c..560778dc 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -65,7 +65,11 @@ export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [ ]; export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed'; -export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed'; +export type MatchResultPollStateValue = + | 'polling' + | 'complete' + | 'expired' + | 'failed'; export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [ 'polling', 'complete', @@ -562,8 +566,79 @@ export interface AuctionHistoryEntry extends MongooseTimestamps { takenAt: Date; } -export type AuctionHistoryEntryDocument = - HydratedDocument; +export type AuctionHistoryEntryDocument = HydratedDocument; + +// ===== MatchStats (precomputed internal stats fragment) ===== +export interface MatchStatsRecord { + matchId: string; + title: string; + scheduledAt: Date; + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + userId: string; + summonerName: string; + profileIconId: number; + teamIndex: number; + side: TeamSide; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + win: boolean; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageTaken: number; + damageShare: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + rating: number; +} + +export interface MatchStatsGameDetail { + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + winnerSide: TeamSide; + teams: Array<{ + teamIndex: number; + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: MatchStatsRecord[]; + }>; +} + +export interface MatchStats extends MongooseTimestamps { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + scheduledAt: Date; + gameCreationMin: number; + gameCreationMax: number; + userIds: mongoose.Types.ObjectId[]; + championIds: number[]; + matchCard: Record; + records: MatchStatsRecord[]; + gameDetails: MatchStatsGameDetail[]; + builtAt: Date; + builderVersion: number; +} + +export type MatchStatsDocument = HydratedDocument; // ===== Sub-schemas ===== const PositionPreferenceSubSchema = new Schema( @@ -1068,7 +1143,9 @@ const MatchScheduleItemSubSchema = new Schema( { _id: false }, ); -const MatchLegacyImportSourceSubSchema = new Schema>( +const MatchLegacyImportSourceSubSchema = new Schema< + NonNullable +>( { importedAt: { type: Date, required: true }, importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true }, @@ -1109,7 +1186,8 @@ export const MatchSchema = new Schema( default: 10, min: 10, validate: { - validator: (value: number) => Number.isInteger(value) && value % 10 === 0, + validator: (value: number) => + Number.isInteger(value) && value % 10 === 0, message: 'maxParticipants must be a multiple of 10.', }, }, @@ -1379,7 +1457,15 @@ const AuctionHistoryEntrySchema = new Schema( sequence: { type: Number, required: true, min: 1 }, action: { type: String, - enum: ['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete'], + enum: [ + 'start', + 'open-bidding', + 'bid', + 'sold', + 'passed', + 'next', + 'complete', + ], required: true, }, actorUserId: { type: Schema.Types.ObjectId, ref: 'user', required: false }, @@ -1394,6 +1480,42 @@ const AuctionHistoryEntrySchema = new Schema( AuctionHistoryEntrySchema.index({ auctionId: 1, sequence: -1 }); +export const MatchStatsSchema: mongoose.Schema = new Schema( + { + matchId: { + type: Schema.Types.ObjectId, + ref: 'match', + required: true, + unique: true, + }, + communityId: { + type: Schema.Types.ObjectId, + ref: 'community', + required: true, + }, + scheduledAt: { type: Date, required: true }, + gameCreationMin: { type: Number, required: true }, + gameCreationMax: { type: Number, required: true }, + userIds: { type: [Schema.Types.ObjectId], required: true, default: [] }, + championIds: { type: [Number], required: true, default: [] }, + matchCard: { type: Schema.Types.Mixed, required: true }, + records: { type: [Schema.Types.Mixed], required: true, default: [] }, + gameDetails: { type: [Schema.Types.Mixed], required: true, default: [] }, + builtAt: { type: Date, required: true, default: Date.now }, + builderVersion: { type: Number, required: true, default: 1 }, + } as mongoose.SchemaDefinition, + { timestamps: true, collection: 'match_stats' }, +) as mongoose.Schema; + +MatchStatsSchema.index({ communityId: 1, scheduledAt: -1 }); +MatchStatsSchema.index({ + communityId: 1, + gameCreationMin: 1, + gameCreationMax: 1, +}); +MatchStatsSchema.index({ communityId: 1, userIds: 1 }); +MatchStatsSchema.index({ communityId: 1, championIds: 1 }); + export const tournamentModelDefinitions: ModelDefinition[] = [ { name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, { name: 'community', schema: CommunitySchema, schemaName: 'community' }, @@ -1416,6 +1538,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [ schema: AuctionHistoryEntrySchema, schemaName: 'auctionHistory', }, + { + name: 'matchStats', + schema: MatchStatsSchema, + schemaName: 'matchStats', + }, ]; export interface TournamentModelTypes { @@ -1428,4 +1555,5 @@ export interface TournamentModelTypes { match: Match; auction: Auction; auctionHistory: AuctionHistoryEntry; + matchStats: MatchStats; } diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts index f8b2da80..9f6a9244 100644 --- a/apps/api/src/modules/legacy-import/legacy-import.service.ts +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -7,6 +7,7 @@ import { } from '@nestjs/common'; import { randomUUID } from 'crypto'; import mongoose from 'mongoose'; +import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import type { @@ -55,6 +56,7 @@ export class LegacyImportService { private readonly garnetService: GarnetService, private readonly riotMatchService: RiotMatchService, private readonly communityStatsService: CommunityStatsService, + private readonly matchStatsService: MatchStatsService, ) {} public async previewMembers(params: { @@ -107,8 +109,12 @@ export class LegacyImportService { ]), ); const windows = users - .map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides)) - .filter((window) => window.startTime.getTime() <= window.endTime.getTime()); + .map((user) => + this.resolveMemberWindow(user, windowStart, windowEnd, overrides), + ) + .filter( + (window) => window.startTime.getTime() <= window.endTime.getTime(), + ); const LegacyImportJobModel = await this.connectionService.getModel('legacyImportJob'); await LegacyImportJobModel.create({ @@ -174,7 +180,9 @@ export class LegacyImportService { }): Promise<{ jobs: LegacyImportJobDocument[] }> { const LegacyImportJobModel = await this.connectionService.getModel('legacyImportJob'); - const jobs = await LegacyImportJobModel.find({ communityId: params.communityId }) + const jobs = await LegacyImportJobModel.find({ + communityId: params.communityId, + }) .sort({ startedAt: -1 }) .limit(Math.min(params.limit ?? 10, 50)) .exec(); @@ -210,7 +218,8 @@ export class LegacyImportService { { $set: { state: 'cancelled', completedAt: new Date() } }, { returnDocument: 'after' }, ).exec(); - if (!job) throw new NotFoundException('Running legacy import job not found.'); + if (!job) + throw new NotFoundException('Running legacy import job not found.'); await this.garnetService.delete(this.communityLockKey(params.communityId)); return job; } @@ -284,7 +293,9 @@ export class LegacyImportService { .map((match) => match.result?.games[0]?.riotMatchId) .filter((matchId): matchId is string => Boolean(matchId)); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); - const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) + const rawDocs = await RiotMatchModel.find({ + matchId: { $in: riotMatchIds }, + }) .lean() .exec(); const rawById = new Map( @@ -314,7 +325,7 @@ export class LegacyImportService { }), nextCursor: matches.length > limit - ? visible[visible.length - 1]?.scheduledAt.getTime() ?? null + ? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null) : null, }; } @@ -328,11 +339,22 @@ export class LegacyImportService { .map((id) => new mongoose.Types.ObjectId(id)); if (ids.length === 0) return { deleted: 0 }; const MatchModel = await this.connectionService.getModel('match'); - const result = await MatchModel.deleteMany({ + const targets = await MatchModel.find({ _id: { $in: ids }, communityId: params.communityId, legacyImported: true, + }) + .select({ _id: 1 }) + .exec(); + const targetIds = targets.map((match) => match._id); + if (targetIds.length === 0) return { deleted: 0 }; + + const result = await MatchModel.deleteMany({ + _id: { $in: targetIds }, + communityId: params.communityId, + legacyImported: true, }).exec(); + await this.matchStatsService.removeByMatches(targetIds); await this.communityStatsService.invalidateCommunity(params.communityId); return { deleted: result.deletedCount ?? 0 }; } @@ -348,12 +370,15 @@ export class LegacyImportService { const riotMatchIds = matches .map( (match) => - match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0], + match.result?.games[0]?.riotMatchId ?? + match.result?.riotMatchIds?.[0], ) .filter((matchId): matchId is string => Boolean(matchId)); const RiotMatchModel = await this.connectionService.getModel('riotMatch'); - const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) + const rawDocs = await RiotMatchModel.find({ + matchId: { $in: riotMatchIds }, + }) .lean() .exec(); const rawById = new Map(); @@ -387,7 +412,11 @@ export class LegacyImportService { if (!raw || !riotMatchId) { result.skippedMissingRaw += 1; if (Object.keys(update).length > 0) { - await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); + await MatchModel.updateOne( + { _id: match._id }, + { $set: update }, + ).exec(); + await this.matchStatsService.buildAndUpsert(match._id); } continue; } @@ -397,7 +426,11 @@ export class LegacyImportService { if (!gameResult || participants.length === 0) { result.skippedNoKnownParticipants += 1; if (Object.keys(update).length > 0) { - await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); + await MatchModel.updateOne( + { _id: match._id }, + { $set: update }, + ).exec(); + await this.matchStatsService.buildAndUpsert(match._id); } continue; } @@ -429,6 +462,7 @@ export class LegacyImportService { }, { $set: update }, ).exec(); + await this.matchStatsService.buildAndUpsert(match._id); result.rebuilt += 1; } @@ -439,7 +473,9 @@ export class LegacyImportService { return result; } - private async collectMatchIds(job: LegacyImportMemberJob): Promise> { + private async collectMatchIds( + job: LegacyImportMemberJob, + ): Promise> { const matchIds = new Set(); let start = 0; while (true) { @@ -478,7 +514,10 @@ export class LegacyImportService { }); if (existing) return 'duplicate'; - const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region); + const detail = await this.ensureRiotMatchPersisted( + riotMatchId, + job.region, + ); if (!detail.info.tournamentCode) return 'skipped'; const counts = countKnownParticipants(detail, userByPuuid); if (counts.total === 0) return 'skipped'; @@ -527,7 +566,8 @@ export class LegacyImportService { notices: [], schedule: [], }; - await MatchModel.create(matchPayload); + const match = await MatchModel.create(matchPayload); + await this.matchStatsService.buildAndUpsert(match._id); return 'imported'; } catch (error) { await this.recordError(job.parentJobId, { @@ -546,7 +586,9 @@ export class LegacyImportService { region: RiotRegionalRoute, ): Promise { const RiotMatchModel = await this.connectionService.getModel('riotMatch'); - const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec(); + const stored = await RiotMatchModel.findOne({ + matchId: riotMatchId, + }).exec(); if (isRiotMatchDto(stored?.raw)) return stored.raw; const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); @@ -588,7 +630,9 @@ export class LegacyImportService { const average = current.averageMemberSeconds === undefined ? stats.elapsedSeconds - : Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3); + : Math.round( + current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3, + ); const nextProcessed = current.processedMembers + 1; const completed = nextProcessed >= current.totalMembers; @@ -631,7 +675,8 @@ export class LegacyImportService { jobId: job.parentJobId, }).exec(); if (!legacyJob || legacyJob.state === 'cancelled') return null; - if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null; + if (legacyJob.state === 'completed' || legacyJob.state === 'failed') + return null; return legacyJob; } @@ -686,7 +731,12 @@ export class LegacyImportService { windowStart: Date, windowEnd: Date, ): LegacyImportMemberWindowView { - const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map()); + const resolved = this.resolveMemberWindow( + user, + windowStart, + windowEnd, + new Map(), + ); const account = user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? user.riotAccounts[0]; @@ -731,10 +781,7 @@ export class LegacyImportService { }; } - private resolveWindow(params: { - windowStart?: string; - windowEnd?: string; - }) { + private resolveWindow(params: { windowStart?: string; windowEnd?: string }) { const windowStart = this.parseOptionalDate(params.windowStart) ?? new Date(LEGACY_IMPORT_DEFAULT_START_ISO); @@ -755,7 +802,9 @@ export class LegacyImportService { } private minDate(...values: Array): Date { - return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime()))); + return new Date( + Math.min(...values.filter(Boolean).map((date) => date!.getTime())), + ); } private normalizeLegacyTitle(title: string, gameCreation: number): string { @@ -782,8 +831,8 @@ export class LegacyImportService { function isRiotMatchDto(value: unknown): value is RiotMatchDto { return Boolean( value && - typeof value === 'object' && - 'metadata' in value && - 'info' in value, + typeof value === 'object' && + 'metadata' in value && + 'info' in value, ); } diff --git a/apps/api/src/modules/match/match.service.spec.ts b/apps/api/src/modules/match/match.service.spec.ts index 615dd350..a846a29f 100644 --- a/apps/api/src/modules/match/match.service.spec.ts +++ b/apps/api/src/modules/match/match.service.spec.ts @@ -19,14 +19,20 @@ describe('MatchService', () => { const communityStatsService = { invalidateCommunity: jest.fn().mockResolvedValue(undefined), }; + const matchStatsService = { + buildAndUpsert: jest.fn().mockResolvedValue(undefined), + removeByMatch: jest.fn().mockResolvedValue(undefined), + }; return { service: new MatchService( connectionService as never, tournamentCodeService as never, communityStatsService as never, + matchStatsService as never, ), tournamentCodeService, + matchStatsService, }; } @@ -49,7 +55,8 @@ describe('MatchService', () => { }), save: jest.fn().mockResolvedValue(undefined), }; - const { service, tournamentCodeService } = createService(match); + const { service, tournamentCodeService, matchStatsService } = + createService(match); await service.update({ matchId: new mongoose.Types.ObjectId(), @@ -64,6 +71,7 @@ describe('MatchService', () => { expect(match.result).toBeUndefined(); expect(match.resultPollState).toBeUndefined(); expect(match.save).toHaveBeenCalledTimes(1); + expect(matchStatsService.removeByMatch).toHaveBeenCalledWith(match._id); }); it('releases reserved codes when returning a built match to recruiting', async () => { diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts index 1a945728..1bf6b3b6 100644 --- a/apps/api/src/modules/match/match.service.ts +++ b/apps/api/src/modules/match/match.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; +import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import { @@ -59,6 +60,7 @@ export class MatchService { private readonly connectionService: ConnectionService, private readonly tournamentCodeService: TournamentCodeService, private readonly communityStatsService: CommunityStatsService, + private readonly matchStatsService: MatchStatsService, ) {} public async create(params: CreateMatchParams): Promise { @@ -172,6 +174,13 @@ export class MatchService { match.resultPollState = undefined; } await match.save(); + if (previousStatus !== 'recruiting' && match.status === 'recruiting') { + await this.matchStatsService.removeByMatch(match._id); + await this.communityStatsService.invalidateCommunity(params.communityId); + } else if (match.result?.games?.length) { + await this.matchStatsService.buildAndUpsert(match._id); + await this.communityStatsService.invalidateCommunity(params.communityId); + } return match; } @@ -186,6 +195,7 @@ export class MatchService { throw new BadRequestException('Match does not belong to this community.'); } await this.tournamentCodeService.releaseFromMatch(match); + await this.matchStatsService.removeByMatch(match._id); await match.deleteOne(); await this.communityStatsService.invalidateCommunity(params.communityId); } diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 878ec8ce..7c181090 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -17,6 +17,7 @@ function createService() { {} as never, {} as never, {} as never, + {} as never, ) as unknown as TournamentResultServiceInternals; } @@ -189,6 +190,7 @@ describe('TournamentResultService manual result collection', () => { riotMatchService as never, {} as never, { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, + { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, ); return { diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 5033007d..c6f8bb7a 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -5,6 +5,7 @@ import { NotFoundException, } from '@nestjs/common'; import mongoose from 'mongoose'; +import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; import { ConnectionService } from '../global/database/connection.service'; import type { @@ -55,6 +56,7 @@ export class TournamentResultService { private readonly riotMatchService: RiotMatchService, private readonly riotJobQueueService: RiotJobQueueService, private readonly communityStatsService: CommunityStatsService, + private readonly matchStatsService: MatchStatsService, ) {} public async scheduleInitialPoll( @@ -98,7 +100,9 @@ export class TournamentResultService { } const result = await this.scheduleInitialPoll(match, 'high'); if (!result) { - throw new BadRequestException('Tournament result polling is not available.'); + throw new BadRequestException( + 'Tournament result polling is not available.', + ); } return result; } @@ -119,7 +123,10 @@ export class TournamentResultService { const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); - const puuids = this.collectPollingPuuids(collectMatchUserIds(match), lookup); + 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(); @@ -240,7 +247,9 @@ export class TournamentResultService { if (checkedRiotMatchIds.has(riotMatchId)) continue; checkedRiotMatchIds.add(riotMatchId); - const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId }); + const alreadyMatched = await TournamentCodeModel.exists({ + riotMatchId, + }); if (alreadyMatched) continue; let detail: RiotMatchDto; @@ -309,7 +318,9 @@ export class TournamentResultService { } code.state = 'used'; - code.usedAt = new Date(detail.info.gameEndTimestamp ?? detail.info.gameCreation); + code.usedAt = new Date( + detail.info.gameEndTimestamp ?? detail.info.gameCreation, + ); code.riotMatchId = detail.metadata.matchId; await code.save(); @@ -318,6 +329,7 @@ export class TournamentResultService { match.status = 'in-progress'; } await match.save(); + await this.rebuildMatchStatsSafe(match); return true; } @@ -346,7 +358,11 @@ export class TournamentResultService { } this.upsertGameResult(match, gameResult); - await this.markTournamentCodeUsedForManualResult(match, gameResult, detail); + await this.markTournamentCodeUsedForManualResult( + match, + gameResult, + detail, + ); appliedRiotMatchIds.push(detail.metadata.matchId); appliedGameNumbers.push(gameResult.gameNumber); } @@ -356,6 +372,9 @@ export class TournamentResultService { } this.updateManualCollectionState(match, appliedRiotMatchIds.length); await match.save(); + if (appliedRiotMatchIds.length > 0) { + await this.rebuildMatchStatsSafe(match); + } if (this.hasAllRequiredGameResults(match)) { await this.finishMatchFromManualResults(match); } @@ -393,6 +412,7 @@ export class TournamentResultService { state: 'complete', }; await match.save(); + await this.rebuildMatchStatsSafe(match); void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { @@ -419,7 +439,8 @@ export class TournamentResultService { lastPolledAt: pollState?.lastPolledAt, lastPollOutcome: pollState?.lastPollOutcome, matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, + expandedToAllPuuids: + pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, state: 'expired', }; await match.save(); @@ -431,7 +452,8 @@ export class TournamentResultService { const expandedToAllPuuids = job.expandedToAllPuuids || - (elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0); + (elapsedMs >= EXPAND_AFTER_MS && + (match.result?.games?.length ?? 0) === 0); await this.riotJobQueueService.enqueueTournamentResultPoll({ matchId: match._id.toString(), attempt: job.attempt + 1, @@ -446,7 +468,9 @@ export class TournamentResultService { region: RiotRegionalRoute, ): Promise { const RiotMatchModel = await this.connectionService.getModel('riotMatch'); - const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec(); + const stored = await RiotMatchModel.findOne({ + matchId: riotMatchId, + }).exec(); if (isRiotMatchDto(stored?.raw)) return stored.raw; const dto = await this.riotMatchService.getMatch(riotMatchId, { region }); @@ -491,7 +515,9 @@ export class TournamentResultService { return details; } - private async buildPuuidLookup(match: MatchDocument): Promise { + private async buildPuuidLookup( + match: MatchDocument, + ): Promise { const puuidByUserId = new Map(); const userIdByPuuid = new Map(); @@ -651,6 +677,7 @@ export class TournamentResultService { state: 'complete', }; await match.save(); + await this.rebuildMatchStatsSafe(match); void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { @@ -662,6 +689,18 @@ export class TournamentResultService { }); } + 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 async markTournamentCodeUsedForManualResult( match: MatchDocument, gameResult: MatchGameResult, @@ -705,14 +744,12 @@ export class TournamentResultService { 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, - }; + 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 = @@ -750,10 +787,12 @@ export class TournamentResultService { const perSeries = match.gameCount || 1; const pairIndex = Math.max(0, Math.ceil(gameNumber / perSeries) - 1); - return roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { - teamAIndex: 1, - teamBIndex: 2, - }; + return ( + roundRobinPairs(resolveRoundRobinTeamCount(match))[pairIndex] ?? { + teamAIndex: 1, + teamBIndex: 2, + } + ); } const perSeries = match.gameCount || 1; @@ -832,9 +871,9 @@ export class TournamentResultService { 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), + match.tournamentCodeIds.length > 0 && + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), ); } @@ -855,8 +894,8 @@ export class TournamentResultService { private hasBuiltTeams(match: MatchDocument): boolean { return Boolean( match.teamBuiltAt && - match.teams.length >= 2 && - match.teams.every((team) => team.members.length > 0), + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), ); } @@ -887,8 +926,8 @@ export class TournamentResultService { function isRiotMatchDto(value: unknown): value is RiotMatchDto { return Boolean( value && - typeof value === 'object' && - 'metadata' in value && - 'info' in value, + typeof value === 'object' && + 'metadata' in value && + 'info' in value, ); }