Add timeline derived builders

This commit is contained in:
dahyeon committed 2026-07-02 23:10:40 -07:00
1 parent 3460a93eaf
commit 897e2092a3
3 files changed
+664

No files matched your search

@@ -18,6 +18,7 @@ import { AnalysisProcessor } from './analysis.processor';
import { createBullMqOptions } from './bullmq.config';
import { FeatureExtractorService } from './feature-extractor.service';
import { ProfileBuilderService } from './profile-builder.service';
import { TimelineDerivedService } from './timeline-derived.service';
@Module({
imports: [
@@ -48,6 +49,7 @@ import { ProfileBuilderService } from './profile-builder.service';
AnalysisProcessor,
FeatureExtractorService,
ProfileBuilderService,
TimelineDerivedService,
],
controllers: [AnalysisController],
exports: [AnalysisQueueService, AnalysisPipelineService],
@@ -0,0 +1,272 @@
import { TimelineDerivedService } from './timeline-derived.service';
function createTimelinePayload(
eventsByFrame: Array<Record<string, unknown>[]>,
) {
return {
info: {
frames: eventsByFrame.map((events, index) => ({
timestamp: index * 60_000,
events,
})),
},
};
}
describe('TimelineDerivedService', () => {
const service = new TimelineDerivedService();
it('clusters champion kills transitively by time and distance', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
assistingParticipantIds: [2],
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
magicDamageDone: 100,
physicalDamageDone: 50,
trueDamageDone: 0,
},
{
participantId: 1,
magicDamageDone: 20,
physicalDamageDone: 30,
trueDamageDone: 0,
},
],
},
{
type: 'CHAMPION_KILL',
timestamp: 24_000,
killerId: 2,
victimId: 7,
assistingParticipantIds: null,
victimDamageReceived: null,
position: { x: 3_400, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 38_000,
killerId: 4,
victimId: 8,
assistingParticipantIds: [5],
position: { x: 5_800, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters).toEqual([
{
startTimeMs: 10_000,
endTimeMs: 38_000,
killCount: 3,
participantIds: [1, 2, 3, 4, 5, 6, 7, 8],
openerParticipantIds: [1, 2, 3],
cleanupParticipantIds: [4, 5, 8],
isTeamfight: true,
},
]);
});
it('separates champion kills that are not connected by both time and distance', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 20_000,
killerId: 2,
victimId: 7,
position: { x: 7_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 40_000,
killerId: 3,
victimId: 8,
position: { x: 7_500, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters).toHaveLength(3);
expect(derived.fightClusters.map((cluster) => cluster.killCount)).toEqual([
1, 1, 1,
]);
expect(
derived.fightClusters.every((cluster) => cluster.isTeamfight === false),
).toBe(true);
});
it('includes every kill within five seconds of the last kill as cleanup', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 20_000,
killerId: 2,
victimId: 7,
position: { x: 2_000, y: 1_000 },
},
{
type: 'CHAMPION_KILL',
timestamp: 24_000,
killerId: 3,
victimId: 8,
position: { x: 2_500, y: 1_000 },
},
],
]),
);
expect(derived.fightClusters[0].cleanupParticipantIds).toEqual([
2, 3, 7, 8,
]);
});
it('uses explicit victim damage totals without adding component damage twice', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
totalDamageDone: 100,
magicDamageDone: 1_000,
},
{
participantId: 4,
magicDamageDone: 150,
},
],
},
],
]),
);
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 4]);
});
it('aggregates duplicate victim damage rows before selecting the opener contributor', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'CHAMPION_KILL',
timestamp: 10_000,
killerId: 1,
victimId: 6,
position: { x: 1_000, y: 1_000 },
victimDamageReceived: [
{
participantId: 3,
magicDamageDone: 80,
},
{
participantId: 3,
physicalDamageDone: 80,
},
{
participantId: 4,
magicDamageDone: 150,
},
],
},
],
]),
);
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 3]);
});
it('builds objective windows around elite monster kill timestamps', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'HEXTECH_DRAGON',
position: { x: 9_800, y: 4_400 },
},
{
type: 'WARD_PLACED',
timestamp: 905_000,
},
],
]),
);
expect(derived.objectiveWindows).toEqual([
{
objectiveTimeMs: 900_000,
startTimeMs: 780_000,
endTimeMs: 930_000,
killerParticipantId: 4,
killerTeamId: 100,
monsterType: 'DRAGON',
monsterSubType: 'HEXTECH_DRAGON',
position: { x: 9_800, y: 4_400 },
},
]);
});
it('ignores elite monster kills outside dragon, rift herald, and baron', () => {
const derived = service.buildDerivedData(
createTimelinePayload([
[
{
type: 'ELITE_MONSTER_KILL',
timestamp: 900_000,
killerId: 4,
killerTeamId: 100,
monsterType: 'HORDE',
},
{
type: 'ELITE_MONSTER_KILL',
timestamp: 1_200_000,
killerId: 5,
killerTeamId: 200,
monsterType: 'BARON_NASHOR',
},
],
]),
);
expect(derived.objectiveWindows).toHaveLength(1);
expect(derived.objectiveWindows[0].monsterType).toBe('BARON_NASHOR');
});
});
@@ -0,0 +1,390 @@
import { Injectable } from '@nestjs/common';
interface TimelinePosition {
x: number;
y: number;
}
interface TimelineChampionKillEvent {
timestamp: number;
killerId?: number;
victimId?: number;
assistingParticipantIds: number[];
position?: TimelinePosition;
victimDamageReceived: Array<{
participantId: number;
damage: number;
}>;
}
interface TimelineEliteMonsterKillEvent {
timestamp: number;
killerParticipantId?: number;
killerTeamId?: number;
monsterType?: string;
monsterSubType?: string;
position?: TimelinePosition;
}
export interface TimelineFightCluster {
startTimeMs: number;
endTimeMs: number;
killCount: number;
participantIds: number[];
openerParticipantIds: number[];
cleanupParticipantIds: number[];
isTeamfight: boolean;
}
export interface TimelineObjectiveWindow {
objectiveTimeMs: number;
startTimeMs: number;
endTimeMs: number;
killerParticipantId?: number;
killerTeamId?: number;
monsterType?: string;
monsterSubType?: string;
position?: TimelinePosition;
}
export interface TimelineDerivedData {
fightClusters: TimelineFightCluster[];
objectiveWindows: TimelineObjectiveWindow[];
}
const FIGHT_CLUSTER_MAX_GAP_MS = 15_000;
const FIGHT_CLUSTER_MAX_DISTANCE = 3_000;
const CLEANUP_WINDOW_MS = 5_000;
const OBJECTIVE_WINDOW_BEFORE_MS = 120_000;
const OBJECTIVE_WINDOW_AFTER_MS = 30_000;
const OBJECTIVE_MONSTER_TYPES = new Set([
'DRAGON',
'RIFTHERALD',
'BARON_NASHOR',
]);
function asRecord(value: unknown): Record<string, unknown> {
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as Record<string, unknown>;
}
return {};
}
function asArray(value: unknown): unknown[] {
return Array.isArray(value) ? value : [];
}
function asNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value)
? value
: undefined;
}
function asString(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined;
}
function asParticipantId(value: unknown): number | undefined {
const participantId = asNumber(value);
return participantId !== undefined && participantId > 0
? participantId
: undefined;
}
function toSortedIds(values: Iterable<number>): number[] {
return [...new Set(values)].sort((left, right) => left - right);
}
function parsePosition(value: unknown): TimelinePosition | undefined {
const position = asRecord(value);
const x = asNumber(position.x);
const y = asNumber(position.y);
if (x === undefined || y === undefined) {
return undefined;
}
return { x, y };
}
function distance(
left: TimelinePosition | undefined,
right: TimelinePosition | undefined,
): number {
if (!left || !right) {
return Number.POSITIVE_INFINITY;
}
return Math.hypot(left.x - right.x, left.y - right.y);
}
function isConnectedKill(
left: TimelineChampionKillEvent,
right: TimelineChampionKillEvent,
): boolean {
return (
Math.abs(left.timestamp - right.timestamp) <= FIGHT_CLUSTER_MAX_GAP_MS &&
distance(left.position, right.position) <= FIGHT_CLUSTER_MAX_DISTANCE
);
}
function eventParticipantIds(event: TimelineChampionKillEvent): number[] {
return toSortedIds(
[
event.killerId,
event.victimId,
...event.assistingParticipantIds,
...event.victimDamageReceived.map((damage) => damage.participantId),
].filter((id): id is number => id !== undefined),
);
}
function eventOpenerParticipantIds(event: TimelineChampionKillEvent): number[] {
const damageByParticipantId = new Map<number, number>();
for (const damage of event.victimDamageReceived) {
damageByParticipantId.set(
damage.participantId,
(damageByParticipantId.get(damage.participantId) ?? 0) + damage.damage,
);
}
const highestDamageContributor = [...damageByParticipantId.entries()].reduce<
{ participantId: number; damage: number } | undefined
>((selected, [participantId, damage]) => {
if (!selected || damage > selected.damage) {
return { participantId, damage };
}
return selected;
}, undefined);
return toSortedIds(
[
event.killerId,
...event.assistingParticipantIds,
highestDamageContributor?.participantId,
].filter((id): id is number => id !== undefined),
);
}
function isObjectiveMonsterType(monsterType: string | undefined): boolean {
return monsterType !== undefined && OBJECTIVE_MONSTER_TYPES.has(monsterType);
}
function parseAssistingParticipantIds(value: unknown): number[] {
return toSortedIds(
asArray(value).flatMap((item) => {
const participantId = asParticipantId(item);
return participantId === undefined ? [] : [participantId];
}),
);
}
function parseVictimDamageReceived(
value: unknown,
): TimelineChampionKillEvent['victimDamageReceived'] {
return asArray(value).flatMap((item) => {
const damageRecord = asRecord(item);
const participantId = asParticipantId(damageRecord.participantId);
if (participantId === undefined) {
return [];
}
const explicitDamage =
asNumber(damageRecord.totalDamageDone) ?? asNumber(damageRecord.damage);
const componentDamage =
(asNumber(damageRecord.magicDamageDone) ?? 0) +
(asNumber(damageRecord.physicalDamageDone) ?? 0) +
(asNumber(damageRecord.trueDamageDone) ?? 0);
return [
{
participantId,
damage: explicitDamage ?? componentDamage,
},
];
});
}
function parseChampionKillEvent(
event: Record<string, unknown>,
): TimelineChampionKillEvent | undefined {
const timestamp = asNumber(event.timestamp);
if (timestamp === undefined) {
return undefined;
}
return {
timestamp,
killerId: asParticipantId(event.killerId),
victimId: asParticipantId(event.victimId),
assistingParticipantIds: parseAssistingParticipantIds(
event.assistingParticipantIds,
),
position: parsePosition(event.position),
victimDamageReceived: parseVictimDamageReceived(event.victimDamageReceived),
};
}
function parseEliteMonsterKillEvent(
event: Record<string, unknown>,
): TimelineEliteMonsterKillEvent | undefined {
const timestamp = asNumber(event.timestamp);
if (timestamp === undefined) {
return undefined;
}
return {
timestamp,
killerParticipantId: asParticipantId(event.killerId),
killerTeamId: asNumber(event.killerTeamId),
monsterType: asString(event.monsterType),
monsterSubType: asString(event.monsterSubType),
position: parsePosition(event.position),
};
}
function extractTimelineEvents(timeline: Record<string, unknown>) {
const info = asRecord(timeline.info);
const frames = asArray(info.frames).map(asRecord);
const championKills: TimelineChampionKillEvent[] = [];
const eliteMonsterKills: TimelineEliteMonsterKillEvent[] = [];
for (const frame of frames) {
for (const rawEvent of asArray(frame.events)) {
const event = asRecord(rawEvent);
switch (asString(event.type)) {
case 'CHAMPION_KILL': {
const championKill = parseChampionKillEvent(event);
if (championKill) {
championKills.push(championKill);
}
break;
}
case 'ELITE_MONSTER_KILL': {
const eliteMonsterKill = parseEliteMonsterKillEvent(event);
if (eliteMonsterKill) {
eliteMonsterKills.push(eliteMonsterKill);
}
break;
}
}
}
}
return {
championKills: championKills.sort(
(left, right) => left.timestamp - right.timestamp,
),
eliteMonsterKills: eliteMonsterKills.sort(
(left, right) => left.timestamp - right.timestamp,
),
};
}
function findRoot(parents: number[], index: number): number {
let root = index;
while (parents[root] !== root) {
root = parents[root];
}
while (parents[index] !== index) {
const parent = parents[index];
parents[index] = root;
index = parent;
}
return root;
}
function union(parents: number[], left: number, right: number): void {
const leftRoot = findRoot(parents, left);
const rightRoot = findRoot(parents, right);
if (leftRoot !== rightRoot) {
parents[rightRoot] = leftRoot;
}
}
function buildFightClusters(
kills: TimelineChampionKillEvent[],
): TimelineFightCluster[] {
const parents = kills.map((_, index) => index);
for (let leftIndex = 0; leftIndex < kills.length; leftIndex += 1) {
for (
let rightIndex = leftIndex + 1;
rightIndex < kills.length;
rightIndex += 1
) {
if (isConnectedKill(kills[leftIndex], kills[rightIndex])) {
union(parents, leftIndex, rightIndex);
}
}
}
const clusterGroups = new Map<number, TimelineChampionKillEvent[]>();
for (const [index, kill] of kills.entries()) {
const root = findRoot(parents, index);
clusterGroups.set(root, [...(clusterGroups.get(root) ?? []), kill]);
}
return [...clusterGroups.values()]
.map((clusterKills) => {
const sortedKills = [...clusterKills].sort(
(left, right) => left.timestamp - right.timestamp,
);
const firstKill = sortedKills[0];
const lastKill = sortedKills[sortedKills.length - 1];
const cleanupStartTimeMs = lastKill.timestamp - CLEANUP_WINDOW_MS;
const cleanupEndTimeMs = lastKill.timestamp + CLEANUP_WINDOW_MS;
const cleanupParticipantIds = sortedKills
.filter(
(kill) =>
kill.timestamp >= cleanupStartTimeMs &&
kill.timestamp <= cleanupEndTimeMs,
)
.flatMap(eventParticipantIds);
return {
startTimeMs: firstKill.timestamp,
endTimeMs: lastKill.timestamp,
killCount: sortedKills.length,
participantIds: toSortedIds(sortedKills.flatMap(eventParticipantIds)),
openerParticipantIds: eventOpenerParticipantIds(firstKill),
cleanupParticipantIds: toSortedIds(cleanupParticipantIds),
isTeamfight: sortedKills.length >= 3,
};
})
.sort((left, right) => left.startTimeMs - right.startTimeMs);
}
function buildObjectiveWindows(
eliteMonsterKills: TimelineEliteMonsterKillEvent[],
): TimelineObjectiveWindow[] {
return eliteMonsterKills
.filter((event) => isObjectiveMonsterType(event.monsterType))
.map((event) => ({
objectiveTimeMs: event.timestamp,
startTimeMs: event.timestamp - OBJECTIVE_WINDOW_BEFORE_MS,
endTimeMs: event.timestamp + OBJECTIVE_WINDOW_AFTER_MS,
...(event.killerParticipantId !== undefined
? { killerParticipantId: event.killerParticipantId }
: {}),
...(event.killerTeamId !== undefined
? { killerTeamId: event.killerTeamId }
: {}),
...(event.monsterType ? { monsterType: event.monsterType } : {}),
...(event.monsterSubType ? { monsterSubType: event.monsterSubType } : {}),
...(event.position ? { position: event.position } : {}),
}));
}
@Injectable()
export class TimelineDerivedService {
public buildDerivedData(
timeline: Record<string, unknown>,
): TimelineDerivedData {
const { championKills, eliteMonsterKills } =
extractTimelineEvents(timeline);
return {
fightClusters: buildFightClusters(championKills),
objectiveWindows: buildObjectiveWindows(eliteMonsterKills),
};
}
}