release/86 #2

Merged
dahyeon merged 108 commits from release/86 into main 2026-07-15 08:56:05 +00:00
11 changed files with 2563 additions and 1679 deletions
Showing only changes of commit ab9c48b1e6 - Show all commits

No files matched your search

@@ -0,0 +1,281 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import type { CompetitionResultSnapshot } from './competition-result.adapter';
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
describe('CompetitionAssignmentProvisioner', () => {
it('reserves an available code and creates the stable GameSlot assignment in one transaction', async () => {
const harness = createHarness();
const provisioner = new CompetitionAssignmentProvisioner(
harness.connectionService as never,
);
const result = await provisioner.provisionReadyAssignments({
matchId: harness.matchId,
competition: harness.competition,
});
expect(result).toMatchObject({
requested: 1,
reserved: 1,
existing: 0,
unavailable: 0,
});
expect(harness.competitionModel.updateOne).toHaveBeenCalledWith(
{ _id: harness.competitionId, revision: 2 },
{ $set: { revision: 2 } },
{ session: harness.session, timestamps: false },
);
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({ state: 'available' }),
{
$set: expect.objectContaining({
state: 'reserved',
matchId: harness.matchId,
gameNumber: 1,
}),
},
expect.objectContaining({
new: true,
session: harness.session,
sort: { expiresAt: 1 },
}),
);
expect(harness.assignmentModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
competitionId: harness.competitionId,
seriesId: harness.seriesId,
gameSlotId: harness.gameSlotId,
tournamentCodeId: harness.codeId,
state: 'reserved',
commandId: `provision-code:${harness.competitionId.toString()}:${harness.gameSlotId.toString()}:2:${harness.codeId.toString()}`,
}),
],
{ session: harness.session },
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: harness.matchId },
{ $addToSet: { tournamentCodeIds: harness.codeId } },
{ session: harness.session },
);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
it('converges after a unique-index race by rereading the active GameSlot assignment', async () => {
const harness = createHarness({
assignmentInsertError: duplicateKeyError(),
});
const activeAssignment = {
competitionId: harness.competitionId,
seriesId: harness.seriesId,
gameSlotId: harness.gameSlotId,
tournamentCodeId: harness.codeId,
state: 'reserved',
};
harness.assignmentModel.findOne
.mockReturnValueOnce(queryResult(null))
.mockReturnValueOnce(queryResult(activeAssignment));
const provisioner = new CompetitionAssignmentProvisioner(
harness.connectionService as never,
);
const result = await provisioner.provisionReadyAssignments({
matchId: harness.matchId,
competition: harness.competition,
});
expect(result).toMatchObject({ reserved: 0, existing: 1, unavailable: 0 });
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.endSession).toHaveBeenCalledTimes(1);
});
it('releases a reserved code when an early Series outcome makes its GameSlot inactive', async () => {
const harness = createHarness();
harness.competition.projection.gameSlots[0].status = 'inactive';
const assignmentId = new mongoose.Types.ObjectId();
harness.assignmentModel.find.mockReturnValue(
queryResult([
{
_id: assignmentId,
competitionId: harness.competitionId,
seriesId: harness.seriesId,
gameSlotId: harness.gameSlotId,
tournamentCodeId: harness.codeId,
state: 'reserved',
},
]),
);
harness.assignmentModel.findOneAndUpdate.mockReturnValue(
queryResult({ _id: assignmentId, state: 'released' }),
);
const provisioner = new CompetitionAssignmentProvisioner(
harness.connectionService as never,
);
const result = await provisioner.provisionReadyAssignments({
matchId: harness.matchId,
competition: harness.competition,
});
expect(result).toMatchObject({ requested: 0, released: 1 });
expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: assignmentId, state: 'reserved' },
{ $set: expect.objectContaining({ state: 'released' }) },
{ new: true, session: harness.session },
);
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: harness.codeId, state: 'reserved' },
expect.objectContaining({
$set: expect.objectContaining({ state: 'released' }),
}),
{ new: true, session: harness.session },
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: harness.matchId },
{ $pull: { tournamentCodeIds: harness.codeId } },
{ session: harness.session },
);
});
it('refuses to reserve without a MongoDB transaction', async () => {
const harness = createHarness();
harness.connectionService.createSession.mockResolvedValue(undefined);
const provisioner = new CompetitionAssignmentProvisioner(
harness.connectionService as never,
);
await expect(
provisioner.provisionReadyAssignments({
matchId: harness.matchId,
competition: harness.competition,
}),
).rejects.toMatchObject({
code: 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE',
});
expect(harness.codeModel.findOneAndUpdate).not.toHaveBeenCalled();
});
it('rejects a stale projection revision before reserving a code', async () => {
const harness = createHarness();
harness.competitionModel.updateOne.mockResolvedValue({ matchedCount: 0 });
const provisioner = new CompetitionAssignmentProvisioner(
harness.connectionService as never,
);
await expect(
provisioner.provisionReadyAssignments({
matchId: harness.matchId,
competition: harness.competition,
}),
).rejects.toMatchObject({
code: 'COMPETITION_ASSIGNMENT_STALE_REVISION',
});
expect(harness.codeModel.findOneAndUpdate).not.toHaveBeenCalled();
});
});
function createHarness(options: { assignmentInsertError?: Error } = {}) {
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 competition: CompetitionResultSnapshot = {
competitionId: competitionId.toString(),
revision: 2,
phase: 'running',
teams: [],
projection: {
phase: 'running',
series: [],
games: [],
gameSlots: [
{
id: gameSlotId.toString(),
seriesId: seriesId.toString(),
ordinal: 1,
displayNumber: 1,
status: 'ready',
},
],
},
};
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const assignmentModel = {
find: jest.fn().mockReturnValue(queryResult([])),
findOne: jest.fn().mockReturnValue(queryResult(null)),
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(null)),
insertMany: options.assignmentInsertError
? jest.fn().mockRejectedValue(options.assignmentInsertError)
: jest.fn().mockResolvedValue([]),
};
const code = {
_id: codeId,
state: 'reserved',
reservedAt: new Date('2026-07-12T10:00:00.000Z'),
};
const codeModel = {
find: jest.fn().mockReturnValue(queryResult([])),
findOneAndUpdate: jest.fn().mockReturnValue(queryResult(code)),
};
const matchModel = {
updateOne: jest.fn().mockReturnValue(execResult(undefined)),
};
const competitionModel = {
findOne: jest.fn().mockReturnValue(queryResult({ _id: competitionId })),
updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }),
};
const models: Record<string, unknown> = {
tournamentCodeAssignment: assignmentModel,
tournamentCode: codeModel,
match: matchModel,
competition: competitionModel,
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest
.fn()
.mockImplementation((name: string) => Promise.resolve(models[name])),
};
return {
connectionService,
session,
assignmentModel,
codeModel,
matchModel,
competitionModel,
matchId,
competitionId,
seriesId,
gameSlotId,
codeId,
competition,
};
}
function queryResult<T>(value: T) {
const query = {
sort: jest.fn(),
session: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.sort.mockReturnValue(query);
query.session.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
function execResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function duplicateKeyError(): Error & { code: number } {
return Object.assign(new Error('E11000 duplicate key'), { code: 11000 });
}
@@ -0,0 +1,471 @@
import { Injectable } from '@nestjs/common';
import { createHash } from 'node:crypto';
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants';
import type {
CompetitionResultGameSlotProjection,
CompetitionResultSnapshot,
} from './competition-result.adapter';
const PROVISION_ATTEMPTS = 3;
const ACTIVE_ASSIGNMENT_STATES = ['reserved', 'used'] as const;
export type CompetitionAssignmentProvisionErrorCode =
| 'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE'
| 'COMPETITION_ASSIGNMENT_STALE_REVISION'
| 'COMPETITION_ASSIGNMENT_PROVISION_FAILED';
export class CompetitionAssignmentProvisionError extends Error {
constructor(
public readonly code: CompetitionAssignmentProvisionErrorCode,
message: string,
public readonly cause?: unknown,
) {
super(message);
this.name = 'CompetitionAssignmentProvisionError';
}
}
export interface CompetitionAssignmentProvisionResult {
requested: number;
reserved: number;
existing: number;
unavailable: number;
released: number;
}
type ReservationOutcome = 'reserved' | 'existing' | 'unavailable';
interface AssignmentRecord {
_id: mongoose.Types.ObjectId;
competitionId: mongoose.Types.ObjectId;
seriesId: mongoose.Types.ObjectId;
gameSlotId: mongoose.Types.ObjectId;
tournamentCodeId: mongoose.Types.ObjectId;
state: 'reserved' | 'used' | 'released' | 'voided';
}
interface CodeRecord {
_id: mongoose.Types.ObjectId;
state: string;
reservedAt?: Date;
}
@Injectable()
export class CompetitionAssignmentProvisioner {
constructor(private readonly connectionService: ConnectionService) {}
public async provisionReadyAssignments(params: {
matchId: mongoose.Types.ObjectId;
competition: CompetitionResultSnapshot;
}): Promise<CompetitionAssignmentProvisionResult> {
const targets = uniqueReadyTargets(params.competition);
const released = await this.releaseInactiveAssignments({
...params,
readyGameSlotIds: new Set(targets.map(({ id }) => id)),
});
const result: CompetitionAssignmentProvisionResult = {
requested: targets.length,
reserved: 0,
existing: 0,
unavailable: 0,
released,
};
for (const target of targets) {
const outcome = await this.reserveTarget({ ...params, target });
result[outcome] += 1;
}
return result;
}
private async releaseInactiveAssignments(params: {
matchId: mongoose.Types.ObjectId;
competition: CompetitionResultSnapshot;
readyGameSlotIds: ReadonlySet<string>;
}): Promise<number> {
const competitionId = objectId(
params.competition.competitionId,
'Competition',
);
const [AssignmentModel, TournamentCodeModel, MatchModel, CompetitionModel] =
await Promise.all([
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
const reserved = (await AssignmentModel.find({
competitionId,
state: 'reserved',
gameSlotId: {
$nin: [...params.readyGameSlotIds].map((id) =>
objectId(id, 'GameSlot'),
),
},
})
.sort({ reservedAt: 1, _id: 1 })
.lean()
.exec()) as AssignmentRecord[];
let released = 0;
for (const assignment of reserved) {
const didRelease = await this.releaseAssignment({
matchId: params.matchId,
assignment,
AssignmentModel,
TournamentCodeModel,
MatchModel,
CompetitionModel,
competitionId,
expectedRevision: params.competition.revision,
});
if (didRelease) released += 1;
}
return released;
}
private async releaseAssignment(params: {
matchId: mongoose.Types.ObjectId;
assignment: AssignmentRecord;
AssignmentModel: mongoose.Model<any>;
TournamentCodeModel: mongoose.Model<any>;
MatchModel: mongoose.Model<any>;
CompetitionModel: mongoose.Model<any>;
competitionId: mongoose.Types.ObjectId;
expectedRevision: number;
}): Promise<boolean> {
for (let attempt = 1; attempt <= PROVISION_ATTEMPTS; attempt += 1) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required to release Competition GameSlot codes.',
);
}
try {
session.startTransaction();
await assertCurrentRevision({
CompetitionModel: params.CompetitionModel,
competitionId: params.competitionId,
expectedRevision: params.expectedRevision,
session,
});
const releasedAt = new Date();
const assignment = (await params.AssignmentModel.findOneAndUpdate(
{ _id: params.assignment._id, state: 'reserved' },
{ $set: { state: 'released', releasedAt } },
{ new: true, session },
).exec()) as AssignmentRecord | null;
if (!assignment) {
await session.commitTransaction();
return false;
}
const code = (await params.TournamentCodeModel.findOneAndUpdate(
{ _id: params.assignment.tournamentCodeId, state: 'reserved' },
{
$set: { state: 'released', releasedAt },
$unset: {
matchId: 1,
gameNumber: 1,
bracketMatchId: 1,
reservedAt: 1,
},
},
{ new: true, session },
).exec()) as CodeRecord | null;
if (!code) {
throw new Error(
'Reserved assignment points to a Tournament Code that is not reserved.',
);
}
await params.MatchModel.updateOne(
{ _id: params.matchId },
{ $pull: { tournamentCodeIds: params.assignment.tournamentCodeId } },
{ session },
).exec();
await session.commitTransaction();
return true;
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (isStaleRevisionError(error)) throw error;
const current = (await params.AssignmentModel.findById(
params.assignment._id,
)
.lean()
.exec()) as AssignmentRecord | null;
if (current && current.state !== 'reserved') return false;
if (attempt < PROVISION_ATTEMPTS && isRetryable(error)) continue;
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_PROVISION_FAILED',
`Failed to release Tournament Code assignment ${params.assignment._id.toString()}.`,
error,
);
} finally {
await session.endSession().catch(() => undefined);
}
}
return false;
}
private async reserveTarget(params: {
matchId: mongoose.Types.ObjectId;
competition: CompetitionResultSnapshot;
target: CompetitionResultGameSlotProjection;
}): Promise<ReservationOutcome> {
const competitionId = objectId(
params.competition.competitionId,
'Competition',
);
const seriesId = objectId(params.target.seriesId, 'Series');
const gameSlotId = objectId(params.target.id, 'GameSlot');
const [AssignmentModel, TournamentCodeModel, MatchModel, CompetitionModel] =
await Promise.all([
this.connectionService.getModel('tournamentCodeAssignment'),
this.connectionService.getModel('tournamentCode'),
this.connectionService.getModel('match'),
this.connectionService.getModel('competition'),
]);
for (let attempt = 1; attempt <= PROVISION_ATTEMPTS; attempt += 1) {
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required to reserve Competition GameSlot codes.',
);
}
try {
session.startTransaction();
await assertCurrentRevision({
CompetitionModel,
competitionId,
expectedRevision: params.competition.revision,
session,
});
const existing = (await AssignmentModel.findOne({
competitionId,
gameSlotId,
state: { $in: ACTIVE_ASSIGNMENT_STATES },
})
.session(session)
.lean()
.exec()) as AssignmentRecord | null;
if (existing) {
await session.commitTransaction();
return 'existing';
}
const code = await this.claimCode({
matchId: params.matchId,
competitionId,
displayNumber: params.target.displayNumber,
AssignmentModel,
TournamentCodeModel,
session,
});
if (!code) {
await session.commitTransaction();
return 'unavailable';
}
const commandId = `provision-code:${params.competition.competitionId}:${params.target.id}:${params.competition.revision}:${code._id.toString()}`;
await AssignmentModel.insertMany(
[
{
_id: deterministicObjectId(commandId),
competitionId,
seriesId,
gameSlotId,
tournamentCodeId: code._id,
state: 'reserved',
reservedAt: code.reservedAt ?? new Date(),
commandId,
},
],
{ session },
);
await MatchModel.updateOne(
{ _id: params.matchId },
{ $addToSet: { tournamentCodeIds: code._id } },
{ session },
).exec();
await session.commitTransaction();
return 'reserved';
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (isStaleRevisionError(error)) throw error;
const converged = await this.findActiveAssignment(
AssignmentModel,
competitionId,
gameSlotId,
);
if (converged) return 'existing';
if (attempt < PROVISION_ATTEMPTS && isRetryable(error)) continue;
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_PROVISION_FAILED',
`Failed to reserve a Tournament Code for GameSlot ${params.target.id}.`,
error,
);
} finally {
await session.endSession().catch(() => undefined);
}
}
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_PROVISION_FAILED',
`Reservation retry budget was exhausted for GameSlot ${params.target.id}.`,
);
}
private async claimCode(params: {
matchId: mongoose.Types.ObjectId;
competitionId: mongoose.Types.ObjectId;
displayNumber: number;
AssignmentModel: mongoose.Model<any>;
TournamentCodeModel: mongoose.Model<any>;
session: mongoose.ClientSession;
}): Promise<CodeRecord | null> {
const legacyCandidates = (await params.TournamentCodeModel.find({
matchId: params.matchId,
state: 'reserved',
gameNumber: params.displayNumber,
})
.sort({ reservedAt: 1, _id: 1 })
.session(params.session)
.exec()) as CodeRecord[];
for (const candidate of legacyCandidates) {
const assigned = (await params.AssignmentModel.findOne({
tournamentCodeId: candidate._id,
state: { $in: ACTIVE_ASSIGNMENT_STATES },
})
.session(params.session)
.lean()
.exec()) as AssignmentRecord | null;
if (assigned) continue;
const promoted = (await params.TournamentCodeModel.findOneAndUpdate(
{
_id: candidate._id,
matchId: params.matchId,
state: 'reserved',
gameNumber: params.displayNumber,
},
{ $set: { gameNumber: params.displayNumber } },
{ new: true, session: params.session },
).exec()) as CodeRecord | null;
if (promoted) return promoted;
}
return (await params.TournamentCodeModel.findOneAndUpdate(
{
state: 'available',
region: 'kr',
mapType: 'SUMMONERS_RIFT',
teamSize: 5,
expiresAt: {
$gt: new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS),
},
},
{
$set: {
state: 'reserved',
matchId: params.matchId,
gameNumber: params.displayNumber,
reservedAt: new Date(),
},
},
{ new: true, session: params.session, sort: { expiresAt: 1 } },
).exec()) as CodeRecord | null;
}
private async findActiveAssignment(
AssignmentModel: mongoose.Model<any>,
competitionId: mongoose.Types.ObjectId,
gameSlotId: mongoose.Types.ObjectId,
): Promise<AssignmentRecord | null> {
return (await AssignmentModel.findOne({
competitionId,
gameSlotId,
state: { $in: ACTIVE_ASSIGNMENT_STATES },
})
.lean()
.exec()) as AssignmentRecord | null;
}
}
function uniqueReadyTargets(
competition: CompetitionResultSnapshot,
): CompetitionResultGameSlotProjection[] {
const byId = new Map<string, CompetitionResultGameSlotProjection>();
for (const slot of competition.projection.gameSlots) {
if (slot.status === 'ready') byId.set(slot.id, slot);
}
return [...byId.values()].sort(
(left, right) =>
left.displayNumber - right.displayNumber || left.ordinal - right.ordinal,
);
}
function objectId(value: string, label: string): mongoose.Types.ObjectId {
if (!mongoose.Types.ObjectId.isValid(value)) {
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_PROVISION_FAILED',
`${label} id is not a valid ObjectId.`,
);
}
return new mongoose.Types.ObjectId(value);
}
function deterministicObjectId(key: string): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId(
createHash('sha256').update(key).digest('hex').slice(0, 24),
);
}
async function assertCurrentRevision(params: {
CompetitionModel: mongoose.Model<any>;
competitionId: mongoose.Types.ObjectId;
expectedRevision: number;
session: mongoose.ClientSession;
}): Promise<void> {
const current = await params.CompetitionModel.updateOne(
{
_id: params.competitionId,
revision: params.expectedRevision,
},
{ $set: { revision: params.expectedRevision } },
{ session: params.session, timestamps: false },
);
if (current.matchedCount === 1) return;
throw new CompetitionAssignmentProvisionError(
'COMPETITION_ASSIGNMENT_STALE_REVISION',
'Competition changed before Tournament Code assignments were reconciled.',
);
}
function isStaleRevisionError(
error: unknown,
): error is CompetitionAssignmentProvisionError {
return (
error instanceof CompetitionAssignmentProvisionError &&
error.code === 'COMPETITION_ASSIGNMENT_STALE_REVISION'
);
}
function isRetryable(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.code === 11000 ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict' ||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'),
);
}
@@ -0,0 +1,227 @@
import mongoose from 'mongoose';
import type { RiotMatchDto } from '../riot/riot.types';
import type { MatchPuuidLookup } from './team-mapping.util';
import {
compareRiotGameChronology,
mapRiotGameToCompetitionSlot,
resolveReadyCompetitionSlot,
type CompetitionResultSnapshot,
} from './competition-result.adapter';
const competitionId = new mongoose.Types.ObjectId().toString();
const seriesId = new mongoose.Types.ObjectId().toString();
const gameSlotId = new mongoose.Types.ObjectId().toString();
const teamAId = new mongoose.Types.ObjectId().toString();
const teamBId = new mongoose.Types.ObjectId().toString();
function fixture(): {
competition: CompetitionResultSnapshot;
detail: RiotMatchDto;
lookup: MatchPuuidLookup;
} {
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `puuid-${index + 1}`,
}));
const lookup: MatchPuuidLookup = {
puuidByUserId: new Map(
users.map(({ userId, puuid }) => [userId.toString(), puuid]),
),
userIdByPuuid: new Map(users.map(({ userId, puuid }) => [puuid, userId])),
};
const competition: CompetitionResultSnapshot = {
competitionId,
revision: 4,
phase: 'running',
teams: [
{
teamId: teamAId,
members: users.slice(0, 5).map(({ userId }) => ({
userId: userId.toString(),
})),
},
{
teamId: teamBId,
members: users.slice(5).map(({ userId }) => ({
userId: userId.toString(),
})),
},
],
projection: {
phase: 'running',
series: [
{
seriesId,
status: 'ready',
entries: [
{ slot: 'A', teamId: teamAId, gameWins: 0 },
{ slot: 'B', teamId: teamBId, gameWins: 0 },
],
},
],
gameSlots: [
{
id: gameSlotId,
seriesId,
ordinal: 1,
displayNumber: 17,
status: 'ready',
},
],
games: [],
},
};
const participants = [
...users.slice(5).map(({ puuid }, index) => ({
puuid,
participantId: index + 1,
teamId: 100,
championId: index + 1,
kills: 10,
deaths: 2,
assists: 8,
win: true,
})),
...users.slice(0, 5).map(({ puuid }, index) => ({
puuid,
participantId: index + 6,
teamId: 200,
championId: index + 6,
kills: 2,
deaths: 10,
assists: 3,
win: false,
})),
];
const detail = {
metadata: {
dataVersion: '2',
matchId: 'KR_123456789',
participants: participants.map(({ puuid }) => puuid),
},
info: {
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;
return { competition, detail, lookup };
}
describe('Competition result Riot mapping', () => {
it('maps Riot sides to stable team ids using the frozen roster snapshot', () => {
const { competition, detail, lookup } = fixture();
const accepted = mapRiotGameToCompetitionSlot({
competition,
target: competition.projection.gameSlots[0],
detail,
lookup,
});
expect(accepted).toMatchObject({
seriesId,
gameSlotId,
ordinal: 1,
displayNumber: 17,
mapping: {
mappingVersion: 1,
blueTeamId: teamBId,
redTeamId: teamAId,
winnerTeamId: teamBId,
algorithmVersion: 'roster-overlap-v1',
confidence: 1,
diagnostics: {
trustedOverlap: 10,
normalOverlap: 0,
reversedOverlap: 10,
},
},
evidence: {
type: 'riot',
riotMatchId: 'KR_123456789',
normalizedSnapshot: {
startedAt: '2026-07-12T10:00:00.000Z',
durationSeconds: 1800,
},
},
});
expect(accepted?.evidence.payloadHash).toMatch(/^[a-f0-9]{64}$/);
expect(accepted?.normalizedParticipants).toHaveLength(10);
expect(accepted?.normalizedParticipants[0]).toMatchObject({
userId: expect.any(String),
teamId: teamBId,
side: 'blue',
summonerName: '',
tagLine: '',
});
});
it('retains unknown Riot participants as normalized evidence with a null user id', () => {
const { competition, detail, lookup } = fixture();
detail.info.participants[0].puuid = 'unknown-substitute';
const accepted = mapRiotGameToCompetitionSlot({
competition,
target: competition.projection.gameSlots[0],
detail,
lookup,
});
expect(accepted?.mapping.confidence).toBe(0.9);
expect(accepted?.normalizedParticipants).toHaveLength(10);
expect(accepted?.normalizedParticipants[0]).toMatchObject({
userId: null,
teamId: teamBId,
side: 'blue',
});
expect(accepted?.mapping.participantAssignments).toHaveLength(9);
});
it('resolves a manual result from ready stable GameSlots, not display codes', () => {
const { competition, detail, lookup } = fixture();
const accepted = resolveReadyCompetitionSlot({
competition,
detail,
lookup,
});
expect(accepted).toMatchObject({ seriesId, gameSlotId, displayNumber: 17 });
});
it('rejects an untrusted roster overlap instead of guessing a team', () => {
const { competition, detail, lookup } = fixture();
detail.info.participants.forEach((participant, index) => {
participant.puuid = `unknown-${index}`;
});
expect(
mapRiotGameToCompetitionSlot({
competition,
target: competition.projection.gameSlots[0],
detail,
lookup,
}),
).toBeNull();
});
it('orders collected Riot games by occurrence before first-to projection', () => {
const { detail } = fixture();
const later = {
...detail,
metadata: { ...detail.metadata, matchId: 'KR_LATER' },
info: { ...detail.info, gameCreation: detail.info.gameCreation + 60_000 },
};
expect([later, detail].sort(compareRiotGameChronology).map((game) => game.metadata.matchId)).toEqual([
'KR_123456789',
'KR_LATER',
]);
});
});
@@ -0,0 +1,361 @@
import { createHash } from 'node:crypto';
import type { RiotMatchDto } from '../riot/riot.types';
import type { MatchPuuidLookup } from './team-mapping.util';
const RIOT_BLUE_TEAM_ID = 100;
const RIOT_RED_TEAM_ID = 200;
const MINIMUM_TRUSTED_OVERLAP = 6;
const MAPPING_ALGORITHM_VERSION = 'roster-overlap-v1';
type CompetitionPhase = 'ready' | 'running' | 'completed' | 'cancelled';
export interface CompetitionResultTeamSnapshot {
teamId: string;
members: Array<{ userId: string }>;
}
export interface CompetitionResultSeriesProjection {
seriesId: string;
status: 'inactive' | 'waiting' | 'ready' | 'in-progress' | 'completed';
entries: Array<{
slot: 'A' | 'B';
teamId: string | null;
gameWins: number;
}>;
}
export interface CompetitionResultGameSlotProjection {
id: string;
seriesId: string;
ordinal: number;
displayNumber: number;
status: 'inactive' | 'waiting' | 'ready' | 'completed' | 'voided';
}
export interface CompetitionResultSnapshot {
competitionId: string;
revision: number;
phase: CompetitionPhase;
teams: CompetitionResultTeamSnapshot[];
projection: {
phase: Exclude<CompetitionPhase, 'cancelled'>;
series: CompetitionResultSeriesProjection[];
gameSlots: CompetitionResultGameSlotProjection[];
games: Array<{
evidence?: { type?: string; riotMatchId?: string };
}>;
};
}
export interface MappedCompetitionRiotGame {
gameId: string;
seriesId: string;
gameSlotId: string;
ordinal: number;
displayNumber: number;
occurredAt: Date;
startedAt: Date;
durationSeconds: number;
normalizedParticipants: Array<Record<string, unknown>>;
evidence: {
type: 'riot';
riotMatchId: string;
payloadHash: string;
normalizedSnapshot: {
startedAt: string;
durationSeconds: number;
participantCount: number;
};
};
mapping: {
mappingVersion: 1;
blueTeamId: string;
redTeamId: string;
winnerTeamId: string;
algorithmVersion: typeof MAPPING_ALGORITHM_VERSION;
confidence: number;
diagnostics: {
trustedOverlap: number;
normalOverlap: number;
reversedOverlap: number;
};
participantAssignments: Array<{
userId: string;
teamId: string;
side: 'blue' | 'red';
}>;
snapshot: {
slotATeamId: string;
slotBTeamId: string;
slotAPuuids: string[];
slotBPuuids: string[];
bluePuuids: string[];
redPuuids: string[];
};
};
}
export function compareRiotGameChronology(
left: RiotMatchDto,
right: RiotMatchDto,
): number {
return (
left.info.gameCreation - right.info.gameCreation ||
left.metadata.matchId.localeCompare(right.metadata.matchId)
);
}
export function mapRiotGameToCompetitionSlot(params: {
competition: CompetitionResultSnapshot;
target: CompetitionResultGameSlotProjection;
detail: RiotMatchDto;
lookup: MatchPuuidLookup;
}): MappedCompetitionRiotGame | null {
const { competition, target, detail, lookup } = params;
if (target.status !== 'ready') return null;
const series = competition.projection.series.find(
(candidate) => candidate.seriesId === target.seriesId,
);
if (
!series ||
(series.status !== 'ready' && series.status !== 'in-progress')
) {
return null;
}
const slotATeamId = series.entries.find(({ slot }) => slot === 'A')?.teamId;
const slotBTeamId = series.entries.find(({ slot }) => slot === 'B')?.teamId;
if (!slotATeamId || !slotBTeamId || slotATeamId === slotBTeamId) return null;
const slotATeam = competition.teams.find(
({ teamId }) => teamId === slotATeamId,
);
const slotBTeam = competition.teams.find(
({ teamId }) => teamId === slotBTeamId,
);
if (!slotATeam || !slotBTeam) return null;
const slotAPuuids = rosterPuuids(slotATeam, lookup);
const slotBPuuids = rosterPuuids(slotBTeam, lookup);
const bluePuuids = participantPuuids(detail, RIOT_BLUE_TEAM_ID);
const redPuuids = participantPuuids(detail, RIOT_RED_TEAM_ID);
const normalOverlap =
countOverlap(bluePuuids, slotAPuuids) +
countOverlap(redPuuids, slotBPuuids);
const reversedOverlap =
countOverlap(bluePuuids, slotBPuuids) +
countOverlap(redPuuids, slotAPuuids);
const trustedOverlap = Math.max(normalOverlap, reversedOverlap);
if (
trustedOverlap < MINIMUM_TRUSTED_OVERLAP ||
normalOverlap === reversedOverlap
) {
return null;
}
const blueTeamId =
normalOverlap > reversedOverlap ? slotATeamId : slotBTeamId;
const redTeamId = normalOverlap > reversedOverlap ? slotBTeamId : slotATeamId;
const winningRiotTeam = detail.info.teams.find(({ win }) => win);
const winnerTeamId =
winningRiotTeam?.teamId === RIOT_BLUE_TEAM_ID
? blueTeamId
: winningRiotTeam?.teamId === RIOT_RED_TEAM_ID
? redTeamId
: undefined;
if (!winnerTeamId) return null;
const startedAt = new Date(detail.info.gameCreation);
const durationSeconds = detail.info.gameDuration;
const occurredAt = new Date(
detail.info.gameEndTimestamp ??
detail.info.gameCreation + durationSeconds * 1_000,
);
const normalizedParticipants = detail.info.participants.flatMap(
(participant) => {
const userId = lookup.userIdByPuuid.get(participant.puuid);
const teamId =
participant.teamId === RIOT_BLUE_TEAM_ID
? blueTeamId
: participant.teamId === RIOT_RED_TEAM_ID
? redTeamId
: undefined;
const side =
participant.teamId === RIOT_BLUE_TEAM_ID
? 'blue'
: participant.teamId === RIOT_RED_TEAM_ID
? 'red'
: undefined;
if (!teamId || !side) return [];
return [
{
userId: userId?.toString() ?? null,
teamId,
side,
summonerName:
participant.riotIdGameName ?? participant.summonerName ?? '',
tagLine: participant.riotIdTagLine ?? '',
championId: participant.championId,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
},
];
},
);
return {
gameId: deterministicGameId(
competition.competitionId,
detail.metadata.matchId,
),
seriesId: target.seriesId,
gameSlotId: target.id,
ordinal: target.ordinal,
displayNumber: target.displayNumber,
occurredAt,
startedAt,
durationSeconds,
normalizedParticipants,
evidence: {
type: 'riot',
riotMatchId: detail.metadata.matchId,
payloadHash: sha256(detail),
normalizedSnapshot: {
startedAt: startedAt.toISOString(),
durationSeconds,
participantCount: normalizedParticipants.length,
},
},
mapping: {
mappingVersion: 1,
blueTeamId,
redTeamId,
winnerTeamId,
algorithmVersion: MAPPING_ALGORITHM_VERSION,
confidence:
trustedOverlap /
Math.max(slotAPuuids.length + slotBPuuids.length, 1),
diagnostics: { trustedOverlap, normalOverlap, reversedOverlap },
participantAssignments: normalizedParticipants.flatMap((participant) =>
typeof participant.userId === 'string'
? [
{
userId: participant.userId,
teamId: String(participant.teamId),
side: participant.side as 'blue' | 'red',
},
]
: [],
),
snapshot: {
slotATeamId,
slotBTeamId,
slotAPuuids,
slotBPuuids,
bluePuuids,
redPuuids,
},
},
};
}
export function resolveReadyCompetitionSlot(params: {
competition: CompetitionResultSnapshot;
detail: RiotMatchDto;
lookup: MatchPuuidLookup;
}): MappedCompetitionRiotGame | null {
const firstReadySlotBySeries = new Map<
string,
CompetitionResultGameSlotProjection
>();
for (const slot of [...params.competition.projection.gameSlots].sort(
(left, right) =>
left.displayNumber - right.displayNumber || left.ordinal - right.ordinal,
)) {
if (slot.status !== 'ready' || firstReadySlotBySeries.has(slot.seriesId)) {
continue;
}
firstReadySlotBySeries.set(slot.seriesId, slot);
}
const candidates = [...firstReadySlotBySeries.values()]
.map((target) => mapRiotGameToCompetitionSlot({ ...params, target }))
.filter((candidate): candidate is MappedCompetitionRiotGame =>
Boolean(candidate),
)
.sort(
(left, right) =>
right.mapping.diagnostics.trustedOverlap -
left.mapping.diagnostics.trustedOverlap ||
left.displayNumber - right.displayNumber,
);
if (candidates.length === 0) return null;
if (
candidates.length > 1 &&
candidates[0].mapping.diagnostics.trustedOverlap ===
candidates[1].mapping.diagnostics.trustedOverlap
) {
return null;
}
return candidates[0];
}
export function hasAcceptedRiotMatch(
competition: CompetitionResultSnapshot,
riotMatchId: string,
): boolean {
return competition.projection.games.some(
({ evidence }) =>
evidence?.type === 'riot' && evidence.riotMatchId === riotMatchId,
);
}
function rosterPuuids(
team: CompetitionResultTeamSnapshot,
lookup: MatchPuuidLookup,
): string[] {
return team.members.flatMap(({ userId }) => {
const puuid = lookup.puuidByUserId.get(userId);
return puuid ? [puuid] : [];
});
}
function participantPuuids(detail: RiotMatchDto, riotTeamId: number): string[] {
return detail.info.participants
.filter(({ teamId }) => teamId === riotTeamId)
.map(({ puuid }) => puuid);
}
function countOverlap(left: string[], right: string[]): number {
const rightSet = new Set(right);
return left.filter((item) => rightSet.has(item)).length;
}
function deterministicGameId(
competitionId: string,
riotMatchId: string,
): string {
return sha256([competitionId, 'riot-game', riotMatchId]).slice(0, 24);
}
function sha256(value: unknown): string {
return createHash('sha256').update(canonicalJson(value)).digest('hex');
}
function canonicalJson(value: unknown): string {
return JSON.stringify(canonicalize(value));
}
function canonicalize(value: unknown): unknown {
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(canonicalize);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value as Record<string, unknown>)
.filter(([, child]) => child !== undefined)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, child]) => [key, canonicalize(child)]),
);
}
return value;
}
@@ -1,18 +1,9 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types'; import { collectCaptainAndLimitedTeamMemberUserIds } from './team-mapping.util';
import {
collectCaptainAndLimitedTeamMemberUserIds,
computeGameResult,
type MatchPuuidLookup,
} from './team-mapping.util';
function makeMatch(): { describe('collectCaptainAndLimitedTeamMemberUserIds', () => {
match: MatchDocument; it('keeps captains and caps extra members per team', () => {
lookup: MatchPuuidLookup;
blueUserIds: mongoose.Types.ObjectId[];
redUserIds: mongoose.Types.ObjectId[];
} {
const blueUserIds = Array.from( const blueUserIds = Array.from(
{ length: 5 }, { length: 5 },
() => new mongoose.Types.ObjectId(), () => new mongoose.Types.ObjectId(),
@@ -21,161 +12,22 @@ function makeMatch(): {
{ length: 5 }, { length: 5 },
() => new mongoose.Types.ObjectId(), () => new mongoose.Types.ObjectId(),
); );
const puuidByUserId = new Map<string, string>();
const userIdByPuuid = new Map<string, mongoose.Types.ObjectId>();
for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) {
const puuid = `puuid-${index}`;
puuidByUserId.set(userId.toString(), puuid);
userIdByPuuid.set(puuid, userId);
}
const match = { const match = {
teams: [ teams: [
{ {
teamIndex: 1, teamIndex: 1,
name: '1팀', captainUserId: blueUserIds[0],
members: blueUserIds.map((userId) => ({ members: blueUserIds.map((userId) => ({ userId })),
userId,
assignedPosition: 'MID',
})),
}, },
{ {
teamIndex: 2, teamIndex: 2,
name: '2팀', captainUserId: redUserIds[0],
members: redUserIds.map((userId) => ({ members: redUserIds.map((userId) => ({ userId })),
userId,
assignedPosition: 'MID',
})),
}, },
], ],
participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({ participants: [],
userId,
puuid: `puuid-${index}`,
preferredPositions: [],
joinedAt: new Date(),
})),
} as unknown as MatchDocument; } as unknown as MatchDocument;
return {
match,
lookup: { puuidByUserId, userIdByPuuid },
blueUserIds,
redUserIds,
};
}
function makeRiotMatch(params: {
team100Puuids: string[];
team200Puuids: string[];
winningTeamId: 100 | 200;
}): RiotMatchDto {
const participants = [
...params.team100Puuids.map((puuid, index) => ({
puuid,
participantId: index + 1,
teamId: 100,
championId: 10 + index,
kills: index,
deaths: 1,
assists: 2,
win: params.winningTeamId === 100,
})),
...params.team200Puuids.map((puuid, index) => ({
puuid,
participantId: index + 6,
teamId: 200,
championId: 20 + index,
kills: index,
deaths: 2,
assists: 3,
win: params.winningTeamId === 200,
})),
];
return {
metadata: {
dataVersion: '2',
matchId: 'KR_1',
participants: participants.map((participant) => participant.puuid),
},
info: {
gameCreation: 1,
gameDuration: 1800,
participants,
teams: [
{ teamId: 100, win: params.winningTeamId === 100 },
{ teamId: 200, win: params.winningTeamId === 200 },
],
},
} as unknown as RiotMatchDto;
}
describe('computeGameResult', () => {
it('maps Riot teams to local blue/red by overlap', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 1 });
expect(result).toMatchObject({
gameNumber: 1,
riotMatchId: 'KR_1',
winnerSide: 'blue',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
gameDuration: 1800,
});
expect(result?.participants).toHaveLength(10);
expect(result?.participants[0]).toMatchObject({
teamIndex: 1,
side: 'blue',
});
});
it('handles reversed Riot side assignment', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'],
team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 2 });
expect(result).toMatchObject({
blueTeamIndex: 2,
redTeamIndex: 1,
winnerSide: 'blue',
winnerTeamIndex: 2,
});
});
it('rejects matches with too little overlap', () => {
const { match, lookup } = makeMatch();
const detail = makeRiotMatch({
team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'],
team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'],
winningTeamId: 100,
});
const result = computeGameResult({ match, lookup, detail, gameNumber: 3 });
expect(result).toBeNull();
});
});
describe('collectCaptainAndLimitedTeamMemberUserIds', () => {
it('keeps captains and caps extra members per team', () => {
const { blueUserIds, match, redUserIds } = makeMatch();
match.teams[0].captainUserId = blueUserIds[0];
match.teams[1].captainUserId = redUserIds[0];
const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map( const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map(
(userId) => userId.toString(), (userId) => userId.toString(),
); );
@@ -1,14 +1,5 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { import type { MatchDocument } from '../global/database/schema';
MatchDocument,
MatchGameResult,
TeamSide,
} from '../global/database/schema';
import type { RiotMatchDto } from '../riot/riot.types';
const RIOT_BLUE_TEAM_ID = 100;
const RIOT_RED_TEAM_ID = 200;
const MINIMUM_TRUSTED_OVERLAP = 6;
export interface MatchPuuidLookup { export interface MatchPuuidLookup {
puuidByUserId: Map<string, string>; puuidByUserId: Map<string, string>;
@@ -61,113 +52,3 @@ export function collectMatchUserIds(
} }
return [...ids.values()]; return [...ids.values()];
} }
export function collectTeamPuuids(
match: MatchDocument,
teamIndex: number,
lookup: MatchPuuidLookup,
): string[] {
const team = match.teams.find((item) => item.teamIndex === teamIndex);
if (!team) return [];
const userIds = [
...(team.captainUserId ? [team.captainUserId] : []),
...team.members.map((member) => member.userId),
];
return userIds
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
.filter((puuid): puuid is string => Boolean(puuid));
}
export function computeGameResult(params: {
match: MatchDocument;
detail: RiotMatchDto;
gameNumber: number;
lookup: MatchPuuidLookup;
teamAIndex?: number;
teamBIndex?: number;
}): MatchGameResult | null {
const {
match,
detail,
gameNumber,
lookup,
teamAIndex = 1,
teamBIndex = 2,
} = params;
const teamAPuuids = collectTeamPuuids(match, teamAIndex, lookup);
const teamBPuuids = collectTeamPuuids(match, teamBIndex, lookup);
const team100Puuids = detail.info.participants
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
.map((participant) => participant.puuid);
const team200Puuids = detail.info.participants
.filter((participant) => participant.teamId === RIOT_RED_TEAM_ID)
.map((participant) => participant.puuid);
const normalOverlap =
countOverlap(team100Puuids, teamAPuuids) +
countOverlap(team200Puuids, teamBPuuids);
const reversedOverlap =
countOverlap(team100Puuids, teamBPuuids) +
countOverlap(team200Puuids, teamAPuuids);
const blueTeamIndex =
normalOverlap >= reversedOverlap ? teamAIndex : teamBIndex;
const redTeamIndex =
normalOverlap >= reversedOverlap ? teamBIndex : teamAIndex;
const teamIndexByRiotTeamId: Record<number, number> = {
[RIOT_BLUE_TEAM_ID]: blueTeamIndex,
[RIOT_RED_TEAM_ID]: redTeamIndex,
};
const sideByRiotTeamId: Record<number, TeamSide> = {
[RIOT_BLUE_TEAM_ID]: 'blue',
[RIOT_RED_TEAM_ID]: 'red',
};
if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) {
return null;
}
const winningTeam = detail.info.teams.find((team) => team.win);
if (!winningTeam) return null;
const winnerSide = sideByRiotTeamId[winningTeam.teamId];
if (!winnerSide) return null;
const winnerTeamIndex = teamIndexByRiotTeamId[winningTeam.teamId];
if (!winnerTeamIndex) return null;
const participants = detail.info.participants
.map((participant) => {
const userId = lookup.userIdByPuuid.get(participant.puuid);
const side = sideByRiotTeamId[participant.teamId];
const teamIndex = teamIndexByRiotTeamId[participant.teamId];
if (!userId || !side || !teamIndex) return null;
return {
userId,
teamIndex,
side,
championId: participant.championId,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
};
})
.filter((participant): participant is NonNullable<typeof participant> =>
Boolean(participant),
);
return {
gameNumber,
riotMatchId: detail.metadata.matchId,
blueTeamIndex,
redTeamIndex,
winnerTeamIndex,
winnerSide,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
};
}
export function countOverlap(left: string[], right: string[]): number {
const rightSet = new Set(right);
return left.filter((item) => rightSet.has(item)).length;
}
@@ -0,0 +1,294 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
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 cutover', () => {
it('accepts a manually collected Riot game through Competition without mutating legacy result state', async () => {
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 earlierGameSlotId = new mongoose.Types.ObjectId();
const gameSlotId = new mongoose.Types.ObjectId();
const tournamentCodeId = 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: `cutover-puuid-${index + 1}`,
}));
const legacyResult = {
winnerTeamIndex: 2,
riotMatchIds: ['legacy'],
games: [],
seriesResults: [],
};
const legacyBracket = { marker: 'must-not-change' };
const match = {
_id: matchId,
communityId,
status: 'team-built',
gameCount: 1,
gameMode: 'pair',
teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'),
tournamentCodeIds: [tournamentCodeId],
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 })),
},
],
result: legacyResult,
doubleElimination: legacyBracket,
save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & { save: jest.Mock };
const readyCompetition = {
_id: competitionId,
revision: 0,
phase: 'ready',
teams: [
{
teamId: teamAId,
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
},
{
teamId: teamBId,
members: users.slice(5).map(({ userId }) => ({ userId })),
},
],
projection: {
phase: 'ready',
series: [
{
seriesId: seriesId.toString(),
status: 'ready',
entries: [
{ slot: 'A', teamId: teamAId.toString(), gameWins: 0 },
{ slot: 'B', teamId: teamBId.toString(), gameWins: 0 },
],
},
],
gameSlots: [
{
id: earlierGameSlotId.toString(),
seriesId: seriesId.toString(),
ordinal: 1,
displayNumber: 16,
status: 'ready',
},
{
id: gameSlotId.toString(),
seriesId: seriesId.toString(),
ordinal: 2,
displayNumber: 17,
status: 'ready',
},
],
games: [],
},
};
const completedCompetition = {
...readyCompetition,
revision: 1,
phase: 'completed',
projection: {
...readyCompetition.projection,
phase: 'completed',
games: [
{
evidence: { type: 'riot', riotMatchId: 'KR_CUTOVER_1' },
},
],
},
};
const detail = riotDetail(users.map(({ puuid }) => puuid));
const connectionService = {
getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') {
return Promise.resolve({
findById: jest.fn().mockResolvedValue(match),
});
}
if (name === 'community') {
return Promise.resolve({
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }),
}),
}),
}),
});
}
if (name === 'riotMatch') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(null),
}),
updateOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
}),
});
}
if (name === 'competition') {
return Promise.resolve({
findById: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(readyCompetition),
}),
}),
});
}
if (name === 'tournamentCode') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
_id: tournamentCodeId,
code: 'CUTOVER-CODE',
state: 'reserved',
gameNumber: 17,
}),
}),
});
}
if (name === 'tournamentCodeAssignment') {
return Promise.resolve({
findOne: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({
competitionId,
seriesId,
gameSlotId,
tournamentCodeId,
state: 'reserved',
}),
}),
}),
updateOne: jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue(undefined),
}),
});
}
throw new Error(`Unexpected model ${name}`);
}),
};
const commandService = {
acceptGame: jest.fn().mockResolvedValue({
competition: completedCompetition,
commandId: 'cmpcmd-result',
revision: 1,
replayed: false,
}),
};
const matchStatsService = {
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
};
const service = new TournamentResultService(
connectionService as never,
{ getMatch: jest.fn().mockResolvedValue(detail) } as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
matchStatsService as never,
{
runWithLock: jest.fn(),
runWithRenewedLock: jest.fn(),
} as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
{
provisionReadyAssignments: jest.fn().mockResolvedValue({
requested: 1,
reserved: 0,
existing: 1,
unavailable: 0,
}),
} as never,
);
const response = await service.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: ' KR_CUTOVER_1 ',
});
expect(response).toMatchObject({
scanned: 1,
matched: 1,
skipped: 0,
riotMatchIds: ['KR_CUTOVER_1'],
gameNumbers: [17],
});
expect(commandService.acceptGame).toHaveBeenCalledWith(
expect.objectContaining({
competitionId,
expectedRevision: 0,
idempotencyKey: 'riot-result:KR_CUTOVER_1',
seriesId,
gameSlotId,
ordinal: 2,
mapping: expect.objectContaining({
blueTeamId: teamAId.toString(),
redTeamId: teamBId.toString(),
winnerTeamId: teamAId.toString(),
}),
startedAt: new Date('2026-07-12T10:00:00.000Z'),
durationSeconds: 1800,
participants: expect.any(Array),
tournamentCode: {
tournamentCodeId,
riotMatchId: 'KR_CUTOVER_1',
},
}),
);
expect(match.result).toBe(legacyResult);
expect(match.doubleElimination).toBe(legacyBracket);
expect(match.status).toBe('finished');
expect(matchStatsService.buildAndUpsert).toHaveBeenCalledWith(matchId, {
sourceRevision: 1,
});
});
});
function riotDetail(puuids: 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_CUTOVER_1',
participants: puuids,
},
info: {
tournamentCode: 'CUTOVER-CODE',
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;
}
@@ -1,14 +1,21 @@
import { forwardRef, Module } from '@nestjs/common'; import { forwardRef, Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module'; import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { CompetitionModule } from '../competition/competition.module';
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
import { RiotModule } from '../riot/riot.module'; import { RiotModule } from '../riot/riot.module';
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
import { TournamentResultController } from './tournament-result.controller'; import { TournamentResultController } from './tournament-result.controller';
import { TournamentResultService } from './tournament-result.service'; import { TournamentResultService } from './tournament-result.service';
@Module({ @Module({
imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)], imports: [
RiotModule,
CommunityStatsModule,
CompetitionModule,
forwardRef(() => RiotJobQueueModule),
],
controllers: [TournamentResultController], controllers: [TournamentResultController],
providers: [TournamentResultService], providers: [CompetitionAssignmentProvisioner, TournamentResultService],
exports: [TournamentResultService], exports: [TournamentResultService],
}) })
export class TournamentResultModule {} export class TournamentResultModule {}
@@ -1,303 +1,151 @@
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import type { MatchDocument } from '../global/database/schema'; import type { MatchDocument } from '../global/database/schema';
import { DistributedLockService } from '../global/redis/distributed-lock.service';
import type { RiotMatchDto } from '../riot/riot.types'; import type { RiotMatchDto } from '../riot/riot.types';
import { TournamentResultService } from './tournament-result.service'; import { TournamentResultService } from './tournament-result.service';
import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util';
type TournamentResultServiceInternals = TournamentResultService & { describe('TournamentResultService Competition polling', () => {
nextPollDelayMs(elapsedMs: number): number | null; it('promotes a reserved legacy code to a stable GameSlot assignment and accepts through Competition', async () => {
resolveRequiredGameSlots(match: MatchDocument): number; const harness = pollHarness({
resolveSeriesRefForGameNumber( storedCode: 'AbC-12345',
match: MatchDocument, riotTournamentCode: 'AbC-12345',
gameNumber: number,
): { teamAIndex: number; teamBIndex: number };
buildSeriesResults(
games: NonNullable<MatchDocument['result']>['games'],
): NonNullable<MatchDocument['result']>['seriesResults'];
advanceDoubleEliminationIfNeeded(
match: MatchDocument,
gameResult: NonNullable<MatchDocument['result']>['games'][number],
completedBy: 'riot-result' | 'walkover',
): string | undefined;
};
function createService() {
const distributedLockService = createDistributedLockService();
return new TournamentResultService(
{} as never,
{} as never,
{} as never,
{} as never,
{} as never,
distributedLockService as never,
) as unknown as TournamentResultServiceInternals;
}
function createDistributedLockService() {
return {
runWithLock: jest.fn().mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
runWithRenewedLock: jest
.fn()
.mockImplementation(async (options, operation) =>
operation({
lockKey: options.lockKey,
lockOwnershipToken: 'lock-owner',
lockExpirationDurationMilliseconds:
options.lockExpirationDurationMilliseconds,
}),
),
} as unknown as jest.Mocked<DistributedLockService>;
}
interface MatchOverrides {
gameCount?: number;
gameMode?: 'pair' | 'bracket' | 'round-robin' | 'double-elimination';
roundRobinMaxRounds?: number;
participants?: Array<{ excluded?: boolean }>;
teams?: Array<{ teamIndex: number }>;
doubleElimination?: MatchDocument['doubleElimination'];
result?: MatchDocument['result'];
gameSchedule?: Array<{
gameNumber: number;
roundNumber?: number;
teamAIndex: number;
teamBIndex: number;
}>;
}
function createMatch(overrides: MatchOverrides): MatchDocument {
return {
gameCount: 1,
gameMode: 'pair',
participants: [],
teams: [],
gameSchedule: [],
result: undefined,
...overrides,
} as unknown as MatchDocument;
}
describe('TournamentResultService round-robin scheduling', () => {
it('calculates required slots for round-robin polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
teams: Array.from({ length: 6 }, (_, index) => ({
teamIndex: index + 1,
})),
}); });
expect(service.resolveRequiredGameSlots(match)).toBe(15); await harness.service.processPollJob({
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
}); });
it('calculates limited round-robin slots for polling', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameCount: 1,
roundRobinMaxRounds: 3,
teams: Array.from({ length: 8 }, (_, index) => ({
teamIndex: index + 1,
})),
});
expect(service.resolveRequiredGameSlots(match)).toBe(12);
});
it('uses persisted round-robin schedule when mapping a game number', () => {
const service = createService();
const match = createMatch({
gameMode: 'round-robin',
gameSchedule: [
{ gameNumber: 1, teamAIndex: 3, teamBIndex: 6 },
{ gameNumber: 2, teamAIndex: 1, teamBIndex: 5 },
],
});
expect(service.resolveSeriesRefForGameNumber(match, 2)).toEqual({
teamAIndex: 1,
teamBIndex: 5,
});
});
it('keeps pair game number mapping unchanged', () => {
const service = createService();
const match = createMatch({ gameCount: 3 });
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
teamAIndex: 3,
teamBIndex: 4,
});
});
it('keeps double-elimination rematches separated by bracket match id', () => {
const service = createService();
expect( expect(
service.buildSeriesResults([ harness.assignmentProvisioner.provisionReadyAssignments,
{ ).toHaveBeenCalledWith({
gameNumber: 1, matchId: harness.match._id,
bracketMatchId: 'WB_FINAL', competition: expect.objectContaining({
riotMatchId: 'KR_1', competitionId: harness.competitionId.toString(),
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1,
gameDuration: 1800,
participants: [],
},
{
gameNumber: 2,
bracketMatchId: 'GF',
riotMatchId: 'KR_2',
blueTeamIndex: 1,
redTeamIndex: 2,
winnerTeamIndex: 2,
winnerSide: 'red',
gameCreation: 2,
gameDuration: 1800,
participants: [],
},
]),
).toEqual([
{
bracketMatchId: 'GF',
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 0,
teamBWins: 1,
winnerTeamIndex: 2,
},
{
bracketMatchId: 'WB_FINAL',
teamAIndex: 1,
teamBIndex: 2,
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
},
]);
});
it('maps double-elimination series game numbers to bracket matches', () => {
const service = createService();
const match = createMatch({
gameMode: 'double-elimination',
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
}), }),
}); });
expect(harness.assignmentModel.updateOne).toHaveBeenCalledWith(
expect(service.resolveRequiredGameSlots(match)).toBe(12); expect.objectContaining({
expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ competitionId: harness.competitionId,
teamAIndex: 1, tournamentCodeId: harness.codeId,
teamBIndex: 4,
});
expect(service.resolveSeriesRefForGameNumber(match, 4)).toEqual({
teamAIndex: 2,
teamBIndex: 3,
});
});
it('advances double-elimination only after a team reaches required series wins', () => {
const service = createService();
const game = {
gameNumber: 1,
bracketMatchId: 'WB_R1_M1',
riotMatchId: 'KR_1',
blueTeamIndex: 1,
redTeamIndex: 4,
winnerTeamIndex: 1,
winnerSide: 'blue',
gameCreation: 1,
gameDuration: 1800,
participants: [],
} as NonNullable<MatchDocument['result']>['games'][number];
const match = createMatch({
gameMode: 'double-elimination',
doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], {
resetFinalEnabled: true,
}), }),
result: { expect.objectContaining({
riotMatchIds: ['KR_1'], $setOnInsert: expect.objectContaining({
games: [game], seriesId: harness.seriesId,
seriesResults: [ gameSlotId: harness.gameSlotId,
{ state: 'reserved',
bracketMatchId: 'WB_R1_M1', }),
teamAIndex: 1, }),
teamBIndex: 4, { upsert: true },
teamAWins: 1,
teamBWins: 0,
winnerTeamIndex: 1,
},
],
},
} as MatchOverrides);
expect(
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'),
).toBeUndefined();
const firstGameBracketMatch = match.doubleElimination?.bracketMatches.find(
(entry) => entry.bracketMatchId === 'WB_R1_M1',
); );
expect(firstGameBracketMatch).toMatchObject({ state: 'ready' }); expect(harness.commandService.acceptGame).toHaveBeenCalledWith(
expect(firstGameBracketMatch?.winnerTeamIndex).toBeUndefined(); expect.objectContaining({
competitionId: harness.competitionId,
match.result!.seriesResults = [ seriesId: harness.seriesId,
{ gameSlotId: harness.gameSlotId,
bracketMatchId: 'WB_R1_M1', tournamentCode: {
teamAIndex: 1, tournamentCodeId: harness.codeId,
teamBIndex: 4, riotMatchId: 'KR_POLL_1',
teamAWins: 2,
teamBWins: 0,
winnerTeamIndex: 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({
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({
matchId: harness.match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect( expect(
service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'), harness.assignmentProvisioner.provisionReadyAssignments,
).toBe('WB_R1_M1'); ).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( expect(
match.doubleElimination?.bracketMatches.find( harness.riotJobQueueService.enqueueTournamentResultPoll,
(entry) => entry.bracketMatchId === 'WB_R1_M1', ).toHaveBeenCalledTimes(1);
),
).toMatchObject({ state: 'completed', winnerTeamIndex: 1 });
expect(
match.doubleElimination?.bracketMatches.find(
(entry) => entry.bracketMatchId === 'WB_FINAL',
),
).toMatchObject({ teamAIndex: 1 });
}); });
}); });
describe('TournamentResultService tournament code polling', () => { function pollHarness(params: {
function queryResult<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}
function sortedQueryResult<T>(value: T) {
return {
sort: jest.fn().mockReturnValue(queryResult(value)),
};
}
function createPollFixture(params: {
storedCode: string; storedCode: string;
riotTournamentCode: string; riotTournamentCode: string;
}) { }) {
const communityId = new mongoose.Types.ObjectId(); const communityId = new mongoose.Types.ObjectId();
const matchId = 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 codeId = new mongoose.Types.ObjectId();
const teamAId = new mongoose.Types.ObjectId();
const teamBId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({ const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(), userId: new mongoose.Types.ObjectId(),
puuid: `poll-puuid-${index + 1}`, puuid: `poll-puuid-${index + 1}`,
@@ -306,107 +154,149 @@ describe('TournamentResultService tournament code polling', () => {
_id: matchId, _id: matchId,
communityId, communityId,
status: 'team-built', status: 'team-built',
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'), teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'),
gameCount: 1, gameCount: 1,
gameMode: 'pair', gameMode: 'pair',
tournamentCodeIds: [codeId], tournamentCodeIds: [codeId],
gameSchedule: [],
resultPollState: { resultPollState: {
startedAt: new Date(), startedAt: new Date(),
matchedCount: 0, matchedCount: 0,
expandedToAllPuuids: true, expandedToAllPuuids: true,
state: 'polling', state: 'polling',
}, },
participants: users.map((user) => ({ participants: users.map(({ userId, puuid }) => ({
userId: user.userId, userId,
puuid: user.puuid, puuid,
excluded: false, excluded: false,
})), })),
teams: [ teams: [
{ {
teamIndex: 1, teamIndex: 1,
members: users.slice(0, 5).map((user) => ({ userId: user.userId })), name: 'Team A',
members: users.slice(0, 5).map(({ userId }) => ({ userId })),
}, },
{ {
teamIndex: 2, teamIndex: 2,
members: users.slice(5).map((user) => ({ userId: user.userId })), name: 'Team B',
members: users.slice(5).map(({ userId }) => ({ userId })),
}, },
], ],
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
} as unknown as MatchDocument & { } as unknown as MatchDocument & { save: jest.Mock };
save: jest.Mock;
result?: MatchDocument['result'];
};
const code = { const code = {
_id: codeId, _id: codeId,
code: params.storedCode, code: params.storedCode,
state: 'reserved', state: 'reserved',
gameNumber: 1, gameNumber: 1,
riotMatchId: undefined, reservedAt: new Date('2026-07-12T09:00:00.000Z'),
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
const detail = { const readyCompetition = competitionDocument({
metadata: { competitionId,
matchId: 'KR_9876543210', seriesId,
participants: users.map((user) => user.puuid), gameSlotId,
}, teamAId,
info: { teamBId,
tournamentCode: params.riotTournamentCode, users,
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), completed: false,
gameEndTimestamp: Date.parse('2026-05-03T11:00:00.000Z'), });
gameDuration: 1800, const completedCompetition = competitionDocument({
participants: users.map((user, index) => ({ competitionId,
puuid: user.puuid, seriesId,
teamId: index < 5 ? 100 : 200, gameSlotId,
championId: 1, teamAId,
kills: 1, teamBId,
deaths: 1, users,
assists: 1, completed: true,
win: index < 5, });
})), const detail = riotDetail(
teams: [ users.map(({ puuid }) => puuid),
{ teamId: 100, win: true }, params.riotTournamentCode,
{ teamId: 200, win: false }, );
], const assignmentModel = {
},
} as unknown as RiotMatchDto;
const TournamentCodeModel = {
find: jest
.fn()
.mockReturnValueOnce(sortedQueryResult([code]))
.mockReturnValueOnce(sortedQueryResult([code])),
exists: jest.fn().mockResolvedValue(null),
};
const RiotMatchModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)), findOne: jest.fn().mockReturnValue(queryResult(null)),
updateOne: jest.fn().mockReturnValue(queryResult(undefined)), updateOne: jest.fn().mockReturnValue(execResult(undefined)),
};
const CommunityModel = {
findById: jest.fn().mockReturnValue({
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue(queryResult({ riotRegion: 'asia' })),
}),
}),
}; };
const connectionService = { const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => { getModel: jest.fn().mockImplementation((name: string) => {
if (name === 'match') { switch (name) {
return { findById: jest.fn().mockResolvedValue(match) }; 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}`);
} }
if (name === 'tournamentCode') return TournamentCodeModel;
if (name === 'community') return CommunityModel;
if (name === 'riotMatch') return RiotMatchModel;
throw new Error(`Unexpected model: ${name}`);
}), }),
}; };
const riotMatchService = { const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_9876543210']), getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_POLL_1']),
getMatch: jest.fn().mockResolvedValue(detail), 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 = { const riotJobQueueService = {
enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined), enqueueTournamentResultPoll: jest.fn().mockResolvedValue({
jobId: 'poll-job-1',
matchId: matchId.toString(),
priority: 'high',
attempt: 1,
expandedToAllPuuids: false,
}),
}; };
const distributedLockService = createDistributedLockService();
const service = new TournamentResultService( const service = new TournamentResultService(
connectionService as never, connectionService as never,
riotMatchService as never, riotMatchService as never,
@@ -414,249 +304,123 @@ describe('TournamentResultService tournament code polling', () => {
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
distributedLockService as never, distributedLockService as never,
{ bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never,
commandService as never,
assignmentProvisioner as never,
); );
return { service, match, code, riotMatchService }; return {
} service,
match,
code,
competitionId,
seriesId,
gameSlotId,
codeId,
assignmentModel,
commandService,
assignmentProvisioner,
riotMatchService,
riotJobQueueService,
};
}
it('matches Riot tournament codes using exact casing', async () => { function competitionDocument(params: {
const { service, match, code } = createPollFixture({ competitionId: mongoose.Types.ObjectId;
storedCode: 'AbC-12345', seriesId: mongoose.Types.ObjectId;
riotTournamentCode: 'AbC-12345', gameSlotId: mongoose.Types.ObjectId;
}); teamAId: mongoose.Types.ObjectId;
teamBId: mongoose.Types.ObjectId;
await service.processPollJob({ users: Array<{ userId: mongoose.Types.ObjectId }>;
matchId: match._id.toString(), completed: boolean;
attempt: 1, }) {
expandedToAllPuuids: true, const phase = params.completed ? 'completed' : 'ready';
}); return {
_id: params.competitionId,
expect(code.state).toBe('used'); revision: params.completed ? 1 : 0,
expect(code.riotMatchId).toBe('KR_9876543210'); phase,
expect(code.save).toHaveBeenCalled();
expect(match.result?.games).toHaveLength(1);
});
it('limits expanded polling to two team members per team', async () => {
const { service, match, riotMatchService } = createPollFixture({
storedCode: 'AbC-12345',
riotTournamentCode: 'AbC-12345',
});
await service.processPollJob({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(
riotMatchService.getMatchIdsByPuuid.mock.calls.map(([puuid]) => puuid),
).toEqual(['poll-puuid-1', 'poll-puuid-2', 'poll-puuid-6', 'poll-puuid-7']);
});
it('does not match tournament codes when casing differs', async () => {
const { service, match, code } = createPollFixture({
storedCode: 'ABC-12345',
riotTournamentCode: 'abc-12345',
});
await service.processPollJob({
matchId: match._id.toString(),
attempt: 1,
expandedToAllPuuids: true,
});
expect(code.state).toBe('reserved');
expect(code.riotMatchId).toBeUndefined();
expect(code.save).not.toHaveBeenCalled();
expect(match.result?.games).toBeUndefined();
});
});
describe('TournamentResultService polling cadence', () => {
it('polls every two minutes during the first hour', () => {
const service = createService();
expect(service.nextPollDelayMs(0)).toBe(2 * 60_000);
expect(service.nextPollDelayMs(60 * 60_000)).toBe(2 * 60_000);
});
});
describe('TournamentResultService manual result collection', () => {
function createManualFixture() {
const communityId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const users = Array.from({ length: 10 }, (_, index) => ({
userId: new mongoose.Types.ObjectId(),
puuid: `puuid-${index + 1}`,
}));
const match = {
_id: matchId,
communityId,
gameCount: 1,
gameMode: 'pair',
teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'),
status: 'team-built',
tournamentCodeIds: [],
gameSchedule: [],
participants: users.map((user) => ({
userId: user.userId,
puuid: user.puuid,
excluded: false,
})),
teams: [ teams: [
{ {
teamIndex: 1, teamId: params.teamAId,
members: users.slice(0, 5).map((user) => ({ userId: user.userId })), members: params.users.slice(0, 5).map(({ userId }) => ({ userId })),
}, },
{ {
teamIndex: 2, teamId: params.teamBId,
members: users.slice(5).map((user) => ({ userId: user.userId })), members: params.users.slice(5).map(({ userId }) => ({ userId })),
}, },
], ],
save: jest.fn().mockResolvedValue(undefined), projection: {
} as unknown as MatchDocument & { phase,
save: jest.Mock; series: [
result?: MatchDocument['result']; {
}; seriesId: params.seriesId.toString(),
const detail = { status: params.completed ? 'completed' : 'ready',
metadata: { entries: [
matchId: 'KR_1234567890', {
participants: users.map((user) => user.puuid), slot: 'A',
teamId: params.teamAId.toString(),
gameWins: params.completed ? 1 : 0,
}, },
info: { { slot: 'B', teamId: params.teamBId.toString(), gameWins: 0 },
gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), ],
gameDuration: 1800, },
participants: users.map((user, index) => ({ ],
puuid: user.puuid, 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, teamId: index < 5 ? 100 : 200,
championId: 1, championId: index + 1,
kills: 1, kills: 1,
deaths: 1, deaths: 1,
assists: 1, assists: 1,
win: index < 5, 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: [ teams: [
{ teamId: 100, win: true }, { teamId: 100, win: true },
{ teamId: 200, win: false }, { teamId: 200, win: false },
], ],
}, },
} as unknown as RiotMatchDto; } as unknown as RiotMatchDto;
const communityFindById = jest.fn().mockReturnValue({ }
select: jest.fn().mockReturnValue({
lean: jest.fn().mockReturnValue({ function execResult<T>(value: T) {
exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }), return { exec: jest.fn().mockResolvedValue(value) };
}), }
}),
}); function sortedResult<T>(value: T) {
const riotMatchFindOne = jest.fn().mockReturnValue({ return { sort: jest.fn().mockReturnValue(execResult(value)) };
exec: jest.fn().mockResolvedValue(null), }
});
const riotMatchUpdateOne = jest.fn().mockReturnValue({ function queryResult<T>(value: T) {
exec: jest.fn().mockResolvedValue(undefined), const query = {
}); lean: jest.fn(),
const tournamentCodeUpdateOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue(value),
exec: jest.fn().mockResolvedValue(undefined),
});
const connectionService = {
getModel: jest.fn().mockImplementation(async (name: string) => {
if (name === 'match') {
return { findById: jest.fn().mockResolvedValue(match) };
}
if (name === 'community') {
return { findById: communityFindById };
}
if (name === 'riotMatch') {
return {
findOne: riotMatchFindOne,
updateOne: riotMatchUpdateOne,
}; };
} query.lean.mockReturnValue(query);
if (name === 'tournamentCode') { return query;
return { updateOne: tournamentCodeUpdateOne }; }
}
return {};
}),
};
const riotMatchService = {
getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_1234567890']),
getMatch: jest.fn().mockResolvedValue(detail),
};
const distributedLockService = createDistributedLockService();
const service = new TournamentResultService(
connectionService as never,
riotMatchService as never,
{} as never,
{ invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never,
{ buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never,
distributedLockService as never,
);
return {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
};
}
it('collects by time window without setting Riot match type', async () => {
const { service, match, communityId, matchId, riotMatchService } =
createManualFixture();
const result = await service.collectManualByWindow({
matchId,
communityId,
startTime: new Date('2026-05-03T10:00:00.000Z'),
endTime: new Date('2026-05-03T11:00:00.000Z'),
});
expect(result).toMatchObject({
scanned: 1,
matched: 1,
gameNumbers: [1],
riotMatchIds: ['KR_1234567890'],
});
expect(riotMatchService.getMatchIdsByPuuid).toHaveBeenCalledWith(
'puuid-1',
expect.not.objectContaining({ type: expect.anything() }),
);
expect(match.result?.games).toHaveLength(1);
expect(match.status).toBe('finished');
});
it('collects directly by Riot match id', async () => {
const {
service,
match,
communityId,
matchId,
riotMatchService,
tournamentCodeUpdateOne,
} = createManualFixture();
const result = await service.collectManualByRiotMatch({
matchId,
communityId,
riotMatchId: ' KR_1234567890 ',
});
expect(result.matched).toBe(1);
expect(riotMatchService.getMatchIdsByPuuid).not.toHaveBeenCalled();
expect(riotMatchService.getMatch).toHaveBeenCalledWith('KR_1234567890', {
region: 'asia',
});
expect(tournamentCodeUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({
matchId,
gameNumber: 1,
}),
expect.objectContaining({
$set: expect.objectContaining({ riotMatchId: 'KR_1234567890' }),
}),
);
expect(match.result?.games[0].winnerTeamIndex).toBe(1);
});
});
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,3 @@
import type { TeamSide } from '../global/database/schema';
import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types';
export interface PollTournamentResultJob { export interface PollTournamentResultJob {
@@ -26,14 +25,3 @@ export interface ManualTournamentResultCollectResponse {
riotMatchIds: string[]; riotMatchIds: string[];
gameNumbers: number[]; gameNumbers: number[];
} }
export interface ComputedGameParticipant {
userId: string;
teamIndex: number;
side: TeamSide;
championId: number;
kills: number;
deaths: number;
assists: number;
win: boolean;
}