release/86 #2
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,180 +1,32 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import {
|
||||
collectCaptainAndLimitedTeamMemberUserIds,
|
||||
computeGameResult,
|
||||
type MatchPuuidLookup,
|
||||
} from './team-mapping.util';
|
||||
|
||||
function makeMatch(): {
|
||||
match: MatchDocument;
|
||||
lookup: MatchPuuidLookup;
|
||||
blueUserIds: mongoose.Types.ObjectId[];
|
||||
redUserIds: mongoose.Types.ObjectId[];
|
||||
} {
|
||||
const blueUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const redUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => 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 = {
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
name: '1팀',
|
||||
members: blueUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
})),
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
name: '2팀',
|
||||
members: redUserIds.map((userId) => ({
|
||||
userId,
|
||||
assignedPosition: 'MID',
|
||||
})),
|
||||
},
|
||||
],
|
||||
participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({
|
||||
userId,
|
||||
puuid: `puuid-${index}`,
|
||||
preferredPositions: [],
|
||||
joinedAt: new Date(),
|
||||
})),
|
||||
} 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();
|
||||
});
|
||||
});
|
||||
import { collectCaptainAndLimitedTeamMemberUserIds } from './team-mapping.util';
|
||||
|
||||
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 blueUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const redUserIds = Array.from(
|
||||
{ length: 5 },
|
||||
() => new mongoose.Types.ObjectId(),
|
||||
);
|
||||
const match = {
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId: blueUserIds[0],
|
||||
members: blueUserIds.map((userId) => ({ userId })),
|
||||
},
|
||||
{
|
||||
teamIndex: 2,
|
||||
captainUserId: redUserIds[0],
|
||||
members: redUserIds.map((userId) => ({ userId })),
|
||||
},
|
||||
],
|
||||
participants: [],
|
||||
} as unknown as MatchDocument;
|
||||
|
||||
const userIds = collectCaptainAndLimitedTeamMemberUserIds(match, 2).map(
|
||||
(userId) => userId.toString(),
|
||||
|
||||
@@ -1,14 +1,5 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
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;
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
|
||||
export interface MatchPuuidLookup {
|
||||
puuidByUserId: Map<string, string>;
|
||||
@@ -61,113 +52,3 @@ export function collectMatchUserIds(
|
||||
}
|
||||
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 { CommunityStatsModule } from '../community-stats/community-stats.module';
|
||||
import { CompetitionModule } from '../competition/competition.module';
|
||||
import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
|
||||
import { TournamentResultController } from './tournament-result.controller';
|
||||
import { TournamentResultService } from './tournament-result.service';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)],
|
||||
imports: [
|
||||
RiotModule,
|
||||
CommunityStatsModule,
|
||||
CompetitionModule,
|
||||
forwardRef(() => RiotJobQueueModule),
|
||||
],
|
||||
controllers: [TournamentResultController],
|
||||
providers: [TournamentResultService],
|
||||
providers: [CompetitionAssignmentProvisioner, TournamentResultService],
|
||||
exports: [TournamentResultService],
|
||||
})
|
||||
export class TournamentResultModule {}
|
||||
File diff suppressed because it is too large.
Load diff
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';
|
||||
|
||||
export interface PollTournamentResultJob {
|
||||
@@ -26,14 +25,3 @@ export interface ManualTournamentResultCollectResponse {
|
||||
riotMatchIds: string[];
|
||||
gameNumbers: number[];
|
||||
}
|
||||
|
||||
export interface ComputedGameParticipant {
|
||||
userId: string;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
win: boolean;
|
||||
}
|
||||
Reference in new issue
Block a user