From aa675199afd271a8326b9f102c268709e25d1b5f Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Mon, 13 Jul 2026 09:35:25 +0000 Subject: [PATCH] feat: enrich internal match game analysis --- .gitignore | 2 + .../community-stats.service.spec.ts | 350 ++++++++++++-- .../community-stats.service.ts | 77 ++- .../community-stats/community-stats.types.ts | 5 + .../match-stats-fragment.builder.spec.ts | 438 +++++++++++++++++- .../match-stats-fragment.builder.ts | 384 ++++++++++++--- .../match-stats.service.spec.ts | 181 +++++++- .../community-stats/match-stats.service.ts | 71 ++- .../community-stats/match-stats.types.ts | 2 +- .../api/src/modules/global/database/schema.ts | 40 ++ .../modules/riot/riot-match.service.spec.ts | 48 ++ .../src/modules/riot/riot-match.service.ts | 4 + apps/api/src/modules/riot/riot.types.ts | 1 + apps/web/src/api/types.ts | 39 ++ .../components/InternalGameAnalysisTabs.tsx | 333 ++++++++----- apps/web/src/lib/internal-game-matchups.ts | 127 +++++ apps/web/src/lib/internal-match-timeline.ts | 218 +++++++++ apps/web/src/pages/MatchGameDetailPage.tsx | 434 ++++++++++++++++- apps/web/test/internal-game-matchups.test.ts | 134 ++++++ apps/web/test/internal-match-timeline.test.ts | 228 +++++++++ .../internal-match-game-analysis-p0-p1.md | 78 ++++ docs/specs/internal-match-game-analysis.md | 170 +++++++ 22 files changed, 3123 insertions(+), 241 deletions(-) create mode 100644 apps/web/src/lib/internal-game-matchups.ts create mode 100644 apps/web/src/lib/internal-match-timeline.ts create mode 100644 apps/web/test/internal-game-matchups.test.ts create mode 100644 apps/web/test/internal-match-timeline.test.ts create mode 100644 docs/plans/internal-match-game-analysis-p0-p1.md create mode 100644 docs/specs/internal-match-game-analysis.md diff --git a/.gitignore b/.gitignore index 18024dde..8c149245 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,8 @@ website/LICENSE *.md !README.md !AGENTS.md +!docs/specs/internal-match-game-analysis.md +!docs/plans/internal-match-game-analysis-p0-p1.md !agents/**/*.md !skills/**/*.md /tmp/ diff --git a/apps/api/src/modules/community-stats/community-stats.service.spec.ts b/apps/api/src/modules/community-stats/community-stats.service.spec.ts index 954a7b12..ba53125b 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.spec.ts @@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord { } describe('CommunityStatsService', () => { - it('ignores stale detail cache entries missing timeline build fields', async () => { + it('ignores detail caches missing unified events or containing invalid checkpoints', async () => { const communityId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); const match: InternalMatchCardView = { @@ -97,6 +97,20 @@ describe('CommunityStatsService', () => { seriesResults: [], }; const participant = record(matchId); + Object.assign(participant, { + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + }); const gameDetail: InternalGameDetail = { gameNumber: 1, riotMatchId: 'KR_1', @@ -125,38 +139,81 @@ describe('CommunityStatsService', () => { }, ], }; - const staleCache = { - match, - games: [ + Object.assign(gameDetail, { + timelineEvents: [ { - gameNumber: 1, - riotMatchId: 'KR_1', - gameCreation: 1_000, - gameDuration: 1_800, - teams: [ + timestamp: 300, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [], + }, + ], + }); + const otherwiseCompleteCachedGame = { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + timeline: [], + objectiveEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue' as const, + win: true, + objectives: objectives(), + bans: [], + participants: [ { - teamIndex: 1, - side: 'blue', - win: true, - objectives: { tower: 1, dragon: 0, baron: 0 }, - participants: [ - { - summonerName: 'Player', - perks: { - primaryStyle: 8000, - subStyle: 8400, - keystone: 8010, - }, - }, - ], + summonerName: 'Cached Player', + tagLine: 'KR1', + itemBuild: [], + skillBuild: [], }, ], }, ], + }; + const missingTimelineEventsCache = { + match, + games: [otherwiseCompleteCachedGame], } as unknown as InternalMatchDetailResponse; + const invalidCheckpointCache = { + match, + games: [ + { + ...otherwiseCompleteCachedGame, + timelineEvents: [], + teams: otherwiseCompleteCachedGame.teams.map((team) => ({ + ...team, + participants: team.participants.map((cachedParticipant) => ({ + ...cachedParticipant, + participantId: 1, + checkpoints: { + at10: { + timestamp: '590', + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + })), + })), + }, + ], + } as unknown as InternalMatchDetailResponse; + const setDetail = jest.fn().mockResolvedValue(undefined); const cacheService = { - get: jest.fn().mockResolvedValue(staleCache), - setDetail: jest.fn().mockResolvedValue(undefined), + get: jest + .fn() + .mockResolvedValueOnce(missingTimelineEventsCache) + .mockResolvedValueOnce(invalidCheckpointCache), + setDetail, } as unknown as jest.Mocked; const matchStatsService = { buildAndUpsert: jest.fn().mockResolvedValue(undefined), @@ -180,22 +237,245 @@ describe('CommunityStatsService', () => { detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]), }); - const response = await service.getMatchDetail({ communityId, matchId }); + const missingEventsResponse = await service.getMatchDetail({ + communityId, + matchId, + }); + const invalidCheckpointResponse = await service.getMatchDetail({ + communityId, + matchId, + }); - expect(response.games[0].timeline).toHaveLength(1); - expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength( - 1, - ); - expect(response.games[0].teams[0].participants[0].perks).toMatchObject({ - selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + expect(missingEventsResponse.games[0].timeline).toHaveLength(1); + expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1); + expect(invalidCheckpointResponse.games[0]).toMatchObject({ + timelineEvents: [ + { + timestamp: 300, + side: 'blue', + type: 'championKill', + }, + ], + }); + expect( + invalidCheckpointResponse.games[0].teams[0].participants[0], + ).toMatchObject({ + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + }, + itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }], + perks: { + selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451], + }, }); expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled(); - expect(cacheService.setDetail).toHaveBeenCalledWith( - expect.stringContaining(':r3:'), - response, + expect(setDetail).toHaveBeenCalledTimes(2); + expect(setDetail).toHaveBeenNthCalledWith( + 2, + expect.stringContaining(':r4:'), + invalidCheckpointResponse, ); }); + it('backs off failed timeline hydration and retries after the short cache expires', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const match: InternalMatchCardView = { + matchId: matchId.toString(), + title: '내전', + scheduledAt: '2026-06-18T12:00:00.000Z', + status: 'finished', + gameCount: 1, + games: [], + teams: [], + seriesResults: [], + }; + const participant = record(matchId); + const gameDetail: InternalGameDetail = { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + winnerSide: 'blue', + timelineLoaded: false, + timeline: [], + objectiveEvents: [], + timelineEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue', + win: true, + objectives: objectives(), + bans: [], + participants: [participant], + }, + ], + }; + const dataset = (timelineLoaded: boolean) => ({ + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [match], + records: [participant], + detailsByMatchId: new Map([ + [matchId.toString(), [{ ...gameDetail, timelineLoaded }]], + ]), + }); + let cachedResponse: InternalMatchDetailResponse | null = null; + const set = jest + .fn() + .mockImplementation( + (_key: string, value: InternalMatchDetailResponse) => { + cachedResponse = value; + return Promise.resolve(); + }, + ); + const setDetail = jest + .fn() + .mockImplementation( + (_key: string, value: InternalMatchDetailResponse) => { + cachedResponse = value; + return Promise.resolve(); + }, + ); + const cacheService = { + get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)), + set, + setDetail, + } as unknown as jest.Mocked; + const buildAndUpsert = jest.fn().mockResolvedValue(undefined); + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + { buildAndUpsert } as unknown as MatchStatsService, + ); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + jest + .fn() + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(false)) + .mockResolvedValueOnce(dataset(true)); + + const fallback = await service.getMatchDetail({ communityId, matchId }); + const backedOff = await service.getMatchDetail({ communityId, matchId }); + + expect(backedOff).toBe(fallback); + expect(buildAndUpsert).toHaveBeenCalledTimes(1); + expect(set).toHaveBeenCalledWith( + expect.stringContaining(':r4:'), + fallback, + 60, + ); + expect(setDetail).not.toHaveBeenCalled(); + + cachedResponse = null; + const recovered = await service.getMatchDetail({ communityId, matchId }); + + expect(buildAndUpsert).toHaveBeenCalledTimes(2); + expect(setDetail).toHaveBeenCalledTimes(1); + expect(setDetail).toHaveBeenCalledWith( + expect.stringContaining(':r4:'), + recovered, + ); + }); + + it('coalesces concurrent internal match detail cache misses', async () => { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const match: InternalMatchCardView = { + matchId: matchId.toString(), + title: '내전', + scheduledAt: '2026-06-18T12:00:00.000Z', + status: 'finished', + gameCount: 1, + games: [], + teams: [], + seriesResults: [], + }; + const participant = record(matchId); + const dataset = { + season: { + id: 'all', + label: '전체', + startTime: null, + endTime: null, + }, + matches: [match], + records: [participant], + detailsByMatchId: new Map([ + [ + matchId.toString(), + [ + { + gameNumber: 1, + riotMatchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1_800, + winnerSide: 'blue' as const, + timelineLoaded: true, + timeline: [], + objectiveEvents: [], + timelineEvents: [], + teams: [ + { + teamIndex: 1, + side: 'blue' as const, + win: true, + objectives: objectives(), + bans: [], + participants: [participant], + }, + ], + }, + ], + ], + ]), + }; + let resolveDataset: ((value: typeof dataset) => void) | undefined; + const datasetPromise = new Promise((resolve) => { + resolveDataset = resolve; + }); + const setDetail = jest.fn().mockResolvedValue(undefined); + const cacheService = { + get: jest.fn().mockResolvedValue(null), + setDetail, + } as unknown as jest.Mocked; + const service = new CommunityStatsService( + {} as ConnectionService, + cacheService, + {} as MatchStatsRepository, + {} as MatchStatsService, + ); + const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise); + (service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset = + buildBaseDataset; + + const first = service.getMatchDetail({ communityId, matchId }); + const second = service.getMatchDetail({ communityId, matchId }); + await Promise.resolve(); + resolveDataset?.(dataset); + const [firstResponse, secondResponse] = await Promise.all([first, second]); + + expect(firstResponse).toBe(secondResponse); + expect(buildBaseDataset).toHaveBeenCalledTimes(1); + expect(setDetail).toHaveBeenCalledTimes(1); + }); + it('includes internal match route fields in user internal history matches', async () => { const communityId = new mongoose.Types.ObjectId(); const matchId = new mongoose.Types.ObjectId(); 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 59cc774d..9c605fa3 100644 --- a/apps/api/src/modules/community-stats/community-stats.service.ts +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -40,7 +40,8 @@ const DEFAULT_LIST_LIMIT = 20; const MAX_LIST_LIMIT = 50; const MAX_MATCH_SCAN = 300; const MIN_HIGHLIGHT_GAMES = 5; -const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3; +const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4; +const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60; interface CommunityStatsContext { community: CommunityDocument; @@ -59,6 +60,10 @@ interface BaseDataset { @Injectable() export class CommunityStatsService { private readonly logger = new Logger(CommunityStatsService.name); + private readonly matchDetailInFlight = new Map< + string, + Promise + >(); private readonly userInternalHistoryInFlight = new Map< string, Promise @@ -219,6 +224,27 @@ export class CommunityStatsService { await this.cacheService.get(key); if (cached && isCompleteMatchDetailResponse(cached)) return cached; + const inFlight = this.matchDetailInFlight.get(key); + if (inFlight) return inFlight; + + const promise = this.buildMatchDetailResponse(params, key); + this.matchDetailInFlight.set(key, promise); + try { + return await promise; + } finally { + if (this.matchDetailInFlight.get(key) === promise) { + this.matchDetailInFlight.delete(key); + } + } + } + + private async buildMatchDetailResponse( + params: { + communityId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + }, + key: string, + ): Promise { const dataset = await this.buildBaseDataset(params.communityId, { seasonId: 'all', }); @@ -246,6 +272,7 @@ export class CommunityStatsService { gameVersion: game.gameVersion, timeline: game.timeline ?? [], objectiveEvents: game.objectiveEvents ?? [], + timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [], teams: game.teams.map((team) => ({ teamIndex: team.teamIndex, side: team.side, @@ -253,6 +280,8 @@ export class CommunityStatsService { objectives: team.objectives, bans: team.bans ?? [], participants: team.participants.map((record) => ({ + participantId: record.participantId, + checkpoints: record.checkpoints, userId: record.userId, summonerName: record.summonerName, tagLine: record.tagLine, @@ -289,7 +318,15 @@ export class CommunityStatsService { })), })), }; - await this.cacheService.setDetail(key, response); + if (gameDetails.every((game) => game.timelineLoaded === true)) { + await this.cacheService.setDetail(key, response); + } else { + await this.cacheService.set( + key, + response, + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS, + ); + } return response; } @@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse( (game) => Array.isArray(game.timeline) && Array.isArray(game.objectiveEvents) && + Array.isArray(game.timelineEvents) && game.teams.every( (team) => Array.isArray(team.bans) && @@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse( (participant) => typeof participant.tagLine === 'string' && Array.isArray(participant.itemBuild) && - Array.isArray(participant.skillBuild), + Array.isArray(participant.skillBuild) && + isOptionalFiniteNumber(participant.participantId) && + isCompleteParticipantCheckpoints(participant.checkpoints), ), ), ); } + +function isCompleteParticipantCheckpoints(value: unknown): boolean { + if (value === undefined) return true; + if (!isRecord(value)) return false; + return ['at10', 'at15'].every((key) => { + const checkpoint = value[key]; + if (checkpoint === undefined) return true; + if (!isRecord(checkpoint)) return false; + return [ + 'timestamp', + 'gold', + 'cs', + 'xp', + 'kills', + 'deaths', + 'assists', + ].every((field) => isFiniteNumber(checkpoint[field])); + }); +} + +function isOptionalFiniteNumber(value: unknown): boolean { + return value === undefined || isFiniteNumber(value); +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value); +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index 7fde72e2..e6824841 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -1,7 +1,9 @@ import type { + MatchStatsParticipantCheckpoints, MatchStatsItemBuildEvent, MatchStatsRunePerks, MatchStatsSkillBuildEvent, + MatchStatsTimelineEvent, RiotLane, TeamSide, } from '../global/database/schema'; @@ -128,6 +130,7 @@ export interface InternalMatchDetailResponse { type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; monsterSubType?: string; }>; + timelineEvents: MatchStatsTimelineEvent[]; teams: Array<{ teamIndex: number; side: TeamSide; @@ -143,6 +146,8 @@ export interface InternalMatchDetailResponse { }; bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ + participantId?: number; + checkpoints?: MatchStatsParticipantCheckpoints; userId: string | null; summonerName: string; tagLine: string; 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 index c7fde734..a805b23f 100644 --- 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 @@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => { it('builds rich set detail from raw Riot match data', () => { const builder = new MatchStatsFragmentBuilder(); const match = makeMatch(); + const redUserId = new mongoose.Types.ObjectId(); + match.participants.push({ + userId: redUserId, + puuid: 'puuid-2', + gameName: 'Opponent', + profileIconId: 8, + }); + match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' }); + match.result?.games[0].participants.push({ + userId: redUserId, + teamIndex: 2, + side: 'red', + championId: 24, + kills: 1, + deaths: 3, + assists: 0, + win: false, + }); const raw = { metadata: { dataVersion: '2', @@ -206,6 +224,51 @@ describe('MatchStatsFragmentBuilder', () => { ], }, }; + raw.info.participants.push( + { + ...raw.info.participants[0], + assists: 0, + championId: 24, + championName: 'Jax', + deaths: 3, + kills: 1, + participantId: 2, + puuid: 'puuid-2', + riotIdGameName: 'Opponent', + summonerId: 'summoner-2', + summonerName: 'Opponent', + teamId: 200, + win: false, + }, + { + ...raw.info.participants[0], + assists: 2, + championId: 64, + championName: 'LeeSin', + deaths: 0, + kills: 1, + participantId: 3, + puuid: 'puuid-3', + riotIdGameName: 'Jungler', + summonerId: 'summoner-3', + summonerName: 'Jungler', + teamId: 100, + }, + ); + raw.info.teams.push({ + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 3 }, + dragon: { first: false, kills: 0 }, + horde: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 200, + win: false, + }); const timeline = { metadata: { dataVersion: '2', @@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => { { timestamp: 0, participantFrames: { - '1': { participantId: 1, totalGold: 500, xp: 0 }, + '1': { + participantId: 1, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, + '2': { + participantId: 2, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, }, }, { @@ -291,7 +367,137 @@ describe('MatchStatsFragmentBuilder', () => { }, ], participantFrames: { - '1': { participantId: 1, totalGold: 1_150, xp: 550 }, + '1': { + participantId: 1, + totalGold: 1_150, + xp: 550, + minionsKilled: 5, + jungleMinionsKilled: 1, + }, + '2': { + participantId: 2, + totalGold: 1_050, + xp: 500, + minionsKilled: 4, + jungleMinionsKilled: 0, + }, + }, + }, + { + timestamp: 540_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 300_000, + killerId: 1, + victimId: 2, + assistingParticipantIds: [3], + }, + { + type: 'CHAMPION_KILL', + timestamp: 400_000, + killerId: 0, + victimId: 1, + }, + { + type: 'BUILDING_KILL', + timestamp: 450_000, + killerId: 0, + teamId: 200, + buildingType: 'TOWER_BUILDING', + towerType: 'OUTER_TURRET', + }, + { + type: 'BUILDING_KILL', + timestamp: 450_000, + killerId: 1, + teamId: 200, + buildingType: 'INHIBITOR_BUILDING', + }, + { + type: 'CHAMPION_KILL', + timestamp: 500_000, + killerId: 3, + victimId: 2, + assistingParticipantIds: [1], + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 4_900, + xp: 3_900, + minionsKilled: 72, + jungleMinionsKilled: 8, + }, + '2': { + participantId: 2, + totalGold: 4_300, + xp: 3_500, + minionsKilled: 68, + jungleMinionsKilled: 2, + }, + }, + }, + { + timestamp: 590_000, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 5_200, + xp: 4_200, + minionsKilled: 80, + jungleMinionsKilled: 10, + }, + }, + }, + { + timestamp: 900_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 900_000, + killerId: 1, + victimId: 2, + assistingParticipantIds: [3], + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 8_100, + xp: 7_300, + minionsKilled: 130, + jungleMinionsKilled: 15, + }, + '2': { + participantId: 2, + totalGold: 6_700, + xp: 6_100, + minionsKilled: 115, + jungleMinionsKilled: 5, + }, + }, + }, + { + timestamp: 1_800_000, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 12_500, + xp: 14_000, + minionsKilled: 205, + jungleMinionsKilled: 23, + }, + '2': { + participantId: 2, + totalGold: 10_200, + xp: 12_700, + minionsKilled: 190, + jungleMinionsKilled: 10, + }, }, }, ], @@ -329,19 +535,105 @@ describe('MatchStatsFragmentBuilder', () => { { timestamp: 0, blue: { gold: 500, xp: 0 }, - red: { gold: 0, xp: 0 }, - goldDiff: 500, + red: { gold: 500, xp: 0 }, + goldDiff: 0, xpDiff: 0, }, { timestamp: 60, blue: { gold: 1_150, xp: 550 }, + red: { gold: 1_050, xp: 500 }, + goldDiff: 100, + xpDiff: 50, + }, + { + timestamp: 540, + blue: { gold: 4_900, xp: 3_900 }, + red: { gold: 4_300, xp: 3_500 }, + goldDiff: 600, + xpDiff: 400, + }, + { + timestamp: 590, + blue: { gold: 5_200, xp: 4_200 }, red: { gold: 0, xp: 0 }, - goldDiff: 1_150, - xpDiff: 550, + goldDiff: 5_200, + xpDiff: 4_200, + }, + { + timestamp: 900, + blue: { gold: 8_100, xp: 7_300 }, + red: { gold: 6_700, xp: 6_100 }, + goldDiff: 1_400, + xpDiff: 1_200, + }, + { + timestamp: 1_800, + blue: { gold: 12_500, xp: 14_000 }, + red: { gold: 10_200, xp: 12_700 }, + goldDiff: 2_300, + xpDiff: 1_300, }, ], }); + expect(fragment.gameDetails[0].timelineEvents).toEqual([ + { + timestamp: 20, + side: 'blue', + type: 'dragon', + monsterSubType: 'FIRE_DRAGON', + }, + { + timestamp: 30, + side: 'blue', + type: 'elderDragon', + monsterSubType: 'ELDER_DRAGON', + }, + { timestamp: 40, side: 'blue', type: 'voidGrub' }, + { timestamp: 50, side: 'blue', type: 'baron' }, + { timestamp: 55, side: 'blue', type: 'riftHerald' }, + { + timestamp: 300, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [3], + }, + { + timestamp: 400, + type: 'championKill', + victimParticipantId: 1, + }, + { + timestamp: 450, + side: 'blue', + type: 'tower', + towerType: 'OUTER_TURRET', + }, + { + timestamp: 450, + side: 'blue', + type: 'inhibitor', + killerParticipantId: 1, + }, + { + timestamp: 500, + side: 'blue', + type: 'championKill', + killerParticipantId: 3, + victimParticipantId: 2, + assistingParticipantIds: [1], + }, + { + timestamp: 900, + side: 'blue', + type: 'championKill', + killerParticipantId: 1, + victimParticipantId: 2, + assistingParticipantIds: [3], + }, + ]); expect(fragment.gameDetails[0].teams[0].bans).toEqual([ { championId: 14, pickTurn: 1 }, { championId: 43, pickTurn: 2 }, @@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => { voidGrub: 1, }); expect(fragment.records[0]).toMatchObject({ + participantId: 1, + checkpoints: { + at10: { + timestamp: 590, + gold: 5_200, + cs: 90, + xp: 4_200, + kills: 1, + deaths: 1, + assists: 1, + }, + at15: { + timestamp: 900, + gold: 8_100, + cs: 145, + xp: 7_300, + kills: 2, + deaths: 1, + assists: 1, + }, + }, championLevel: 15, cs: 228, damageDealtToChampions: 18_765, @@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => { { timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' }, ], }); + expect(fragment.records[1]).toMatchObject({ + participantId: 2, + checkpoints: { + at15: { + timestamp: 900, + gold: 6_700, + cs: 120, + xp: 6_100, + kills: 0, + deaths: 3, + assists: 0, + }, + }, + }); + expect(fragment.records[1].checkpoints).not.toHaveProperty('at10'); + + const timelineWithoutEvents = { + ...timeline, + info: { + ...timeline.info, + frames: timeline.info.frames.map((frame) => ({ + ...frame, + events: [], + })), + }, + } as RiotMatchTimelineDto; + const objectiveFallback = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]), + }); + expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({ + baron: 1, + dragon: 2, + elderDragon: 0, + riftHerald: 0, + voidGrub: 3, + }); + + const dragonOnlyTimeline = { + ...timeline, + info: { + ...timeline.info, + frames: timeline.info.frames.map((frame) => ({ + ...frame, + events: (frame.events ?? []).filter( + (event) => + event.type !== 'ELITE_MONSTER_KILL' || + event.monsterType === 'DRAGON', + ), + })), + }, + } as RiotMatchTimelineDto; + const partialObjectiveFallback = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]), + }); + expect( + partialObjectiveFallback.gameDetails[0].teams[0].objectives, + ).toMatchObject({ + baron: 1, + dragon: 1, + elderDragon: 1, + riftHerald: 0, + voidGrub: 3, + }); + + const shortMatch = { + ...match, + result: { + ...match.result!, + games: match.result!.games.map((game) => ({ + ...game, + gameDuration: 599, + })), + }, + } as MatchDocument; + const shortFragment = builder.buildFragment({ + match: shortMatch, + rawByRiotMatchId: new Map([ + [ + 'KR_1', + { + ...raw, + info: { ...raw.info, gameDuration: 599 }, + } as RiotMatchDto, + ], + ]), + timelineByRiotMatchId: new Map([ + ['KR_1', timeline as RiotMatchTimelineDto], + ]), + }); + expect( + shortFragment.records.every((record) => record.checkpoints === undefined), + ).toBe(true); + + const invalidIntervalTimeline = { + ...timeline, + info: { ...timeline.info, frameInterval: Number.NaN }, + } as RiotMatchTimelineDto; + const invalidIntervalFragment = builder.buildFragment({ + match, + rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]), + timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]), + }); + expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false); + expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]); + expect( + invalidIntervalFragment.records.every( + (record) => record.checkpoints === undefined, + ), + ).toBe(true); }); }); 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 index dc7860e0..c91a5d77 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -3,10 +3,13 @@ import mongoose from 'mongoose'; import type { MatchDocument, MatchGameResultParticipant, + MatchStatsCheckpoint, MatchStatsItemBuildEvent, MatchStatsObjectiveEvent, MatchStatsObjectiveSummary, + MatchStatsParticipantCheckpoints, MatchStatsSkillBuildEvent, + MatchStatsTimelineEvent, MatchStatsTimelinePoint, TeamSide, } from '../global/database/schema'; @@ -27,13 +30,17 @@ interface ParticipantBuildEvents { skills: MatchStatsSkillBuildEvent[]; } +interface TimelineProjection { + objectiveEvents: MatchStatsObjectiveEvent[]; + timelineEvents: MatchStatsTimelineEvent[]; +} + @Injectable() export class MatchStatsFragmentBuilder { public buildFragment(params: { match: MatchDocument; rawByRiotMatchId: Map; timelineByRiotMatchId?: Map; - timelineLoadAttempted?: boolean; }): MatchStatsFragment { const games = [...(params.match.result?.games ?? [])].sort( (left, right) => left.gameNumber - right.gameNumber, @@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder { const raw = params.rawByRiotMatchId.get(game.riotMatchId); const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId); return raw - ? this.toGameDetail( - params.match, - game, - raw, - timeline, - params.timelineLoadAttempted === true, - ) + ? this.toGameDetail(params.match, game, raw, timeline) : this.toFallbackGameDetail(params.match, game); }); const records = gameDetails.flatMap((detail) => @@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder { game: NonNullable['games'][number], raw: RiotMatchDto, timeline?: RiotMatchTimelineDto, - timelineLoadAttempted = false, ): InternalGameDetail { + const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration) + ? timeline + : undefined; const puuidByUserId = new Map( match.participants .filter((participant) => participant.puuid) @@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder { raw, rawTeamIdBySide, ); - const objectiveEvents = this.toObjectiveEvents( - timeline, + const { objectiveEvents, timelineEvents } = this.toTimelineEvents( + usableTimeline, rawTeamIdBySide, sideByParticipantId, ); const timelineObjectives = this.toTimelineObjectives(objectiveEvents); const buildEventsByParticipantId = - this.toBuildEventsByParticipantId(timeline); + this.toBuildEventsByParticipantId(usableTimeline); + const checkpointsByParticipantId = this.toCheckpointsByParticipantId( + usableTimeline, + raw.info.gameDuration, + ); return { gameNumber: game.gameNumber, @@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder { gameDuration: game.gameDuration, gameVersion: raw.info.gameVersion, winnerSide: game.winnerSide, - timeline: this.toTimeline(raw, rawTeamIdBySide, timeline), - timelineLoaded: timelineLoadAttempted || Boolean(timeline), + timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline), + timelineLoaded: Boolean(usableTimeline), objectiveEvents, + timelineEvents, teams: (['blue', 'red'] as TeamSide[]).map((side) => { const teamIndex = side === 'blue' ? game.blueTeamIndex : game.redTeamIndex; @@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder { objectives: this.toObjectiveSummary( rawTeam, timelineObjectives.get(side), - Boolean(timeline), ), bans: (rawTeam?.bans ?? []).map((ban) => ({ championId: ban.championId, @@ -224,6 +231,9 @@ export class MatchStatsFragmentBuilder { rawParticipant.participantId, ) : undefined, + checkpoints: rawParticipant + ? checkpointsByParticipantId.get(rawParticipant.participantId) + : undefined, teamKills, teamDamage, }); @@ -246,6 +256,7 @@ export class MatchStatsFragmentBuilder { timeline: [], timelineLoaded: false, objectiveEvents: [], + timelineEvents: [], teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex, side, @@ -273,6 +284,7 @@ export class MatchStatsFragmentBuilder { participant: MatchGameResultParticipant; rawParticipant?: RiotMatchParticipantDto; buildEvents?: ParticipantBuildEvents; + checkpoints?: MatchStatsParticipantCheckpoints; teamKills: number; teamDamage: number; }): InternalRecord { @@ -282,6 +294,7 @@ export class MatchStatsFragmentBuilder { participant, rawParticipant, buildEvents, + checkpoints, teamKills, teamDamage, } = params; @@ -319,6 +332,8 @@ export class MatchStatsFragmentBuilder { riotMatchId: game.riotMatchId, gameCreation: game.gameCreation, gameDuration: game.gameDuration, + participantId: rawParticipant?.participantId, + checkpoints, userId: participant.userId.toString(), summonerName: snapshot?.gameName ?? @@ -455,6 +470,107 @@ export class MatchStatsFragmentBuilder { return buildEventsByParticipantId; } + private toCheckpointsByParticipantId( + timeline: RiotMatchTimelineDto | undefined, + gameDurationSeconds: number, + ): Map { + const checkpointsByParticipantId = new Map< + number, + MatchStatsParticipantCheckpoints + >(); + if ( + !timeline?.info.frames.length || + !Number.isFinite(timeline.info.frameInterval) || + timeline.info.frameInterval <= 0 + ) { + return checkpointsByParticipantId; + } + + const participantIds = new Set(); + const championKillEvents = timeline.info.frames.flatMap((frame) => + (frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'), + ); + for (const frame of timeline.info.frames) { + for (const participantFrame of Object.values(frame.participantFrames)) { + participantIds.add(participantFrame.participantId); + } + } + + const targets = [ + ['at10', 600_000], + ['at15', 900_000], + ] as const; + for (const participantId of participantIds) { + const checkpoints: MatchStatsParticipantCheckpoints = {}; + for (const [key, targetTimestamp] of targets) { + if (gameDurationSeconds * 1_000 < targetTimestamp) continue; + + const selectedFrame = timeline.info.frames.reduce< + RiotMatchTimelineDto['info']['frames'][number] | undefined + >((latest, frame) => { + if ( + frame.timestamp > targetTimestamp || + !Object.values(frame.participantFrames).some( + (participantFrame) => + participantFrame.participantId === participantId, + ) + ) { + return latest; + } + return !latest || frame.timestamp > latest.timestamp ? frame : latest; + }, undefined); + if ( + !selectedFrame || + targetTimestamp - selectedFrame.timestamp >= + timeline.info.frameInterval + ) { + continue; + } + + const participantFrame = Object.values( + selectedFrame.participantFrames, + ).find((frame) => frame.participantId === participantId); + if ( + !participantFrame || + typeof participantFrame.minionsKilled !== 'number' || + !Number.isFinite(participantFrame.minionsKilled) || + typeof participantFrame.jungleMinionsKilled !== 'number' || + !Number.isFinite(participantFrame.jungleMinionsKilled) + ) { + continue; + } + + const checkpoint: MatchStatsCheckpoint = { + timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)), + gold: participantFrame.totalGold, + cs: + participantFrame.minionsKilled + + participantFrame.jungleMinionsKilled, + xp: participantFrame.xp, + kills: 0, + deaths: 0, + assists: 0, + }; + for (const event of championKillEvents) { + if (event.timestamp > selectedFrame.timestamp) continue; + if (event.killerId === participantId && event.killerId > 0) { + checkpoint.kills += 1; + } + if (event.victimId === participantId) checkpoint.deaths += 1; + if (event.assistingParticipantIds?.includes(participantId)) { + checkpoint.assists += 1; + } + } + checkpoints[key] = checkpoint; + } + if (checkpoints.at10 || checkpoints.at15) { + checkpointsByParticipantId.set(participantId, checkpoints); + } + } + + return checkpointsByParticipantId; + } + private toTimeline( raw: RiotMatchDto, rawTeamIdBySide: Map, @@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder { return sideByParticipantId; } - private toObjectiveEvents( + private toTimelineEvents( timeline: RiotMatchTimelineDto | undefined, rawTeamIdBySide: Map, sideByParticipantId: Map, - ): MatchStatsObjectiveEvent[] { - if (!timeline?.info.frames.length) return []; + ): TimelineProjection { + if (!timeline?.info.frames.length) { + return { objectiveEvents: [], timelineEvents: [] }; + } const sideByTeamId = new Map(); for (const [side, teamId] of rawTeamIdBySide.entries()) { sideByTeamId.set(teamId, side); } - const objectiveEvents: MatchStatsObjectiveEvent[] = []; + const projected: Array<{ + sourceSequence: number; + event: MatchStatsTimelineEvent; + }> = []; + let sourceSequence = 0; for (const frame of timeline.info.frames) { for (const event of frame.events ?? []) { - if (event.type !== 'ELITE_MONSTER_KILL') continue; - const side = - (typeof event.killerTeamId === 'number' - ? sideByTeamId.get(event.killerTeamId) - : undefined) ?? - (typeof event.killerId === 'number' - ? sideByParticipantId.get(event.killerId) - : undefined); - if (!side) continue; + const currentSequence = sourceSequence; + sourceSequence += 1; const timestamp = Math.max(0, Math.round(event.timestamp / 1000)); - switch (event.monsterType) { - case 'BARON_NASHOR': - objectiveEvents.push({ timestamp, side, type: 'baron' }); - break; - case 'RIFTHERALD': - objectiveEvents.push({ timestamp, side, type: 'riftHerald' }); - break; - case 'HORDE': - objectiveEvents.push({ timestamp, side, type: 'voidGrub' }); - break; - case 'DRAGON': - if (event.monsterSubType === 'ELDER_DRAGON') { - objectiveEvents.push({ - timestamp, - side, - type: 'elderDragon', - monsterSubType: event.monsterSubType, - }); - } else { - objectiveEvents.push({ - timestamp, - side, - type: 'dragon', - monsterSubType: event.monsterSubType, - }); - } - break; - default: - break; + if (event.type === 'ELITE_MONSTER_KILL') { + const side = + (typeof event.killerTeamId === 'number' + ? sideByTeamId.get(event.killerTeamId) + : undefined) ?? + (typeof event.killerId === 'number' + ? sideByParticipantId.get(event.killerId) + : undefined); + if (!side) continue; + const objectiveEvent = toObjectiveTimelineEvent({ + timestamp, + side, + monsterType: event.monsterType, + monsterSubType: event.monsterSubType, + }); + if (objectiveEvent) { + projected.push({ + sourceSequence: currentSequence, + event: objectiveEvent, + }); + } + continue; } + + if (event.type === 'CHAMPION_KILL') { + const side = + typeof event.killerId === 'number' && event.killerId > 0 + ? sideByParticipantId.get(event.killerId) + : undefined; + projected.push({ + sourceSequence: currentSequence, + event: { + timestamp, + type: 'championKill', + ...(side ? { side } : {}), + ...(typeof event.killerId === 'number' && event.killerId > 0 + ? { killerParticipantId: event.killerId } + : {}), + ...(typeof event.victimId === 'number' && event.victimId > 0 + ? { victimParticipantId: event.victimId } + : {}), + ...(event.assistingParticipantIds + ? { assistingParticipantIds: event.assistingParticipantIds } + : {}), + }, + }); + continue; + } + + if (event.type !== 'BUILDING_KILL') continue; + const destroyedSide = + typeof event.teamId === 'number' + ? sideByTeamId.get(event.teamId) + : undefined; + const side = + (typeof event.killerId === 'number' && event.killerId > 0 + ? sideByParticipantId.get(event.killerId) + : undefined) ?? + (destroyedSide ? oppositeSide(destroyedSide) : undefined); + const type = + event.buildingType === 'TOWER_BUILDING' + ? 'tower' + : event.buildingType === 'INHIBITOR_BUILDING' + ? 'inhibitor' + : undefined; + if (!side || !type) continue; + projected.push({ + sourceSequence: currentSequence, + event: { + timestamp, + side, + type, + ...(typeof event.killerId === 'number' && event.killerId > 0 + ? { killerParticipantId: event.killerId } + : {}), + ...(type === 'tower' && event.towerType + ? { towerType: event.towerType } + : {}), + }, + }); } } - return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp); + const timelineEvents = projected + .sort( + (left, right) => + left.event.timestamp - right.event.timestamp || + left.sourceSequence - right.sourceSequence, + ) + .map(({ event }) => event); + return { + timelineEvents, + objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent), + }; } private toTimelineObjectives( @@ -608,29 +783,29 @@ export class MatchStatsFragmentBuilder { } private toObjectiveSummary( - rawTeam: - | RiotMatchDto['info']['teams'][number] - | undefined, + rawTeam: RiotMatchDto['info']['teams'][number] | undefined, timelineObjectives: MatchStatsObjectiveSummary | undefined, - hasTimeline: boolean, ): MatchStatsObjectiveSummary { const rawObjectives = rawTeam?.objectives; + const timelineDragon = timelineObjectives?.dragon ?? 0; + const timelineElder = timelineObjectives?.elderDragon ?? 0; + const hasProjectedDragon = timelineDragon + timelineElder > 0; return { tower: rawObjectives?.tower?.kills ?? 0, - dragon: hasTimeline - ? (timelineObjectives?.dragon ?? 0) + dragon: hasProjectedDragon + ? timelineDragon : (rawObjectives?.dragon?.kills ?? 0), inhibitor: rawObjectives?.inhibitor?.kills ?? 0, - baron: hasTimeline + baron: (timelineObjectives?.baron ?? 0) > 0 ? (timelineObjectives?.baron ?? 0) : (rawObjectives?.baron?.kills ?? 0), - riftHerald: hasTimeline + riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0 ? (timelineObjectives?.riftHerald ?? 0) : (rawObjectives?.riftHerald?.kills ?? 0), - voidGrub: hasTimeline + voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0 ? (timelineObjectives?.voidGrub ?? 0) : (rawObjectives?.horde?.kills ?? 0), - elderDragon: timelineObjectives?.elderDragon ?? 0, + elderDragon: hasProjectedDragon ? timelineElder : 0, }; } @@ -687,6 +862,79 @@ function toItemBuildType( } } +function toObjectiveTimelineEvent(params: { + timestamp: number; + side: TeamSide; + monsterType?: string; + monsterSubType?: string; +}): MatchStatsObjectiveEvent | null { + switch (params.monsterType) { + case 'BARON_NASHOR': + return { timestamp: params.timestamp, side: params.side, type: 'baron' }; + case 'RIFTHERALD': + return { + timestamp: params.timestamp, + side: params.side, + type: 'riftHerald', + }; + case 'HORDE': + return { + timestamp: params.timestamp, + side: params.side, + type: 'voidGrub', + }; + case 'DRAGON': + return { + timestamp: params.timestamp, + side: params.side, + type: + params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon', + monsterSubType: params.monsterSubType, + }; + default: + return null; + } +} + +function isObjectiveTimelineEvent( + event: MatchStatsTimelineEvent, +): event is MatchStatsObjectiveEvent { + return ( + event.type === 'dragon' || + event.type === 'elderDragon' || + event.type === 'baron' || + event.type === 'riftHerald' || + event.type === 'voidGrub' + ); +} + +function oppositeSide(side: TeamSide): TeamSide { + return side === 'blue' ? 'red' : 'blue'; +} + +function isUsableTimeline( + timeline: RiotMatchTimelineDto | undefined, + gameDurationSeconds: number, +): timeline is RiotMatchTimelineDto { + if ( + !timeline || + !Number.isFinite(timeline.info.frameInterval) || + timeline.info.frameInterval <= 0 || + !Array.isArray(timeline.info.frames) || + timeline.info.frames.length === 0 + ) { + return false; + } + const finalTimestamp = Math.max( + ...timeline.info.frames.map((frame) => frame.timestamp), + ); + return ( + Number.isFinite(finalTimestamp) && + Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) < + timeline.info.frameInterval + ); +} + function round(value: number): number { return Math.round(value * 10) / 10; } 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 index 4c76b51a..a2e6e5e3 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.spec.ts @@ -3,6 +3,7 @@ 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'; +import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types'; describe('MatchStatsService', () => { it('deletes an existing fragment when the match is no longer eligible', async () => { @@ -158,8 +159,10 @@ describe('MatchStatsService', () => { match, rawByRiotMatchId: expect.any(Map), timelineByRiotMatchId: expect.any(Map), - timelineLoadAttempted: false, }); + expect( + builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId, + ).toHaveProperty('size', 0); expect(repository.upsert).toHaveBeenCalledWith( expect.objectContaining({ matchId, @@ -167,11 +170,169 @@ describe('MatchStatsService', () => { scheduledAt, gameCreationMin: 1_000, gameCreationMax: 2_000, - builderVersion: 9, + builderVersion: MATCH_STATS_BUILDER_VERSION, }), ); }); + it('retries unusable timeline caches and stores a later usable fetch', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const match = { + _id: matchId, + communityId, + scheduledAt: new Date('2026-05-03T00:00:00.000Z'), + status: 'finished', + result: { games: [{ riotMatchId: 'KR_1' }] }, + }; + const emptyTimeline = { + info: { frameInterval: 60_000, frames: [] }, + }; + const partialTimeline = { + info: { + frameInterval: 60_000, + frames: [{ timestamp: 0, events: [] }], + }, + }; + const nonPositiveTimeline = { + info: { + frameInterval: 0, + frames: [timelineFrame(120_000)], + }, + }; + const truncatedTimeline = { + info: { + frameInterval: 60_000, + frames: [timelineFrame()], + }, + }; + const usableTimeline = { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [timelineFrame(120_000)], + }, + }; + const cachedTimelines = [ + emptyTimeline, + partialTimeline, + nonPositiveTimeline, + truncatedTimeline, + ]; + let buildIndex = 0; + const riotFind = jest.fn().mockImplementation(() => ({ + lean: () => ({ + exec: jest.fn().mockResolvedValue([ + { + matchId: 'KR_1', + raw: { info: { gameDuration: 120 } }, + timeline: cachedTimelines[Math.min(buildIndex++, 3)], + }, + ]), + }), + })); + const updateExec = jest.fn().mockResolvedValue(undefined); + let storedUpdate: + | { + filter: unknown; + update: { $set: { timeline: unknown; timelineFetchedAt: Date } }; + } + | undefined; + const updateOne = jest.fn( + ( + filter: unknown, + update: { $set: { timeline: unknown; timelineFetchedAt: Date } }, + ) => { + storedUpdate = { filter, update }; + return { exec: updateExec }; + }, + ); + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + if (name === 'match') { + return Promise.resolve({ findById: () => queryResult(match, false) }); + } + if (name === 'competition') { + return Promise.resolve({ findOne: () => queryResult(null) }); + } + if (name === 'riotMatch') { + return Promise.resolve({ find: riotFind, updateOne }); + } + if (name === 'community') { + return Promise.resolve({ + findById: () => ({ + select: () => queryResult({ riotRegion: 'asia' }), + }), + }); + } + return Promise.reject(new Error(`Unexpected model: ${name}`)); + }), + } as unknown as ConnectionService; + const repository = { + upsert: jest.fn().mockResolvedValue(undefined), + deleteByMatch: jest.fn(), + deleteLegacyByMatch: jest.fn(), + } as unknown as jest.Mocked; + type BuildParams = Parameters< + MatchStatsFragmentBuilder['buildFragment'] + >[0]; + const buildCalls: BuildParams[] = []; + const builtFragment = { + matchCard: { matchId: matchId.toString() }, + records: [], + gameDetails: [], + userIds: [], + championIds: [], + gameCreationMin: 1_000, + gameCreationMax: 2_000, + } as ReturnType; + const buildFragment = jest.fn((params: BuildParams) => { + buildCalls.push(params); + return builtFragment; + }); + const builder = { + buildFragment, + } as unknown as jest.Mocked; + const getMatchTimeline = jest + .fn() + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockRejectedValueOnce(new Error('temporary Riot failure')) + .mockResolvedValueOnce(usableTimeline); + const service = new MatchStatsService( + connectionService, + repository, + builder, + { getMatchTimeline } as never, + ); + + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + await service.buildAndUpsert(matchId, { includeTimeline: true }); + + expect(getMatchTimeline).toHaveBeenCalledTimes(4); + expect(buildFragment).toHaveBeenCalledTimes(4); + expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0); + expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0); + expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined(); + expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe( + usableTimeline, + ); + for (const call of buildCalls) { + expect(call).not.toHaveProperty('timelineLoadAttempted'); + } + expect(updateOne).toHaveBeenCalledTimes(1); + expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' }); + expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline); + expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date); + expect(updateExec).toHaveBeenCalledTimes(1); + }); + it('builds from the Competition projection and records its source revision', async () => { const matchId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId(); @@ -451,3 +612,19 @@ function queryResult(value: T, lean = true) { query.lean.mockReturnValue(query); return lean ? query : { exec: query.exec }; } + +function timelineFrame(timestamp = 0) { + return { + timestamp, + events: [], + participantFrames: { + '1': { + participantId: 1, + totalGold: 500, + xp: 0, + minionsKilled: 0, + jungleMinionsKilled: 0, + }, + }, + }; +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts index 1b54c86b..6978276a 100644 --- a/apps/api/src/modules/community-stats/match-stats.service.ts +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -77,7 +77,7 @@ export class MatchStatsService { ); const timelineByRiotMatchId = new Map(); for (const doc of riotDocs) { - if (isRiotMatchTimelineDto(doc.timeline)) { + if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) { timelineByRiotMatchId.set(doc.matchId, doc.timeline); } } @@ -94,6 +94,12 @@ export class MatchStatsService { doc.matchId, { region }, ); + if (!isUsableRiotMatchTimeline(timeline, doc.raw)) { + this.logger.warn( + `Ignored unusable match timeline for ${doc.matchId}.`, + ); + continue; + } await RiotMatchModel.updateOne( { matchId: doc.matchId }, { @@ -118,7 +124,6 @@ export class MatchStatsService { match: sourceMatch, rawByRiotMatchId, timelineByRiotMatchId, - timelineLoadAttempted: options.includeTimeline === true, }); await this.repository.upsert({ @@ -253,9 +258,65 @@ export class MatchStatsService { } } -function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto { - if (!isRecord(value) || !isRecord(value.info)) return false; - return Array.isArray(value.info.frames); +function isUsableRiotMatchTimeline( + value: unknown, + rawMatch: unknown, +): value is RiotMatchTimelineDto { + if ( + !isRecord(value) || + !isRecord(value.info) || + !isRecord(rawMatch) || + !isRecord(rawMatch.info) + ) { + return false; + } + const frameInterval = finiteNumber(value.info.frameInterval); + const gameDuration = finiteNumber(rawMatch.info.gameDuration); + const frames = value.info.frames; + if ( + frameInterval === undefined || + frameInterval <= 0 || + gameDuration === undefined || + gameDuration < 0 || + !Array.isArray(frames) || + frames.length === 0 || + !frames.every(isUsableTimelineFrame) + ) { + return false; + } + + const lastTimestamp = Math.max( + ...frames.map((frame) => (frame as { timestamp: number }).timestamp), + ); + return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval; +} + +function isUsableTimelineFrame(value: unknown): boolean { + if ( + !isRecord(value) || + finiteNumber(value.timestamp) === undefined || + !Array.isArray(value.events) || + !value.events.every( + (event) => + isRecord(event) && + typeof event.type === 'string' && + finiteNumber(event.timestamp) !== undefined, + ) || + !isRecord(value.participantFrames) + ) { + return false; + } + const participantFrames = Object.values(value.participantFrames); + return ( + participantFrames.length > 0 && + participantFrames.every( + (participantFrame) => + isRecord(participantFrame) && + finiteNumber(participantFrame.participantId) !== undefined && + finiteNumber(participantFrame.totalGold) !== undefined && + finiteNumber(participantFrame.xp) !== undefined, + ) + ); } function isRecord(value: unknown): value is Record { diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts index d77cb8a1..a864c124 100644 --- a/apps/api/src/modules/community-stats/match-stats.types.ts +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -4,7 +4,7 @@ import type { } from '../global/database/schema'; import type { InternalMatchCardView } from './community-stats.types'; -export const MATCH_STATS_BUILDER_VERSION = 9; +export const MATCH_STATS_BUILDER_VERSION = 10; export type InternalRecord = MatchStatsRecord; export type InternalGameDetail = MatchStatsGameDetail; diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts index a162f2b6..f42da202 100644 --- a/apps/api/src/modules/global/database/schema.ts +++ b/apps/api/src/modules/global/database/schema.ts @@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent { levelUpType?: string; } +export interface MatchStatsCheckpoint { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; +} + +export interface MatchStatsParticipantCheckpoints { + at10?: MatchStatsCheckpoint; + at15?: MatchStatsCheckpoint; +} + export interface MatchStatsRecord { matchId: string; title: string; @@ -948,6 +963,8 @@ export interface MatchStatsRecord { riotMatchId: string; gameCreation: number; gameDuration: number; + participantId?: number; + checkpoints?: MatchStatsParticipantCheckpoints; userId: string; summonerName: string; tagLine: string; @@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail { timeline: MatchStatsTimelinePoint[]; timelineLoaded?: boolean; objectiveEvents: MatchStatsObjectiveEvent[]; + timelineEvents?: MatchStatsTimelineEvent[]; teams: Array<{ teamIndex: number; side: TeamSide; @@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent { monsterSubType?: string; } +export interface MatchStatsChampionKillEvent { + timestamp: number; + side?: TeamSide; + type: 'championKill'; + killerParticipantId?: number; + victimParticipantId?: number; + assistingParticipantIds?: number[]; +} + +export interface MatchStatsBuildingEvent { + timestamp: number; + side: TeamSide; + type: 'tower' | 'inhibitor'; + killerParticipantId?: number; + towerType?: string; +} + +export type MatchStatsTimelineEvent = + | MatchStatsObjectiveEvent + | MatchStatsChampionKillEvent + | MatchStatsBuildingEvent; + export interface MatchStatsTimelinePoint { timestamp: number; blue: { gold: number; xp: number }; diff --git a/apps/api/src/modules/riot/riot-match.service.spec.ts b/apps/api/src/modules/riot/riot-match.service.spec.ts index bcc3b321..84475301 100644 --- a/apps/api/src/modules/riot/riot-match.service.spec.ts +++ b/apps/api/src/modules/riot/riot-match.service.spec.ts @@ -214,4 +214,52 @@ describe('RiotMatchService', () => { levelUpType: 'NORMAL', }); }); + + it('rejects non-numeric champion kill victim ids', async () => { + const payload = { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + frameInterval: 60_000, + frames: [ + { + timestamp: 60_000, + events: [ + { + type: 'CHAMPION_KILL', + timestamp: 30_000, + killerId: 1, + victimId: '2', + }, + ], + participantFrames: { + '1': { + participantId: 1, + totalGold: 1_150, + xp: 550, + }, + }, + }, + ], + }, + }; + const riotClientService = { + get: jest.fn( + (_path: string, _options: unknown, parser?: RiotResponseParser) => + Promise.resolve().then(() => + parser ? parser(payload) : (payload as T), + ), + ), + } as unknown as RiotClientService; + const service = new RiotMatchService(riotClientService); + + await expect( + service.getMatchTimeline('KR_8188913502', { region: 'asia' }), + ).rejects.toThrow( + 'timeline.info.frames[0].events[0].victimId must be a finite number when present.', + ); + }); }); diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts index 2f82ce4d..7dfb0020 100644 --- a/apps/api/src/modules/riot/riot-match.service.ts +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -415,6 +415,10 @@ function parseTimelineEvent( value.type, `timeline.info.frames[${frameIndex}].events[${eventIndex}].type`, ), + victimId: optionalNumber( + value.victimId, + `timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`, + ), }; } diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts index 2590b7de..7119c6a3 100644 --- a/apps/api/src/modules/riot/riot.types.ts +++ b/apps/api/src/modules/riot/riot.types.ts @@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record { skillSlot?: number; teamId?: number; towerType?: string; + victimId?: number; } export interface RiotMatchTimelineParticipantFrameDto diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 09523bf6..96a337b1 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -701,6 +701,24 @@ export interface ApiInternalMatchDetailResponse { type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub'; monsterSubType?: string; }>; + timelineEvents?: Array<{ + timestamp: number; + side?: TeamSide; + type: + | 'dragon' + | 'elderDragon' + | 'baron' + | 'riftHerald' + | 'voidGrub' + | 'championKill' + | 'tower' + | 'inhibitor'; + monsterSubType?: string; + killerParticipantId?: number; + victimParticipantId?: number; + assistingParticipantIds?: number[]; + towerType?: string; + }>; teams: Array<{ teamIndex: number; side: TeamSide; @@ -716,6 +734,27 @@ export interface ApiInternalMatchDetailResponse { }; bans: Array<{ championId: number; pickTurn: number }>; participants: Array<{ + participantId?: number; + checkpoints?: { + at10?: { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; + }; + at15?: { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; + }; + }; userId: string | null; summonerName: string; tagLine: string; diff --git a/apps/web/src/components/InternalGameAnalysisTabs.tsx b/apps/web/src/components/InternalGameAnalysisTabs.tsx index 2ebf3edc..54d9594b 100644 --- a/apps/web/src/components/InternalGameAnalysisTabs.tsx +++ b/apps/web/src/components/InternalGameAnalysisTabs.tsx @@ -6,6 +6,14 @@ import { } from "../lib/ddragon"; import { teamIndexLabel } from "../lib/league"; import { LANE_LABELS } from "../lib/riot-history"; +import { + DEFAULT_LANE_CHECKPOINT, + pairLaneParticipants, + resolveCheckpointComparison, + type LaneCheckpointKey, + type LaneParticipantLike, + type NormalizedLanePosition, +} from "../lib/internal-game-matchups"; import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip"; export type InternalGameDetailTab = "scoreboard" | "matchup" | "build"; @@ -13,6 +21,7 @@ export type InternalGameDetailTab = "scoreboard" | "matchup" | "build"; type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number]; type InternalGameTeam = InternalGameDetail["teams"][number]; type InternalGameParticipant = InternalGameTeam["participants"][number]; +type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike; type DdragonManifestData = DdragonManifest | null | undefined; type RuneStyleEntry = DdragonManifest["runesReforged"][number]; @@ -44,8 +53,6 @@ const STAT_PERK_LABELS: Record = { 5011: "체력", }; -const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"]; - function formatDuration(seconds: number) { const minutes = Math.floor(seconds / 60); const rest = seconds % 60; @@ -56,6 +63,11 @@ function formatNumber(value: number) { return new Intl.NumberFormat("ko-KR").format(value); } +function formatSignedNumber(value: number) { + if (value === 0) return "0"; + return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`; +} + function sideTone(side: TeamSide) { return side === "blue" ? { @@ -111,11 +123,6 @@ function runeStyleSelection( return participant.perks.styles?.find((style) => style.styleId === styleId); } -function laneSortValue(position: string) { - const index = LANE_SORT_ORDER.indexOf(position); - return index === -1 ? 99 : index; -} - function ChampionCell({ participant, manifest, @@ -648,12 +655,14 @@ function SkillBuildPanel({ function MatchupMetricRow({ label, + difference, blueLead, redLead, blueText, redText, }: { label: string; + difference?: string; blueLead: boolean; redLead: boolean; blueText: string; @@ -668,8 +677,13 @@ function MatchupMetricRow({ > {blueText} - - {label} + + {label} + {difference ? ( + + {difference} + + ) : null} + {ambiguous ? "포지션 중복" : "선수 없음"} + + ); + } - const metrics = [ - { - key: "kda", - label: "KDA", - blueValue: - blue.deaths === 0 - ? blue.kills + blue.assists - : (blue.kills + blue.assists) / blue.deaths, - redValue: - red.deaths === 0 - ? red.kills + red.assists - : (red.kills + red.assists) / red.deaths, - blueText: `${blue.kills}/${blue.deaths}/${blue.assists}`, - redText: `${red.kills}/${red.deaths}/${red.assists}`, - }, - { - key: "gold", - label: "골드", - blueValue: blue.gold, - redValue: red.gold, - blueText: formatNumber(blue.gold), - redText: formatNumber(red.gold), - }, - { - key: "cs", - label: "CS", - blueValue: blue.cs, - redValue: red.cs, - blueText: `${blue.cs} (${blue.csPerMin}/m)`, - redText: `${red.cs} (${red.csPerMin}/m)`, - }, - ]; - - const championName = (participant: InternalGameParticipant) => + const championName = championDisplayName(manifest, participant.championId) ?? String(participant.championId); + const details = ( +
+
+ {participant.summonerName} +
+
+ {championName} +
+
+ ); + + return ( +
+ {align === "right" ? details : null} + + {align === "left" ? details : null} +
+ ); +} + +function LaneMatchupCard({ + position, + blue, + red, + ambiguousBlue, + ambiguousRed, + checkpointKey, + manifest, +}: { + position: NormalizedLanePosition; + blue: CheckpointParticipant | null; + red: CheckpointParticipant | null; + ambiguousBlue: boolean; + ambiguousRed: boolean; + checkpointKey: LaneCheckpointKey; + manifest: DdragonManifestData; +}) { + const laneLabel = LANE_LABELS[position] ?? position; + const comparison = resolveCheckpointComparison(blue, red, checkpointKey); + const metrics = comparison + ? [ + { + key: "gold", + label: "골드", + difference: `GD ${formatSignedNumber(comparison.goldDiff)}`, + blueValue: comparison.blue.gold, + redValue: comparison.red.gold, + blueText: formatNumber(comparison.blue.gold), + redText: formatNumber(comparison.red.gold), + }, + { + key: "cs", + label: "CS", + difference: `CSD ${formatSignedNumber(comparison.csDiff)}`, + blueValue: comparison.blue.cs, + redValue: comparison.red.cs, + blueText: formatNumber(comparison.blue.cs), + redText: formatNumber(comparison.red.cs), + }, + { + key: "xp", + label: "경험치", + difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`, + blueValue: comparison.blue.xp, + redValue: comparison.red.xp, + blueText: formatNumber(comparison.blue.xp), + redText: formatNumber(comparison.red.xp), + }, + { + key: "kda", + label: "K / D / A", + blueValue: checkpointKda( + comparison.blue.kills, + comparison.blue.deaths, + comparison.blue.assists, + ), + redValue: checkpointKda( + comparison.red.kills, + comparison.red.deaths, + comparison.red.assists, + ), + blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`, + redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`, + }, + ] + : []; return (
-
-
-
- {blue.summonerName} -
-
- {championName(blue)} -
-
- -
+ {laneLabel} -
- -
-
- {red.summonerName} -
-
- {championName(red)} -
+ +
+ {comparison ? ( + <> +
+ {metrics.map((metric) => ( + metric.redValue} + redLead={metric.redValue > metric.blueValue} + blueText={metric.blueText} + redText={metric.redText} + /> + ))}
+
+ 실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)} +
+ + ) : ( +
+ {ambiguousBlue || ambiguousRed + ? "포지션이 중복되어 상대를 확정할 수 없습니다" + : "선택한 시점의 라인전 데이터가 없습니다"}
-
-
- {metrics.map((metric) => ( - metric.redValue} - redLead={metric.redValue > metric.blueValue} - blueText={metric.blueText} - redText={metric.redText} - /> - ))} -
+ )}
); } @@ -790,6 +875,8 @@ function LaneMatchupPanel({ detail: ApiInternalMatchDetailResponse; manifest: DdragonManifestData; }) { + const [checkpointKey, setCheckpointKey] = + useState(DEFAULT_LANE_CHECKPOINT); const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); const redTeam = selectedGame.teams.find((team) => team.side === "red"); @@ -801,40 +888,64 @@ function LaneMatchupPanel({ ); } - const blueSorted = [...blueTeam.participants].sort( - (left, right) => - laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition), - ); - const redSorted = [...redTeam.participants].sort( - (left, right) => - laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition), + const matchups = pairLaneParticipants( + blueTeam.participants as CheckpointParticipant[], + redTeam.participants as CheckpointParticipant[], ); const blueTeamName = getTeamName(detail, blueTeam.teamIndex); const redTeamName = getTeamName(detail, redTeam.teamIndex); return (
-
- - {blueTeamName} - - VS - {redTeamName} +
+
+ + {blueTeamName} + + VS + {redTeamName} +
+
+ {(["at10", "at15"] as const).map((key) => ( + + ))} +
- {blueSorted.map((blue, index) => { - const red = redSorted[index]; - if (!red) return null; - return ( + {matchups.length > 0 ? ( + matchups.map((matchup) => ( - ); - })} + )) + ) : ( +
+ 비교 가능한 포지션 정보가 없습니다 +
+ )}
); diff --git a/apps/web/src/lib/internal-game-matchups.ts b/apps/web/src/lib/internal-game-matchups.ts new file mode 100644 index 00000000..b8dfd0f1 --- /dev/null +++ b/apps/web/src/lib/internal-game-matchups.ts @@ -0,0 +1,127 @@ +export type LaneCheckpointKey = "at10" | "at15"; + +export const DEFAULT_LANE_CHECKPOINT: LaneCheckpointKey = "at15"; + +export type NormalizedLanePosition = + | "TOP" + | "JUNGLE" + | "MIDDLE" + | "BOTTOM" + | "UTILITY"; + +export interface LaneCheckpoint { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; +} + +export interface LaneParticipantLike { + teamPosition: string; + checkpoints?: Partial>; +} + +export interface LanePair { + position: NormalizedLanePosition; + blue: TParticipant | null; + red: TParticipant | null; + ambiguousBlue: boolean; + ambiguousRed: boolean; +} + +export interface LaneCheckpointComparison { + blue: LaneCheckpoint; + red: LaneCheckpoint; + goldDiff: number; + csDiff: number; + xpDiff: number; +} + +const LANE_ORDER: readonly NormalizedLanePosition[] = [ + "TOP", + "JUNGLE", + "MIDDLE", + "BOTTOM", + "UTILITY", +]; + +const LANE_ALIASES: Readonly> = { + TOP: "TOP", + JUNGLE: "JUNGLE", + JGL: "JUNGLE", + MIDDLE: "MIDDLE", + MID: "MIDDLE", + BOTTOM: "BOTTOM", + ADC: "BOTTOM", + UTILITY: "UTILITY", + SUPPORT: "UTILITY", + SUP: "UTILITY", +}; + +export function normalizeLanePosition( + value: string | undefined, +): NormalizedLanePosition | null { + if (!value) return null; + return LANE_ALIASES[value.toUpperCase()] ?? null; +} + +export function pairLaneParticipants( + blueParticipants: readonly TParticipant[], + redParticipants: readonly TParticipant[], +): Array> { + const blueByPosition = groupByPosition(blueParticipants); + const redByPosition = groupByPosition(redParticipants); + + return LANE_ORDER.flatMap((position) => { + const blue = blueByPosition.get(position) ?? []; + const red = redByPosition.get(position) ?? []; + if (blue.length === 0 && red.length === 0) return []; + + return [ + { + position, + blue: blue.length === 1 ? blue[0] : null, + red: red.length === 1 ? red[0] : null, + ambiguousBlue: blue.length > 1, + ambiguousRed: red.length > 1, + }, + ]; + }); +} + +export function resolveCheckpointComparison< + TParticipant extends LaneParticipantLike, +>( + blueParticipant: TParticipant | null, + redParticipant: TParticipant | null, + checkpointKey: LaneCheckpointKey, +): LaneCheckpointComparison | null { + const blue = blueParticipant?.checkpoints?.[checkpointKey]; + const red = redParticipant?.checkpoints?.[checkpointKey]; + if (!blue || !red) return null; + + return { + blue, + red, + goldDiff: blue.gold - red.gold, + csDiff: blue.cs - red.cs, + xpDiff: blue.xp - red.xp, + }; +} + +function groupByPosition( + participants: readonly TParticipant[], +) { + const grouped = new Map(); + for (const participant of participants) { + const position = normalizeLanePosition(participant.teamPosition); + if (!position) continue; + const values = grouped.get(position) ?? []; + values.push(participant); + grouped.set(position, values); + } + return grouped; +} diff --git a/apps/web/src/lib/internal-match-timeline.ts b/apps/web/src/lib/internal-match-timeline.ts new file mode 100644 index 00000000..4f62a2a0 --- /dev/null +++ b/apps/web/src/lib/internal-match-timeline.ts @@ -0,0 +1,218 @@ +export type InternalMatchTeamSide = "blue" | "red"; + +export type InternalMatchObjectiveType = + | "dragon" + | "elderDragon" + | "baron" + | "riftHerald" + | "voidGrub"; + +export type InternalMatchTimelineEventType = + | InternalMatchObjectiveType + | "championKill" + | "tower" + | "inhibitor"; + +export type TimelineEventCategory = "objective" | "kill" | "structure"; +export type TimelineEventFilter = "all" | TimelineEventCategory; + +export interface InternalMatchTimelineEvent { + timestamp: number; + side?: InternalMatchTeamSide; + type: InternalMatchTimelineEventType; + killerParticipantId?: number; + victimParticipantId?: number; + assistingParticipantIds?: number[]; + monsterSubType?: string; + towerType?: string; +} + +export interface InternalMatchObjectiveEvent { + timestamp: number; + side: InternalMatchTeamSide; + type: InternalMatchObjectiveType; + monsterSubType?: string; +} + +export interface NormalizedObjectiveEvent extends InternalMatchObjectiveEvent { + label: string; + markerLabel: string; +} + +export interface NormalizedTimelineEvent extends InternalMatchTimelineEvent { + category: TimelineEventCategory; + label: string; + markerLabel: string; +} + +const DRAGON_TYPE_LABELS: Readonly> = { + AIR_DRAGON: "바람", + EARTH_DRAGON: "대지", + WATER_DRAGON: "바다", + FIRE_DRAGON: "화염", + HEXTECH_DRAGON: "마법공학", + CHEMTECH_DRAGON: "화학공학", + ELDER_DRAGON: "장로", +}; + +const OBJECTIVE_LABELS: Readonly< + Record, string> +> = { + elderDragon: "장로 드래곤", + baron: "바론", + riftHerald: "협곡의 전령", + voidGrub: "공허 유충", +}; + +const OBJECTIVE_MARKER_LABELS: Readonly< + Record, string> +> = { + elderDragon: "장로", + baron: "바론", + riftHerald: "전령", + voidGrub: "유충", +}; + +export function dragonTypeLabel( + monsterSubType: string | undefined, +): string | null { + if (!monsterSubType) return null; + return DRAGON_TYPE_LABELS[monsterSubType] ?? null; +} + +export function normalizeObjectiveEvents( + events: readonly InternalMatchObjectiveEvent[], +): NormalizedObjectiveEvent[] { + return events + .map((event) => { + if (event.type === "dragon") { + const dragonLabel = dragonTypeLabel(event.monsterSubType); + return { + ...event, + label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤", + markerLabel: dragonLabel ?? "용", + }; + } + + return { + ...event, + label: OBJECTIVE_LABELS[event.type], + markerLabel: OBJECTIVE_MARKER_LABELS[event.type], + }; + }) + .sort((left, right) => left.timestamp - right.timestamp); +} + +export function normalizeTimelineEvents( + events: readonly InternalMatchTimelineEvent[], +): NormalizedTimelineEvent[] { + return events + .map((event): NormalizedTimelineEvent => { + if (event.type === "championKill") { + return { + ...event, + category: "kill", + label: "챔피언 처치", + markerLabel: "킬", + }; + } + if (event.type === "tower") { + return { + ...event, + category: "structure", + label: "포탑 파괴", + markerLabel: "포탑", + }; + } + if (event.type === "inhibitor") { + return { + ...event, + category: "structure", + label: "억제기 파괴", + markerLabel: "억제기", + }; + } + if (event.type === "dragon") { + const dragonLabel = dragonTypeLabel(event.monsterSubType); + return { + ...event, + category: "objective", + label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤", + markerLabel: dragonLabel ?? "용", + }; + } + return { + ...event, + category: "objective", + label: OBJECTIVE_LABELS[event.type], + markerLabel: OBJECTIVE_MARKER_LABELS[event.type], + }; + }) + .sort((left, right) => left.timestamp - right.timestamp); +} + +export function selectTimelineEventSource< + TTimeline extends InternalMatchTimelineEvent, + TObjective extends InternalMatchObjectiveEvent, +>( + timelineEvents: readonly TTimeline[] | undefined, + objectiveEvents: readonly TObjective[], +): readonly (TTimeline | TObjective)[] { + return timelineEvents && timelineEvents.length > 0 + ? timelineEvents + : objectiveEvents; +} + +export function filterTimelineEvents( + events: readonly TEvent[], + filter: TimelineEventFilter, +): TEvent[] { + return filter === "all" + ? [...events] + : events.filter((event) => event.category === filter); +} + +export function summarizeDragonTypes( + events: readonly NormalizedObjectiveEvent[], + side: InternalMatchTeamSide, +): Array<{ label: string; count: number }> { + const counts = new Map(); + + for (const event of events) { + if (event.side !== side || event.type !== "dragon") continue; + const label = dragonTypeLabel(event.monsterSubType); + if (!label) continue; + counts.set(label, (counts.get(label) ?? 0) + 1); + } + + return [...counts.entries()].map(([label, count]) => ({ label, count })); +} + +export function projectObjectiveMarkers< + TEvent extends NormalizedObjectiveEvent, +>( + events: readonly TEvent[], + points: readonly { timestamp: number; value: number }[], +): Array { + return projectTimelineEventMarkers(events, points); +} + +export function projectTimelineEventMarkers( + events: readonly TEvent[], + points: readonly { timestamp: number; value: number }[], +): Array { + if (points.length === 0) return []; + + const orderedPoints = [...points].sort( + (left, right) => left.timestamp - right.timestamp, + ); + + return events.map((event) => { + let selected = orderedPoints[0]; + for (const point of orderedPoints) { + if (point.timestamp > event.timestamp) break; + selected = point; + } + return { ...event, value: selected.value }; + }); +} diff --git a/apps/web/src/pages/MatchGameDetailPage.tsx b/apps/web/src/pages/MatchGameDetailPage.tsx index 9ccbd39b..efd686bd 100644 --- a/apps/web/src/pages/MatchGameDetailPage.tsx +++ b/apps/web/src/pages/MatchGameDetailPage.tsx @@ -5,6 +5,7 @@ import { AreaChart, CartesianGrid, Line, + ReferenceDot, ReferenceLine, ResponsiveContainer, Tooltip, @@ -28,6 +29,16 @@ import { internalMatchGamePath, } from "../lib/internal-match-routes"; import { LANE_LABELS } from "../lib/riot-history"; +import { + filterTimelineEvents, + normalizeObjectiveEvents, + normalizeTimelineEvents, + projectTimelineEventMarkers, + selectTimelineEventSource, + summarizeDragonTypes, + type NormalizedTimelineEvent, + type TimelineEventFilter, +} from "../lib/internal-match-timeline"; import { InternalGameAnalysisPanel, InternalGameDetailTabBar, @@ -58,6 +69,16 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [ { id: "xp", label: "경험치" }, ]; +const TIMELINE_EVENT_FILTERS: Array<{ + id: TimelineEventFilter; + label: string; +}> = [ + { id: "all", label: "전체" }, + { id: "objective", label: "오브젝트" }, + { id: "kill", label: "킬" }, + { id: "structure", label: "구조물" }, +]; + function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } @@ -142,6 +163,16 @@ function formatPercent(value: number) { return `${value}%`; } +function formatDragonTypeSummary( + values: Array<{ label: string; count: number }>, + total: number, +) { + if (values.length === 0) return total > 0 ? "유형 정보 없음" : "-"; + return values + .map(({ label, count }) => (count > 1 ? `${label}×${count}` : label)) + .join(" · "); +} + function barWidth(value: number, max: number) { return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`; } @@ -411,13 +442,13 @@ function PlayerRow({ {participant.assists}
- {formatKda( + KDA {formatKda( participant.kills, participant.deaths, participant.assists, )} - ({participant.killParticipation}%) + · KP {participant.killParticipation}%
@@ -451,6 +482,12 @@ function PlayerRow({ {participant.csPerMin}/m + + {formatCompactNumber(participant.gold)} + + {formatNumber(participant.gpm)} GPM + + @@ -486,13 +523,13 @@ function PlayerCard({ {participant.assists}
- {formatKda( + KDA {formatKda( participant.kills, participant.deaths, participant.assists, )} - ({participant.killParticipation}%) + · KP {participant.killParticipation}%
@@ -527,13 +564,19 @@ function PlayerCard({
- CS + CS · 경제
{participant.cs} {participant.csPerMin}/m + + {formatCompactNumber(participant.gold)} + + {formatNumber(participant.gpm)} GPM + +
@@ -701,11 +744,125 @@ function PostgameBreakdown({ ); })}
+ ); } +function ObjectiveComparisonStrip({ + selectedGame, +}: { + selectedGame: MatchGameDetail; +}) { + const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); + const redTeam = selectedGame.teams.find((team) => team.side === "red"); + if (!blueTeam || !redTeam) return null; + + const events = normalizeObjectiveEvents(selectedGame.objectiveEvents ?? []); + const blueDragonTypes = formatDragonTypeSummary( + summarizeDragonTypes(events, "blue"), + blueTeam.objectives.dragon, + ); + const redDragonTypes = formatDragonTypeSummary( + summarizeDragonTypes(events, "red"), + redTeam.objectives.dragon, + ); + const objectives = [ + { + key: "tower", + label: "포탑", + blue: blueTeam.objectives.tower, + red: redTeam.objectives.tower, + }, + { + key: "dragon", + label: "드래곤", + blue: blueTeam.objectives.dragon, + red: redTeam.objectives.dragon, + blueDetail: blueDragonTypes, + redDetail: redDragonTypes, + }, + { + key: "inhibitor", + label: "억제기", + blue: blueTeam.objectives.inhibitor, + red: redTeam.objectives.inhibitor, + }, + { + key: "baron", + label: "바론", + blue: blueTeam.objectives.baron, + red: redTeam.objectives.baron, + }, + { + key: "riftHerald", + label: "전령", + blue: blueTeam.objectives.riftHerald, + red: redTeam.objectives.riftHerald, + }, + { + key: "voidGrub", + label: "공허 유충", + blue: blueTeam.objectives.voidGrub, + red: redTeam.objectives.voidGrub, + }, + { + key: "elderDragon", + label: "장로", + blue: blueTeam.objectives.elderDragon, + red: redTeam.objectives.elderDragon, + }, + ]; + + return ( +
+

오브젝트 비교

+
+ {objectives.map((objective) => ( +
+
+ objective.red + ? "text-blue-400" + : "text-base-content/50" + }`} + > + {objective.blue} + + + {objective.label} + + objective.blue + ? "text-red-400" + : "text-base-content/50" + }`} + > + {objective.red} + +
+ {objective.key === "dragon" ? ( +
+ + {objective.blueDetail} + + {objective.redDetail} +
+ ) : null} +
+ ))} +
+
+ ); +} + function GoldComparisonStrip({ selectedGame, detail, @@ -848,14 +1005,74 @@ function TimelineTooltip({ ); } +function timelineEventKey(event: NormalizedTimelineEvent, index: number) { + return [ + event.timestamp, + event.side ?? "unknown", + event.type, + event.killerParticipantId ?? "none", + event.victimParticipantId ?? "none", + index, + ].join(":"); +} + +function timelineParticipantLabel( + participant: MatchGameParticipant | undefined, + manifest: ReturnType["data"], +) { + if (!participant) return null; + const championName = + championDisplayName(manifest, participant.championId) ?? + String(participant.championId); + return `${participant.summonerName} (${championName})`; +} + +function timelineEventActors( + event: NormalizedTimelineEvent, + participantById: ReadonlyMap, + manifest: ReturnType["data"], +) { + const killer = timelineParticipantLabel( + event.killerParticipantId === undefined + ? undefined + : participantById.get(event.killerParticipantId), + manifest, + ); + const victim = timelineParticipantLabel( + event.victimParticipantId === undefined + ? undefined + : participantById.get(event.victimParticipantId), + manifest, + ); + const assistants = (event.assistingParticipantIds ?? []) + .map((participantId) => + timelineParticipantLabel(participantById.get(participantId), manifest), + ) + .filter((label): label is string => Boolean(label)); + const assistLabel = + assistants.length > 0 ? ` · 도움 ${assistants.join(", ")}` : ""; + + if (event.type === "championKill") { + if (killer && victim) return `${killer} → ${victim}${assistLabel}`; + if (killer) return `${killer} 처치${assistLabel}`; + if (victim) return `${victim} 사망`; + } + if (killer) return `${killer} 기여${assistLabel}`; + return null; +} + function TimelineGraph({ selectedGame, detail, + manifest, }: { selectedGame: MatchGameDetail; detail: ApiInternalMatchDetailResponse; + manifest: ReturnType["data"]; }) { const [metric, setMetric] = useState("gold"); + const [eventFilter, setEventFilter] = useState("all"); + const [selectedEventKey, setSelectedEventKey] = useState(null); const blueTeam = selectedGame.teams.find((team) => team.side === "blue"); const redTeam = selectedGame.teams.find((team) => team.side === "red"); const blueTeamName = blueTeam @@ -883,6 +1100,41 @@ function TimelineGraph({ ...chartData.map((point) => Math.abs(point.value)), ); const finalPoint = chartData[chartData.length - 1]; + const timelineEvents = normalizeTimelineEvents( + selectTimelineEventSource( + selectedGame.timelineEvents, + selectedGame.objectiveEvents ?? [], + ), + ); + const visibleEvents = filterTimelineEvents(timelineEvents, eventFilter); + const visibleEventEntries = visibleEvents.map((event) => { + const index = timelineEvents.indexOf(event); + return { + event, + key: timelineEventKey(event, index), + }; + }); + const selectedEvent = visibleEventEntries.find( + (entry) => entry.key === selectedEventKey, + ); + const selectedTimestamp = selectedEvent?.event.timestamp ?? null; + const timelineMarkers = projectTimelineEventMarkers( + visibleEventEntries.map(({ event, key }) => ({ ...event, eventKey: key })), + chartData, + ); + const participantById = new Map(); + for (const team of selectedGame.teams) { + for (const participant of team.participants) { + if (participant.participantId !== undefined) { + participantById.set(participant.participantId, participant); + } + } + } + const chartMaxTimestamp = Math.max( + selectedGame.gameDuration, + finalPoint?.timestamp ?? 0, + timelineEvents[timelineEvents.length - 1]?.timestamp ?? 0, + ); const finalLeader = finalPoint?.leaderSide === "blue" ? blueTeamName @@ -901,11 +1153,16 @@ function TimelineGraph({ : "타임라인 대기"} -
+
{TIMELINE_METRICS.map((item) => ( + ))} +
+
    + {visibleEventEntries.map(({ event, key }) => { + const selected = key === selectedEventKey; + const teamName = + event.side === "blue" + ? blueTeamName + : event.side === "red" + ? redTeamName + : null; + const actorLabel = timelineEventActors( + event, + participantById, + manifest, + ); + return ( +
  • + +
  • + ); + })} +
+ {visibleEventEntries.length === 0 ? ( +

+ 이 유형의 사건이 없습니다 +

+ ) : null} +
+ ) : null} ); } @@ -1045,7 +1454,7 @@ function TeamTable({ 가한 피해량 받은 피해량 시야 - CS + CS · 경제 아이템 @@ -1306,6 +1715,13 @@ export default function MatchGameDetailPage() { manifest={ddragon} /> + +
- - ); } diff --git a/apps/web/test/internal-game-matchups.test.ts b/apps/web/test/internal-game-matchups.test.ts new file mode 100644 index 00000000..da3a9d97 --- /dev/null +++ b/apps/web/test/internal-game-matchups.test.ts @@ -0,0 +1,134 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + DEFAULT_LANE_CHECKPOINT, + pairLaneParticipants, + resolveCheckpointComparison, +} from "../src/lib/internal-game-matchups.ts"; + +function participant( + name: string, + side: "blue" | "red", + teamPosition: string, + gold: number, + cs: number, + xp: number, +) { + return { + name, + side, + teamPosition, + checkpoints: { + at15: { + timestamp: 900, + gold, + cs, + xp, + kills: side === "blue" ? 2 : 1, + deaths: side === "blue" ? 1 : 2, + assists: 3, + }, + }, + }; +} + +test("pairLaneParticipants matches shuffled players by normalized team position", () => { + const blue = [ + participant("Blue ADC", "blue", "BOTTOM", 6_000, 120, 7_000), + participant("Blue Top", "blue", "TOP", 5_500, 110, 6_800), + participant("Blue Mid", "blue", "MID", 6_200, 115, 7_100), + ]; + const red = [ + participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900), + participant("Red Top", "red", "TOP", 5_300, 105, 6_600), + participant("Red ADC", "red", "ADC", 5_800, 116, 6_850), + ]; + + const pairs = pairLaneParticipants(blue, red); + + assert.deepEqual( + pairs.map((pair) => [pair.position, pair.blue?.name, pair.red?.name]), + [ + ["TOP", "Blue Top", "Red Top"], + ["MIDDLE", "Blue Mid", "Red Mid"], + ["BOTTOM", "Blue ADC", "Red ADC"], + ], + ); +}); + +test("pairLaneParticipants leaves a duplicated role ambiguous instead of pairing by index", () => { + const blue = [ + participant("Blue Top A", "blue", "TOP", 5_500, 110, 6_800), + participant("Blue Top B", "blue", "TOP", 5_000, 100, 6_200), + ]; + const red = [ + participant("Red Top", "red", "TOP", 5_300, 105, 6_600), + ]; + + assert.deepEqual(pairLaneParticipants(blue, red), [ + { + position: "TOP", + blue: null, + red: red[0], + ambiguousBlue: true, + ambiguousRed: false, + }, + ]); +}); + +test("resolveCheckpointComparison calculates blue-side GD, CSD, and XPD", () => { + const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100); + const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900); + + const comparison = resolveCheckpointComparison(blue, red, "at15"); + + assert.deepEqual(comparison, { + blue: blue.checkpoints.at15, + red: red.checkpoints.at15, + goldDiff: 300, + csDiff: 6, + xpDiff: 200, + }); +}); + +test("resolveCheckpointComparison returns null when either checkpoint is unavailable", () => { + const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100); + const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900); + + assert.equal(resolveCheckpointComparison(blue, red, "at10"), null); + assert.equal(resolveCheckpointComparison(blue, null, "at15"), null); +}); + +test("the lane panel defaults to 15 minutes and supports an available 10-minute comparison", () => { + assert.equal(DEFAULT_LANE_CHECKPOINT, "at15"); + + const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100); + const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900); + blue.checkpoints.at10 = { + timestamp: 590, + gold: 4_000, + cs: 75, + xp: 4_600, + kills: 1, + deaths: 0, + assists: 2, + }; + red.checkpoints.at10 = { + timestamp: 590, + gold: 3_700, + cs: 69, + xp: 4_450, + kills: 0, + deaths: 1, + assists: 1, + }; + + assert.deepEqual(resolveCheckpointComparison(blue, red, "at10"), { + blue: blue.checkpoints.at10, + red: red.checkpoints.at10, + goldDiff: 300, + csDiff: 6, + xpDiff: 150, + }); +}); diff --git a/apps/web/test/internal-match-timeline.test.ts b/apps/web/test/internal-match-timeline.test.ts new file mode 100644 index 00000000..46c94e23 --- /dev/null +++ b/apps/web/test/internal-match-timeline.test.ts @@ -0,0 +1,228 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + dragonTypeLabel, + filterTimelineEvents, + normalizeObjectiveEvents, + normalizeTimelineEvents, + projectObjectiveMarkers, + selectTimelineEventSource, + summarizeDragonTypes, +} from "../src/lib/internal-match-timeline.ts"; + +test("dragonTypeLabel maps Riot dragon subtypes to Korean labels", () => { + assert.deepEqual( + [ + "AIR_DRAGON", + "EARTH_DRAGON", + "WATER_DRAGON", + "FIRE_DRAGON", + "HEXTECH_DRAGON", + "CHEMTECH_DRAGON", + "ELDER_DRAGON", + ].map(dragonTypeLabel), + ["바람", "대지", "바다", "화염", "마법공학", "화학공학", "장로"], + ); + assert.equal(dragonTypeLabel("UNKNOWN_DRAGON"), null); + assert.equal(dragonTypeLabel(undefined), null); +}); + +test("normalizeObjectiveEvents sorts events and adds conservative Korean labels", () => { + const events = normalizeObjectiveEvents([ + { timestamp: 1_443, side: "blue", type: "baron" }, + { + timestamp: 339, + side: "blue", + type: "dragon", + monsterSubType: "EARTH_DRAGON", + }, + { timestamp: 963, side: "red", type: "riftHerald" }, + { + timestamp: 1_356, + side: "red", + type: "dragon", + monsterSubType: "UNKNOWN_DRAGON", + }, + { timestamp: 530, side: "blue", type: "voidGrub" }, + { timestamp: 1_600, side: "red", type: "elderDragon" }, + ]); + + assert.deepEqual( + events.map(({ timestamp, label, markerLabel }) => ({ + timestamp, + label, + markerLabel, + })), + [ + { timestamp: 339, label: "대지 드래곤", markerLabel: "대지" }, + { timestamp: 530, label: "공허 유충", markerLabel: "유충" }, + { timestamp: 963, label: "협곡의 전령", markerLabel: "전령" }, + { timestamp: 1_356, label: "드래곤", markerLabel: "용" }, + { timestamp: 1_443, label: "바론", markerLabel: "바론" }, + { timestamp: 1_600, label: "장로 드래곤", markerLabel: "장로" }, + ], + ); +}); + +test("summarizeDragonTypes groups repeated dragon types per side in event order", () => { + const events = normalizeObjectiveEvents([ + { + timestamp: 300, + side: "blue", + type: "dragon", + monsterSubType: "FIRE_DRAGON", + }, + { + timestamp: 600, + side: "red", + type: "dragon", + monsterSubType: "WATER_DRAGON", + }, + { + timestamp: 900, + side: "blue", + type: "dragon", + monsterSubType: "FIRE_DRAGON", + }, + { + timestamp: 1_200, + side: "blue", + type: "dragon", + monsterSubType: "HEXTECH_DRAGON", + }, + { + timestamp: 1_500, + side: "red", + type: "dragon", + monsterSubType: "UNKNOWN_DRAGON", + }, + ]); + + assert.deepEqual(summarizeDragonTypes(events, "blue"), [ + { label: "화염", count: 2 }, + { label: "마법공학", count: 1 }, + ]); + assert.deepEqual(summarizeDragonTypes(events, "red"), [ + { label: "바다", count: 1 }, + ]); +}); + +test("projectObjectiveMarkers anchors events to the latest available chart value", () => { + const events = normalizeObjectiveEvents([ + { timestamp: 10, side: "blue", type: "voidGrub" }, + { timestamp: 90, side: "red", type: "riftHerald" }, + { timestamp: 180, side: "blue", type: "baron" }, + ]); + + assert.deepEqual( + projectObjectiveMarkers(events, [ + { timestamp: 0, value: 0 }, + { timestamp: 60, value: 100 }, + { timestamp: 120, value: 80 }, + ]).map(({ timestamp, value }) => ({ timestamp, value })), + [ + { timestamp: 10, value: 0 }, + { timestamp: 90, value: 100 }, + { timestamp: 180, value: 80 }, + ], + ); +}); + +test("normalizeTimelineEvents labels and sorts objectives, kills, and structures", () => { + const events = normalizeTimelineEvents([ + { + timestamp: 700, + side: "blue", + type: "tower", + killerParticipantId: 1, + towerType: "OUTER_TURRET", + }, + { + timestamp: 500, + side: "red", + type: "championKill", + killerParticipantId: 6, + victimParticipantId: 1, + assistingParticipantIds: [7, 8], + }, + { + timestamp: 300, + side: "blue", + type: "dragon", + monsterSubType: "FIRE_DRAGON", + }, + { timestamp: 800, side: "red", type: "inhibitor" }, + ]); + + assert.deepEqual( + events.map(({ timestamp, category, label, markerLabel }) => ({ + timestamp, + category, + label, + markerLabel, + })), + [ + { + timestamp: 300, + category: "objective", + label: "화염 드래곤", + markerLabel: "화염", + }, + { + timestamp: 500, + category: "kill", + label: "챔피언 처치", + markerLabel: "킬", + }, + { + timestamp: 700, + category: "structure", + label: "포탑 파괴", + markerLabel: "포탑", + }, + { + timestamp: 800, + category: "structure", + label: "억제기 파괴", + markerLabel: "억제기", + }, + ], + ); + assert.equal(events[1].killerParticipantId, 6); + assert.equal(events[1].victimParticipantId, 1); +}); + +test("selectTimelineEventSource falls back to objective events during rolling updates", () => { + const objectives = [ + { timestamp: 300, side: "blue" as const, type: "voidGrub" as const }, + ]; + const timeline = [ + { timestamp: 400, side: "red" as const, type: "championKill" as const }, + ]; + + assert.equal(selectTimelineEventSource(timeline, objectives), timeline); + assert.equal(selectTimelineEventSource([], objectives), objectives); + assert.equal(selectTimelineEventSource(undefined, objectives), objectives); +}); + +test("filterTimelineEvents filters event categories without changing order", () => { + const events = normalizeTimelineEvents([ + { timestamp: 300, side: "blue", type: "dragon" }, + { timestamp: 500, side: "red", type: "championKill" }, + { timestamp: 700, side: "blue", type: "tower" }, + ]); + + assert.deepEqual( + filterTimelineEvents(events, "all").map((event) => event.timestamp), + [300, 500, 700], + ); + assert.deepEqual( + filterTimelineEvents(events, "kill").map((event) => event.timestamp), + [500], + ); + assert.deepEqual( + filterTimelineEvents(events, "structure").map((event) => event.timestamp), + [700], + ); +}); diff --git a/docs/plans/internal-match-game-analysis-p0-p1.md b/docs/plans/internal-match-game-analysis-p0-p1.md new file mode 100644 index 00000000..5844c98b --- /dev/null +++ b/docs/plans/internal-match-game-analysis-p0-p1.md @@ -0,0 +1,78 @@ +# Implementation Plan: Internal Match Game Analysis P0/P1 + +## Overview + +Deliver three independently verifiable slices: P0 existing-data UI, P1-A timeline +checkpoints and lane comparison, and P1-B unified notable events. Preserve the +existing detail endpoint and use builder/cache versioning to refresh old projections. + +## Task List + +### Phase 1: P0 Existing Data + +- [x] Add tested objective normalization, chart markers, an accessible event list, + and move game flow above the detail tabs. +- [x] Add a complete objective comparison strip with conservative dragon-type + fallback behavior. +- [x] Label KP and add participant gold/GPM to the combined CS/economy presentation. + +### Checkpoint: P0 + +- [x] Web tests, lint, and production build pass. +- [x] Desktop and mobile layouts retain all existing scoreboard/build behavior. + +### Phase 2: P1-A Lane Checkpoints + +- [x] Parse the remaining participant event identifier fields and project tested + participant checkpoints at 10 and 15 minutes. +- [x] Persist and expose optional checkpoint fields, reject stale caches, and bump + the match-stats builder/detail-response versions. +- [x] Replace final-state lane comparisons with tested role-based 10/15-minute + GD/CSD/XPD and K/D/A comparisons. + +### Checkpoint: P1-A + +- [x] Focused API tests and builds pass. +- [x] Web tests and production build pass. +- [x] Short and missing-timeline games show unavailable states rather than zeros. + +### Phase 3: P1-B Unified Events + +- [x] Project objectives, champion kills, towers, and inhibitors into a deterministic + tested event stream. +- [x] Expose `timelineEvents` while retaining `objectiveEvents` compatibility and + bump persisted/cache versions as required. +- [x] Add accessible event filtering and chart selection with objective-only fallback. +- [x] Coalesce concurrent hydration and short-cache incomplete results so transient + failures retry without rebuilding on every sequential page request. + +### Checkpoint: Complete + +- [x] API and web focused suites pass without skipped tests. +- [x] API and web production builds pass. +- [x] Responsive runtime review passes at 320px, 390px, 768px, 1024px, and 1440px. +- [x] P0/P1 edits exclude unrelated Competition/bracket modifications already in + the shared worktree. + +## Risks and Mitigations + +| Risk | Impact | Mitigation | +|---|---|---| +| Missing or delayed Riot frames misrepresent @10/@15 | High | Use only a frame at/before the target within one frame interval and expose its actual timestamp. | +| Building events attribute the destroyed team's side as the scorer | High | Prefer killer participant side; otherwise invert the destroyed `teamId`; cover both paths in tests. | +| Old cached shapes hide new fields | High | Increment builder and response cache versions and strengthen completeness validation. | +| A kill-heavy game makes the page excessively long | Medium | Add event-category filters and a bounded scroll region. | +| Mobile chart remains hard to reach | Medium | Move flow directly below the summary before any participant cards. | +| Existing dirty work is accidentally included | High | Restrict edits and verification to the named game-analysis files and inspect the final diff by path. | + +## Dependencies + +```text +P0 event normalization -> P0 objective strip +P1 checkpoint projector -> response contract -> lane UI +P1 checkpoint identifiers -> event projector -> response contract -> event UI +``` + +## Open Questions + +None. diff --git a/docs/specs/internal-match-game-analysis.md b/docs/specs/internal-match-game-analysis.md new file mode 100644 index 00000000..5ad0e5f5 --- /dev/null +++ b/docs/specs/internal-match-game-analysis.md @@ -0,0 +1,170 @@ +# Spec: Internal Match Game Analysis P0/P1 + +## Objective + +Make an internal-match game result explain both the final numbers and how the game +reached them. P0 exposes data already present in the detail response: objective +events, complete team objectives, participant gold/GPM, and explicitly labelled +kill participation. P1 projects Riot Match-V5 timeline frames into real 10- and +15-minute lane checkpoints and a unified event stream for kills and structures. + +The primary user is a tournament participant or organizer reviewing a completed +game on desktop or mobile. Success means the user can identify the major objective +sequence before reading ten player cards, compare lane state at 10/15 minutes, and +trace kills and building events without mistaking unavailable data for zero. + +## Approved Product Decisions + +- Place game flow immediately after the game summary and before detail tabs. +- Render chart events as both visual markers and a keyboard-readable text list. +- Keep the existing gold/XP toggle and runes/build experience. +- Show tower, dragon, inhibitor, Baron, Rift Herald, Void Grub, and Elder Dragon + totals; derive dragon type labels only when objective events are available. +- Combine participant CS and economy instead of adding another wide table column. +- Label kill participation explicitly as `KP`. +- Replace final-state values in the lane tab with 10/15-minute checkpoints; default + to 15 minutes and pair players by `teamPosition`, never array position. +- Keep `objectiveEvents` for compatibility and add `timelineEvents` for the unified + P1 stream. +- Treat missing checkpoints and events as unavailable, not zero. +- Do not add an opaque MVP/rating or new external data feed in this scope. + +## Tech Stack + +- React 19, TypeScript 6, Recharts 3, Tailwind CSS 4, and daisyUI under `apps/web` +- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api` +- Riot Match-V5 match and timeline payloads already cached in `RiotMatchModel` +- Node's built-in test runner for pure web transformations + +## Commands + +- Focused web tests: `pnpm --filter web test` +- Web lint: `pnpm --filter web lint` +- Web production build: `pnpm --filter web build:prod` +- Focused API tests: `pnpm --filter api test -- --runInBand riot-match.service.spec.ts match-stats-fragment.builder.spec.ts community-stats.service.spec.ts` +- API build: `pnpm --filter api build` +- Development web server: `pnpm --filter web start:dev` + +## Project Structure + +- `apps/web/src/pages/MatchGameDetailPage.tsx` owns the result summary, + participant scoreboard, flow chart, and accessible event list. +- `apps/web/src/components/InternalGameAnalysisTabs.tsx` owns the lane and build + tabs. +- `apps/web/src/lib/internal-match-timeline.ts` owns pure event normalization, + labels, filtering, and chart projection. +- `apps/web/src/lib/internal-game-matchups.ts` owns pure role pairing and checkpoint + comparisons. +- `apps/web/test/` contains Node unit tests for the pure web transformations. +- `apps/api/src/modules/riot/` parses trusted fields from Riot match timelines. +- `apps/api/src/modules/community-stats/match-stats-fragment.builder.ts` projects + stored Riot payloads into cached internal-match records. +- `apps/api/src/modules/community-stats/community-stats.service.ts` maps persisted + records into the public detail response and versions response caches. +- `apps/api/src/modules/global/database/schema.ts` defines persisted TypeScript + shapes; nested `gameDetails` remains a Mongoose Mixed array. + +## Data Contract + +Participant checkpoint data is additive and optional for legacy/fallback games: + +```ts +interface MatchStatsCheckpoint { + timestamp: number; + gold: number; + cs: number; + xp: number; + kills: number; + deaths: number; + assists: number; +} + +interface MatchStatsParticipantCheckpoints { + at10?: MatchStatsCheckpoint; + at15?: MatchStatsCheckpoint; +} +``` + +Each detailed participant gains optional `participantId` and `checkpoints`. Each +game gains optional `timelineEvents`, whose `type` is an existing objective type or +`championKill`, `tower`, or `inhibitor`. Actor IDs, assists, monster subtype, and +tower subtype are optional fields appropriate to the event type. + +For a 10/15-minute target, use the latest frame at or before the target only when it +is less than one `frameInterval` old. Persist the actual selected timestamp. CS is +`minionsKilled + jungleMinionsKilled`; checkpoint K/D/A includes champion-kill +events through the selected timestamp. A game ending before a target has no value +for that checkpoint. + +## Code Style + +Keep timeline calculations independent from React and use discriminated event +types with conservative fallbacks: + +```ts +const events = game.timelineEvents?.length + ? game.timelineEvents + : game.objectiveEvents; + +const checkpoint = participant.checkpoints?.at15; +if (!checkpoint) return { kind: "unavailable" }; +``` + +Use existing semantic color tokens and square bordered panels. Dynamic chart +coordinates may use numeric props; spacing, colors, and typography remain in the +existing Tailwind/daisyUI system. + +## Testing Strategy + +- Develop pure event normalization, checkpoint selection, role pairing, and metric + comparison test-first. +- Builder tests cover exact and missing checkpoints, jungle CS, cumulative K/D/A, + executes, objective fallback, building ownership, and deterministic event order. +- Service tests reject stale cached response shapes and verify additive mapping. +- Browser verification covers 320px, 390px, 768px, 1024px, and 1440px; the event + text list is the accessible equivalent of decorative chart markers. +- Verify the supplied production-like game as well as a short game and a game with + no timeline. + +## Boundaries + +### Always + +- Preserve existing `objectiveEvents`, runes/builds, and match-detail routes. +- Derive participant checkpoint values from stored Riot timeline frames. +- Pair lanes by normalized `teamPosition` and show unavailable states explicitly. +- Communicate team/event meaning with text as well as color. +- Increment the match-stats builder and detail-response cache versions whenever a + persisted or cached response shape changes. + +### Ask First + +- Add a frontend or backend dependency. +- Change the public route or remove compatibility fields. +- Add a database migration or make a bulk external Riot API fetch. +- Deploy, push, or alter CI configuration. + +### Never + +- Infer absent checkpoint data as zero. +- Pair opponents by array order. +- Claim that a nearby objective caused a gold swing. +- Expose unparsed arbitrary Riot event fields. +- Modify unrelated Competition/bracket work already present in the worktree. + +## Success Criteria + +- Game flow appears before player details and includes objective markers plus an + equivalent textual sequence on desktop and mobile. +- Summary shows all currently projected objective totals and available dragon types. +- Every participant shows labelled KP, gold, GPM, CS, and CS/min without breaking + the responsive scoreboard. +- The lane tab defaults to 15 minutes, can switch to 10 minutes, and presents + GD/CSD/XPD and checkpoint K/D/A for correctly paired roles. +- The unified timeline can filter and display objectives, champion kills, towers, + and inhibitors, while falling back to objective-only data during rolling updates. +- Focused API/web tests, lint, and production builds pass. + +## Open Questions + +None. The user reviewed the P0/P1 task plan and requested implementation.