From 2ee8c3807ba18404b696fe67ac2c4f65e9484288 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 28 Jun 2026 01:10:37 -0700 Subject: [PATCH] perf: aggregate champion stats in MongoDB --- .../match-history.service.spec.ts | 140 ++++++++++++++++++ .../match-history/match-history.service.ts | 137 +++++++++++++++-- 2 files changed, 261 insertions(+), 16 deletions(-) create mode 100644 apps/api/src/modules/match-history/match-history.service.spec.ts diff --git a/apps/api/src/modules/match-history/match-history.service.spec.ts b/apps/api/src/modules/match-history/match-history.service.spec.ts new file mode 100644 index 00000000..2c059e0e --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.service.spec.ts @@ -0,0 +1,140 @@ +import mongoose from 'mongoose'; +import { MatchHistoryService } from './match-history.service'; + +describe('MatchHistoryService.getChampionStats', () => { + it('aggregates champion stats in MongoDB with secondaryPreferred reads', async () => { + const communityId = new mongoose.Types.ObjectId(); + const userId = new mongoose.Types.ObjectId(); + const aggregateExec = jest.fn().mockResolvedValue([ + { + championId: 103, + games: 2, + wins: 1, + totalKills: 15, + totalDeaths: 5, + totalAssists: 20, + totalCs: 320, + totalGameMinutes: 62, + doubleKills: 2, + tripleKills: 1, + quadraKills: 0, + pentaKills: 0, + lastFetchedAt: new Date('2026-01-03T00:00:00.000Z'), + }, + { + championId: 64, + games: 1, + wins: 1, + totalKills: 5, + totalDeaths: 0, + totalAssists: 7, + totalCs: 110, + totalGameMinutes: 25, + doubleKills: 0, + tripleKills: 0, + quadraKills: 0, + pentaKills: 0, + lastFetchedAt: new Date('2026-01-04T00:00:00.000Z'), + }, + ]); + const read = jest.fn().mockReturnThis(); + const aggregate = jest.fn().mockReturnValue({ read, exec: aggregateExec }); + const UserModel = { + findById: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + _id: userId, + communityId, + riotAccounts: [ + { + puuid: 'puuid-1', + isPrimary: true, + recentStatsFetchedAt: new Date('2026-01-05T00:00:00.000Z'), + }, + ], + }), + }), + }; + const CommunityModel = { + findById: jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue({ + _id: communityId, + seasonStartedAt: new Date('2026-01-01T00:00:00.000Z'), + seasons: [ + { + id: 'current', + label: '현재 시즌', + startedAt: new Date('2026-01-01T00:00:00.000Z'), + }, + ], + }), + }), + }; + const connectionService = { + getModel: jest.fn(async (name: string) => { + if (name === 'user') return UserModel; + if (name === 'community') return CommunityModel; + if (name === 'riotMatch') return { aggregate }; + throw new Error(`Unexpected model: ${name}`); + }), + }; + const service = new MatchHistoryService(connectionService as never); + + const response = await service.getChampionStats({ + communityId, + userId, + filters: { queueGroup: 'summoners-rift', rank: 'all' }, + }); + + expect(aggregate).toHaveBeenCalledTimes(1); + expect(read).toHaveBeenCalledWith('secondaryPreferred'); + expect(aggregateExec).toHaveBeenCalledTimes(1); + expect(aggregate.mock.calls[0][0]).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + $match: expect.objectContaining({ + participantPuuids: 'puuid-1', + gameCreation: { + $gte: new Date('2026-01-01T00:00:00.000Z').getTime(), + }, + }), + }), + { $limit: 500 }, + expect.objectContaining({ $group: expect.any(Object) }), + ]), + ); + expect(response.champions).toEqual([ + expect.objectContaining({ + championId: 103, + games: 2, + wins: 1, + losses: 1, + winRate: 50, + avgKills: 7.5, + avgDeaths: 2.5, + avgAssists: 10, + kda: 7, + avgCs: 160, + }), + expect.objectContaining({ + championId: 64, + games: 1, + wins: 1, + losses: 0, + winRate: 100, + kda: 12, + }), + ]); + expect(response.totals).toEqual( + expect.objectContaining({ + championId: 0, + games: 3, + wins: 2, + losses: 1, + totalKills: 20, + totalDeaths: 5, + totalAssists: 27, + }), + ); + expect(response.lastFetchedAt).toBe('2026-01-03T00:00:00.000Z'); + }); +}); diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts index 895689f8..c70900cd 100644 --- a/apps/api/src/modules/match-history/match-history.service.ts +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -69,6 +69,10 @@ interface AggregatedChampion { pentaKills: number; } +interface ChampionAggregateRow extends AggregatedChampion { + lastFetchedAt?: Date; +} + @Injectable() export class MatchHistoryService { constructor(private readonly connectionService: ConnectionService) {} @@ -129,29 +133,17 @@ export class MatchHistoryService { const { queueGroup, rank, queueIds } = this.resolveQueueFilters( params.filters, ); - const docs = await this.findStoredMatches({ + const aggregates = await this.aggregateChampionStats({ context, queueIds, limit: MAX_AGGREGATE_MATCHES, }); - const aggregates = new Map(); - for (const doc of docs) { - const dto = doc.raw as unknown as RiotMatchDto; - const participant = this.findParticipant(dto, context.account.puuid); - if (!participant) continue; - const aggregate = - aggregates.get(participant.championId) ?? - this.createChampionAggregate(participant.championId); - this.addParticipantToChampionAggregate(aggregate, participant, dto); - aggregates.set(participant.championId, aggregate); - } - - const champions = [...aggregates.values()] + const champions = aggregates .map((aggregate) => this.toChampionStatsRow(aggregate)) .sort((a, b) => b.games - a.games || b.winRate - a.winRate); const totals = this.toChampionStatsRow( - [...aggregates.values()].reduce( + aggregates.reduce( (acc, aggregate) => this.mergeChampionAggregate(acc, aggregate), this.createChampionAggregate(0), ), @@ -162,7 +154,7 @@ export class MatchHistoryService { rank, queueIds, season: context.season, - lastFetchedAt: this.resolveLastFetchedAt(docs, context), + lastFetchedAt: this.resolveAggregateLastFetchedAt(aggregates, context), champions, totals, }; @@ -363,6 +355,101 @@ export class MatchHistoryService { .slice(0, params.limit); } + private async aggregateChampionStats(params: { + context: HistoryContext; + queueIds: number[]; + limit: number; + }): Promise { + if (params.queueIds.length === 0) return []; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const gameCreation: Record = {}; + if (params.context.seasonStartedAt) { + gameCreation.$gte = params.context.seasonStartedAt.getTime(); + } + + const match: Record = { + participantPuuids: params.context.account.puuid, + queueId: { $in: params.queueIds }, + }; + if (Object.keys(gameCreation).length > 0) match.gameCreation = gameCreation; + + return RiotMatchModel.aggregate([ + { $match: match }, + { $sort: { gameCreation: -1 } }, + { $limit: params.limit }, + { + $project: { + fetchedAt: 1, + gameDuration: '$raw.info.gameDuration', + participant: { + $first: { + $filter: { + input: '$raw.info.participants', + as: 'participant', + cond: { + $eq: ['$$participant.puuid', params.context.account.puuid], + }, + }, + }, + }, + }, + }, + { $match: { participant: { $ne: null } } }, + { + $group: { + _id: '$participant.championId', + championId: { $first: '$participant.championId' }, + games: { $sum: 1 }, + wins: { + $sum: { $cond: ['$participant.win', 1, 0] }, + }, + totalKills: { $sum: { $ifNull: ['$participant.kills', 0] } }, + totalDeaths: { $sum: { $ifNull: ['$participant.deaths', 0] } }, + totalAssists: { $sum: { $ifNull: ['$participant.assists', 0] } }, + totalCs: { + $sum: { + $add: [ + { $ifNull: ['$participant.totalMinionsKilled', 0] }, + { $ifNull: ['$participant.neutralMinionsKilled', 0] }, + ], + }, + }, + totalGameMinutes: { + $sum: { + $max: [ + { + $divide: [ + { + $ifNull: ['$participant.timePlayed', '$gameDuration'], + }, + 60, + ], + }, + 1, + ], + }, + }, + doubleKills: { + $sum: { $ifNull: ['$participant.doubleKills', 0] }, + }, + tripleKills: { + $sum: { $ifNull: ['$participant.tripleKills', 0] }, + }, + quadraKills: { + $sum: { $ifNull: ['$participant.quadraKills', 0] }, + }, + pentaKills: { + $sum: { $ifNull: ['$participant.pentaKills', 0] }, + }, + lastFetchedAt: { $min: '$fetchedAt' }, + }, + }, + { $sort: { games: -1, wins: -1, championId: 1 } }, + ]) + .read('secondaryPreferred') + .exec(); + } + private findParticipant( match: RiotMatchDto, puuid: string, @@ -760,6 +847,24 @@ export class MatchHistoryService { return oldest.toISOString(); } + private resolveAggregateLastFetchedAt( + rows: ChampionAggregateRow[], + context: HistoryContext, + ): string | null { + if (rows.length === 0) { + return context.account.recentStatsFetchedAt?.toISOString() ?? null; + } + const oldest = rows + .map((row) => row.lastFetchedAt) + .filter((value): value is Date => value instanceof Date) + .reduce( + (acc, value) => + !acc || value.getTime() < acc.getTime() ? value : acc, + null, + ); + return oldest?.toISOString() ?? null; + } + 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));