Files
lolympus-tournament-support/apps/api/src/modules/competition/domain/series-graph.ts
T

787 lines
22 KiB
TypeScript

import { createHash } from 'node:crypto';
export type SeriesSlot = 'A' | 'B';
export type FirstToSeriesRule = {
type: 'first-to';
winsRequired: number;
maxGames: number;
};
export type FixedGamesSeriesRule = {
type: 'fixed-games';
gameCount: number;
drawPolicy: 'allow' | 'tiebreak-required';
};
export type SeriesRule = FirstToSeriesRule | FixedGamesSeriesRule;
export type ParticipantSource =
| { type: 'team'; teamId: string }
| { type: 'seed'; seedNumber: number }
| {
type: 'series-outcome';
seriesId: string;
select: 'winner' | 'loser';
}
| {
type: 'series-slot';
seriesId: string;
slot: SeriesSlot;
};
export type SeriesStageType =
| 'pair'
| 'round-robin'
| 'upper'
| 'lower'
| 'grand-final'
| 'reset-final';
export interface SeriesDefinition {
id: string;
code?: string;
stage: {
type: SeriesStageType;
roundNumber?: number;
displayOrder: number;
};
slots: [
{ position: 'A'; source: ParticipantSource },
{ position: 'B'; source: ParticipantSource },
];
rule: SeriesRule;
schedule?: {
date: string;
time: string | null;
timeZone: 'Asia/Seoul';
};
activation?: {
type: 'grand-final-reset-required';
grandFinalSeriesId: string;
};
gameSlots: Array<{
id: string;
seriesId: string;
ordinal: number;
}>;
}
export interface CompetitionGraphTeam {
teamId: string;
displayOrder: number;
seedNumber?: number;
}
export interface RoundRobinPairing {
roundNumber: number;
matchNumber: number;
teamAId: string;
teamBId: string;
}
export type CompetitionGraphFormat =
| {
type: 'paired-series';
rule: FixedGamesSeriesRule;
}
| {
type: 'round-robin';
rule: FixedGamesSeriesRule;
maxRounds?: number;
pairings?: readonly RoundRobinPairing[];
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
}
| {
type: 'double-elimination';
teamCount?: 4 | 8;
resetFinalEnabled: boolean;
rules: {
upper: FirstToSeriesRule;
lower: FirstToSeriesRule;
grandFinal: FirstToSeriesRule;
resetFinal: FirstToSeriesRule;
};
};
export interface GenerateSeriesGraphInput {
competitionId: string;
teams: readonly CompetitionGraphTeam[];
format: CompetitionGraphFormat;
}
interface DoubleEliminationTemplate {
code: string;
stage: Extract<
SeriesStageType,
'upper' | 'lower' | 'grand-final' | 'reset-final'
>;
roundNumber: number;
sources: [TemplateParticipantSource, TemplateParticipantSource];
}
type TemplateParticipantSource =
| { type: 'seed'; seedNumber: number }
| {
type: 'series-outcome';
seriesCode: string;
select: 'winner' | 'loser';
}
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
interface CanonicalRoundRobinPairing {
roundNumber: number;
teamAIndex: number;
teamBIndex: number;
}
/**
* Builds the immutable Series graph. Identifiers depend only on the Competition
* identity and the logical node/slot key, never on array position or a display
* number supplied by a client.
*/
export function generateSeriesGraph(
input: GenerateSeriesGraphInput,
): SeriesDefinition[] {
assertCompetitionId(input.competitionId);
const teams = normalizeTeams(input.teams);
let graph: SeriesDefinition[];
switch (input.format.type) {
case 'paired-series':
graph = generatePairedSeriesGraph(
input.competitionId,
teams,
input.format.rule,
);
break;
case 'round-robin':
graph = generateRoundRobinGraph(input.competitionId, teams, input.format);
break;
case 'double-elimination':
graph = generateDoubleEliminationGraph(
input.competitionId,
teams,
input.format,
);
break;
}
assertValidGraph(graph);
return graph;
}
function generatePairedSeriesGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
rule: FixedGamesSeriesRule,
): SeriesDefinition[] {
assertFixedGamesRule(rule);
if (teams.length < 2 || teams.length % 2 !== 0) {
throw graphError(
'INVALID_PAIRED_TEAM_COUNT',
'Paired Series requires a positive, even number of teams.',
);
}
const definitions: SeriesDefinition[] = [];
for (let teamIndex = 0; teamIndex < teams.length; teamIndex += 2) {
const code = `PAIR_M${teamIndex / 2 + 1}`;
definitions.push(
createSeriesDefinition({
competitionId,
code,
stage: 'pair',
roundNumber: 1,
displayOrder: definitions.length + 1,
sources: [
{ type: 'team', teamId: teams[teamIndex].teamId },
{ type: 'team', teamId: teams[teamIndex + 1].teamId },
],
rule,
}),
);
}
return definitions;
}
function generateRoundRobinGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
format: Extract<CompetitionGraphFormat, { type: 'round-robin' }>,
): SeriesDefinition[] {
assertFixedGamesRule(format.rule);
if (teams.length < 2) {
throw graphError(
'INVALID_ROUND_ROBIN_TEAM_COUNT',
'Round robin requires at least two teams.',
);
}
const pairings = format.pairings
? validateExplicitRoundRobinPairings(
teams,
format.pairings,
format.maxRounds,
)
: canonicalRoundRobinPairings(teams, format.maxRounds);
return pairings.map((pairing, index) => {
const code = `RR_R${pairing.roundNumber}_M${pairing.matchNumber}`;
return createSeriesDefinition({
competitionId,
code,
stage: 'round-robin',
roundNumber: pairing.roundNumber,
displayOrder: index + 1,
sources: [
{ type: 'team', teamId: pairing.teamAId },
{ type: 'team', teamId: pairing.teamBId },
],
rule: format.rule,
});
});
}
function canonicalRoundRobinPairings(
teams: CompetitionGraphTeam[],
maxRounds?: number,
): RoundRobinPairing[] {
const matchNumberByRound = new Map<number, number>();
return roundRobinPairings(teams.length, maxRounds).map((pairing) => {
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
matchNumberByRound.set(pairing.roundNumber, matchNumber);
return {
roundNumber: pairing.roundNumber,
matchNumber,
teamAId: teams[pairing.teamAIndex].teamId,
teamBId: teams[pairing.teamBIndex].teamId,
};
});
}
function validateExplicitRoundRobinPairings(
teams: CompetitionGraphTeam[],
pairings: readonly RoundRobinPairing[],
maxRounds?: number,
): RoundRobinPairing[] {
if (pairings.length === 0) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Explicit round-robin pairings cannot be empty.',
);
}
const teamIds = new Set(teams.map(({ teamId }) => teamId));
const positions = new Set<string>();
const opponentPairs = new Set<string>();
const teamsByRound = new Map<number, Set<string>>();
const sorted = pairings
.map((pairing) => ({ ...pairing }))
.sort(
(left, right) =>
left.roundNumber - right.roundNumber ||
left.matchNumber - right.matchNumber,
);
for (const pairing of sorted) {
if (
!Number.isInteger(pairing.roundNumber) ||
pairing.roundNumber < 1 ||
!Number.isInteger(pairing.matchNumber) ||
pairing.matchNumber < 1 ||
(maxRounds !== undefined && pairing.roundNumber > maxRounds) ||
!teamIds.has(pairing.teamAId) ||
!teamIds.has(pairing.teamBId) ||
pairing.teamAId === pairing.teamBId
) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'Every explicit round-robin pairing needs a valid position and two known, distinct teams.',
);
}
const position = `${pairing.roundNumber}:${pairing.matchNumber}`;
if (positions.has(position)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
`Round-robin pairing position ${position} occurs more than once.`,
);
}
positions.add(position);
const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort());
if (opponentPairs.has(opponents)) {
throw graphError(
'DUPLICATE_ROUND_ROBIN_OPPONENTS',
'A round-robin opponent pair occurs more than once.',
);
}
opponentPairs.add(opponents);
const roundTeams = teamsByRound.get(pairing.roundNumber) ?? new Set();
if (roundTeams.has(pairing.teamAId) || roundTeams.has(pairing.teamBId)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
'A team cannot appear in multiple Series in the same round.',
);
}
roundTeams.add(pairing.teamAId);
roundTeams.add(pairing.teamBId);
teamsByRound.set(pairing.roundNumber, roundTeams);
}
for (const roundNumber of new Set(
sorted.map((pairing) => pairing.roundNumber),
)) {
const matches = sorted.filter(
(pairing) => pairing.roundNumber === roundNumber,
);
if (matches.some((pairing, index) => pairing.matchNumber !== index + 1)) {
throw graphError(
'INVALID_ROUND_ROBIN_PAIRING',
`Round ${roundNumber} match numbers must be contiguous from one.`,
);
}
}
const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds);
const expectedMatchesPerRound = Math.floor(teams.length / 2);
for (
let roundNumber = 1;
roundNumber <= expectedRoundCount;
roundNumber += 1
) {
const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2;
if (matchCount !== expectedMatchesPerRound) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`,
);
}
}
if (teamsByRound.size !== expectedRoundCount) {
throw graphError(
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
`Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`,
);
}
return sorted;
}
function generateDoubleEliminationGraph(
competitionId: string,
teams: CompetitionGraphTeam[],
format: Extract<CompetitionGraphFormat, { type: 'double-elimination' }>,
): SeriesDefinition[] {
if (teams.length !== 4 && teams.length !== 8) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_TEAM_COUNT',
'Double elimination supports only four or eight teams.',
);
}
if (format.teamCount !== undefined && format.teamCount !== teams.length) {
throw graphError(
'DOUBLE_ELIMINATION_TEAM_COUNT_MISMATCH',
'The configured team count does not match the team snapshots.',
);
}
assertContiguousSeeds(teams);
assertFirstToRule(format.rules.upper);
assertFirstToRule(format.rules.lower);
assertFirstToRule(format.rules.grandFinal);
assertFirstToRule(format.rules.resetFinal);
const templates =
teams.length === 4
? fourTeamDoubleEliminationTemplate()
: eightTeamDoubleEliminationTemplate();
if (format.resetFinalEnabled) templates.push(resetFinalTemplate());
return templates.map((template, index) => {
const rule = ruleForStage(template.stage, format.rules);
const grandFinalSeriesId = stableSeriesId(competitionId, 'GF');
return createSeriesDefinition({
competitionId,
code: template.code,
stage: template.stage,
roundNumber: template.roundNumber,
displayOrder: index + 1,
sources: template.sources.map((source) =>
resolveTemplateSource(competitionId, source),
) as [ParticipantSource, ParticipantSource],
rule,
activation:
template.stage === 'reset-final'
? {
type: 'grand-final-reset-required',
grandFinalSeriesId,
}
: undefined,
});
});
}
function createSeriesDefinition(params: {
competitionId: string;
code: string;
stage: SeriesStageType;
roundNumber: number;
displayOrder: number;
sources: [ParticipantSource, ParticipantSource];
rule: SeriesRule;
activation?: SeriesDefinition['activation'];
}): SeriesDefinition {
const id = stableSeriesId(params.competitionId, params.code);
const rule = cloneRule(params.rule);
const gameCount =
rule.type === 'fixed-games' ? rule.gameCount : rule.maxGames;
return {
id,
code: params.code,
stage: {
type: params.stage,
roundNumber: params.roundNumber,
displayOrder: params.displayOrder,
},
slots: [
{ position: 'A', source: { ...params.sources[0] } },
{ position: 'B', source: { ...params.sources[1] } },
],
rule,
...(params.activation ? { activation: { ...params.activation } } : {}),
gameSlots: Array.from({ length: gameCount }, (_, index) => ({
id: stableGameSlotId(params.competitionId, params.code, index + 1),
seriesId: id,
ordinal: index + 1,
})),
};
}
function fourTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] {
return [
deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(4)),
deSeries('WB_R1_M2', 'upper', 1, seed(2), seed(3)),
deSeries('WB_FINAL', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')),
deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')),
deSeries('LB_FINAL', 'lower', 2, winner('LB_R1_M1'), loser('WB_FINAL')),
deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')),
];
}
function eightTeamDoubleEliminationTemplate(): DoubleEliminationTemplate[] {
return [
deSeries('WB_R1_M1', 'upper', 1, seed(1), seed(8)),
deSeries('WB_R1_M2', 'upper', 1, seed(4), seed(5)),
deSeries('WB_R1_M3', 'upper', 1, seed(2), seed(7)),
deSeries('WB_R1_M4', 'upper', 1, seed(3), seed(6)),
deSeries('WB_R2_M1', 'upper', 2, winner('WB_R1_M1'), winner('WB_R1_M2')),
deSeries('WB_R2_M2', 'upper', 2, winner('WB_R1_M3'), winner('WB_R1_M4')),
deSeries('WB_FINAL', 'upper', 3, winner('WB_R2_M1'), winner('WB_R2_M2')),
deSeries('LB_R1_M1', 'lower', 1, loser('WB_R1_M1'), loser('WB_R1_M2')),
deSeries('LB_R1_M2', 'lower', 1, loser('WB_R1_M3'), loser('WB_R1_M4')),
deSeries('LB_R2_M1', 'lower', 2, winner('LB_R1_M1'), loser('WB_R2_M2')),
deSeries('LB_R2_M2', 'lower', 2, winner('LB_R1_M2'), loser('WB_R2_M1')),
deSeries('LB_R3_M1', 'lower', 3, winner('LB_R2_M1'), winner('LB_R2_M2')),
deSeries('LB_FINAL', 'lower', 4, winner('LB_R3_M1'), loser('WB_FINAL')),
deSeries('GF', 'grand-final', 1, winner('WB_FINAL'), winner('LB_FINAL')),
];
}
function resetFinalTemplate(): DoubleEliminationTemplate {
return deSeries(
'GF_RESET',
'reset-final',
1,
seriesSlot('GF', 'A'),
seriesSlot('GF', 'B'),
);
}
function deSeries(
code: string,
stage: DoubleEliminationTemplate['stage'],
roundNumber: number,
sourceA: TemplateParticipantSource,
sourceB: TemplateParticipantSource,
): DoubleEliminationTemplate {
return { code, stage, roundNumber, sources: [sourceA, sourceB] };
}
function seed(seedNumber: number): TemplateParticipantSource {
return { type: 'seed', seedNumber };
}
function winner(seriesCode: string): TemplateParticipantSource {
return { type: 'series-outcome', seriesCode, select: 'winner' };
}
function loser(seriesCode: string): TemplateParticipantSource {
return { type: 'series-outcome', seriesCode, select: 'loser' };
}
function seriesSlot(
seriesCode: string,
slot: SeriesSlot,
): TemplateParticipantSource {
return { type: 'series-slot', seriesCode, slot };
}
function resolveTemplateSource(
competitionId: string,
source: TemplateParticipantSource,
): ParticipantSource {
switch (source.type) {
case 'seed':
return { ...source };
case 'series-outcome':
return {
type: 'series-outcome',
seriesId: stableSeriesId(competitionId, source.seriesCode),
select: source.select,
};
case 'series-slot':
return {
type: 'series-slot',
seriesId: stableSeriesId(competitionId, source.seriesCode),
slot: source.slot,
};
}
}
function ruleForStage(
stage: DoubleEliminationTemplate['stage'],
rules: Extract<
CompetitionGraphFormat,
{ type: 'double-elimination' }
>['rules'],
): FirstToSeriesRule {
switch (stage) {
case 'upper':
return rules.upper;
case 'lower':
return rules.lower;
case 'grand-final':
return rules.grandFinal;
case 'reset-final':
return rules.resetFinal;
}
}
function roundRobinPairings(
teamCount: number,
maxRounds?: number,
): CanonicalRoundRobinPairing[] {
const bye = -1;
const rotating = Array.from({ length: teamCount }, (_, index) => index);
if (rotating.length % 2 === 1) rotating.push(bye);
const roundCount = roundRobinRoundCount(teamCount, maxRounds);
const pairings: CanonicalRoundRobinPairing[] = [];
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
for (let index = 0; index < rotating.length / 2; index += 1) {
const left = rotating[index];
const right = rotating[rotating.length - 1 - index];
if (left === bye || right === bye) continue;
pairings.push({
roundNumber: roundIndex + 1,
teamAIndex: Math.min(left, right),
teamBIndex: Math.max(left, right),
});
}
const fixed = rotating[0];
const tail = rotating.slice(1);
tail.unshift(tail.pop() as number);
rotating.splice(0, rotating.length, fixed, ...tail);
}
return pairings;
}
function roundRobinRoundCount(teamCount: number, maxRounds?: number): number {
const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount;
const requestedRounds =
maxRounds === undefined
? fullRoundCount
: Number.isFinite(maxRounds)
? Math.floor(maxRounds)
: fullRoundCount;
return Math.max(0, Math.min(fullRoundCount, requestedRounds));
}
function normalizeTeams(
teams: readonly CompetitionGraphTeam[],
): CompetitionGraphTeam[] {
const normalized = teams.map((team) => ({ ...team }));
const teamIds = new Set<string>();
const displayOrders = new Set<number>();
for (const team of normalized) {
if (typeof team.teamId !== 'string' || team.teamId.trim().length === 0) {
throw graphError('INVALID_TEAM_ID', 'Every team needs an opaque ID.');
}
if (teamIds.has(team.teamId)) {
throw graphError(
'DUPLICATE_TEAM_ID',
`Duplicate team ID: ${team.teamId}`,
);
}
if (!Number.isInteger(team.displayOrder) || team.displayOrder < 1) {
throw graphError(
'INVALID_TEAM_DISPLAY_ORDER',
'Team display order must be a positive integer.',
);
}
if (displayOrders.has(team.displayOrder)) {
throw graphError(
'DUPLICATE_TEAM_DISPLAY_ORDER',
`Duplicate team display order: ${team.displayOrder}`,
);
}
teamIds.add(team.teamId);
displayOrders.add(team.displayOrder);
}
return normalized.sort(
(left, right) =>
left.displayOrder - right.displayOrder ||
left.teamId.localeCompare(right.teamId),
);
}
function assertContiguousSeeds(teams: CompetitionGraphTeam[]): void {
const seeds = teams.map((team) => team.seedNumber);
if (
seeds.some((seedNumber) => !Number.isInteger(seedNumber)) ||
new Set(seeds).size !== teams.length
) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_SEEDS',
'Double-elimination seeds must be unique integers.',
);
}
const sorted = [...(seeds as number[])].sort((left, right) => left - right);
if (sorted.some((seedNumber, index) => seedNumber !== index + 1)) {
throw graphError(
'INVALID_DOUBLE_ELIMINATION_SEEDS',
'Double-elimination seeds must be contiguous from one to the team count.',
);
}
}
function assertCompetitionId(competitionId: string): void {
if (typeof competitionId !== 'string' || competitionId.trim().length === 0) {
throw graphError(
'INVALID_COMPETITION_ID',
'Competition ID must be a non-empty string.',
);
}
}
function assertFixedGamesRule(rule: FixedGamesSeriesRule): void {
if (!Number.isInteger(rule.gameCount) || rule.gameCount < 1) {
throw graphError(
'INVALID_FIXED_GAMES_RULE',
'Fixed-game Series need a positive game count.',
);
}
if (rule.drawPolicy !== 'allow' && rule.drawPolicy !== 'tiebreak-required') {
throw graphError(
'INVALID_FIXED_GAMES_RULE',
'Fixed-game Series need a supported draw policy.',
);
}
}
function assertFirstToRule(rule: FirstToSeriesRule): void {
if (
!Number.isInteger(rule.winsRequired) ||
rule.winsRequired < 1 ||
!Number.isInteger(rule.maxGames) ||
rule.maxGames < rule.winsRequired * 2 - 1
) {
throw graphError(
'INVALID_FIRST_TO_RULE',
'First-to Series need positive, achievable win and game limits.',
);
}
}
function cloneRule(rule: SeriesRule): SeriesRule {
return rule.type === 'fixed-games' ? { ...rule } : { ...rule };
}
function assertValidGraph(graph: SeriesDefinition[]): void {
const seriesIndexById = new Map<string, number>();
const gameSlotIds = new Set<string>();
graph.forEach((series, index) => {
if (seriesIndexById.has(series.id)) {
throw graphError('DUPLICATE_SERIES_ID', 'Series IDs must be unique.');
}
seriesIndexById.set(series.id, index);
for (const gameSlot of series.gameSlots) {
if (gameSlotIds.has(gameSlot.id)) {
throw graphError(
'DUPLICATE_GAME_SLOT_ID',
'GameSlot IDs must be unique.',
);
}
gameSlotIds.add(gameSlot.id);
}
});
graph.forEach((series, index) => {
for (const slot of series.slots) {
if (
slot.source.type !== 'series-outcome' &&
slot.source.type !== 'series-slot'
) {
continue;
}
const sourceIndex = seriesIndexById.get(slot.source.seriesId);
if (sourceIndex === undefined) {
throw graphError(
'UNKNOWN_SERIES_SOURCE',
`Series ${series.id} references an unknown source.`,
);
}
if (sourceIndex >= index) {
throw graphError(
'CYCLIC_SERIES_GRAPH',
`Series ${series.id} does not follow its source in topological order.`,
);
}
}
});
}
function stableSeriesId(competitionId: string, code: string): string {
return stableOpaqueId(competitionId, 'series', code);
}
function stableGameSlotId(
competitionId: string,
seriesCode: string,
ordinal: number,
): string {
return stableOpaqueId(competitionId, 'game-slot', seriesCode, ordinal);
}
function stableOpaqueId(
competitionId: string,
entityKind: string,
...logicalKey: Array<string | number>
): string {
return createHash('sha256')
.update(JSON.stringify([competitionId, entityKind, ...logicalKey]))
.digest('hex')
.slice(0, 24);
}
function graphError(code: string, message: string): Error & { code: string } {
return Object.assign(new Error(message), { code });
}