Files
persona-lenz/apps/api/src/modules/analysis/analysis-pipeline.service.spec.ts
T
2026-07-02 23:50:10 -07:00

665 lines
20 KiB
TypeScript

import { Logger } from '@nestjs/common';
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
import type { ConnectionService } from '../global/database/connection.service';
import type { Account } from '../global/database/schemas';
import { RiotNotFoundError, type RiotApiClient } from '../riot/riot-api.client';
import type { UserAnalysisJobData } from './analysis.types';
import { FeatureExtractorService } from './feature-extractor.service';
import { AnalysisPipelineService } from './analysis-pipeline.service';
import { ProfileBuilderService } from './profile-builder.service';
import { TimelineDerivedService } from './timeline-derived.service';
function createJobData(): UserAnalysisJobData {
return {
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
queueId: 420,
requestedMatchCount: 20,
};
}
function createMatchPayload(matchId = 'KR_1') {
return {
metadata: {
matchId,
participants: ['target-puuid', 'ally-puuid'],
},
info: {
gameCreation: 1_700_000_000_000,
gameDuration: 1800,
gameVersion: '26.13.123.456',
queueId: 420,
participants: [
{
participantId: 1,
puuid: 'target-puuid',
teamId: 100,
teamPosition: 'MIDDLE',
championId: 103,
kills: 6,
deaths: 2,
assists: 8,
totalDamageDealtToChampions: 24_000,
goldEarned: 12_000,
totalMinionsKilled: 210,
neutralMinionsKilled: 12,
visionScore: 24,
wardsKilled: 4,
detectorWardsPlaced: 3,
win: true,
challenges: {
kda: 7,
killParticipation: 0.7,
teamDamagePercentage: 0.32,
damagePerMinute: 800,
goldPerMinute: 400,
visionScorePerMinute: 0.8,
controlWardsPlaced: 3,
soloKills: 2,
},
},
{
participantId: 2,
puuid: 'ally-puuid',
teamId: 100,
teamPosition: 'JUNGLE',
championId: 64,
kills: 10,
totalDamageDealtToChampions: 30_000,
},
],
},
};
}
function createTimelinePayload(
matchId = 'KR_1',
events: Record<string, unknown>[] = [],
) {
return {
metadata: {
matchId,
participants: ['target-puuid', 'ally-puuid'],
},
info: {
frameInterval: 60_000,
frames: events.length > 0 ? [{ timestamp: 0, events }] : [],
},
};
}
function createTimelinePayloadWithFrames(
matchId = 'KR_1',
frames: Array<{
timestamp?: number;
events?: Record<string, unknown>[];
participantFrames?: Record<string, unknown>;
}> = [],
) {
return {
metadata: {
matchId,
participants: ['target-puuid', 'ally-puuid'],
},
info: {
frameInterval: 60_000,
frames: frames.map((frame, index) => ({
timestamp: frame.timestamp ?? index * 60_000,
events: frame.events ?? [],
participantFrames: frame.participantFrames ?? {},
})),
},
};
}
interface ExecQuery<T> {
exec: jest.Mock<Promise<T>, []>;
}
type AcknowledgedUpdate = { acknowledged: boolean };
type UpdateOneMock = jest.Mock<
ExecQuery<AcknowledgedUpdate>,
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
>;
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as 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) };
}
function leanExecResolved<T>(value: T) {
return {
lean: jest.fn(() => execResolved(value)),
};
}
function createStoredAccount(overrides: Partial<Account> = {}): Account {
return {
createdAt: new Date('2026-07-01T00:00:00.000Z'),
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
puuid: 'target-puuid',
gameName: 'Hide on bush',
tagLine: 'KR1',
platformRoute: 'kr',
regionalRoute: 'asia',
profileIconId: 1,
summonerLevel: 500,
tiers: [],
isSeed: false,
...overrides,
};
}
function suppressLoggerError() {
return jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
}
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;
}
function createPipelineHarness(options: PipelineHarnessOptions = {}) {
const updateAnalysisJob: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
const findOneAndUpdateAccount = jest
.fn()
.mockReturnValue(
leanExecResolved(options.storedAccount ?? createStoredAccount()),
);
const updateAccount: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
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 }));
const updatePlayerMatchFeature: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
const updatePlayerProfile: UpdateOneMock = jest
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
.mockReturnValue(execResolved({ acknowledged: true }));
const models = {
account: {
findOneAndUpdate: findOneAndUpdateAccount,
updateOne: updateAccount,
},
analysisJob: {
updateOne: updateAnalysisJob,
},
playerMatchFeature: {
updateOne: updatePlayerMatchFeature,
},
playerProfile: {
updateOne: updatePlayerProfile,
},
riotMatch: {
findOne: findOneRiotMatch,
updateOne: updateRiotMatch,
},
};
const connectionService = {
getModel: jest.fn((modelKey: keyof typeof models) =>
Promise.resolve(models[modelKey]),
),
} as unknown as ConnectionService;
const getAccountByRiotId = options.accountError
? jest.fn().mockRejectedValue(options.accountError)
: jest.fn().mockResolvedValue({
puuid: 'target-puuid',
gameName: 'Hide on bush',
tagLine: 'KR1',
});
const getMatch =
options.getMatch ??
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({
puuid: 'target-puuid',
profileIconId: 1,
summonerLevel: 500,
}),
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,
new FeatureExtractorService(),
new ProfileBuilderService(),
new TimelineDerivedService(),
),
updateAnalysisJob,
updatePlayerMatchFeature,
updatePlayerProfile,
updateRiotMatch,
};
}
describe('AnalysisPipelineService', () => {
it('fetches missing match details, stores features, builds a profile, and completes the job', async () => {
const {
findOneRiotMatch,
getMatch,
getMatchTimeline,
service,
updateAnalysisJob,
updatePlayerMatchFeature,
updatePlayerProfile,
updateRiotMatch,
} = createPipelineHarness();
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
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({
$setOnInsert: {
matchId: 'KR_1',
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({
$set: {
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
matchId: 'KR_1',
},
});
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
expect(playerProfileUpdate).toMatchObject({
$set: {
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
puuid: 'target-puuid',
sampleGameCount: 1,
},
});
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
);
expect(completedJobUpdate).toBeDefined();
expect(asRecord(asRecord(completedJobUpdate?.[1]).$set)).toMatchObject({
status: 'completed',
stage: 'completed',
});
});
it('completes without building a profile when no ranked matches are returned', async () => {
const { service, updateAnalysisJob, updatePlayerProfile } =
createPipelineHarness({
matchIds: [],
});
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
expect(updatePlayerProfile).not.toHaveBeenCalled();
const completedJobUpdate = updateAnalysisJob.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
);
expect(completedJobUpdate).toBeDefined();
});
it('uses cached match details without recalling Riot Match-V5', async () => {
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(),
});
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
expect(getMatch).not.toHaveBeenCalled();
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
const timelineSet = findTimelineSet(updateRiotMatch);
expect(timelineSet.timeline).toEqual(createTimelinePayload());
expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date);
});
it('stores derived timeline data when a timeline is available', async () => {
const timeline = createTimelinePayloadWithFrames('KR_1', [
{
timestamp: 0,
participantFrames: {
'1': { position: { x: 4_020, y: 6_000 } },
'6': { position: { x: 3_000, y: 6_000 } },
'7': { position: { x: 8_000, y: 6_000 } },
},
},
{
timestamp: 10_000,
events: [
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
assistingParticipantIds: [2],
},
],
},
{
timestamp: 60_000,
participantFrames: {
'1': { position: { x: 4_020, y: 6_000 } },
'6': { position: { x: 9_000, y: 6_000 } },
'7': { position: { x: 14_000, y: 6_000 } },
},
},
{
timestamp: 8 * 60_000,
participantFrames: {
'1': { position: { x: 8_000, y: 7_000 } },
'2': { position: { x: 8_000, y: 7_000 } },
},
},
{
timestamp: 900_000,
events: [
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
},
],
},
]);
const getMatchTimeline = jest
.fn<Promise<Record<string, unknown>>, [string, string]>()
.mockResolvedValue(timeline);
const { service, updatePlayerMatchFeature } = createPipelineHarness({
getMatchTimeline,
});
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
const playerMatchFeatureSet = asRecord(
asRecord(updatePlayerMatchFeature.mock.calls[0][1]).$set,
);
expect(playerMatchFeatureSet.timelineProcessed).toBe(true);
expect(playerMatchFeatureSet.derived).toEqual({
fightClusters: [
{
startTimeMs: 10_000,
endTimeMs: 10_000,
killCount: 1,
participantIds: [1, 2, 6],
openerParticipantIds: [1, 2],
cleanupParticipantIds: [1, 2, 6],
isTeamfight: false,
},
],
advantageEvents: [
{
timestampMs: 10_000,
teamId: 100,
type: 'championKill',
score: 1,
participantIds: [1, 2],
},
{
timestampMs: 900_000,
teamId: 100,
type: 'dragon',
score: 1.5,
participantIds: [4],
},
],
deathEvents: [
{
t: 10_000,
victimParticipantId: 6,
x: 4_000,
y: 6_000,
zone: 'southWestJungle',
shutdownBountyGiven: 0,
nearestAllyDistanceApprox: 5_000,
},
],
objectiveWindows: [
{
objectiveTimeMs: 900_000,
startTimeMs: 780_000,
endTimeMs: 930_000,
killerParticipantId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
},
],
roamFrames: [
{
t: 8 * 60_000,
participantId: 1,
teamId: 100,
x: 8_000,
y: 7_000,
zone: 'river',
assignedLaneZone: 'middleLane',
},
],
});
});
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 () => {
const getMatch = jest
.fn<Promise<Record<string, unknown>>, [string, string]>()
.mockRejectedValueOnce(new Error('temporary upstream failure'))
.mockResolvedValueOnce(createMatchPayload('KR_2'));
const {
getMatchTimeline,
service,
updateAnalysisJob,
updatePlayerProfile,
} = createPipelineHarness({
getMatch,
matchIds: ['KR_1', 'KR_2'],
});
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 () => {
const { service, updateAnalysisJob } = createPipelineHarness({
accountError: new Error('upstream unavailable'),
});
await expect(
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
isFinalAttempt: false,
}),
).rejects.toThrow('upstream unavailable');
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
);
expect(failedJobUpdate).toBeUndefined();
});
it('marks the job failed with a public error on the final BullMQ attempt', async () => {
const loggerErrorSpy = suppressLoggerError();
const { service, updateAnalysisJob } = createPipelineHarness({
accountError: new Error('internal host redis.local refused connection'),
});
await expect(
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
isFinalAttempt: true,
}),
).rejects.toThrow('internal host redis.local refused connection');
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
);
expect(asRecord(asRecord(failedJobUpdate?.[1]).$set)).toMatchObject({
status: 'failed',
error: 'Analysis failed during processing.',
});
loggerErrorSpy.mockRestore();
});
it('marks Riot account lookup misses with a public not-found error', async () => {
const loggerErrorSpy = suppressLoggerError();
const { service, updateAnalysisJob } = createPipelineHarness({
accountError: new RiotNotFoundError(404),
});
await expect(
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
isFinalAttempt: true,
}),
).rejects.toThrow(RiotNotFoundError);
const failedJobUpdate = updateAnalysisJob.mock.calls.find(
([, update]) => asRecord(asRecord(update).$set).status === 'failed',
);
expect(asRecord(asRecord(failedJobUpdate?.[1]).$set)).toMatchObject({
status: 'failed',
error: 'Riot account was not found for the selected region.',
});
loggerErrorSpy.mockRestore();
});
it('logs final pipeline failures with job context', async () => {
const loggerErrorSpy = suppressLoggerError();
const { service } = createPipelineHarness({
accountError: new Error('internal host redis.local refused connection'),
});
await expect(
service.processUserAnalysisJob(createJobData(), 'analysis-job-1', {
isFinalAttempt: true,
}),
).rejects.toThrow('internal host redis.local refused connection');
expect(loggerErrorSpy).toHaveBeenCalledWith(
expect.stringContaining('Analysis job failed jobId="analysis-job-1"'),
expect.any(String),
);
expect(loggerErrorSpy.mock.calls[0][0]).toContain(
'publicError="Analysis failed during processing."',
);
loggerErrorSpy.mockRestore();
});
});