Files
lolympus-tournament-support/apps/api/src/modules/community-stats/match-stats.service.spec.ts
T

631 lines
20 KiB
TypeScript

import mongoose from 'mongoose';
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 () => {
const matchId = new mongoose.Types.ObjectId();
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: matchId,
status: 'recruiting',
result: undefined,
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
expect(repository.upsert).not.toHaveBeenCalled();
});
it('revision-guards deletion when a Competition reversal leaves zero games', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [],
projection: { phase: 'ready', games: [] },
};
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: () => queryResult(match, false) };
}
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
deleteByMatch: jest.fn().mockResolvedValue(undefined),
upsert: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const service = new MatchStatsService(
connectionService,
repository,
{} as MatchStatsFragmentBuilder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert).not.toHaveBeenCalled();
});
it('upserts a fragment for eligible matches', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
const match = {
_id: matchId,
communityId,
scheduledAt,
status: 'finished',
result: { games: [{ riotMatchId: 'KR_1' }] },
};
const findById = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(match),
});
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest.fn().mockResolvedValue([
{
matchId: 'KR_1',
raw: {},
timeline: {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: [],
},
info: { frameInterval: 60_000, frames: [] },
},
},
]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: () => queryResult(null) };
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: { matchId: matchId.toString() },
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1_000,
gameCreationMax: 2_000,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId);
expect(builder.buildFragment).toHaveBeenCalledWith({
match,
rawByRiotMatchId: expect.any(Map),
timelineByRiotMatchId: expect.any(Map),
});
expect(
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
).toHaveProperty('size', 0);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
communityId,
scheduledAt,
gameCreationMin: 1_000,
gameCreationMax: 2_000,
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();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const userAId = new mongoose.Types.ObjectId();
const userBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: { games: [{ riotMatchId: 'KR_LEGACY_MUST_NOT_BE_USED' }] },
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 8, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 3, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
displayNumber: 4,
evidence: { type: 'riot', riotMatchId: 'KR_COMPETITION' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
startedAt: '2026-07-12T10:00:00.000Z',
durationSeconds: 1800,
participants: [
participant(userAId, teamAId, 'blue', true),
participant(userBId, teamBId, 'red', false),
],
},
],
},
};
const riotFind = jest.fn().mockReturnValue({
lean: () => ({
exec: jest
.fn()
.mockResolvedValue([{ matchId: 'KR_COMPETITION', raw: {} }]),
}),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match')
return { findById: () => queryResult(match, false) };
if (name === 'competition') {
return { findOne: () => queryResult(competition) };
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).toHaveBeenCalledWith({
matchId: { $in: ['KR_COMPETITION'] },
});
expect(builder.buildFragment).toHaveBeenCalledWith(
expect.objectContaining({
match: expect.objectContaining({
result: expect.objectContaining({
riotMatchIds: ['KR_COMPETITION'],
games: [
expect.objectContaining({
gameNumber: 4,
blueTeamIndex: 8,
redTeamIndex: 3,
winnerTeamIndex: 8,
}),
],
}),
}),
}),
);
expect(repository.upsert).toHaveBeenCalledWith(
expect.objectContaining({
sourceCompetitionId: competitionId,
sourceRevision: 12,
projectorVersion: 3,
}),
);
});
it('removes a fragment written after its Competition Match was deleted', async () => {
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const match = {
_id: matchId,
communityId,
scheduledAt: new Date('2026-07-12T10:00:00.000Z'),
status: 'in-progress',
teams: [],
result: undefined,
};
const competition = {
_id: competitionId,
revision: 12,
projectorVersion: 3,
teams: [
{ teamId: teamAId, legacyTeamIndex: 1, displayOrder: 1 },
{ teamId: teamBId, legacyTeamIndex: 2, displayOrder: 2 },
],
projection: {
phase: 'running',
games: [
{
id: new mongoose.Types.ObjectId(),
displayNumber: 1,
evidence: { type: 'legacy', legacyReference: 'legacy:1' },
teams: {
blue: { teamId: teamAId.toString() },
red: { teamId: teamBId.toString() },
},
winnerTeamId: teamAId.toString(),
},
],
},
};
const findById = jest
.fn()
.mockReturnValueOnce(queryResult(match, false))
.mockReturnValueOnce(queryResult(null, false));
const findCompetition = jest.fn().mockReturnValue(queryResult(competition));
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') return { findById };
if (name === 'competition') return { findOne: findCompetition };
if (name === 'riotMatch') return {};
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn().mockResolvedValue(undefined),
deleteByMatch: jest.fn().mockResolvedValue(undefined),
deleteLegacyByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn().mockReturnValue({
matchCard: {},
records: [],
gameDetails: [],
userIds: [],
championIds: [],
gameCreationMin: 1,
gameCreationMax: 2,
}),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(repository.upsert).toHaveBeenCalled();
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId, {
sourceCompetitionId: competitionId,
sourceRevision: 12,
});
expect(repository.upsert.mock.invocationCallOrder[0]).toBeLessThan(
repository.deleteByMatch.mock.invocationCallOrder[0],
);
});
it('does not rebuild before the requested Competition revision is visible', async () => {
const matchId = new mongoose.Types.ObjectId();
const riotFind = jest.fn();
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return {
findById: () =>
queryResult(
{
_id: matchId,
status: 'in-progress',
},
false,
),
};
}
if (name === 'competition') {
return {
findOne: () => queryResult({ revision: 11 }),
};
}
if (name === 'riotMatch') return { find: riotFind };
throw new Error(`Unexpected model: ${name}`);
}),
} as unknown as ConnectionService;
const repository = {
upsert: jest.fn(),
deleteByMatch: jest.fn(),
} as unknown as jest.Mocked<MatchStatsRepository>;
const builder = {
buildFragment: jest.fn(),
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
const service = new MatchStatsService(
connectionService,
repository,
builder,
{ getMatchTimeline: jest.fn() } as never,
);
await service.buildAndUpsert(matchId, { sourceRevision: 12 });
expect(riotFind).not.toHaveBeenCalled();
expect(builder.buildFragment).not.toHaveBeenCalled();
expect(repository.upsert).not.toHaveBeenCalled();
expect(repository.deleteByMatch).not.toHaveBeenCalled();
});
});
function participant(
userId: mongoose.Types.ObjectId,
teamId: mongoose.Types.ObjectId,
side: 'blue' | 'red',
win: boolean,
) {
return {
userId: userId.toString(),
teamId: teamId.toString(),
side,
summonerName: 'player',
tagLine: 'KR1',
championId: 1,
kills: 1,
deaths: 1,
assists: 1,
win,
};
}
function queryResult<T>(value: T, lean = true) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
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,
},
},
};
}