From 43662a86d82ca22ddb393875f427c51b8c978101 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Thu, 2 Jul 2026 22:38:24 -0700 Subject: [PATCH] Collect match timelines during analysis --- .../analysis-pipeline.service.spec.ts | 119 ++++++++++++++++-- .../analysis/analysis-pipeline.service.ts | 55 ++++++++ 2 files changed, 164 insertions(+), 10 deletions(-) diff --git a/apps/api/src/modules/analysis/analysis-pipeline.service.spec.ts b/apps/api/src/modules/analysis/analysis-pipeline.service.spec.ts index 60be448..a4a89a0 100644 --- a/apps/api/src/modules/analysis/analysis-pipeline.service.spec.ts +++ b/apps/api/src/modules/analysis/analysis-pipeline.service.spec.ts @@ -71,6 +71,19 @@ function createMatchPayload(matchId = 'KR_1') { }; } +function createTimelinePayload(matchId = 'KR_1') { + return { + metadata: { + matchId, + participants: ['target-puuid', 'ally-puuid'], + }, + info: { + frameInterval: 60_000, + frames: [], + }, + }; +} + interface ExecQuery { exec: jest.Mock, []>; } @@ -88,6 +101,14 @@ function asRecord(value: unknown): Record { return {}; } +function findTimelineSet(updateRiotMatch: UpdateOneMock) { + const timelineUpdate = updateRiotMatch.mock.calls.find(([, update]) => + Boolean(asRecord(asRecord(update).$set).timeline), + ); + expect(timelineUpdate).toBeDefined(); + return asRecord(asRecord(timelineUpdate?.[1]).$set); +} + function execResolved(value: T): ExecQuery { return { exec: jest.fn, []>().mockResolvedValue(value) }; } @@ -124,7 +145,12 @@ function suppressLoggerError() { interface PipelineHarnessOptions { accountError?: Error; existingMatchRaw?: Record | null; + existingTimeline?: Record; getMatch?: jest.Mock>, [string, string]>; + getMatchTimeline?: jest.Mock< + Promise>, + [string, string] + >; matchIds?: string[]; storedAccount?: Account; } @@ -141,13 +167,16 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) { const updateAccount: UpdateOneMock = jest .fn, Parameters>() .mockReturnValue(execResolved({ acknowledged: true })); - const findOneRiotMatch = jest - .fn() - .mockReturnValue( - leanExecResolved( - options.existingMatchRaw ? { raw: options.existingMatchRaw } : null, - ), - ); + const findOneRiotMatch = jest.fn().mockReturnValue( + leanExecResolved( + options.existingMatchRaw + ? { + raw: options.existingMatchRaw, + timeline: options.existingTimeline, + } + : null, + ), + ); const updateRiotMatch: UpdateOneMock = jest .fn, Parameters>() .mockReturnValue(execResolved({ acknowledged: true })); @@ -194,6 +223,11 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) { jest .fn>, [string, string]>() .mockResolvedValue(createMatchPayload()); + const getMatchTimeline = + options.getMatchTimeline ?? + jest + .fn>, [string, string]>() + .mockResolvedValue(createTimelinePayload()); const riotApiClient = { getAccountByRiotId, getSummonerByPuuid: jest.fn().mockResolvedValue({ @@ -204,11 +238,13 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) { getLeagueEntriesByPuuid: jest.fn().mockResolvedValue([]), getMatchIds: jest.fn().mockResolvedValue(options.matchIds ?? ['KR_1']), getMatch, + getMatchTimeline, } as unknown as RiotApiClient; return { findOneRiotMatch, getMatch, + getMatchTimeline, service: new AnalysisPipelineService( connectionService, riotApiClient, @@ -227,6 +263,7 @@ describe('AnalysisPipelineService', () => { const { findOneRiotMatch, getMatch, + getMatchTimeline, service, updateAnalysisJob, updatePlayerMatchFeature, @@ -238,6 +275,7 @@ describe('AnalysisPipelineService', () => { expect(findOneRiotMatch).toHaveBeenCalledWith({ matchId: 'KR_1' }); expect(getMatch).toHaveBeenCalledWith('KR_1', 'asia'); + expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia'); const riotMatchUpdate = updateRiotMatch.mock.calls[0][1]; expect(riotMatchUpdate).toMatchObject({ @@ -246,6 +284,9 @@ describe('AnalysisPipelineService', () => { queueId: 420, }, }); + const timelineSet = findTimelineSet(updateRiotMatch); + expect(timelineSet.timeline).toEqual(createTimelinePayload()); + expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date); const playerMatchFeatureUpdate = updatePlayerMatchFeature.mock.calls[0][1]; expect(playerMatchFeatureUpdate).toMatchObject({ @@ -290,7 +331,31 @@ describe('AnalysisPipelineService', () => { }); it('uses cached match details without recalling Riot Match-V5', async () => { - const { getMatch, service, updatePlayerMatchFeature } = + const { + getMatch, + getMatchTimeline, + service, + updatePlayerMatchFeature, + updateRiotMatch, + } = createPipelineHarness({ + existingMatchRaw: createMatchPayload(), + existingTimeline: createTimelinePayload(), + }); + + await service.processUserAnalysisJob(createJobData(), 'analysis-job-1'); + + expect(getMatch).not.toHaveBeenCalled(); + expect(getMatchTimeline).not.toHaveBeenCalled(); + expect( + updateRiotMatch.mock.calls.find(([, update]) => + Boolean(asRecord(asRecord(update).$set).timeline), + ), + ).toBeUndefined(); + expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1); + }); + + it('fetches a missing timeline for cached match details', async () => { + const { getMatch, getMatchTimeline, service, updateRiotMatch } = createPipelineHarness({ existingMatchRaw: createMatchPayload(), }); @@ -298,7 +363,30 @@ describe('AnalysisPipelineService', () => { await service.processUserAnalysisJob(createJobData(), 'analysis-job-1'); expect(getMatch).not.toHaveBeenCalled(); - expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1); + expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia'); + const timelineSet = findTimelineSet(updateRiotMatch); + expect(timelineSet.timeline).toEqual(createTimelinePayload()); + expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date); + }); + + it('continues raw match analysis when timeline fetch fails', async () => { + const loggerWarnSpy = jest + .spyOn(Logger.prototype, 'warn') + .mockImplementation(() => undefined); + const getMatchTimeline = jest + .fn>, [string, string]>() + .mockRejectedValue(new Error('timeline upstream failure')); + const { service, updatePlayerProfile } = createPipelineHarness({ + getMatchTimeline, + }); + + await service.processUserAnalysisJob(createJobData(), 'analysis-job-1'); + + expect(updatePlayerProfile).toHaveBeenCalled(); + expect(loggerWarnSpy).toHaveBeenCalledWith( + expect.stringContaining('Skipping timeline fetch'), + ); + loggerWarnSpy.mockRestore(); }); it('skips individual match fetch failures and still builds from successful matches', async () => { @@ -306,7 +394,12 @@ describe('AnalysisPipelineService', () => { .fn>, [string, string]>() .mockRejectedValueOnce(new Error('temporary upstream failure')) .mockResolvedValueOnce(createMatchPayload('KR_2')); - const { service, updatePlayerProfile } = createPipelineHarness({ + const { + getMatchTimeline, + service, + updateAnalysisJob, + updatePlayerProfile, + } = createPipelineHarness({ getMatch, matchIds: ['KR_1', 'KR_2'], }); @@ -314,12 +407,18 @@ describe('AnalysisPipelineService', () => { await service.processUserAnalysisJob(createJobData(), 'analysis-job-1'); expect(getMatch).toHaveBeenCalledTimes(2); + expect(getMatchTimeline).toHaveBeenCalledTimes(1); + expect(getMatchTimeline).toHaveBeenCalledWith('KR_2', 'asia'); const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1]; expect(playerProfileUpdate).toMatchObject({ $set: { sampleGameCount: 1, }, }); + const completedJobUpdate = updateAnalysisJob.mock.calls.find( + ([, update]) => asRecord(asRecord(update).$set).status === 'completed', + ); + expect(completedJobUpdate).toBeDefined(); }); it('does not mark the job failed before BullMQ exhausts retries', async () => { diff --git a/apps/api/src/modules/analysis/analysis-pipeline.service.ts b/apps/api/src/modules/analysis/analysis-pipeline.service.ts index bb264c2..9e290d9 100644 --- a/apps/api/src/modules/analysis/analysis-pipeline.service.ts +++ b/apps/api/src/modules/analysis/analysis-pipeline.service.ts @@ -42,6 +42,10 @@ function asRecord(value: unknown): Record { return {}; } +function isRecordValue(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + function asNumber(value: unknown, fallback = 0): number { return typeof value === 'number' && Number.isFinite(value) ? value : fallback; } @@ -225,6 +229,11 @@ export class AnalysisPipelineService { if (existingMatch) { if (this.isEligibleMatch(existingMatch.raw, data.queueId)) { + await this.fetchAndStoreMissingTimeline( + matchId, + existingMatch.timeline, + data.regionalRoute, + ); matchRecords.push({ matchId, raw: existingMatch.raw }); } } else { @@ -234,6 +243,11 @@ export class AnalysisPipelineService { ); await this.storeRiotMatch(matchId, rawMatch); if (this.isEligibleMatch(rawMatch, data.queueId)) { + await this.fetchAndStoreMissingTimeline( + matchId, + undefined, + data.regionalRoute, + ); matchRecords.push({ matchId, raw: rawMatch }); } } @@ -281,6 +295,47 @@ export class AnalysisPipelineService { .exec(); } + private async fetchAndStoreMissingTimeline( + matchId: string, + existingTimeline: unknown, + regionalRoute: UserAnalysisJobData['regionalRoute'], + ): Promise { + if (isRecordValue(existingTimeline)) { + return; + } + + try { + const timeline = await this.riotApiClient.getMatchTimeline( + matchId, + regionalRoute, + ); + await this.storeRiotMatchTimeline(matchId, timeline); + } catch (error) { + this.logger.warn( + `Skipping timeline fetch for matchId="${this.safeLogText(matchId)}": ${this.safeLogText(errorMessage(error))}`, + ); + } + } + + private async storeRiotMatchTimeline( + matchId: string, + timeline: Record, + ): Promise { + const riotMatchModel = await this.connectionService.getModel('riotMatch'); + + await riotMatchModel + .updateOne( + { matchId }, + { + $set: { + timeline, + timelineFetchedAt: new Date(), + }, + }, + ) + .exec(); + } + private async extractAndStoreFeatures( matchRecords: MatchRecord[], puuid: string,