feat: enrich internal match game analysis

This commit is contained in:
dahyeon committed 2026-07-13 09:35:25 +00:00
1 parent 9f698a8fec
commit aa675199af
22 files changed
+3123 -241

No files matched your search

@@ -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<CommunityStatsCacheService>;
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<CommunityStatsCacheService>;
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<typeof dataset>((resolve) => {
resolveDataset = resolve;
});
const setDetail = jest.fn().mockResolvedValue(undefined);
const cacheService = {
get: jest.fn().mockResolvedValue(null),
setDetail,
} as unknown as jest.Mocked<CommunityStatsCacheService>;
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();
@@ -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<InternalMatchDetailResponse>
>();
private readonly userInternalHistoryInFlight = new Map<
string,
Promise<UserInternalHistoryResponse>
@@ -219,6 +224,27 @@ export class CommunityStatsService {
await this.cacheService.get<InternalMatchDetailResponse>(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<InternalMatchDetailResponse> {
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<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -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;
@@ -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);
});
});
@@ -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<string, RiotMatchDto>;
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
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<MatchDocument['result']>['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<number, MatchStatsParticipantCheckpoints> {
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<number>();
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<TeamSide, number>,
@@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder {
return sideByParticipantId;
}
private toObjectiveEvents(
private toTimelineEvents(
timeline: RiotMatchTimelineDto | undefined,
rawTeamIdBySide: Map<TeamSide, number>,
sideByParticipantId: Map<number, TeamSide>,
): MatchStatsObjectiveEvent[] {
if (!timeline?.info.frames.length) return [];
): TimelineProjection {
if (!timeline?.info.frames.length) {
return { objectiveEvents: [], timelineEvents: [] };
}
const sideByTeamId = new Map<number, TeamSide>();
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;
}
@@ -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<MatchStatsRepository>;
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<MatchStatsFragmentBuilder['buildFragment']>;
const buildFragment = jest.fn((params: BuildParams) => {
buildCalls.push(params);
return builtFragment;
});
const builder = {
buildFragment,
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
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<T>(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,
},
},
};
}
@@ -77,7 +77,7 @@ export class MatchStatsService {
);
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
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<string, unknown> {
@@ -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;
@@ -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 };
@@ -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(
<T>(_path: string, _options: unknown, parser?: RiotResponseParser<T>) =>
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.',
);
});
});
@@ -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`,
),
};
}
+1
View File
@@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
skillSlot?: number;
teamId?: number;
towerType?: string;
victimId?: number;
}
export interface RiotMatchTimelineParticipantFrameDto