Collect match timelines during analysis

This commit is contained in:
dahyeon committed 2026-07-02 22:38:24 -07:00
1 parent 304f157b91
commit 43662a86d8
2 files changed
+164 -10

No files matched your search

@@ -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<T> {
exec: jest.Mock<Promise<T>, []>;
}
@@ -88,6 +101,14 @@ function asRecord(value: unknown): Record<string, unknown> {
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<T>(value: T): ExecQuery<T> {
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
}
@@ -124,7 +145,12 @@ function suppressLoggerError() {
interface PipelineHarnessOptions {
accountError?: Error;
existingMatchRaw?: Record<string, unknown> | null;
existingTimeline?: Record<string, unknown>;
getMatch?: jest.Mock<Promise<Record<string, unknown>>, [string, string]>;
getMatchTimeline?: jest.Mock<
Promise<Record<string, unknown>>,
[string, string]
>;
matchIds?: string[];
storedAccount?: Account;
}
@@ -141,13 +167,16 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) {
const updateAccount: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.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<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
@@ -194,6 +223,11 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) {
jest
.fn<Promise<Record<string, unknown>>, [string, string]>()
.mockResolvedValue(createMatchPayload());
const getMatchTimeline =
options.getMatchTimeline ??
jest
.fn<Promise<Record<string, unknown>>, [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<Promise<Record<string, unknown>>, [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<Promise<Record<string, unknown>>, [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 () => {
@@ -42,6 +42,10 @@ function asRecord(value: unknown): Record<string, unknown> {
return {};
}
function isRecordValue(value: unknown): value is Record<string, unknown> {
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<void> {
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<string, unknown>,
): Promise<void> {
const riotMatchModel = await this.connectionService.getModel('riotMatch');
await riotMatchModel
.updateOne(
{ matchId },
{
$set: {
timeline,
timelineFetchedAt: new Date(),
},
},
)
.exec();
}
private async extractAndStoreFeatures(
matchRecords: MatchRecord[],
puuid: string,