640 lines
19 KiB
TypeScript
640 lines
19 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
import { Injectable } from '@nestjs/common';
|
|
import mongoose, { Types } from 'mongoose';
|
|
import { ConnectionService } from '../global/database/connection.service';
|
|
import type {
|
|
MatchGameMode,
|
|
MatchParticipant,
|
|
MatchStatus,
|
|
MatchTeam,
|
|
} from '../global/database/schema';
|
|
import type {
|
|
CompetitionDocument,
|
|
CompetitionTeamSnapshot,
|
|
} from './competition.schema';
|
|
import {
|
|
generateSeriesGraph,
|
|
type CompetitionGraphFormat,
|
|
type CompetitionGraphTeam,
|
|
type SeriesDefinition,
|
|
} from './domain/series-graph';
|
|
import {
|
|
projectCompetition,
|
|
type CompetitionProjection,
|
|
} from './domain/competition-projector';
|
|
|
|
const COMPETITION_SCHEMA_VERSION = 1;
|
|
const COMPETITION_PROJECTOR_VERSION = 1;
|
|
const BOOTSTRAP_TRANSACTION_ATTEMPTS = 3;
|
|
|
|
export interface CompetitionBootstrapMatch {
|
|
_id: Types.ObjectId;
|
|
communityId: Types.ObjectId;
|
|
competitionId?: Types.ObjectId;
|
|
status: MatchStatus;
|
|
teamBuiltAt: Date;
|
|
gameCount: number;
|
|
gameMode: MatchGameMode;
|
|
roundRobinMaxRounds?: number;
|
|
participants: MatchParticipant[];
|
|
teams: MatchTeam[];
|
|
doubleElimination?: {
|
|
teamCount: 4 | 8;
|
|
resetFinalEnabled: boolean;
|
|
seeds: Array<{ seedNumber: number; teamIndex: number }>;
|
|
};
|
|
}
|
|
|
|
export interface CompetitionBootstrapOptions {
|
|
/** `bracket` is accepted only by the explicit legacy migration path. */
|
|
source?: 'live' | 'legacy-migration';
|
|
}
|
|
|
|
export type CompetitionBootstrapErrorCode =
|
|
| 'INVALID_MATCH_TEAM_SNAPSHOT'
|
|
| 'INVALID_MATCH_FORMAT'
|
|
| 'UNSUPPORTED_LIVE_MATCH_MODE'
|
|
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
|
|
| 'COMPETITION_BOOTSTRAP_FAILED'
|
|
| 'COMPETITION_BOOTSTRAP_RACE'
|
|
| 'MATCH_COMPETITION_LINK_CONFLICT';
|
|
|
|
export class CompetitionBootstrapError extends Error {
|
|
constructor(
|
|
public readonly code: CompetitionBootstrapErrorCode,
|
|
message: string,
|
|
public readonly httpStatus: 409 | 422 | 500,
|
|
public readonly details?: Readonly<Record<string, unknown>>,
|
|
) {
|
|
super(message);
|
|
this.name = 'CompetitionBootstrapError';
|
|
}
|
|
}
|
|
|
|
interface CompetitionInsertPayload {
|
|
_id: Types.ObjectId;
|
|
matchId: Types.ObjectId;
|
|
communityId: Types.ObjectId;
|
|
schemaVersion: number;
|
|
projectorVersion: number;
|
|
revision: number;
|
|
phase: CompetitionProjection['phase'];
|
|
teams: CompetitionTeamSnapshot[];
|
|
format: CompetitionGraphFormat;
|
|
seriesGraph: SeriesDefinition[];
|
|
projection: CompetitionProjection;
|
|
}
|
|
|
|
/**
|
|
* Freezes the recruiting Match into the one-to-one Competition aggregate.
|
|
* Retries only repeat deterministic upserts, so duplicate creators and unknown
|
|
* commit outcomes converge without replacing an existing immutable snapshot.
|
|
*/
|
|
@Injectable()
|
|
export class CompetitionBootstrapService {
|
|
constructor(private readonly connectionService: ConnectionService) {}
|
|
|
|
public async bootstrap(
|
|
match: CompetitionBootstrapMatch,
|
|
options: CompetitionBootstrapOptions = {},
|
|
): Promise<CompetitionDocument> {
|
|
const payload = buildCompetitionInsertPayload(
|
|
match,
|
|
options.source ?? 'live',
|
|
);
|
|
const [CompetitionModel, MatchModel] = await Promise.all([
|
|
this.connectionService.getModel('competition'),
|
|
this.connectionService.getModel('match'),
|
|
]);
|
|
|
|
let lastRetryableError: unknown;
|
|
for (
|
|
let attempt = 1;
|
|
attempt <= BOOTSTRAP_TRANSACTION_ATTEMPTS;
|
|
attempt += 1
|
|
) {
|
|
const session = await this.connectionService.createSession();
|
|
if (!session) {
|
|
throw new CompetitionBootstrapError(
|
|
'COMPETITION_TRANSACTION_UNAVAILABLE',
|
|
'A MongoDB transaction is required to bootstrap a Competition.',
|
|
500,
|
|
);
|
|
}
|
|
|
|
try {
|
|
session.startTransaction();
|
|
const competition = await CompetitionModel.findOneAndUpdate(
|
|
{ matchId: match._id },
|
|
{ $setOnInsert: payload },
|
|
{
|
|
upsert: true,
|
|
returnDocument: 'after',
|
|
setDefaultsOnInsert: true,
|
|
session,
|
|
},
|
|
).exec();
|
|
if (!competition) {
|
|
throw new CompetitionBootstrapError(
|
|
'COMPETITION_BOOTSTRAP_FAILED',
|
|
'Competition upsert returned no document.',
|
|
500,
|
|
);
|
|
}
|
|
|
|
const linkResult = await MatchModel.updateOne(
|
|
{
|
|
_id: match._id,
|
|
status: match.status,
|
|
teamBuiltAt: match.teamBuiltAt,
|
|
$or: [
|
|
{ competitionId: { $exists: false } },
|
|
{ competitionId: null },
|
|
{ competitionId: competition._id },
|
|
],
|
|
},
|
|
{ $set: { competitionId: competition._id } },
|
|
{ session },
|
|
);
|
|
if (linkResult.matchedCount !== 1) {
|
|
throw new CompetitionBootstrapError(
|
|
'MATCH_COMPETITION_LINK_CONFLICT',
|
|
'Match is missing or linked to a different Competition.',
|
|
409,
|
|
{ matchId: match._id.toString() },
|
|
);
|
|
}
|
|
|
|
await session.commitTransaction();
|
|
return competition;
|
|
} catch (error) {
|
|
await session.abortTransaction().catch(() => undefined);
|
|
if (
|
|
attempt < BOOTSTRAP_TRANSACTION_ATTEMPTS &&
|
|
isRetryableBootstrapError(error)
|
|
) {
|
|
lastRetryableError = error;
|
|
continue;
|
|
}
|
|
if (isRetryableBootstrapError(error)) {
|
|
throw new CompetitionBootstrapError(
|
|
'COMPETITION_BOOTSTRAP_RACE',
|
|
'Competition bootstrap did not converge after concurrent writes.',
|
|
409,
|
|
{ matchId: match._id.toString() },
|
|
);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
await session.endSession().catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
throw new CompetitionBootstrapError(
|
|
'COMPETITION_BOOTSTRAP_RACE',
|
|
'Competition bootstrap retry budget was exhausted.',
|
|
409,
|
|
{
|
|
matchId: match._id.toString(),
|
|
cause:
|
|
lastRetryableError instanceof Error
|
|
? lastRetryableError.message
|
|
: String(lastRetryableError),
|
|
},
|
|
);
|
|
}
|
|
}
|
|
|
|
function buildCompetitionInsertPayload(
|
|
match: CompetitionBootstrapMatch,
|
|
source: NonNullable<CompetitionBootstrapOptions['source']>,
|
|
): CompetitionInsertPayload {
|
|
assertObjectId(match._id, 'Match ID');
|
|
assertObjectId(match.communityId, 'Community ID');
|
|
if (match.status === 'recruiting' || !(match.teamBuiltAt instanceof Date)) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_TEAM_SNAPSHOT',
|
|
'Competition bootstrap requires a finalized team-built Match lifecycle.',
|
|
422,
|
|
);
|
|
}
|
|
assertPositiveInteger(match.gameCount, 'Match game count');
|
|
|
|
const competitionId = stableObjectId(match._id, 'competition');
|
|
const teams = snapshotTeams(match, competitionId);
|
|
const graphTeams = teams.map(
|
|
({ teamId, displayOrder, seedNumber }): CompetitionGraphTeam => ({
|
|
teamId: teamId.toString(),
|
|
displayOrder,
|
|
seedNumber,
|
|
}),
|
|
);
|
|
const format = mapMatchFormat(match, teams, source);
|
|
|
|
let seriesGraph: SeriesDefinition[];
|
|
let projection: CompetitionProjection;
|
|
try {
|
|
seriesGraph = generateSeriesGraph({
|
|
competitionId: competitionId.toString(),
|
|
teams: graphTeams,
|
|
format,
|
|
});
|
|
projection = projectCompetition({
|
|
competitionId: competitionId.toString(),
|
|
revision: 0,
|
|
projectorVersion: COMPETITION_PROJECTOR_VERSION,
|
|
teams: graphTeams,
|
|
format,
|
|
seriesGraph,
|
|
facts: [],
|
|
});
|
|
} catch (error) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_FORMAT',
|
|
error instanceof Error
|
|
? error.message
|
|
: 'The Match cannot produce a valid Competition graph.',
|
|
422,
|
|
{
|
|
matchId: match._id.toString(),
|
|
domainCode: readErrorCode(error),
|
|
},
|
|
);
|
|
}
|
|
|
|
return {
|
|
_id: competitionId,
|
|
matchId: match._id,
|
|
communityId: match.communityId,
|
|
schemaVersion: COMPETITION_SCHEMA_VERSION,
|
|
projectorVersion: COMPETITION_PROJECTOR_VERSION,
|
|
revision: 0,
|
|
phase: projection.phase,
|
|
teams,
|
|
format,
|
|
seriesGraph,
|
|
projection,
|
|
};
|
|
}
|
|
|
|
function snapshotTeams(
|
|
match: CompetitionBootstrapMatch,
|
|
competitionId: Types.ObjectId,
|
|
): CompetitionTeamSnapshot[] {
|
|
if (!Array.isArray(match.teams) || match.teams.length < 2) {
|
|
throw invalidTeamSnapshot(
|
|
'A Competition requires at least two built teams.',
|
|
);
|
|
}
|
|
if (!Array.isArray(match.participants)) {
|
|
throw invalidTeamSnapshot('Match participants are missing.');
|
|
}
|
|
|
|
const participantById = new Map<string, MatchParticipant>();
|
|
for (const participant of match.participants) {
|
|
const userId = objectIdString(participant?.userId);
|
|
if (!userId || participantById.has(userId)) {
|
|
throw invalidTeamSnapshot(
|
|
'Match participants must have unique ObjectId user identities.',
|
|
);
|
|
}
|
|
participantById.set(userId, participant);
|
|
}
|
|
|
|
const orderedTeams = [...match.teams].sort(
|
|
(left, right) => left.teamIndex - right.teamIndex,
|
|
);
|
|
const teamIndexes = new Set<number>();
|
|
const assignedUserIds = new Set<string>();
|
|
const memberCounts = new Set<number>();
|
|
const snapshots: CompetitionTeamSnapshot[] = [];
|
|
|
|
for (const [displayIndex, team] of orderedTeams.entries()) {
|
|
if (
|
|
!Number.isInteger(team.teamIndex) ||
|
|
team.teamIndex < 1 ||
|
|
teamIndexes.has(team.teamIndex)
|
|
) {
|
|
throw invalidTeamSnapshot(
|
|
'Built teams must have unique positive integer team indexes.',
|
|
);
|
|
}
|
|
teamIndexes.add(team.teamIndex);
|
|
if (typeof team.name !== 'string' || team.name.trim().length === 0) {
|
|
throw invalidTeamSnapshot('Every built team needs a non-empty name.');
|
|
}
|
|
if (!Array.isArray(team.members) || team.members.length === 0) {
|
|
throw invalidTeamSnapshot('Every built team needs at least one member.');
|
|
}
|
|
memberCounts.add(team.members.length);
|
|
|
|
const memberSnapshots = [...team.members]
|
|
.sort(compareTeamMembers)
|
|
.map((member) => {
|
|
const userId = objectIdString(member.userId);
|
|
const participant = userId ? participantById.get(userId) : undefined;
|
|
if (
|
|
!userId ||
|
|
!participant ||
|
|
participant.excluded === true ||
|
|
assignedUserIds.has(userId)
|
|
) {
|
|
throw invalidTeamSnapshot(
|
|
'Every non-excluded participant must be assigned to exactly one team.',
|
|
);
|
|
}
|
|
assignedUserIds.add(userId);
|
|
|
|
const gameName = nonEmptyString(participant.gameName);
|
|
const tagLine = nonEmptyString(participant.tagLine);
|
|
return {
|
|
userId: member.userId,
|
|
displayName: gameName
|
|
? tagLine
|
|
? `${gameName}#${tagLine}`
|
|
: gameName
|
|
: userId,
|
|
...(gameName ? { gameName } : {}),
|
|
...(tagLine ? { tagLine } : {}),
|
|
...(participant.profileIconId === undefined
|
|
? {}
|
|
: { profileIconId: participant.profileIconId }),
|
|
assignedPosition: member.assignedPosition,
|
|
...(member.cost === undefined ? {} : { cost: member.cost }),
|
|
};
|
|
});
|
|
|
|
if (team.captainUserId) {
|
|
const captainUserId = team.captainUserId.toString();
|
|
if (
|
|
!memberSnapshots.some(
|
|
({ userId }) => userId.toString() === captainUserId,
|
|
)
|
|
) {
|
|
throw invalidTeamSnapshot('A team captain must belong to that team.');
|
|
}
|
|
}
|
|
|
|
snapshots.push({
|
|
teamId: stableObjectId(
|
|
competitionId,
|
|
'team',
|
|
`legacy-team-index:${team.teamIndex}`,
|
|
),
|
|
legacyTeamIndex: team.teamIndex,
|
|
displayOrder: displayIndex + 1,
|
|
seedNumber: displayIndex + 1,
|
|
name: team.name.trim(),
|
|
...(team.captainUserId ? { captainUserId: team.captainUserId } : {}),
|
|
members: memberSnapshots,
|
|
});
|
|
}
|
|
|
|
if (memberCounts.size !== 1) {
|
|
throw invalidTeamSnapshot(
|
|
'All built teams must have the same member count.',
|
|
);
|
|
}
|
|
const activeParticipantIds = [...participantById]
|
|
.filter(([, participant]) => participant.excluded !== true)
|
|
.map(([userId]) => userId);
|
|
if (
|
|
activeParticipantIds.length !== assignedUserIds.size ||
|
|
activeParticipantIds.some((userId) => !assignedUserIds.has(userId))
|
|
) {
|
|
throw invalidTeamSnapshot(
|
|
'Every non-excluded participant must be assigned to exactly one team.',
|
|
);
|
|
}
|
|
|
|
applySeeds(match, snapshots);
|
|
return snapshots;
|
|
}
|
|
|
|
function applySeeds(
|
|
match: CompetitionBootstrapMatch,
|
|
teams: CompetitionTeamSnapshot[],
|
|
): void {
|
|
if (match.gameMode !== 'double-elimination') return;
|
|
const configuredSeeds = match.doubleElimination?.seeds ?? [];
|
|
if (configuredSeeds.length === 0) {
|
|
throw invalidTeamSnapshot(
|
|
'Double-elimination seeds must be finalized before Competition bootstrap.',
|
|
);
|
|
}
|
|
if (configuredSeeds.length !== teams.length) {
|
|
throw invalidTeamSnapshot(
|
|
'Double-elimination seeds must include every built team exactly once.',
|
|
);
|
|
}
|
|
|
|
const validTeamIndexes = new Set(
|
|
teams.map(({ legacyTeamIndex }) => legacyTeamIndex as number),
|
|
);
|
|
const seedByTeamIndex = new Map<number, number>();
|
|
const seedNumbers = new Set<number>();
|
|
for (const seed of configuredSeeds) {
|
|
if (
|
|
!Number.isInteger(seed.seedNumber) ||
|
|
seed.seedNumber < 1 ||
|
|
seed.seedNumber > teams.length ||
|
|
seedNumbers.has(seed.seedNumber) ||
|
|
!validTeamIndexes.has(seed.teamIndex) ||
|
|
seedByTeamIndex.has(seed.teamIndex)
|
|
) {
|
|
throw invalidTeamSnapshot(
|
|
'Double-elimination seeds must be unique and contiguous.',
|
|
);
|
|
}
|
|
seedNumbers.add(seed.seedNumber);
|
|
seedByTeamIndex.set(seed.teamIndex, seed.seedNumber);
|
|
}
|
|
for (const team of teams) {
|
|
team.seedNumber = seedByTeamIndex.get(team.legacyTeamIndex as number)!;
|
|
}
|
|
}
|
|
|
|
function mapMatchFormat(
|
|
match: CompetitionBootstrapMatch,
|
|
teams: CompetitionTeamSnapshot[],
|
|
source: NonNullable<CompetitionBootstrapOptions['source']>,
|
|
): CompetitionGraphFormat {
|
|
switch (match.gameMode) {
|
|
case 'pair':
|
|
return fixedGameFormat('paired-series', match.gameCount);
|
|
case 'bracket':
|
|
if (source !== 'legacy-migration') {
|
|
throw new CompetitionBootstrapError(
|
|
'UNSUPPORTED_LIVE_MATCH_MODE',
|
|
'Legacy bracket mode can only be bootstrapped by migration.',
|
|
422,
|
|
);
|
|
}
|
|
return fixedGameFormat('paired-series', match.gameCount);
|
|
case 'round-robin':
|
|
if (
|
|
match.roundRobinMaxRounds !== undefined &&
|
|
(!Number.isInteger(match.roundRobinMaxRounds) ||
|
|
match.roundRobinMaxRounds < 1)
|
|
) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_FORMAT',
|
|
'Round-robin max rounds must be a positive integer.',
|
|
422,
|
|
);
|
|
}
|
|
return {
|
|
type: 'round-robin',
|
|
rule: fixedGamesRule(match.gameCount),
|
|
...(match.roundRobinMaxRounds === undefined
|
|
? {}
|
|
: { maxRounds: match.roundRobinMaxRounds }),
|
|
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
|
|
};
|
|
case 'double-elimination': {
|
|
if (teams.length !== 4 && teams.length !== 8) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_FORMAT',
|
|
'Double elimination supports only four or eight teams.',
|
|
422,
|
|
);
|
|
}
|
|
if (
|
|
match.doubleElimination?.teamCount !== undefined &&
|
|
match.doubleElimination.teamCount !== teams.length
|
|
) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_FORMAT',
|
|
'Double-elimination team count does not match the built teams.',
|
|
422,
|
|
);
|
|
}
|
|
const bestOfOne = {
|
|
type: 'first-to' as const,
|
|
winsRequired: 1,
|
|
maxGames: 1,
|
|
};
|
|
return {
|
|
type: 'double-elimination',
|
|
teamCount: teams.length,
|
|
resetFinalEnabled: match.doubleElimination?.resetFinalEnabled ?? false,
|
|
rules: {
|
|
upper: {
|
|
type: 'first-to',
|
|
winsRequired: Math.floor(match.gameCount / 2) + 1,
|
|
maxGames: match.gameCount,
|
|
},
|
|
lower: { ...bestOfOne },
|
|
grandFinal: { ...bestOfOne },
|
|
resetFinal: { ...bestOfOne },
|
|
},
|
|
};
|
|
}
|
|
}
|
|
}
|
|
|
|
function fixedGameFormat(
|
|
type: 'paired-series',
|
|
gameCount: number,
|
|
): Extract<CompetitionGraphFormat, { type: 'paired-series' }> {
|
|
return { type, rule: fixedGamesRule(gameCount) };
|
|
}
|
|
|
|
function fixedGamesRule(gameCount: number) {
|
|
return {
|
|
type: 'fixed-games' as const,
|
|
gameCount,
|
|
drawPolicy: 'allow' as const,
|
|
};
|
|
}
|
|
|
|
function stableObjectId(
|
|
namespaceId: Types.ObjectId,
|
|
entityKind: string,
|
|
...logicalKey: string[]
|
|
): Types.ObjectId {
|
|
const hex = createHash('sha256')
|
|
.update(JSON.stringify([namespaceId.toString(), entityKind, ...logicalKey]))
|
|
.digest('hex')
|
|
.slice(0, 24);
|
|
return new Types.ObjectId(hex);
|
|
}
|
|
|
|
function compareTeamMembers(
|
|
left: MatchTeam['members'][number],
|
|
right: MatchTeam['members'][number],
|
|
): number {
|
|
const positionOrder = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
|
return (
|
|
positionOrder.indexOf(left.assignedPosition) -
|
|
positionOrder.indexOf(right.assignedPosition) ||
|
|
left.userId.toString().localeCompare(right.userId.toString())
|
|
);
|
|
}
|
|
|
|
function invalidTeamSnapshot(message: string): CompetitionBootstrapError {
|
|
return new CompetitionBootstrapError(
|
|
'INVALID_MATCH_TEAM_SNAPSHOT',
|
|
message,
|
|
422,
|
|
);
|
|
}
|
|
|
|
function assertPositiveInteger(value: number, label: string): void {
|
|
if (!Number.isInteger(value) || value < 1) {
|
|
throw new CompetitionBootstrapError(
|
|
'INVALID_MATCH_FORMAT',
|
|
`${label} must be a positive integer.`,
|
|
422,
|
|
);
|
|
}
|
|
}
|
|
|
|
function assertObjectId(
|
|
value: unknown,
|
|
label: string,
|
|
): asserts value is Types.ObjectId {
|
|
if (!(value instanceof mongoose.Types.ObjectId)) {
|
|
throw invalidTeamSnapshot(`${label} must be a MongoDB ObjectId.`);
|
|
}
|
|
}
|
|
|
|
function objectIdString(value: unknown): string | undefined {
|
|
return value instanceof mongoose.Types.ObjectId
|
|
? value.toString()
|
|
: undefined;
|
|
}
|
|
|
|
function nonEmptyString(value: unknown): string | undefined {
|
|
if (typeof value !== 'string') return undefined;
|
|
const trimmed = value.trim();
|
|
return trimmed.length > 0 ? trimmed : undefined;
|
|
}
|
|
|
|
function readErrorCode(error: unknown): string | undefined {
|
|
if (
|
|
typeof error === 'object' &&
|
|
error !== null &&
|
|
'code' in error &&
|
|
typeof error.code === 'string'
|
|
) {
|
|
return error.code;
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
function isRetryableBootstrapError(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'),
|
|
);
|
|
}
|