diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts new file mode 100644 index 00000000..ebc19e9e --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts @@ -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 = { + 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(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(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function duplicateKeyError(): Error & { code: number } { + return Object.assign(new Error('E11000 duplicate key'), { code: 11000 }); +} diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts new file mode 100644 index 00000000..8a6a4c34 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.ts @@ -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 { + 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; + }): Promise { + 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; + TournamentCodeModel: mongoose.Model; + MatchModel: mongoose.Model; + CompetitionModel: mongoose.Model; + competitionId: mongoose.Types.ObjectId; + expectedRevision: number; + }): Promise { + 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 { + 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; + TournamentCodeModel: mongoose.Model; + session: mongoose.ClientSession; + }): Promise { + 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, + competitionId: mongoose.Types.ObjectId, + gameSlotId: mongoose.Types.ObjectId, + ): Promise { + 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(); + 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; + competitionId: mongoose.Types.ObjectId; + expectedRevision: number; + session: mongoose.ClientSession; +}): Promise { + 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'), + ); +} diff --git a/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts b/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts new file mode 100644 index 00000000..05026de3 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-result.adapter.spec.ts @@ -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', + ]); + }); +}); diff --git a/apps/api/src/modules/tournament-result/competition-result.adapter.ts b/apps/api/src/modules/tournament-result/competition-result.adapter.ts new file mode 100644 index 00000000..05dd7cd9 --- /dev/null +++ b/apps/api/src/modules/tournament-result/competition-result.adapter.ts @@ -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; + 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>; + 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) + .filter(([, child]) => child !== undefined) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([key, child]) => [key, canonicalize(child)]), + ); + } + return value; +} diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts index de5e512f..5002840f 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -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(); - const userIdByPuuid = new Map(); - - 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(), diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts index d21d551d..5bfcab03 100644 --- a/apps/api/src/modules/tournament-result/team-mapping.util.ts +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -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; @@ -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 = { - [RIOT_BLUE_TEAM_ID]: blueTeamIndex, - [RIOT_RED_TEAM_ID]: redTeamIndex, - }; - const sideByRiotTeamId: Record = { - [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 => - 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; -} diff --git a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts new file mode 100644 index 00000000..514867d4 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts @@ -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; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts index b9281ad0..52c2e19a 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.module.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -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 {} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 733c534f..3884231d 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -1,662 +1,426 @@ +/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; -import { DistributedLockService } from '../global/redis/distributed-lock.service'; import type { RiotMatchDto } from '../riot/riot.types'; import { TournamentResultService } from './tournament-result.service'; -import { buildDoubleEliminationBracket } from '../double-elimination/double-elimination.util'; -type TournamentResultServiceInternals = TournamentResultService & { - nextPollDelayMs(elapsedMs: number): number | null; - resolveRequiredGameSlots(match: MatchDocument): number; - resolveSeriesRefForGameNumber( - match: MatchDocument, - gameNumber: number, - ): { teamAIndex: number; teamBIndex: number }; - buildSeriesResults( - games: NonNullable['games'], - ): NonNullable['seriesResults']; - advanceDoubleEliminationIfNeeded( - match: MatchDocument, - gameResult: NonNullable['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; -} - -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); - }); - - 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( - service.buildSeriesResults([ - { - gameNumber: 1, - bracketMatchId: 'WB_FINAL', - riotMatchId: 'KR_1', - 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(service.resolveRequiredGameSlots(match)).toBe(12); - expect(service.resolveSeriesRefForGameNumber(match, 1)).toEqual({ - teamAIndex: 1, - 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['games'][number]; - const match = createMatch({ - gameMode: 'double-elimination', - doubleElimination: buildDoubleEliminationBracket([1, 2, 3, 4], { - resetFinalEnabled: true, - }), - result: { - riotMatchIds: ['KR_1'], - games: [game], - seriesResults: [ - { - bracketMatchId: 'WB_R1_M1', - teamAIndex: 1, - teamBIndex: 4, - 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(firstGameBracketMatch?.winnerTeamIndex).toBeUndefined(); - - match.result!.seriesResults = [ - { - bracketMatchId: 'WB_R1_M1', - teamAIndex: 1, - teamBIndex: 4, - teamAWins: 2, - teamBWins: 0, - winnerTeamIndex: 1, - }, - ]; - - expect( - service.advanceDoubleEliminationIfNeeded(match, game, 'riot-result'), - ).toBe('WB_R1_M1'); - expect( - match.doubleElimination?.bracketMatches.find( - (entry) => entry.bracketMatchId === 'WB_R1_M1', - ), - ).toMatchObject({ state: 'completed', winnerTeamIndex: 1 }); - expect( - match.doubleElimination?.bracketMatches.find( - (entry) => entry.bracketMatchId === 'WB_FINAL', - ), - ).toMatchObject({ teamAIndex: 1 }); - }); -}); - -describe('TournamentResultService tournament code polling', () => { - function queryResult(value: T) { - return { exec: jest.fn().mockResolvedValue(value) }; - } - - function sortedQueryResult(value: T) { - return { - sort: jest.fn().mockReturnValue(queryResult(value)), - }; - } - - function createPollFixture(params: { - storedCode: string; - riotTournamentCode: string; - }) { - const communityId = new mongoose.Types.ObjectId(); - const matchId = new mongoose.Types.ObjectId(); - const codeId = new mongoose.Types.ObjectId(); - const users = Array.from({ length: 10 }, (_, index) => ({ - userId: new mongoose.Types.ObjectId(), - puuid: `poll-puuid-${index + 1}`, - })); - const match = { - _id: matchId, - communityId, - status: 'team-built', - teamBuiltAt: new Date('2026-05-03T10:00:00.000Z'), - gameCount: 1, - gameMode: 'pair', - tournamentCodeIds: [codeId], - gameSchedule: [], - resultPollState: { - startedAt: new Date(), - matchedCount: 0, - expandedToAllPuuids: true, - state: 'polling', - }, - participants: users.map((user) => ({ - userId: user.userId, - puuid: user.puuid, - excluded: false, - })), - teams: [ - { - teamIndex: 1, - members: users.slice(0, 5).map((user) => ({ userId: user.userId })), - }, - { - teamIndex: 2, - members: users.slice(5).map((user) => ({ userId: user.userId })), - }, - ], - save: jest.fn().mockResolvedValue(undefined), - } as unknown as MatchDocument & { - save: jest.Mock; - result?: MatchDocument['result']; - }; - const code = { - _id: codeId, - code: params.storedCode, - state: 'reserved', - gameNumber: 1, - riotMatchId: undefined, - save: jest.fn().mockResolvedValue(undefined), - }; - const detail = { - metadata: { - matchId: 'KR_9876543210', - participants: users.map((user) => user.puuid), - }, - info: { - tournamentCode: params.riotTournamentCode, - gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), - gameEndTimestamp: Date.parse('2026-05-03T11:00:00.000Z'), - gameDuration: 1800, - participants: users.map((user, index) => ({ - puuid: user.puuid, - teamId: index < 5 ? 100 : 200, - championId: 1, - kills: 1, - deaths: 1, - assists: 1, - win: index < 5, - })), - teams: [ - { teamId: 100, win: true }, - { teamId: 200, win: false }, - ], - }, - } 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)), - updateOne: jest.fn().mockReturnValue(queryResult(undefined)), - }; - const CommunityModel = { - findById: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - lean: jest.fn().mockReturnValue(queryResult({ riotRegion: 'asia' })), - }), - }), - }; - const connectionService = { - getModel: jest.fn().mockImplementation(async (name: string) => { - if (name === 'match') { - return { findById: jest.fn().mockResolvedValue(match) }; - } - if (name === 'tournamentCode') return TournamentCodeModel; - if (name === 'community') return CommunityModel; - if (name === 'riotMatch') return RiotMatchModel; - throw new Error(`Unexpected model: ${name}`); - }), - }; - const riotMatchService = { - getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_9876543210']), - getMatch: jest.fn().mockResolvedValue(detail), - }; - const riotJobQueueService = { - enqueueTournamentResultPoll: jest.fn().mockResolvedValue(undefined), - }; - const distributedLockService = createDistributedLockService(); - const service = new TournamentResultService( - connectionService as never, - riotMatchService as never, - riotJobQueueService as never, - { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, - { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, - distributedLockService as never, - ); - - return { service, match, code, riotMatchService }; - } - - it('matches Riot tournament codes using exact casing', async () => { - const { service, match, code } = createPollFixture({ +describe('TournamentResultService Competition polling', () => { + it('promotes a reserved legacy code to a stable GameSlot assignment and accepts through Competition', async () => { + const harness = pollHarness({ storedCode: 'AbC-12345', riotTournamentCode: 'AbC-12345', }); - await service.processPollJob({ - matchId: match._id.toString(), - attempt: 1, - expandedToAllPuuids: true, - }); - - expect(code.state).toBe('used'); - expect(code.riotMatchId).toBe('KR_9876543210'); - 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(), + await harness.service.processPollJob({ + matchId: harness.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']); + harness.assignmentProvisioner.provisionReadyAssignments, + ).toHaveBeenCalledWith({ + matchId: harness.match._id, + competition: expect.objectContaining({ + competitionId: harness.competitionId.toString(), + }), + }); + expect(harness.assignmentModel.updateOne).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId: harness.competitionId, + tournamentCodeId: harness.codeId, + }), + expect.objectContaining({ + $setOnInsert: expect.objectContaining({ + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + state: 'reserved', + }), + }), + { upsert: true }, + ); + expect(harness.commandService.acceptGame).toHaveBeenCalledWith( + expect.objectContaining({ + competitionId: harness.competitionId, + seriesId: harness.seriesId, + gameSlotId: harness.gameSlotId, + tournamentCode: { + tournamentCodeId: harness.codeId, + riotMatchId: 'KR_POLL_1', + }, + }), + ); + expect(harness.code.save).not.toHaveBeenCalled(); + expect(harness.match.result).toBeUndefined(); + expect(harness.match.doubleElimination).toBeUndefined(); + expect(harness.match.status).toBe('finished'); }); - it('does not match tournament codes when casing differs', async () => { - const { service, match, code } = createPollFixture({ + it('keeps tournament-code matching case-sensitive and caps expanded polling members', async () => { + const harness = pollHarness({ storedCode: 'ABC-12345', riotTournamentCode: 'abc-12345', }); - await service.processPollJob({ - matchId: match._id.toString(), + await harness.service.processPollJob({ + matchId: harness.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(); + 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(); }); -}); -describe('TournamentResultService polling cadence', () => { - it('polls every two minutes during the first hour', () => { - const service = createService(); + 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, + }); - expect(service.nextPollDelayMs(0)).toBe(2 * 60_000); - expect(service.nextPollDelayMs(60 * 60_000)).toBe(2 * 60_000); + await harness.service.processPollJob({ + matchId: harness.match._id.toString(), + attempt: 1, + expandedToAllPuuids: true, + }); + + expect( + harness.assignmentProvisioner.provisionReadyAssignments, + ).toHaveBeenCalledTimes(3); + expect(harness.commandService.acceptGame).toHaveBeenCalledTimes(1); }); -}); -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: [ - { - teamIndex: 1, - members: users.slice(0, 5).map((user) => ({ userId: user.userId })), - }, - { - teamIndex: 2, - members: users.slice(5).map((user) => ({ userId: user.userId })), - }, - ], - save: jest.fn().mockResolvedValue(undefined), - } as unknown as MatchDocument & { - save: jest.Mock; - result?: MatchDocument['result']; - }; - const detail = { - metadata: { - matchId: 'KR_1234567890', - participants: users.map((user) => user.puuid), - }, - info: { - gameCreation: Date.parse('2026-05-03T10:30:00.000Z'), - gameDuration: 1800, - participants: users.map((user, index) => ({ - puuid: user.puuid, - teamId: index < 5 ? 100 : 200, - championId: 1, - kills: 1, - deaths: 1, - assists: 1, - win: index < 5, - })), - teams: [ - { teamId: 100, win: true }, - { teamId: 200, win: false }, - ], - }, - } as unknown as RiotMatchDto; - const communityFindById = jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - lean: jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue({ riotRegion: 'asia' }), - }), - }), + it('resumes polling when a reversal reopens a Competition whose Match was finished', async () => { + const harness = pollHarness({ + storedCode: 'AbC-12345', + riotTournamentCode: 'AbC-12345', }); - const riotMatchFindOne = jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue(null), - }); - const riotMatchUpdateOne = jest.fn().mockReturnValue({ - exec: jest.fn().mockResolvedValue(undefined), - }); - const tournamentCodeUpdateOne = jest.fn().mockReturnValue({ - 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, - }; - } - if (name === 'tournamentCode') { - 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, + harness.match.status = 'finished'; + + const result = await harness.service.scheduleInitialPoll( + harness.match._id, + 'high', ); - 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'], + matchId: harness.match._id.toString(), + attempt: 1, }); - 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); + expect(harness.match.status).toBe('in-progress'); + expect( + harness.riotJobQueueService.enqueueTournamentResultPoll, + ).toHaveBeenCalledTimes(1); }); }); + +function pollHarness(params: { + storedCode: string; + riotTournamentCode: string; +}) { + const communityId = new mongoose.Types.ObjectId(); + const matchId = new mongoose.Types.ObjectId(); + const competitionId = new mongoose.Types.ObjectId(); + const seriesId = new mongoose.Types.ObjectId(); + const gameSlotId = new mongoose.Types.ObjectId(); + const codeId = new mongoose.Types.ObjectId(); + const teamAId = new mongoose.Types.ObjectId(); + const teamBId = new mongoose.Types.ObjectId(); + const users = Array.from({ length: 10 }, (_, index) => ({ + userId: new mongoose.Types.ObjectId(), + puuid: `poll-puuid-${index + 1}`, + })); + const match = { + _id: matchId, + communityId, + status: 'team-built', + teamBuiltAt: new Date('2026-07-12T09:00:00.000Z'), + gameCount: 1, + gameMode: 'pair', + tournamentCodeIds: [codeId], + resultPollState: { + startedAt: new Date(), + matchedCount: 0, + expandedToAllPuuids: true, + state: 'polling', + }, + participants: users.map(({ userId, puuid }) => ({ + userId, + puuid, + excluded: false, + })), + teams: [ + { + teamIndex: 1, + name: 'Team A', + members: users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamIndex: 2, + name: 'Team B', + members: users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + save: jest.fn().mockResolvedValue(undefined), + } as unknown as MatchDocument & { save: jest.Mock }; + const code = { + _id: codeId, + code: params.storedCode, + state: 'reserved', + gameNumber: 1, + reservedAt: new Date('2026-07-12T09:00:00.000Z'), + save: jest.fn().mockResolvedValue(undefined), + }; + const readyCompetition = competitionDocument({ + competitionId, + seriesId, + gameSlotId, + teamAId, + teamBId, + users, + completed: false, + }); + const completedCompetition = competitionDocument({ + competitionId, + seriesId, + gameSlotId, + teamAId, + teamBId, + users, + completed: true, + }); + const detail = riotDetail( + users.map(({ puuid }) => puuid), + params.riotTournamentCode, + ); + const assignmentModel = { + findOne: jest.fn().mockReturnValue(queryResult(null)), + updateOne: jest.fn().mockReturnValue(execResult(undefined)), + }; + const connectionService = { + getModel: jest.fn().mockImplementation((name: string) => { + switch (name) { + case 'match': + return Promise.resolve({ + findById: jest.fn().mockResolvedValue(match), + }); + case 'tournamentCode': + return Promise.resolve({ + find: jest.fn().mockReturnValue(sortedResult([code])), + }); + case 'tournamentCodeAssignment': + return Promise.resolve(assignmentModel); + case 'community': + return Promise.resolve({ + findById: jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest + .fn() + .mockReturnValue(execResult({ riotRegion: 'asia' })), + }), + }), + }); + case 'riotMatch': + return Promise.resolve({ + findOne: jest.fn().mockReturnValue(execResult(null)), + updateOne: jest.fn().mockReturnValue(execResult(undefined)), + }); + case 'competition': + return Promise.resolve({ + findById: jest.fn().mockReturnValue(queryResult(readyCompetition)), + }); + default: + throw new Error(`Unexpected model ${name}`); + } + }), + }; + const riotMatchService = { + getMatchIdsByPuuid: jest.fn().mockResolvedValue(['KR_POLL_1']), + getMatch: jest.fn().mockResolvedValue(detail), + }; + const commandService = { + acceptGame: jest.fn().mockResolvedValue({ + competition: completedCompetition, + commandId: 'cmpcmd-poll', + revision: 1, + replayed: false, + }), + }; + const assignmentProvisioner = { + provisionReadyAssignments: jest.fn().mockResolvedValue({ + requested: 1, + reserved: 0, + existing: 1, + unavailable: 0, + }), + }; + const distributedLockService = { + runWithRenewedLock: jest + .fn() + .mockImplementation( + (_options: unknown, operation: (context: object) => Promise) => + operation({}), + ), + runWithLock: jest + .fn() + .mockImplementation( + (_options: unknown, operation: (context: object) => Promise) => + operation({}), + ), + }; + const riotJobQueueService = { + enqueueTournamentResultPoll: jest.fn().mockResolvedValue({ + jobId: 'poll-job-1', + matchId: matchId.toString(), + priority: 'high', + attempt: 1, + expandedToAllPuuids: false, + }), + }; + const service = new TournamentResultService( + connectionService as never, + riotMatchService as never, + riotJobQueueService as never, + { invalidateCommunity: jest.fn().mockResolvedValue(undefined) } as never, + { buildAndUpsert: jest.fn().mockResolvedValue(undefined) } as never, + distributedLockService as never, + { bootstrap: jest.fn().mockResolvedValue(readyCompetition) } as never, + commandService as never, + assignmentProvisioner as never, + ); + + return { + service, + match, + code, + competitionId, + seriesId, + gameSlotId, + codeId, + assignmentModel, + commandService, + assignmentProvisioner, + riotMatchService, + riotJobQueueService, + }; +} + +function competitionDocument(params: { + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + teamAId: mongoose.Types.ObjectId; + teamBId: mongoose.Types.ObjectId; + users: Array<{ userId: mongoose.Types.ObjectId }>; + completed: boolean; +}) { + const phase = params.completed ? 'completed' : 'ready'; + return { + _id: params.competitionId, + revision: params.completed ? 1 : 0, + phase, + teams: [ + { + teamId: params.teamAId, + members: params.users.slice(0, 5).map(({ userId }) => ({ userId })), + }, + { + teamId: params.teamBId, + members: params.users.slice(5).map(({ userId }) => ({ userId })), + }, + ], + projection: { + phase, + series: [ + { + seriesId: params.seriesId.toString(), + status: params.completed ? 'completed' : 'ready', + entries: [ + { + slot: 'A', + teamId: params.teamAId.toString(), + gameWins: params.completed ? 1 : 0, + }, + { slot: 'B', teamId: params.teamBId.toString(), gameWins: 0 }, + ], + }, + ], + gameSlots: [ + { + id: params.gameSlotId.toString(), + seriesId: params.seriesId.toString(), + ordinal: 1, + displayNumber: 1, + status: params.completed ? 'completed' : 'ready', + }, + ], + games: params.completed + ? [{ evidence: { type: 'riot', riotMatchId: 'KR_POLL_1' } }] + : [], + }, + }; +} + +function riotDetail(puuids: string[], tournamentCode: string): RiotMatchDto { + const participants = puuids.map((puuid, index) => ({ + puuid, + participantId: index + 1, + teamId: index < 5 ? 100 : 200, + championId: index + 1, + kills: 1, + deaths: 1, + assists: 1, + win: index < 5, + })); + return { + metadata: { dataVersion: '2', matchId: 'KR_POLL_1', participants: puuids }, + info: { + tournamentCode, + gameCreation: Date.parse('2026-07-12T10:00:00.000Z'), + gameEndTimestamp: Date.parse('2026-07-12T10:30:00.000Z'), + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: true }, + { teamId: 200, win: false }, + ], + }, + } as unknown as RiotMatchDto; +} + +function execResult(value: T) { + return { exec: jest.fn().mockResolvedValue(value) }; +} + +function sortedResult(value: T) { + return { sort: jest.fn().mockReturnValue(execResult(value)) }; +} + +function queryResult(value: T) { + const query = { + lean: jest.fn(), + exec: jest.fn().mockResolvedValue(value), + }; + query.lean.mockReturnValue(query); + return query; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts index 59067a14..a3fdcb31 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -4,38 +4,40 @@ import { Logger, NotFoundException, } from '@nestjs/common'; +import { createHash } from 'node:crypto'; import mongoose from 'mongoose'; -import { - buildDoubleEliminationGameSlots, - completeDoubleEliminationBracketMatch, - resolveDoubleEliminationSeriesWinner, - type DoubleEliminationGameSlot, -} from '../double-elimination/double-elimination.util'; -import { MatchStatsService } from '../community-stats/match-stats.service'; import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { MatchStatsService } from '../community-stats/match-stats.service'; +import { + CompetitionBootstrapService, + type CompetitionBootstrapMatch, +} from '../competition/competition-bootstrap.service'; +import { CompetitionCommandService } from '../competition/competition-command.service'; import { ConnectionService } from '../global/database/connection.service'; -import { DistributedLockService } from '../global/redis/distributed-lock.service'; import type { MatchDocument, - MatchGameResult, - MatchSeriesResult, RiotMatch as StoredRiotMatch, TournamentCodeDocument, } from '../global/database/schema'; +import { DistributedLockService } from '../global/redis/distributed-lock.service'; import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import { RiotMatchService } from '../riot/riot-match.service'; import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; +import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; import { - roundRobinGameSchedule, - resolveRoundRobinTeamCount, -} from '../tournament-code/round-robin.util'; -import { TOURNAMENT_CODE_EXPIRY_MARGIN_MS } from '../tournament-code/tournament-code.constants'; + compareRiotGameChronology, + hasAcceptedRiotMatch, + mapRiotGameToCompetitionSlot, + resolveReadyCompetitionSlot, + type CompetitionResultGameSlotProjection, + type CompetitionResultSnapshot, + type MappedCompetitionRiotGame, +} from './competition-result.adapter'; import { collectCaptainAndLimitedTeamMemberUserIds, collectCaptainUserIds, collectMatchUserIds, - computeGameResult, type MatchPuuidLookup, } from './team-mapping.util'; import type { @@ -50,19 +52,39 @@ const POLL_EXPIRY_MS = 24 * 60 * 60_000; const EXPAND_AFTER_MS = 60 * 60_000; const EXPANDED_MEMBER_LIMIT_PER_TEAM = 2; const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; +const RESULT_ACCEPT_ATTEMPTS = 2; const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 30 * 60_000; const TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS = 5 * 60_000; -const TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS = +const TOURNAMENT_RESULT_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS = 5 * 60_000; -interface ManualGameAssignment { - gameNumber: number; - bracketMatchId?: string; - teamAIndex: number; - teamBIndex: number; -} +type CompetitionPersistenceDocument = { + _id: mongoose.Types.ObjectId; + revision: number; + phase: string; + teams: unknown[]; + projection: Record; + toObject?: () => unknown; +}; + +type CodeAssignmentRecord = { + competitionId: mongoose.Types.ObjectId; + seriesId: mongoose.Types.ObjectId; + gameSlotId: mongoose.Types.ObjectId; + tournamentCodeId: mongoose.Types.ObjectId; + state: 'reserved' | 'used' | 'released' | 'voided'; +}; + +type AcceptanceOutcome = + | { + kind: 'accepted'; + displayNumber: number; + competition: CompetitionResultSnapshot; + } + | { kind: 'duplicate'; competition: CompetitionResultSnapshot } + | { kind: 'unmatched'; competition: CompetitionResultSnapshot }; @Injectable() export class TournamentResultService { @@ -75,6 +97,9 @@ export class TournamentResultService { private readonly communityStatsService: CommunityStatsService, private readonly matchStatsService: MatchStatsService, private readonly distributedLockService: DistributedLockService, + private readonly competitionBootstrapService: CompetitionBootstrapService, + private readonly competitionCommandService: CompetitionCommandService, + private readonly competitionAssignmentProvisioner: CompetitionAssignmentProvisioner, ) {} public async scheduleInitialPoll( @@ -86,7 +111,7 @@ export class TournamentResultService { { lockKey: this.tournamentResultPollProcessingLockKey(matchIdentifier), lockExpirationDurationMilliseconds: - TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS, + TOURNAMENT_RESULT_POLL_SCHEDULING_LOCK_EXPIRATION_DURATION_MILLISECONDS, lockAcquireTimeoutMilliseconds: 1_000, lockRetryDelayMilliseconds: 100, }, @@ -99,14 +124,20 @@ export class TournamentResultService { priority: RiotJobPriority, ): Promise { const match = await this.loadMatch(matchOrId); - if (match.status === 'finished') return null; if (!this.isReadyToPoll(match)) return null; + let competition = await this.ensureCompetition(match); + competition = await this.provisionCompetitionAssignments( + match, + competition, + ); + if (competition.projection.phase === 'completed') return null; + if (match.status === 'finished') match.status = 'in-progress'; match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: match.resultPollState?.lastPolledAt, lastPollOutcome: match.resultPollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, + matchedCount: competition.projection.games.length, expandedToAllPuuids: false, state: 'polling', }; @@ -130,7 +161,7 @@ export class TournamentResultService { } if (!this.isReadyToPoll(match)) { throw new BadRequestException( - 'Match needs built teams, teamBuiltAt, and tournament codes before polling.', + 'Match needs built teams and teamBuiltAt before polling.', ); } const result = await this.scheduleInitialPoll(match, 'high'); @@ -162,8 +193,8 @@ export class TournamentResultService { collectMatchUserIds(match), lookup, ); - const startTime = Math.floor(params.startTime.getTime() / 1000); - const endTime = Math.floor(params.endTime.getTime() / 1000); + const startTime = Math.floor(params.startTime.getTime() / 1_000); + const endTime = Math.floor(params.endTime.getTime() / 1_000); const riotMatchIds = new Set(); for (const puuid of puuids) { @@ -177,9 +208,7 @@ export class TournamentResultService { ids.forEach((id) => riotMatchIds.add(id)); } catch (error) { this.logger.warn( - `Manual result match id lookup failed for ${puuid}: ${ - error instanceof Error ? error.message : error - }`, + `Manual result match id lookup failed for ${puuid}: ${errorMessage(error)}`, ); } } @@ -199,18 +228,12 @@ export class TournamentResultService { }): Promise { const match = await this.loadMatch(params.matchId); this.assertManualCollectionAllowed(match, params.communityId); - - const normalizedRiotMatchId = params.riotMatchId.trim(); - if (!normalizedRiotMatchId) { - throw new BadRequestException('riotMatchId is required.'); - } + const riotMatchId = params.riotMatchId.trim(); + if (!riotMatchId) throw new BadRequestException('riotMatchId is required.'); const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); - const detail = await this.ensureRiotMatchPersisted( - normalizedRiotMatchId, - region, - ); + const detail = await this.ensureRiotMatchPersisted(riotMatchId, region); return this.applyManualRiotMatches(match, [detail], lookup); } @@ -223,22 +246,20 @@ export class TournamentResultService { } public async processPollJob(job: PollTournamentResultJob): Promise { - const didProcessPollJob = - await this.distributedLockService.runWithRenewedLock( - { - lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), - lockExpirationDurationMilliseconds: - TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, - lockRenewalIntervalMilliseconds: - TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, - }, - async () => { - await this.processPollJobWhileLockOwned(job); - return true; - }, - ); - - if (didProcessPollJob) return; + const didProcess = await this.distributedLockService.runWithRenewedLock( + { + lockKey: this.tournamentResultPollProcessingLockKey(job.matchId), + lockExpirationDurationMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_EXPIRATION_DURATION_MILLISECONDS, + lockRenewalIntervalMilliseconds: + TOURNAMENT_RESULT_POLL_PROCESSING_LOCK_RENEWAL_INTERVAL_MILLISECONDS, + }, + async () => { + await this.processPollJobWhileLockOwned(job); + return true; + }, + ); + if (didProcess) return; this.logger.debug( `Skipped tournament result poll job ${job.jobId}; another worker is processing match ${job.matchId}.`, ); @@ -250,34 +271,33 @@ export class TournamentResultService { const MatchModel = await this.connectionService.getModel('match'); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); - const CommunityModel = await this.connectionService.getModel('community'); const match = await MatchModel.findById(job.matchId); - if (!match || match.status === 'finished') return; + if (!match) return; if (!this.isReadyToPoll(match)) { await this.updatePollState(match, 'failed', job.expandedToAllPuuids); return; } + let competition = await this.ensureCompetition(match); + competition = await this.provisionCompetitionAssignments( + match, + competition, + ); const codes = await TournamentCodeModel.find({ matchId: match._id }) .sort({ gameNumber: 1 }) .exec(); - const unmatched = codes.filter( + const unmatchedCodes = codes.filter( (code) => code.state === 'reserved' && !code.riotMatchId, ); - if (unmatched.length === 0) { - const completed = await this.advanceMatchIfReady(match, codes); - if (!completed) { - await this.reserveReadyDoubleEliminationCodes(match); - await this.scheduleNextPoll(match, job); + if (unmatchedCodes.length === 0) { + await this.syncMatchLifecycle(match, competition); + if (competition.projection.phase !== 'completed') { + await this.scheduleNextPoll(match, competition, job); } return; } - const community = await CommunityModel.findById(match.communityId) - .select({ riotRegion: 1 }) - .lean() - .exec(); - const region = community?.riotRegion ?? 'asia'; + const region = await this.resolveRiotRegion(match); const lookup = await this.buildPuuidLookup(match); const puuids = job.expandedToAllPuuids ? this.collectPollingPuuids( @@ -288,131 +308,85 @@ export class TournamentResultService { lookup, ) : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); - - const matchedGameNumbers = new Set(); const checkedRiotMatchIds = new Set(); - const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code])); + const unmatchedByCode = new Map( + unmatchedCodes.map((code) => [code.code, code]), + ); + const collected: Array<{ + detail: RiotMatchDto; + code: TournamentCodeDocument; + tournamentCode: string; + }> = []; + let matched = 0; for (const puuid of puuids) { - let ids: string[]; + let riotMatchIds: string[]; try { - ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { + riotMatchIds = await this.riotMatchService.getMatchIdsByPuuid(puuid, { region, type: 'tourney', startTime: this.resolveStartTime(match), - endTime: Math.floor(Date.now() / 1000), + endTime: Math.floor(Date.now() / 1_000), count: 100, }); } catch (error) { this.logger.warn( - `Tournament result match id lookup failed for ${puuid}: ${ - error instanceof Error ? error.message : error - }`, + `Tournament result match id lookup failed for ${puuid}: ${errorMessage(error)}`, ); continue; } - for (const riotMatchId of ids) { + for (const riotMatchId of riotMatchIds) { if (checkedRiotMatchIds.has(riotMatchId)) continue; checkedRiotMatchIds.add(riotMatchId); - - const alreadyMatched = await TournamentCodeModel.exists({ - riotMatchId, - }); - if (alreadyMatched) continue; - let detail: RiotMatchDto; try { detail = await this.ensureRiotMatchPersisted(riotMatchId, region); } catch (error) { this.logger.warn( - `Tournament result detail fetch failed for ${riotMatchId}: ${ - error instanceof Error ? error.message : error - }`, + `Tournament result detail fetch failed for ${riotMatchId}: ${errorMessage(error)}`, ); continue; } const tournamentCode = detail.info.tournamentCode?.trim(); if (!tournamentCode) continue; - const code = unmatchedByCode.get(tournamentCode); if (!code) continue; - - const applied = await this.applyMatchToGameSlot({ - match, - code, - detail, - lookup, - }); - if (applied) { - matchedGameNumbers.add(code.gameNumber ?? 0); - unmatchedByCode.delete(tournamentCode); - } + collected.push({ detail, code, tournamentCode }); } } - const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id }) - .sort({ gameNumber: 1 }) - .exec(); - const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found'; - await this.updatePollState(match, outcome, job.expandedToAllPuuids); - const completed = await this.advanceMatchIfReady(match, reloadedCodes); - if (!completed) { - await this.scheduleNextPoll(match, job); - } - } - - private async applyMatchToGameSlot(params: { - match: MatchDocument; - code: TournamentCodeDocument; - detail: RiotMatchDto; - lookup: MatchPuuidLookup; - }): Promise { - const { match, code, detail, lookup } = params; - if (code.state !== 'reserved' || code.riotMatchId) return false; - if (!code.gameNumber) return false; - - const gameResult = computeGameResult({ - match, - detail, - gameNumber: code.gameNumber, - lookup, - ...this.resolveSeriesRefForGameNumber(match, code.gameNumber), - }); - if (!gameResult) { - this.logger.warn( - `Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`, - ); - return false; - } - - gameResult.bracketMatchId = code.bracketMatchId; - code.state = 'used'; - code.usedAt = new Date( - detail.info.gameEndTimestamp ?? detail.info.gameCreation, + collected.sort((left, right) => + compareRiotGameChronology(left.detail, right.detail), ); - code.riotMatchId = detail.metadata.matchId; - await code.save(); - - this.upsertGameResult(match, gameResult); - const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded( - match, - gameResult, - 'riot-result', - ); - if (completedBracketMatchId) { - await this.releaseUnusedReservedDoubleEliminationCodes( + for (const candidate of collected) { + if (unmatchedByCode.get(candidate.tournamentCode) !== candidate.code) { + continue; + } + const outcome = await this.acceptRiotGame({ match, - completedBracketMatchId, - ); + initialCompetition: competition, + detail: candidate.detail, + lookup, + code: candidate.code, + }); + competition = outcome.competition; + if (outcome.kind === 'accepted') matched += 1; + if (outcome.kind !== 'unmatched') { + unmatchedByCode.delete(candidate.tournamentCode); + } } - if (match.status === 'team-built') { - match.status = 'in-progress'; + + await this.updatePollState( + match, + matched > 0 ? 'matched' : 'not-found', + job.expandedToAllPuuids, + competition, + ); + await this.syncMatchLifecycle(match, competition); + if (competition.projection.phase !== 'completed') { + await this.scheduleNextPoll(match, competition, job); } - await match.save(); - await this.reserveReadyDoubleEliminationCodes(match); - await this.rebuildMatchStatsSafe(match); - return true; } private async applyManualRiotMatches( @@ -420,173 +394,330 @@ export class TournamentResultService { details: RiotMatchDto[], lookup: MatchPuuidLookup, ): Promise { - const sortedDetails = [...details].sort( - (left, right) => left.info.gameCreation - right.info.gameCreation, - ); - const appliedRiotMatchIds: string[] = []; - const appliedGameNumbers: number[] = []; + const sortedDetails = [...details].sort(compareRiotGameChronology); + let competition = await this.ensureCompetition(match); + const riotMatchIds: string[] = []; + const gameNumbers: number[] = []; let skipped = 0; for (const detail of sortedDetails) { - if (this.hasResultForRiotMatch(match, detail.metadata.matchId)) { - skipped += 1; - continue; - } - - const gameResult = this.computeManualGameResult(match, detail, lookup); - if (!gameResult) { - skipped += 1; - continue; - } - - this.upsertGameResult(match, gameResult); - const completedBracketMatchId = this.advanceDoubleEliminationIfNeeded( + const outcome = await this.acceptRiotGame({ match, - gameResult, - 'riot-result', - ); - if (completedBracketMatchId) { - await this.releaseUnusedReservedDoubleEliminationCodes( - match, - completedBracketMatchId, - ); - } - await this.markTournamentCodeUsedForManualResult( - match, - gameResult, + initialCompetition: competition, detail, - ); - appliedRiotMatchIds.push(detail.metadata.matchId); - appliedGameNumbers.push(gameResult.gameNumber); + lookup, + }); + competition = outcome.competition; + if (outcome.kind !== 'accepted') { + skipped += 1; + continue; + } + riotMatchIds.push(detail.metadata.matchId); + gameNumbers.push(outcome.displayNumber); } - if (appliedRiotMatchIds.length > 0 && match.status === 'team-built') { - match.status = 'in-progress'; - } - this.updateManualCollectionState(match, appliedRiotMatchIds.length); - await match.save(); - if (appliedRiotMatchIds.length > 0) { - await this.reserveReadyDoubleEliminationCodes(match); - } - if (appliedRiotMatchIds.length > 0) { - await this.rebuildMatchStatsSafe(match); - } - if (this.hasAllRequiredGameResults(match)) { - await this.finishMatchFromManualResults(match); - } + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: riotMatchIds.length > 0 ? 'matched' : 'not-found', + matchedCount: competition.projection.games.length, + expandedToAllPuuids: true, + state: + competition.projection.phase === 'completed' ? 'complete' : 'polling', + }; + await this.syncMatchLifecycle(match, competition); return { scanned: sortedDetails.length, - matched: appliedRiotMatchIds.length, + matched: riotMatchIds.length, skipped, - riotMatchIds: appliedRiotMatchIds, - gameNumbers: appliedGameNumbers, + riotMatchIds, + gameNumbers, }; } - private async advanceMatchIfReady( - match: MatchDocument, - codes: TournamentCodeDocument[], - ): Promise { - if ((match.gameMode ?? 'pair') === 'double-elimination') { - if (!this.isDoubleEliminationComplete(match)) return false; - match.status = 'finished'; - if (match.result) { - match.result.winnerTeamIndex = - match.doubleElimination?.placements.firstTeamIndex; + private async acceptRiotGame(params: { + match: MatchDocument; + initialCompetition: CompetitionResultSnapshot; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; + code?: TournamentCodeDocument; + }): Promise { + let competition = params.initialCompetition; + for (let attempt = 1; attempt <= RESULT_ACCEPT_ATTEMPTS; attempt += 1) { + if (hasAcceptedRiotMatch(competition, params.detail.metadata.matchId)) { + return { kind: 'duplicate', competition }; } - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: match.resultPollState?.lastPolledAt, - lastPollOutcome: match.resultPollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: - match.resultPollState?.expandedToAllPuuids ?? false, - state: 'complete', - }; - await match.save(); - await this.rebuildMatchStatsSafe(match); + + const declaredCode = + params.code ?? + (await this.findDeclaredTournamentCode(params.match, params.detail)); + const target = declaredCode + ? await this.resolveCodeTarget(competition, declaredCode) + : undefined; + const mapped = target + ? mapRiotGameToCompetitionSlot({ + competition, + target, + detail: params.detail, + lookup: params.lookup, + }) + : declaredCode + ? null + : resolveReadyCompetitionSlot({ + competition, + detail: params.detail, + lookup: params.lookup, + }); + if (!mapped) return { kind: 'unmatched', competition }; + + const manualCode = + declaredCode ?? + (await this.findCodeForMappedSlot(params.match, mapped)); + if (manualCode && !params.code) { + await this.ensureCodeAssignment(competition, manualCode, { + id: mapped.gameSlotId, + seriesId: mapped.seriesId, + ordinal: mapped.ordinal, + displayNumber: mapped.displayNumber, + }); + } + + try { + const result = await this.competitionCommandService.acceptGame({ + competitionId: objectId(competition.competitionId, 'Competition'), + expectedRevision: competition.revision, + idempotencyKey: `riot-result:${params.detail.metadata.matchId}`, + actor: { type: 'system' }, + occurredAt: mapped.occurredAt, + gameId: objectId(mapped.gameId, 'Game'), + seriesId: objectId(mapped.seriesId, 'Series'), + gameSlotId: objectId(mapped.gameSlotId, 'GameSlot'), + ordinal: mapped.ordinal, + evidence: mapped.evidence, + mapping: mapped.mapping, + startedAt: mapped.startedAt, + durationSeconds: mapped.durationSeconds, + participants: mapped.normalizedParticipants, + ...(manualCode + ? { + tournamentCode: { + tournamentCodeId: manualCode._id, + riotMatchId: params.detail.metadata.matchId, + }, + } + : {}), + }); + competition = competitionSnapshot(result.competition); + competition = await this.provisionCompetitionAssignments( + params.match, + competition, + ); + if (!result.replayed) { + await this.rebuildMatchStatsSafe(params.match, result.revision); + } + return { + kind: 'accepted', + displayNumber: mapped.displayNumber, + competition, + }; + } catch (error) { + if (attempt < RESULT_ACCEPT_ATTEMPTS && isStaleRevision(error)) { + competition = await this.loadCompetition(competition.competitionId); + continue; + } + throw error; + } + } + return { kind: 'unmatched', competition }; + } + + private async resolveCodeTarget( + competition: CompetitionResultSnapshot, + code: TournamentCodeDocument, + ): Promise { + const AssignmentModel = await this.connectionService.getModel( + 'tournamentCodeAssignment', + ); + const existing = (await AssignmentModel.findOne({ + competitionId: objectId(competition.competitionId, 'Competition'), + tournamentCodeId: code._id, + }) + .lean() + .exec()) as CodeAssignmentRecord | null; + if (existing) { + if (existing.state !== 'reserved') return undefined; + return competition.projection.gameSlots.find( + (slot) => + slot.id === existing.gameSlotId.toString() && slot.status === 'ready', + ); + } + + if (!code.gameNumber) return undefined; + const target = competition.projection.gameSlots.find( + (slot) => + slot.displayNumber === code.gameNumber && slot.status === 'ready', + ); + if (!target) return undefined; + await this.ensureCodeAssignment(competition, code, target); + return target; + } + + private async ensureCodeAssignment( + competition: CompetitionResultSnapshot, + code: TournamentCodeDocument, + target: Pick< + CompetitionResultGameSlotProjection, + 'id' | 'seriesId' | 'ordinal' | 'displayNumber' + >, + ): Promise { + const AssignmentModel = await this.connectionService.getModel( + 'tournamentCodeAssignment', + ); + const competitionId = objectId(competition.competitionId, 'Competition'); + const seriesId = objectId(target.seriesId, 'Series'); + const gameSlotId = objectId(target.id, 'GameSlot'); + const commandId = `cutover-assignment:${code._id.toString()}:${target.id}:${competition.revision}`; + await AssignmentModel.updateOne( + { + competitionId, + tournamentCodeId: code._id, + state: { $in: ['reserved', 'used'] }, + }, + { + $setOnInsert: { + _id: deterministicObjectId(commandId), + competitionId, + seriesId, + gameSlotId, + tournamentCodeId: code._id, + state: 'reserved', + reservedAt: code.reservedAt ?? new Date(), + commandId, + }, + }, + { upsert: true }, + ).exec(); + } + + private async findDeclaredTournamentCode( + match: MatchDocument, + detail: RiotMatchDto, + ): Promise { + const tournamentCode = detail.info.tournamentCode?.trim(); + if (!tournamentCode) return undefined; + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const code = await TournamentCodeModel.findOne({ + matchId: match._id, + state: 'reserved', + code: tournamentCode, + }).exec(); + return code ?? undefined; + } + + private async findCodeForMappedSlot( + match: MatchDocument, + mapped: MappedCompetitionRiotGame, + ): Promise { + if (match.tournamentCodeIds.length === 0) return undefined; + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const code = await TournamentCodeModel.findOne({ + _id: { $in: match.tournamentCodeIds }, + matchId: match._id, + state: 'reserved', + gameNumber: mapped.displayNumber, + }).exec(); + return code ?? undefined; + } + + private async ensureCompetition( + match: MatchDocument, + ): Promise { + const document = await this.competitionBootstrapService.bootstrap( + match as unknown as CompetitionBootstrapMatch, + ); + const snapshot = competitionSnapshot(document); + match.competitionId = objectId(snapshot.competitionId, 'Competition'); + return snapshot; + } + + private async provisionCompetitionAssignments( + match: MatchDocument, + competition: CompetitionResultSnapshot, + ): Promise { + try { + await this.competitionAssignmentProvisioner.provisionReadyAssignments({ + matchId: match._id, + competition, + }); + return competition; + } catch (error) { + if (!isAssignmentStaleRevision(error)) throw error; + const current = await this.loadCompetition(competition.competitionId); + await this.competitionAssignmentProvisioner.provisionReadyAssignments({ + matchId: match._id, + competition: current, + }); + return current; + } + } + + private async loadCompetition( + competitionId: string, + ): Promise { + const CompetitionModel = + await this.connectionService.getModel('competition'); + const competition = await CompetitionModel.findById(competitionId) + .lean() + .exec(); + if (!competition) throw new NotFoundException('Competition not found.'); + return competitionSnapshot(competition); + } + + private async syncMatchLifecycle( + match: MatchDocument, + competition: CompetitionResultSnapshot, + ): Promise { + if (competition.projection.phase === 'completed') { + match.status = 'finished'; + if (match.resultPollState) match.resultPollState.state = 'complete'; + } else if ( + (competition.projection.phase === 'running' && + match.status === 'team-built') || + match.status === 'finished' + ) { + match.status = 'in-progress'; + } + if (match.resultPollState) { + match.resultPollState.matchedCount = competition.projection.games.length; + } + await match.save(); + if (competition.projection.phase === 'completed') { void this.communityStatsService .invalidateCommunity(match.communityId) .catch((error) => { this.logger.warn( - `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ - error instanceof Error ? error.message : error - }`, + `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${errorMessage(error)}`, ); }); - return true; } - - if (codes.length < this.resolveRequiredGameSlots(match)) return false; - if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { - return false; - } - - match.status = 'finished'; - if (match.result) { - match.result.winnerTeamIndex = this.resolveMatchWinnerTeamIndex( - match.result.seriesResults ?? [], - ); - } - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: match.resultPollState?.lastPolledAt, - lastPollOutcome: match.resultPollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, - state: 'complete', - }; - await match.save(); - await this.rebuildMatchStatsSafe(match); - void this.communityStatsService - .invalidateCommunity(match.communityId) - .catch((error) => { - this.logger.warn( - `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ - error instanceof Error ? error.message : error - }`, - ); - }); - return true; } - private async scheduleNextPoll( + private async rebuildMatchStatsSafe( match: MatchDocument, - job: PollTournamentResultJob, + sourceRevision: number, ): Promise { - const pollState = match.resultPollState; - const startedAt = pollState?.startedAt ?? new Date(); - const elapsedMs = Date.now() - startedAt.getTime(); - const delayMs = this.nextPollDelayMs(elapsedMs); - if (delayMs === null) { - match.resultPollState = { - startedAt, - lastPolledAt: pollState?.lastPolledAt, - lastPollOutcome: pollState?.lastPollOutcome, - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: - pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, - state: 'expired', - }; - await match.save(); + try { + await this.matchStatsService.buildAndUpsert(match._id, { + sourceRevision, + }); + } catch (error) { this.logger.warn( - `Tournament result polling expired for match ${match._id.toString()}.`, + `Failed to rebuild match stats for ${match._id.toString()} at Competition revision ${sourceRevision}: ${errorMessage(error)}`, ); - return; } - - const expandedToAllPuuids = - job.expandedToAllPuuids || - (elapsedMs >= EXPAND_AFTER_MS && - (match.result?.games?.length ?? 0) === 0); - await this.riotJobQueueService.enqueueTournamentResultPoll({ - matchId: match._id.toString(), - attempt: job.attempt + 1, - expandedToAllPuuids, - priority: 'low', - deferUntilMs: Date.now() + delayMs, - }); } private async ensureRiotMatchPersisted( @@ -631,11 +762,7 @@ export class TournamentResultService { try { details.push(await this.ensureRiotMatchPersisted(riotMatchId, region)); } catch (error) { - this.logger.warn( - `${logPrefix} ${riotMatchId}: ${ - error instanceof Error ? error.message : error - }`, - ); + this.logger.warn(`${logPrefix} ${riotMatchId}: ${errorMessage(error)}`); } } return details; @@ -646,11 +773,9 @@ export class TournamentResultService { ): Promise { const puuidByUserId = new Map(); const userIdByPuuid = new Map(); - for (const participant of match.participants) { if (!participant.puuid) continue; - const userId = participant.userId.toString(); - puuidByUserId.set(userId, participant.puuid); + puuidByUserId.set(participant.userId.toString(), participant.puuid); userIdByPuuid.set(participant.puuid, participant.userId); } @@ -671,7 +796,6 @@ export class TournamentResultService { userIdByPuuid.set(primary.puuid, user._id); } } - return { puuidByUserId, userIdByPuuid }; } @@ -681,548 +805,72 @@ export class TournamentResultService { ): string[] { return [ ...new Set( - userIds - .map((userId) => lookup.puuidByUserId.get(userId.toString())) - .filter((puuid): puuid is string => Boolean(puuid)), + userIds.flatMap((userId) => { + const puuid = lookup.puuidByUserId.get(userId.toString()); + return puuid ? [puuid] : []; + }), ), ]; } - private upsertGameResult( - match: MatchDocument, - gameResult: MatchGameResult, - ): void { - const currentGames = match.result?.games ?? []; - const games = [ - ...currentGames.filter( - (game) => - game.gameNumber !== gameResult.gameNumber && - game.riotMatchId !== gameResult.riotMatchId, - ), - gameResult, - ].sort((left, right) => left.gameNumber - right.gameNumber); - const seriesResults = this.buildSeriesResults(games); - - match.result = { - winnerTeamIndex: - (match.gameMode ?? 'pair') === 'double-elimination' - ? match.doubleElimination?.placements.firstTeamIndex - : this.resolveMatchWinnerTeamIndex(seriesResults), - mvpUserId: match.result?.mvpUserId, - riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], - games, - seriesResults, - }; - } - - private computeManualGameResult( - match: MatchDocument, - detail: RiotMatchDto, - lookup: MatchPuuidLookup, - ): MatchGameResult | null { - for (const assignment of this.resolveOpenManualGameAssignments(match)) { - const gameResult = computeGameResult({ - match, - detail, - gameNumber: assignment.gameNumber, - lookup, - teamAIndex: assignment.teamAIndex, - teamBIndex: assignment.teamBIndex, - }); - if (gameResult) { - gameResult.bracketMatchId = assignment.bracketMatchId; - return gameResult; - } - } - return null; - } - - private resolveOpenManualGameAssignments( - match: MatchDocument, - ): ManualGameAssignment[] { - const usedGameNumbers = new Set( - (match.result?.games ?? []).map((game) => game.gameNumber), - ); - const assignments: ManualGameAssignment[] = []; - if ((match.gameMode ?? 'pair') === 'double-elimination') { - for (const slot of buildDoubleEliminationGameSlots( - match.doubleElimination?.bracketMatches ?? [], - )) { - const bracketMatch = slot.bracketMatch; - if (bracketMatch.state !== 'ready') continue; - if (usedGameNumbers.has(slot.gameNumber)) continue; - if (!bracketMatch.teamAIndex || !bracketMatch.teamBIndex) continue; - assignments.push({ - gameNumber: slot.gameNumber, - bracketMatchId: bracketMatch.bracketMatchId, - teamAIndex: bracketMatch.teamAIndex, - teamBIndex: bracketMatch.teamBIndex, - }); - } - return assignments; - } - const requiredSlots = this.resolveRequiredGameSlots(match); - - for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { - if (usedGameNumbers.has(gameNumber)) continue; - assignments.push({ - gameNumber, - ...this.resolveSeriesRefForGameNumber(match, gameNumber), - }); - } - return assignments; - } - - private hasResultForRiotMatch( - match: MatchDocument, - riotMatchId: string, - ): boolean { - return Boolean( - match.result?.games?.some((game) => game.riotMatchId === riotMatchId), - ); - } - - private hasAllRequiredGameResults(match: MatchDocument): boolean { - if ((match.gameMode ?? 'pair') === 'double-elimination') { - return this.isDoubleEliminationComplete(match); - } - const requiredSlots = this.resolveRequiredGameSlots(match); - if (requiredSlots <= 0) return false; - const resultGameNumbers = new Set( - (match.result?.games ?? []).map((game) => game.gameNumber), - ); - for (let gameNumber = 1; gameNumber <= requiredSlots; gameNumber += 1) { - if (!resultGameNumbers.has(gameNumber)) return false; - } - return true; - } - - private updateManualCollectionState( - match: MatchDocument, - matchedCount: number, - ): void { - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: new Date(), - lastPollOutcome: matchedCount > 0 ? 'matched' : 'not-found', - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: true, - state: 'polling', - }; - } - - private async finishMatchFromManualResults( - match: MatchDocument, - ): Promise { - match.status = 'finished'; - if (match.result) { - match.result.winnerTeamIndex = - (match.gameMode ?? 'pair') === 'double-elimination' - ? match.doubleElimination?.placements.firstTeamIndex - : this.resolveMatchWinnerTeamIndex(match.result.seriesResults ?? []); - } - match.resultPollState = { - startedAt: match.resultPollState?.startedAt ?? new Date(), - lastPolledAt: new Date(), - lastPollOutcome: 'matched', - matchedCount: match.result?.games?.length ?? 0, - expandedToAllPuuids: true, - state: 'complete', - }; - await match.save(); - await this.rebuildMatchStatsSafe(match); - void this.communityStatsService - .invalidateCommunity(match.communityId) - .catch((error) => { - this.logger.warn( - `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ - error instanceof Error ? error.message : error - }`, - ); - }); - } - - private async rebuildMatchStatsSafe(match: MatchDocument): Promise { - try { - await this.matchStatsService.buildAndUpsert(match._id); - } catch (error) { - this.logger.warn( - `Failed to rebuild match stats for ${match._id.toString()}: ${ - error instanceof Error ? error.message : error - }`, - ); - } - } - - private advanceDoubleEliminationIfNeeded( - match: MatchDocument, - gameResult: MatchGameResult, - completedBy: 'riot-result' | 'walkover', - ): string | undefined { - if ((match.gameMode ?? 'pair') !== 'double-elimination') return undefined; - if (!match.doubleElimination || !gameResult.bracketMatchId) - return undefined; - const bracketMatch = match.doubleElimination.bracketMatches.find( - (entry) => entry.bracketMatchId === gameResult.bracketMatchId, - ); - if (!bracketMatch || bracketMatch.state !== 'ready') return undefined; - const seriesResult = match.result?.seriesResults?.find( - (entry) => entry.bracketMatchId === gameResult.bracketMatchId, - ); - const winnerTeamIndex = resolveDoubleEliminationSeriesWinner( - seriesResult, - bracketMatch, - ); - if (!winnerTeamIndex) return undefined; - match.doubleElimination = completeDoubleEliminationBracketMatch( - match.doubleElimination, - { - bracketMatchId: gameResult.bracketMatchId, - winnerTeamIndex, - completedBy, - completedAt: new Date(gameResult.gameCreation), - }, - ); - if (match.result && this.isDoubleEliminationComplete(match)) { - match.result.winnerTeamIndex = - match.doubleElimination!.placements.firstTeamIndex; - } - match.markModified?.('doubleElimination'); - return gameResult.bracketMatchId; - } - - private isDoubleEliminationComplete(match: MatchDocument): boolean { - const placements = match.doubleElimination?.placements; - return Boolean( - placements?.firstTeamIndex && - placements.secondTeamIndex && - placements.thirdTeamIndex, - ); - } - - private async reserveReadyDoubleEliminationCodes( - match: MatchDocument, - ): Promise { - await this.distributedLockService.runWithLock( - { - lockKey: this.tournamentResultReadyCodeReservationLockKey( - match._id.toString(), - ), - lockExpirationDurationMilliseconds: - TOURNAMENT_RESULT_READY_CODE_RESERVATION_LOCK_EXPIRATION_DURATION_MILLISECONDS, - }, - async () => this.reserveReadyDoubleEliminationCodesWhileLockOwned(match), - ); - } - - private async reserveReadyDoubleEliminationCodesWhileLockOwned( - match: MatchDocument, - ): Promise { - if ((match.gameMode ?? 'pair') !== 'double-elimination') return; - const readySlots = buildDoubleEliminationGameSlots( - match.doubleElimination?.bracketMatches ?? [], - ).filter((slot) => slot.bracketMatch.state === 'ready'); - if (readySlots.length === 0) return; - - const MatchModel = await this.connectionService.getModel('match'); - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - const existingCodes = - match.tournamentCodeIds.length > 0 - ? await TournamentCodeModel.find({ - _id: { $in: match.tournamentCodeIds }, - }).exec() - : []; - const existingByGameNumber = new Map( - existingCodes - .filter( - (code) => - typeof code.gameNumber === 'number' && - (code.state === 'reserved' || code.state === 'used'), - ) - .map((code) => [code.gameNumber as number, code]), - ); - const reservedIds: mongoose.Types.ObjectId[] = []; - const expiresAfter = new Date( - Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, - ); - - for (const slot of readySlots) { - if (existingByGameNumber.has(slot.gameNumber)) continue; - const code = await TournamentCodeModel.findOneAndUpdate( - { - state: 'available', - region: 'kr', - mapType: 'SUMMONERS_RIFT', - teamSize: 5, - expiresAt: { $gt: expiresAfter }, - }, - { - $set: { - state: 'reserved', - matchId: match._id, - gameNumber: slot.gameNumber, - bracketMatchId: slot.bracketMatch.bracketMatchId, - reservedAt: new Date(), - }, - $unset: { releasedAt: 1 }, - }, - { sort: { expiresAt: 1 }, returnDocument: 'after' }, - ).exec(); - if (!code) break; - reservedIds.push(code._id); - } - - if (reservedIds.length === 0) return; - await MatchModel.updateOne( - { _id: match._id }, - { $addToSet: { tournamentCodeIds: { $each: reservedIds } } }, - ).exec(); - const existingTournamentCodeIds = new Set( - match.tournamentCodeIds.map((tournamentCodeId) => - tournamentCodeId.toString(), - ), - ); - for (const reservedId of reservedIds) { - if (existingTournamentCodeIds.has(reservedId.toString())) continue; - match.tournamentCodeIds.push(reservedId); - } - } - - private async markTournamentCodeUsedForManualResult( - match: MatchDocument, - gameResult: MatchGameResult, - detail: RiotMatchDto, - ): Promise { - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - await TournamentCodeModel.updateOne( - { - matchId: match._id, - gameNumber: gameResult.gameNumber, - ...(gameResult.bracketMatchId - ? { bracketMatchId: gameResult.bracketMatchId } - : {}), - state: { $in: ['reserved', 'released'] }, - }, - { - $set: { - state: 'used', - usedAt: new Date( - detail.info.gameEndTimestamp ?? detail.info.gameCreation, - ), - riotMatchId: detail.metadata.matchId, - ...(gameResult.bracketMatchId - ? { bracketMatchId: gameResult.bracketMatchId } - : {}), - }, - }, - ).exec(); - } - - private async releaseUnusedReservedDoubleEliminationCodes( - match: MatchDocument, - bracketMatchId: string, - ): Promise { - const ids = match.tournamentCodeIds ?? []; - if (ids.length === 0) return; - const usedGameNumbers = new Set( - (match.result?.games ?? []) - .filter((game) => game.bracketMatchId === bracketMatchId) - .map((game) => game.gameNumber), - ); - const TournamentCodeModel = - await this.connectionService.getModel('tournamentCode'); - const codes = await TournamentCodeModel.find({ - _id: { $in: ids }, - matchId: match._id, - bracketMatchId, - state: 'reserved', - gameNumber: { $nin: [...usedGameNumbers] }, - }).exec(); - if (codes.length === 0) return; - const releasedIds = codes.map((code) => code._id.toString()); - await TournamentCodeModel.updateMany( - { _id: { $in: codes.map((code) => code._id) } }, - { - $set: { state: 'released', releasedAt: new Date() }, - $unset: { - matchId: 1, - gameNumber: 1, - bracketMatchId: 1, - reservedAt: 1, - }, - }, - ).exec(); - match.tournamentCodeIds = ids.filter( - (id) => !releasedIds.includes(id.toString()), - ); - } - - private buildSeriesResults( - games: MatchGameResult[], - ): NonNullable['seriesResults'] { - const bySeries = new Map(); - - for (const game of games) { - const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex); - const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex); - const key = game.bracketMatchId ?? `${teamAIndex}:${teamBIndex}`; - const current = bySeries.get(key) ?? { - bracketMatchId: game.bracketMatchId, - teamAIndex, - teamBIndex, - teamAWins: 0, - teamBWins: 0, - }; - if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1; - if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1; - current.winnerTeamIndex = - current.teamAWins > current.teamBWins - ? teamAIndex - : current.teamBWins > current.teamAWins - ? teamBIndex - : undefined; - bySeries.set(key, current); - } - - return [...bySeries.values()].sort( - (left, right) => - (left.bracketMatchId ?? '').localeCompare(right.bracketMatchId ?? '') || - left.teamAIndex - right.teamAIndex || - left.teamBIndex - right.teamBIndex, - ); - } - - private resolveSeriesRefForGameNumber( - match: MatchDocument, - gameNumber: number, - ): { teamAIndex: number; teamBIndex: number } { - const gameMode = match.gameMode ?? 'pair'; - - if (gameMode === 'double-elimination') { - const slot = this.resolveDoubleEliminationGameSlotByGameNumber( - match, - gameNumber, - ); - return slot - ? { - teamAIndex: slot.bracketMatch.teamAIndex ?? 1, - teamBIndex: slot.bracketMatch.teamBIndex ?? 2, - } - : { - teamAIndex: 1, - teamBIndex: 2, - }; - } - - if (gameMode === 'round-robin') { - const persisted = match.gameSchedule?.find( - (entry) => entry.gameNumber === gameNumber, - ); - if (persisted) { - return { - teamAIndex: persisted.teamAIndex, - teamBIndex: persisted.teamBIndex, - }; - } - - const fallback = this.buildRoundRobinGameSchedule(match).find( - (entry) => entry.gameNumber === gameNumber, - ); - return fallback - ? { - teamAIndex: fallback.teamAIndex, - teamBIndex: fallback.teamBIndex, - } - : { - teamAIndex: 1, - teamBIndex: 2, - }; - } - - const perSeries = match.gameCount || 1; - const seriesIndex = Math.max(1, Math.ceil(gameNumber / perSeries)); - return { - teamAIndex: (seriesIndex - 1) * 2 + 1, - teamBIndex: (seriesIndex - 1) * 2 + 2, - }; - } - - private resolveDoubleEliminationGameSlotByGameNumber( - match: MatchDocument, - gameNumber: number, - ): DoubleEliminationGameSlot | undefined { - return buildDoubleEliminationGameSlots( - match.doubleElimination?.bracketMatches ?? [], - ).find((slot) => slot.gameNumber === gameNumber); - } - - private resolveRequiredGameSlots(match: MatchDocument): number { - const gameMode = match.gameMode ?? 'pair'; - if (gameMode === 'double-elimination') { - return buildDoubleEliminationGameSlots( - match.doubleElimination?.bracketMatches ?? [], - ).length; - } - if (gameMode === 'round-robin') { - if ((match.gameSchedule?.length ?? 0) > 0) { - return match.gameSchedule.length; - } - return this.buildRoundRobinGameSchedule(match).length; - } - - const activeParticipantCount = match.participants.filter( - (participant) => !participant.excluded, - ).length; - const participantSeriesCount = Math.floor(activeParticipantCount / 10); - const teamSeriesCount = Math.ceil(match.teams.length / 2); - const seriesCount = Math.max(1, participantSeriesCount, teamSeriesCount); - return seriesCount * (match.gameCount || 1); - } - - private buildRoundRobinGameSchedule(match: MatchDocument) { - return roundRobinGameSchedule(resolveRoundRobinTeamCount(match), { - gamesPerPair: match.gameCount || 1, - maxRounds: match.roundRobinMaxRounds, - }); - } - - private resolveMatchWinnerTeamIndex( - seriesResults: NonNullable['seriesResults'], - ): number | undefined { - const winsByTeam = new Map(); - for (const series of seriesResults ?? []) { - if (!series.winnerTeamIndex) continue; - winsByTeam.set( - series.winnerTeamIndex, - (winsByTeam.get(series.winnerTeamIndex) ?? 0) + 1, - ); - } - const sorted = [...winsByTeam.entries()].sort( - (left, right) => right[1] - left[1], - ); - if (sorted.length === 0) return undefined; - if (sorted.length > 1 && sorted[0][1] === sorted[1][1]) return undefined; - return sorted[0][0]; - } - private async updatePollState( match: MatchDocument, outcome: 'matched' | 'not-found' | 'failed', expandedToAllPuuids: boolean, + competition?: CompetitionResultSnapshot, ): Promise { match.resultPollState = { startedAt: match.resultPollState?.startedAt ?? new Date(), lastPolledAt: new Date(), lastPollOutcome: outcome, - matchedCount: match.result?.games?.length ?? 0, + matchedCount: + competition?.projection.games.length ?? + match.resultPollState?.matchedCount ?? + 0, expandedToAllPuuids, state: outcome === 'failed' ? 'failed' : 'polling', }; await match.save(); } + private async scheduleNextPoll( + match: MatchDocument, + competition: CompetitionResultSnapshot, + job: PollTournamentResultJob, + ): Promise { + const pollState = match.resultPollState; + const startedAt = pollState?.startedAt ?? new Date(); + const elapsedMs = Date.now() - startedAt.getTime(); + const delayMs = this.nextPollDelayMs(elapsedMs); + if (delayMs === null) { + match.resultPollState = { + startedAt, + lastPolledAt: pollState?.lastPolledAt, + lastPollOutcome: pollState?.lastPollOutcome, + matchedCount: competition.projection.games.length, + expandedToAllPuuids: + pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, + state: 'expired', + }; + await match.save(); + this.logger.warn( + `Tournament result polling expired for match ${match._id.toString()}.`, + ); + return; + } + const expandedToAllPuuids = + job.expandedToAllPuuids || + (elapsedMs >= EXPAND_AFTER_MS && + competition.projection.games.length === 0); + await this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: job.attempt + 1, + expandedToAllPuuids, + priority: 'low', + deferUntilMs: Date.now() + delayMs, + }); + } + private nextPollDelayMs(elapsedMs: number): number | null { if (elapsedMs >= POLL_EXPIRY_MS) return null; if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS; @@ -1232,18 +880,13 @@ export class TournamentResultService { private resolveStartTime(match: MatchDocument): number { return Math.max( 0, - Math.floor(match.teamBuiltAt!.getTime() / 1000) - + Math.floor(match.teamBuiltAt!.getTime() / 1_000) - TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, ); } private isReadyToPoll(match: MatchDocument): boolean { - return Boolean( - match.teamBuiltAt && - match.tournamentCodeIds.length > 0 && - match.teams.length >= 2 && - match.teams.every((team) => team.members.length > 0), - ); + return this.hasBuiltTeams(match); } private assertManualCollectionAllowed( @@ -1304,12 +947,102 @@ export class TournamentResultService { ): string { return `distributed-lock:tournament-result:process-poll-job:match:${matchIdentifier}`; } +} - private tournamentResultReadyCodeReservationLockKey( - matchIdentifier: string, - ): string { - return `distributed-lock:tournament-result:reserve-ready-double-elimination-codes:match:${matchIdentifier}`; +function competitionSnapshot(value: unknown): CompetitionResultSnapshot { + const raw = + value && typeof value === 'object' && 'toObject' in value + ? ((value as CompetitionPersistenceDocument).toObject?.() ?? value) + : value; + if (!isRecord(raw)) throw new Error('Competition snapshot is missing.'); + const projection = raw.projection; + if (!isRecord(projection)) + throw new Error('Competition projection is missing.'); + const competitionId = idString(raw._id); + const revision = raw.revision; + if (!competitionId || typeof revision !== 'number') { + throw new Error('Competition identity or revision is invalid.'); } + return { + competitionId, + revision, + phase: String(raw.phase) as CompetitionResultSnapshot['phase'], + teams: asArray(raw.teams).map((team) => ({ + teamId: idString(asRecord(team).teamId), + members: asArray(asRecord(team).members).map((member) => ({ + userId: idString(asRecord(member).userId), + })), + })), + projection: { + phase: String( + projection.phase, + ) as CompetitionResultSnapshot['projection']['phase'], + series: asArray(projection.series).map((series) => { + const record = asRecord(series); + return { + seriesId: idString(record.seriesId), + status: String( + record.status, + ) as CompetitionResultSnapshot['projection']['series'][number]['status'], + entries: asArray(record.entries).map((entry) => { + const row = asRecord(entry); + return { + slot: String(row.slot) as 'A' | 'B', + teamId: row.teamId == null ? null : idString(row.teamId), + gameWins: typeof row.gameWins === 'number' ? row.gameWins : 0, + }; + }), + }; + }), + gameSlots: asArray(projection.gameSlots).map((slot) => { + const record = asRecord(slot); + return { + id: idString(record.id), + seriesId: idString(record.seriesId), + ordinal: Number(record.ordinal), + displayNumber: Number(record.displayNumber), + status: String( + record.status, + ) as CompetitionResultGameSlotProjection['status'], + }; + }), + games: asArray(projection.games).map((game) => { + const evidence = asRecord(asRecord(game).evidence); + return { + evidence: { + type: typeof evidence.type === 'string' ? evidence.type : undefined, + riotMatchId: + typeof evidence.riotMatchId === 'string' + ? evidence.riotMatchId + : undefined, + }, + }; + }), + }, + }; +} + +function objectId(value: string, label: string): mongoose.Types.ObjectId { + if (!mongoose.Types.ObjectId.isValid(value)) { + throw new Error(`${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), + ); +} + +function isStaleRevision(error: unknown): boolean { + return isRecord(error) && error.code === 'STALE_COMPETITION_REVISION'; +} + +function isAssignmentStaleRevision(error: unknown): boolean { + return ( + isRecord(error) && error.code === 'COMPETITION_ASSIGNMENT_STALE_REVISION' + ); } function isRiotMatchDto(value: unknown): value is RiotMatchDto { @@ -1320,3 +1053,28 @@ function isRiotMatchDto(value: unknown): value is RiotMatchDto { 'info' in value, ); } + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +function asRecord(value: unknown): Record { + return isRecord(value) ? value : {}; +} + +function asArray(value: unknown): unknown[] { + return Array.isArray(value) ? value : []; +} + +function idString(value: unknown): string { + if (value instanceof mongoose.Types.ObjectId) return value.toString(); + if (typeof value === 'string') return value; + if (typeof value === 'number' || typeof value === 'bigint') { + return String(value); + } + return ''; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts index 687b9910..9669827f 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.types.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -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; -}