Files
lolympus-tournament-support/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts
T
dahyeon 0d7617e2d2 feat: connect tournament views to APIs and recover archived stats
Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
2026-11-11 02:00:35 +09:00

440 lines
12 KiB
TypeScript

import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service';
describe('TournamentResultService Competition polling', () => {
it('promotes a reserved legacy code to a stable GameSlot assignment and accepts through Competition', async () => {
const harness = pollHarness({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(
harness.assignmentProvisioner.provisionReadyAssignments,
).toHaveBeenCalledWith({
matchId: harness.match._id,
competition: expect.objectContaining({
competitionId: harness.competitionId.toString(),
}),
});
expect(harness.assignmentModel.updateOne).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: harness.competitionId,
tournamentCodeId: harness.codeId,
}),
expect.objectContaining({
$setOnInsert: expect.objectContaining({
seriesId: harness.seriesId,
gameSlotId: harness.gameSlotId,
state: 'reserved',
}),
}),
{ upsert: true },
);
expect(harness.commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
competitionId: harness.competitionId,
seriesId: harness.seriesId,
gameSlotId: harness.gameSlotId,
tournamentCode: {
tournamentCodeId: harness.codeId,
riotMatchId: 'KR_POLL_1',
},
}),
);
expect(harness.code.save).not.toHaveBeenCalled();
expect(harness.match.result).toBeUndefined();
expect(harness.match.doubleElimination).toBeUndefined();
expect(harness.match.status).toBe('finished');
});
it('keeps tournament-code matching case-sensitive and caps expanded polling members', async () => {
const harness = pollHarness({
storedCode: 'ABC-12345',
riotTournamentCode: 'abc-12345',
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
const polledPuuids =
harness.riotMatchService.getMatchIdsByPuuid.mock.calls.map(
([puuid]: [string]) => puuid,
);
expect(polledPuuids).toEqual([
'poll-puuid-1',
'poll-puuid-2',
'poll-puuid-6',
'poll-puuid-7',
]);
expect(harness.commandService.acceptGame).not.toHaveBeenCalled();
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
});
it('reloads Competition once when assignment provisioning loses the revision CAS', async () => {
const harness = pollHarness({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
harness.assignmentProvisioner.provisionReadyAssignments
.mockRejectedValueOnce({
code: 'COMPETITION_ASSIGNMENT_STALE_REVISION',
})
.mockResolvedValue({
requested: 1,
reserved: 0,
existing: 1,
unavailable: 0,
released: 0,
});
await harness.service.processPollJob({
kind: 'poll-tournament-result',
jobId: 'poll-job-1',
enqueuedAt: Date.parse('2026-07-12T10:00:00.000Z'),
priority: 'high',
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(
harness.assignmentProvisioner.provisionReadyAssignments,
).toHaveBeenCalledTimes(3);
expect(harness.commandService.acceptGame).toHaveBeenCalledTimes(1);
});
it('resumes polling when a reversal reopens a Competition whose Match was finished', async () => {
const harness = pollHarness({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
harness.match.status = 'finished';
const result = await harness.service.scheduleInitialPoll(
harness.match._id,
'high',
);
expect(result).toMatchObject({
matchId: harness.match._id.toString(),
attempt: 1,
});
expect(harness.match.status).toBe('in-progress');
expect(
harness.riotJobQueueService.enqueueTournamentResultPoll,
).toHaveBeenCalledTimes(1);
});
});
function pollHarness(params: {
storedCode: string;
riotTournamentCode: string;
}) {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const competitionId = new mongoose.Types.ObjectId();
const seriesId = new mongoose.Types.ObjectId();
const gameSlotId = new mongoose.Types.ObjectId();
const codeId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `poll-puuid-${index + 1}`,
}));
const match = {
_id: matchId,
communityId,
status: 'team-built',
teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'),
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [codeId],
resultPollState: {
startedAt: new Date(),
matchedCount: 0,
expandedToAllPuuids: true,
state: 'polling',
},
participants: users.map(({ userId, puuid }) => ({
userId,
puuid,
excluded: false,
})),
teams: [
{
teamIndex: 1,
name: 'Team A',
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamIndex: 2,
name: 'Team B',
members: users.slice(5).map(({ userId }) => ({ userId })),
},
],
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & { save: jest.Mock };
const code = {
_id: codeId,
code: params.storedCode,
state: 'reserved',
gameNumber: 1,
reservedAt: new Date('2026-07-12T09:00:00.000Z'),
save: jest.fn().mockResolvedValue(undefined),
};
const readyCompetition = competitionDocument({
competitionId,
seriesId,
gameSlotId,
teamAId,
teamBId,
users,
completed: false,
});
const completedCompetition = competitionDocument({
competitionId,
seriesId,
gameSlotId,
teamAId,
teamBId,
users,
completed: true,
});
const detail = riotDetail(
users.map(({ puuid }) => puuid),
params.riotTournamentCode,
);
const assignmentModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)),
updateOne: jest.fn().mockReturnValue(execResult(undefined)),
};
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
switch (name) {
case 'match':
return Promise.resolve({
findById: jest.fn().mockResolvedValue(match),
});
case 'tournamentCode':
return Promise.resolve({
find: jest.fn().mockReturnValue(sortedResult([code])),
});
case 'tournamentCodeAssignment':
return Promise.resolve(assignmentModel);
case 'community':
return Promise.resolve({
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest
.fn()
.mockReturnValue(execResult({ riotRegion: 'asia' })),
}),
}),
});
case 'riotMatch':
return Promise.resolve({
findOne: jest.fn().mockReturnValue(execResult(null)),
updateOne: jest.fn().mockReturnValue(execResult(undefined)),
});
case 'competition':
return Promise.resolve({
findById: jest.fn().mockReturnValue(queryResult(readyCompetition)),
});
default:
throw new Error(`Unexpected model ${name}`);
}
}),
};
const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_POLL_1']),
getMatch: jest.fn().mockResolvedValue(detail),
};
const commandService = {
acceptGame: jest.fn().mockResolvedValue({
competition: completedCompetition,
commandId: 'cmpcmd-poll',
revision: 1,
replayed: false,
}),
};
const assignmentProvisioner = {
provisionReadyAssignments: jest.fn().mockResolvedValue({
requested: 1,
reserved: 0,
existing: 1,
unavailable: 0,
}),
};
const distributedLockService = {
runWithRenewedLock: jest
.fn()
.mockImplementation(
(_options: unknown, operation: (context: object) => Promise<unknown>) =>
operation({}),
),
runWithLock: jest
.fn()
.mockImplementation(
(_options: unknown, operation: (context: object) => Promise<unknown>) =>
operation({}),
),
};
const riotJobQueueService = {
enqueueTournamentResultPoll: jest.fn().mockResolvedValue({
jobId: 'poll-job-1',
matchId: matchId.toString(),
priority: 'high',
attempt: 1,
expandedToAllPuuids: false,
}),
};
const service = new TournamentResultService(
connectionService as never,
riotMatchService as never,
riotJobQueueService as never,
{
refreshForRiotMatches: jest.fn().mockResolvedValue(undefined),
invalidateCommunity: jest.fn().mockResolvedValue(undefined),
} as never,
distributedLockService as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
assignmentProvisioner as never,
);
return {
service,
match,
code,
competitionId,
seriesId,
gameSlotId,
codeId,
assignmentModel,
commandService,
assignmentProvisioner,
riotMatchService,
riotJobQueueService,
};
}
function competitionDocument(params: {
competitionId: mongoose.Types.ObjectId;
seriesId: mongoose.Types.ObjectId;
gameSlotId: mongoose.Types.ObjectId;
teamAId: mongoose.Types.ObjectId;
teamBId: mongoose.Types.ObjectId;
users: Array<{ userId: mongoose.Types.ObjectId }>;
completed: boolean;
}) {
const phase = params.completed ? 'completed' : 'ready';
return {
_id: params.competitionId,
revision: params.completed ? 1 : 0,
phase,
teams: [
{
teamId: params.teamAId,
members: params.users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamId: params.teamBId,
members: params.users.slice(5).map(({ userId }) => ({ userId })),
},
],
projection: {
phase,
series: [
{
seriesId: params.seriesId.toString(),
status: params.completed ? 'completed' : 'ready',
entries: [
{
slot: 'A',
teamId: params.teamAId.toString(),
gameWins: params.completed ? 1 : 0,
},
{ slot: 'B', teamId: params.teamBId.toString(), gameWins: 0 },
],
},
],
gameSlots: [
{
id: params.gameSlotId.toString(),
seriesId: params.seriesId.toString(),
ordinal: 1,
displayNumber: 1,
status: params.completed ? 'completed' : 'ready',
},
],
games: params.completed
? [{ evidence: { type: 'riot', riotMatchId: 'KR_POLL_1' } }]
: [],
},
};
}
function riotDetail(puuids: string[], tournamentCode: string): RiotMatchDto {
const participants = puuids.map((puuid, index) => ({
puuid,
participantId: index + 1,
teamId: index < 5 ? 100 : 200,
championId: index + 1,
kills: 1,
deaths: 1,
assists: 1,
win: index < 5,
}));
return {
metadata: { dataVersion: '2', matchId: 'KR_POLL_1', participants: puuids },
info: {
tournamentCode,
gameCreation: Date.parse('2026-07-12T10:00:00.000Z'),
gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'),
gameDuration: 1800,
participants,
teams: [
{ teamId: 100, win: true },
{ teamId: 200, win: false },
],
},
} as unknown as RiotMatchDto;
}
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function sortedResult<T>(value: T) {
return { sort: jest.fn().mockReturnValue(execResult(value)) };
}
function queryResult<T>(value: T) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.lean.mockReturnValue(query);
return query;
}