fix: harden competition migration recovery
This commit is contained in:
1 parent
bbcb2f43dc
commit
6b1c450752
7 files changed
+1394
-129
No files matched your search
@@ -91,6 +91,9 @@ interface LegacyTournamentCodeInput {
|
||||
reservedAt?: Date | string;
|
||||
usedAt?: Date | string;
|
||||
releasedAt?: Date | string;
|
||||
voidedAt?: Date | string;
|
||||
createdAt?: Date | string;
|
||||
updatedAt?: Date | string;
|
||||
}
|
||||
|
||||
export interface LegacyMatchInput {
|
||||
@@ -226,6 +229,7 @@ export interface CompetitionMigrationAssignment {
|
||||
reservedAt: string;
|
||||
usedAt?: string;
|
||||
releasedAt?: string;
|
||||
voidedAt?: string;
|
||||
riotMatchId?: string;
|
||||
commandId: string;
|
||||
}
|
||||
@@ -405,7 +409,6 @@ export function planCompetitionMigration(
|
||||
facts,
|
||||
seriesGraph,
|
||||
teamBuild.teamIdByLegacyIndex,
|
||||
warnings,
|
||||
reasons,
|
||||
);
|
||||
if (reasons.length > 0) {
|
||||
@@ -614,6 +617,7 @@ function buildFormat(
|
||||
input,
|
||||
teamIds,
|
||||
gameCount,
|
||||
warnings,
|
||||
reasons,
|
||||
);
|
||||
if (pairings === null) return undefined;
|
||||
@@ -667,6 +671,7 @@ function normalizeLegacyRoundRobinPairings(
|
||||
input: LegacyMatchInput,
|
||||
teamIds: ReadonlyMap<number, string>,
|
||||
gameCount: number,
|
||||
warnings: CompetitionMigrationIssue[],
|
||||
reasons: CompetitionMigrationIssue[],
|
||||
): RoundRobinPairing[] | undefined | null {
|
||||
const schedule = input.gameSchedule ?? [];
|
||||
@@ -676,30 +681,44 @@ function normalizeLegacyRoundRobinPairings(
|
||||
const groups = new Map<
|
||||
string,
|
||||
{
|
||||
roundNumber: number;
|
||||
roundNumber?: number;
|
||||
teamAId: string;
|
||||
teamBId: string;
|
||||
gameNumbers: number[];
|
||||
}
|
||||
>();
|
||||
const gamesPerRound = Math.floor(teamIds.size / 2) * gameCount;
|
||||
const hasRoundNumbers = schedule.some(
|
||||
(assignment) => assignment.roundNumber !== undefined,
|
||||
);
|
||||
if (
|
||||
hasRoundNumbers &&
|
||||
schedule.some((assignment) => assignment.roundNumber === undefined)
|
||||
) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'INVALID_ROUND_ROBIN_SCHEDULE',
|
||||
'Persisted round-robin round numbers must be present for every game or absent from every game.',
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const assignment of schedule) {
|
||||
const teamAId = teamIds.get(assignment.teamAIndex);
|
||||
const teamBId = teamIds.get(assignment.teamBIndex);
|
||||
const roundNumber =
|
||||
positiveInteger(assignment.roundNumber) ??
|
||||
(gamesPerRound > 0 && positiveInteger(assignment.gameNumber)
|
||||
? Math.floor((assignment.gameNumber - 1) / gamesPerRound) + 1
|
||||
: undefined);
|
||||
assignment.roundNumber === undefined
|
||||
? undefined
|
||||
: positiveInteger(assignment.roundNumber);
|
||||
if (
|
||||
!positiveInteger(assignment.gameNumber) ||
|
||||
seenGameNumbers.has(assignment.gameNumber) ||
|
||||
!teamAId ||
|
||||
!teamBId ||
|
||||
teamAId === teamBId ||
|
||||
!roundNumber ||
|
||||
(hasRoundNumbers && !roundNumber) ||
|
||||
(positiveInteger(input.roundRobinMaxRounds) !== undefined &&
|
||||
roundNumber !== undefined &&
|
||||
roundNumber > input.roundRobinMaxRounds!)
|
||||
) {
|
||||
reasons.push(
|
||||
@@ -714,7 +733,7 @@ function normalizeLegacyRoundRobinPairings(
|
||||
seenGameNumbers.add(assignment.gameNumber);
|
||||
|
||||
const opponents = [teamAId, teamBId].sort();
|
||||
const key = opponents.join(':');
|
||||
const key = JSON.stringify(opponents);
|
||||
const existing = groups.get(key);
|
||||
if (existing && existing.roundNumber !== roundNumber) {
|
||||
reasons.push(
|
||||
@@ -734,7 +753,7 @@ function normalizeLegacyRoundRobinPairings(
|
||||
teamBId,
|
||||
gameNumbers: [],
|
||||
} satisfies {
|
||||
roundNumber: number;
|
||||
roundNumber?: number;
|
||||
teamAId: string;
|
||||
teamBId: string;
|
||||
gameNumbers: number[];
|
||||
@@ -743,22 +762,59 @@ function normalizeLegacyRoundRobinPairings(
|
||||
groups.set(key, group);
|
||||
}
|
||||
|
||||
const orderedGroups = [...groups.values()].sort(
|
||||
const groupedSeries = [...groups.values()];
|
||||
if (!hasRoundNumbers) {
|
||||
const reconstruction = assignLegacyRoundRobinRounds(
|
||||
groupedSeries,
|
||||
[...teamIds.values()],
|
||||
input.roundRobinMaxRounds,
|
||||
);
|
||||
if (reconstruction !== 'assigned') {
|
||||
const [code, message] =
|
||||
reconstruction === 'unsupported-size'
|
||||
? [
|
||||
'ROUND_ROBIN_ROUND_RECONSTRUCTION_UNSUPPORTED',
|
||||
'Opponent-only partial round-robin reconstruction supports at most 16 teams.',
|
||||
]
|
||||
: reconstruction === 'search-limit-exceeded'
|
||||
? [
|
||||
'ROUND_ROBIN_ROUND_RECONSTRUCTION_LIMIT_EXCEEDED',
|
||||
'Opponent-only round-robin reconstruction exceeded its deterministic search limit.',
|
||||
]
|
||||
: [
|
||||
'INVALID_ROUND_ROBIN_SCHEDULE',
|
||||
'The persisted round-robin opponent pairs cannot be reconstructed as complete playable rounds.',
|
||||
];
|
||||
reasons.push(issue(code, message, { teamCount: teamIds.size }));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (!hasRoundNumbers) {
|
||||
warnings.push(
|
||||
issue(
|
||||
'LEGACY_ROUND_ROBIN_ROUNDS_RECONSTRUCTED',
|
||||
'Playable round numbers were reconstructed deterministically from a legacy opponent-only schedule.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const orderedGroups = groupedSeries.sort(
|
||||
(left, right) =>
|
||||
left.roundNumber - right.roundNumber ||
|
||||
left.roundNumber! - right.roundNumber! ||
|
||||
Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers),
|
||||
);
|
||||
const teamsByRound = new Map<number, Set<string>>();
|
||||
const matchNumberByRound = new Map<number, number>();
|
||||
const pairings: RoundRobinPairing[] = [];
|
||||
for (const group of orderedGroups) {
|
||||
const roundNumber = group.roundNumber!;
|
||||
if (group.gameNumbers.length !== gameCount) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'INVALID_ROUND_ROBIN_SCHEDULE',
|
||||
'Every persisted round-robin Series must contain exactly gameCount scheduled games.',
|
||||
{
|
||||
roundNumber: group.roundNumber,
|
||||
roundNumber,
|
||||
scheduledGameCount: group.gameNumbers.length,
|
||||
expectedGameCount: gameCount,
|
||||
},
|
||||
@@ -766,25 +822,25 @@ function normalizeLegacyRoundRobinPairings(
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const roundTeams = teamsByRound.get(group.roundNumber) ?? new Set();
|
||||
const roundTeams = teamsByRound.get(roundNumber) ?? new Set();
|
||||
if (roundTeams.has(group.teamAId) || roundTeams.has(group.teamBId)) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'INVALID_ROUND_ROBIN_SCHEDULE',
|
||||
'A team appears in multiple persisted Series in the same round.',
|
||||
{ roundNumber: group.roundNumber },
|
||||
{ roundNumber },
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
roundTeams.add(group.teamAId);
|
||||
roundTeams.add(group.teamBId);
|
||||
teamsByRound.set(group.roundNumber, roundTeams);
|
||||
teamsByRound.set(roundNumber, roundTeams);
|
||||
|
||||
const matchNumber = (matchNumberByRound.get(group.roundNumber) ?? 0) + 1;
|
||||
matchNumberByRound.set(group.roundNumber, matchNumber);
|
||||
const matchNumber = (matchNumberByRound.get(roundNumber) ?? 0) + 1;
|
||||
matchNumberByRound.set(roundNumber, matchNumber);
|
||||
pairings.push({
|
||||
roundNumber: group.roundNumber,
|
||||
roundNumber,
|
||||
matchNumber,
|
||||
teamAId: group.teamAId,
|
||||
teamBId: group.teamBId,
|
||||
@@ -793,6 +849,150 @@ function normalizeLegacyRoundRobinPairings(
|
||||
return pairings;
|
||||
}
|
||||
|
||||
function assignLegacyRoundRobinRounds(
|
||||
groups: Array<{
|
||||
roundNumber?: number;
|
||||
teamAId: string;
|
||||
teamBId: string;
|
||||
gameNumbers: number[];
|
||||
}>,
|
||||
teamIds: readonly string[],
|
||||
maxRounds?: number,
|
||||
): 'assigned' | 'invalid' | 'unsupported-size' | 'search-limit-exceeded' {
|
||||
const teamCount = teamIds.length;
|
||||
const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount;
|
||||
const roundCount = Math.min(
|
||||
fullRoundCount,
|
||||
positiveInteger(maxRounds) ?? fullRoundCount,
|
||||
);
|
||||
const matchesPerRound = Math.floor(teamCount / 2);
|
||||
if (groups.length !== roundCount * matchesPerRound) return 'invalid';
|
||||
|
||||
if (roundCount === fullRoundCount) {
|
||||
return assignCompleteLegacyRoundRobinRounds(groups, teamIds)
|
||||
? 'assigned'
|
||||
: 'invalid';
|
||||
}
|
||||
if (teamCount > 16) return 'unsupported-size';
|
||||
|
||||
const degreeByTeam = new Map(teamIds.map((teamId) => [teamId, 0]));
|
||||
for (const group of groups) {
|
||||
degreeByTeam.set(group.teamAId, degreeByTeam.get(group.teamAId)! + 1);
|
||||
degreeByTeam.set(group.teamBId, degreeByTeam.get(group.teamBId)! + 1);
|
||||
}
|
||||
if (
|
||||
[...degreeByTeam.values()].some(
|
||||
(degree) =>
|
||||
degree > roundCount || (teamCount % 2 === 0 && degree !== roundCount),
|
||||
)
|
||||
) {
|
||||
return 'invalid';
|
||||
}
|
||||
|
||||
const ordered = [...groups]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Math.min(...left.gameNumbers) - Math.min(...right.gameNumbers),
|
||||
)
|
||||
.map((group, index) => ({ group, index }));
|
||||
const failedPartitions = new Set<string>();
|
||||
let searchBudget = 1_000_000;
|
||||
|
||||
const partition = (
|
||||
roundNumber: number,
|
||||
remaining: typeof ordered,
|
||||
): boolean => {
|
||||
if (roundNumber > roundCount) return remaining.length === 0;
|
||||
if (remaining.length < matchesPerRound) return false;
|
||||
const partitionKey = remaining.map(({ index }) => index).join(',');
|
||||
if (failedPartitions.has(partitionKey) || searchBudget <= 0) return false;
|
||||
|
||||
const selectedIndexes: number[] = [0];
|
||||
const usedTeams = new Set([
|
||||
remaining[0].group.teamAId,
|
||||
remaining[0].group.teamBId,
|
||||
]);
|
||||
|
||||
const fillRound = (candidateIndex: number): boolean => {
|
||||
searchBudget -= 1;
|
||||
if (searchBudget < 0) return false;
|
||||
if (selectedIndexes.length === matchesPerRound) {
|
||||
const selected = new Set(selectedIndexes);
|
||||
const nextRemaining = remaining.filter(
|
||||
(_group, index) => !selected.has(index),
|
||||
);
|
||||
if (!partition(roundNumber + 1, nextRemaining)) return false;
|
||||
for (const index of selectedIndexes) {
|
||||
remaining[index].group.roundNumber = roundNumber;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
for (let index = candidateIndex; index < remaining.length; index += 1) {
|
||||
if (searchBudget <= 0) return false;
|
||||
const candidate = remaining[index].group;
|
||||
if (
|
||||
usedTeams.has(candidate.teamAId) ||
|
||||
usedTeams.has(candidate.teamBId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
selectedIndexes.push(index);
|
||||
usedTeams.add(candidate.teamAId);
|
||||
usedTeams.add(candidate.teamBId);
|
||||
if (fillRound(index + 1)) return true;
|
||||
selectedIndexes.pop();
|
||||
usedTeams.delete(candidate.teamAId);
|
||||
usedTeams.delete(candidate.teamBId);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const found = fillRound(1);
|
||||
if (!found) failedPartitions.add(partitionKey);
|
||||
return found;
|
||||
};
|
||||
|
||||
const assigned = partition(1, ordered);
|
||||
if (assigned) return 'assigned';
|
||||
return searchBudget <= 0 ? 'search-limit-exceeded' : 'invalid';
|
||||
}
|
||||
|
||||
function assignCompleteLegacyRoundRobinRounds(
|
||||
groups: Array<{
|
||||
roundNumber?: number;
|
||||
teamAId: string;
|
||||
teamBId: string;
|
||||
}>,
|
||||
teamIds: readonly string[],
|
||||
): boolean {
|
||||
const byOpponents = new Map(
|
||||
groups.map((group) => [
|
||||
JSON.stringify([group.teamAId, group.teamBId].sort()),
|
||||
group,
|
||||
]),
|
||||
);
|
||||
const bye = Symbol('round-robin-bye');
|
||||
const rotating: Array<string | typeof bye> = [...teamIds].sort();
|
||||
if (rotating.length % 2 === 1) rotating.push(bye);
|
||||
|
||||
for (let roundIndex = 0; roundIndex < rotating.length - 1; 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;
|
||||
const group = byOpponents.get(JSON.stringify([left, right].sort()));
|
||||
if (!group) return false;
|
||||
group.roundNumber = roundIndex + 1;
|
||||
}
|
||||
const fixed = rotating[0];
|
||||
const tail = rotating.slice(1);
|
||||
tail.unshift(tail.pop()!);
|
||||
rotating.splice(0, rotating.length, fixed, ...tail);
|
||||
}
|
||||
return groups.every((group) => group.roundNumber !== undefined);
|
||||
}
|
||||
|
||||
function fixedFormat(type: 'paired-series', gameCount: number) {
|
||||
return { type, rule: fixedRule(gameCount) } as const;
|
||||
}
|
||||
@@ -832,7 +1032,7 @@ function mapGames(
|
||||
teamIds: Map<number, string>,
|
||||
reasons: CompetitionMigrationIssue[],
|
||||
): PlannedGame[] {
|
||||
const mapped: Array<Omit<PlannedGame, 'ordinal'>> = [];
|
||||
const mapped: Array<Omit<PlannedGame, 'ordinal'> & { ordinal?: number }> = [];
|
||||
const games = input.result?.games ?? [];
|
||||
for (const game of games) {
|
||||
const blueTeamId = teamIds.get(game.blueTeamIndex);
|
||||
@@ -882,10 +1082,14 @@ function mapGames(
|
||||
legacy: game,
|
||||
series: resolution.series,
|
||||
confidence: resolution.confidence,
|
||||
...(resolution.ordinal ? { ordinal: resolution.ordinal } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
const grouped = new Map<string, Array<Omit<PlannedGame, 'ordinal'>>>();
|
||||
const grouped = new Map<
|
||||
string,
|
||||
Array<Omit<PlannedGame, 'ordinal'> & { ordinal?: number }>
|
||||
>();
|
||||
for (const game of mapped) {
|
||||
const group = grouped.get(game.series.id) ?? [];
|
||||
group.push(game);
|
||||
@@ -910,9 +1114,42 @@ function mapGames(
|
||||
);
|
||||
continue;
|
||||
}
|
||||
seriesGames.forEach((game, index) =>
|
||||
result.push({ ...game, ordinal: index + 1 }),
|
||||
);
|
||||
const occupiedOrdinals = new Set<number>();
|
||||
for (const game of seriesGames) {
|
||||
if (game.ordinal === undefined) continue;
|
||||
if (
|
||||
game.ordinal < 1 ||
|
||||
game.ordinal > series.gameSlots.length ||
|
||||
occupiedOrdinals.has(game.ordinal)
|
||||
) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'AMBIGUOUS_GAME_SLOT_MAPPING',
|
||||
`Series ${series.code ?? series.id} has conflicting exact GameSlot evidence.`,
|
||||
{ seriesId, ordinal: game.ordinal },
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
occupiedOrdinals.add(game.ordinal);
|
||||
}
|
||||
const availableOrdinals = series.gameSlots
|
||||
.map(({ ordinal }) => ordinal)
|
||||
.filter((ordinal) => !occupiedOrdinals.has(ordinal));
|
||||
for (const game of seriesGames) {
|
||||
const ordinal = game.ordinal ?? availableOrdinals.shift();
|
||||
if (ordinal === undefined) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'GAME_SLOT_MAPPING_NOT_FOUND',
|
||||
`Series ${series.code ?? series.id} has no remaining stable GameSlot.`,
|
||||
{ seriesId, gameNumber: game.legacy.gameNumber },
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
result.push({ ...game, ordinal });
|
||||
}
|
||||
}
|
||||
return result.sort(
|
||||
(left, right) =>
|
||||
@@ -928,24 +1165,31 @@ function resolveGameSeries(
|
||||
blueTeamId: string,
|
||||
redTeamId: string,
|
||||
):
|
||||
| { series: SeriesDefinition; confidence: number }
|
||||
| { series: SeriesDefinition; confidence: number; ordinal?: number }
|
||||
| { issue: CompetitionMigrationIssue } {
|
||||
if (game.bracketMatchId) {
|
||||
const series = graph.find(
|
||||
(candidate) => candidate.code === game.bracketMatchId,
|
||||
);
|
||||
return series
|
||||
? { series, confidence: 1 }
|
||||
: {
|
||||
issue: issue(
|
||||
'GAME_SERIES_MAPPING_NOT_FOUND',
|
||||
`Legacy bracket code ${game.bracketMatchId} has no Series.`,
|
||||
{
|
||||
gameNumber: game.gameNumber,
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
},
|
||||
),
|
||||
};
|
||||
if (!series) {
|
||||
return {
|
||||
issue: issue(
|
||||
'GAME_SERIES_MAPPING_NOT_FOUND',
|
||||
`Legacy bracket code ${game.bracketMatchId} has no Series.`,
|
||||
{
|
||||
gameNumber: game.gameNumber,
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
const exactSlot = resolveLegacyGameNumberTarget(input, graph, game, series);
|
||||
if ('issue' in exactSlot) return exactSlot;
|
||||
return {
|
||||
series,
|
||||
confidence: 1,
|
||||
...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const assignments = (input.gameSchedule ?? []).filter(
|
||||
@@ -978,9 +1222,17 @@ function resolveGameSeries(
|
||||
staticSeriesHasTeamSet(series, blueTeamId, redTeamId),
|
||||
);
|
||||
if (candidates.length === 1) {
|
||||
const exactSlot = resolveLegacyGameNumberTarget(
|
||||
input,
|
||||
graph,
|
||||
game,
|
||||
candidates[0],
|
||||
);
|
||||
if ('issue' in exactSlot) return exactSlot;
|
||||
return {
|
||||
series: candidates[0],
|
||||
confidence: assignments.length === 1 ? 0.95 : 0.8,
|
||||
...(exactSlot.ordinal ? { ordinal: exactSlot.ordinal } : {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
@@ -999,6 +1251,107 @@ function resolveGameSeries(
|
||||
};
|
||||
}
|
||||
|
||||
function resolveLegacyGameNumberTarget(
|
||||
input: LegacyMatchInput,
|
||||
graph: SeriesDefinition[],
|
||||
game: LegacyGameInput,
|
||||
series: SeriesDefinition,
|
||||
): { ordinal?: number } | { issue: CompetitionMigrationIssue } {
|
||||
if (input.gameMode === 'double-elimination') {
|
||||
if ((input.doubleElimination?.bracketMatches?.length ?? 0) === 0) return {};
|
||||
const target = resolvePersistedDoubleEliminationGameNumberTarget(
|
||||
input,
|
||||
graph,
|
||||
game.gameNumber,
|
||||
);
|
||||
if ('error' in target) {
|
||||
return {
|
||||
issue: issue('GAME_SLOT_MAPPING_NOT_FOUND', target.error, {
|
||||
gameNumber: game.gameNumber,
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
seriesId: series.id,
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (target.series.id !== series.id) {
|
||||
return {
|
||||
issue: issue(
|
||||
'GAME_SLOT_MAPPING_CONFLICT',
|
||||
`Legacy game ${game.gameNumber} conflicts with its persisted double-elimination topology.`,
|
||||
{
|
||||
gameNumber: game.gameNumber,
|
||||
bracketMatchId: game.bracketMatchId,
|
||||
seriesId: series.id,
|
||||
targetSeriesId: target.series.id,
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
return { ordinal: target.slot.ordinal };
|
||||
}
|
||||
|
||||
if (
|
||||
input.gameMode === 'round-robin' &&
|
||||
(input.gameSchedule?.length ?? 0) > 0
|
||||
) {
|
||||
const assignment = input.gameSchedule!.find(
|
||||
(candidate) => candidate.gameNumber === game.gameNumber,
|
||||
);
|
||||
if (!assignment) {
|
||||
return {
|
||||
issue: issue(
|
||||
'GAME_SLOT_MAPPING_NOT_FOUND',
|
||||
`Legacy round-robin game ${game.gameNumber} is absent from its persisted schedule.`,
|
||||
{ gameNumber: game.gameNumber, seriesId: series.id },
|
||||
),
|
||||
};
|
||||
}
|
||||
const samePair = input
|
||||
.gameSchedule!.filter(
|
||||
(candidate) =>
|
||||
unorderedNumberPair(candidate.teamAIndex, candidate.teamBIndex) ===
|
||||
unorderedNumberPair(assignment.teamAIndex, assignment.teamBIndex),
|
||||
)
|
||||
.sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
const ordinal =
|
||||
samePair.findIndex(
|
||||
(candidate) => candidate.gameNumber === game.gameNumber,
|
||||
) + 1;
|
||||
if (!series.gameSlots.some((slot) => slot.ordinal === ordinal)) {
|
||||
return {
|
||||
issue: issue(
|
||||
'GAME_SLOT_MAPPING_NOT_FOUND',
|
||||
`Legacy round-robin game ${game.gameNumber} has no stable GameSlot ordinal.`,
|
||||
{ gameNumber: game.gameNumber, seriesId: series.id, ordinal },
|
||||
),
|
||||
};
|
||||
}
|
||||
return { ordinal };
|
||||
}
|
||||
|
||||
const flattened = graph.flatMap((candidateSeries) =>
|
||||
candidateSeries.gameSlots.map((slot) => ({
|
||||
series: candidateSeries,
|
||||
ordinal: slot.ordinal,
|
||||
})),
|
||||
);
|
||||
const target = flattened[game.gameNumber - 1];
|
||||
if (!target || target.series.id !== series.id) {
|
||||
return {
|
||||
issue: issue(
|
||||
'GAME_SLOT_MAPPING_CONFLICT',
|
||||
`Legacy game ${game.gameNumber} conflicts with the canonical global GameSlot topology.`,
|
||||
{
|
||||
gameNumber: game.gameNumber,
|
||||
seriesId: series.id,
|
||||
targetSeriesId: target?.series.id,
|
||||
},
|
||||
),
|
||||
};
|
||||
}
|
||||
return { ordinal: target.ordinal };
|
||||
}
|
||||
|
||||
function staticSeriesHasTeamSet(
|
||||
series: SeriesDefinition,
|
||||
leftTeamId: string,
|
||||
@@ -1492,53 +1845,14 @@ function resolveGlobalGameNumberTarget(params: {
|
||||
params.input.gameMode === 'double-elimination' &&
|
||||
bracketMatches.length > 0
|
||||
) {
|
||||
const seenBracketNumbers = new Set<number>();
|
||||
const ordered = [...bracketMatches].sort(
|
||||
(left, right) =>
|
||||
(positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) -
|
||||
(positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) ||
|
||||
left.bracketMatchId.localeCompare(right.bracketMatchId),
|
||||
);
|
||||
let nextGameNumber = 1;
|
||||
for (const bracketMatch of ordered) {
|
||||
const bracketNumber = positiveInteger(bracketMatch.gameNumber);
|
||||
if (
|
||||
!bracketNumber ||
|
||||
seenBracketNumbers.has(bracketNumber) ||
|
||||
bracketNumber !== seenBracketNumbers.size + 1
|
||||
) {
|
||||
return assignmentMappingNotFound(
|
||||
params,
|
||||
'The persisted double-elimination topology has ambiguous Series numbering.',
|
||||
);
|
||||
}
|
||||
seenBracketNumbers.add(bracketNumber);
|
||||
const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1;
|
||||
if (
|
||||
gameNumber >= nextGameNumber &&
|
||||
gameNumber < nextGameNumber + gameCount
|
||||
) {
|
||||
const series = params.graph.find(
|
||||
(candidate) => candidate.code === bracketMatch.bracketMatchId,
|
||||
);
|
||||
const ordinal = gameNumber - nextGameNumber + 1;
|
||||
const slot = series?.gameSlots.find(
|
||||
(candidate) => candidate.ordinal === ordinal,
|
||||
);
|
||||
if (!series || !slot) {
|
||||
return assignmentMappingNotFound(
|
||||
params,
|
||||
'The persisted double-elimination GameSlot has no Competition target.',
|
||||
);
|
||||
}
|
||||
return { series, slot };
|
||||
}
|
||||
nextGameNumber += gameCount;
|
||||
}
|
||||
return assignmentMappingNotFound(
|
||||
params,
|
||||
'TournamentCode gameNumber is outside the persisted double-elimination topology.',
|
||||
const target = resolvePersistedDoubleEliminationGameNumberTarget(
|
||||
params.input,
|
||||
params.graph,
|
||||
gameNumber,
|
||||
);
|
||||
return 'error' in target
|
||||
? assignmentMappingNotFound(params, target.error)
|
||||
: target;
|
||||
}
|
||||
|
||||
const schedule = params.input.gameSchedule ?? [];
|
||||
@@ -1608,6 +1922,59 @@ function resolveGlobalGameNumberTarget(params: {
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePersistedDoubleEliminationGameNumberTarget(
|
||||
input: LegacyMatchInput,
|
||||
graph: SeriesDefinition[],
|
||||
gameNumber: number,
|
||||
): TournamentCodeAssignmentTarget | { error: string } {
|
||||
const seenBracketNumbers = new Set<number>();
|
||||
const ordered = [...(input.doubleElimination?.bracketMatches ?? [])].sort(
|
||||
(left, right) =>
|
||||
(positiveInteger(left.gameNumber) ?? Number.MAX_SAFE_INTEGER) -
|
||||
(positiveInteger(right.gameNumber) ?? Number.MAX_SAFE_INTEGER) ||
|
||||
left.bracketMatchId.localeCompare(right.bracketMatchId),
|
||||
);
|
||||
let nextGameNumber = 1;
|
||||
for (const bracketMatch of ordered) {
|
||||
const bracketNumber = positiveInteger(bracketMatch.gameNumber);
|
||||
if (
|
||||
!bracketNumber ||
|
||||
seenBracketNumbers.has(bracketNumber) ||
|
||||
bracketNumber !== seenBracketNumbers.size + 1
|
||||
) {
|
||||
return {
|
||||
error:
|
||||
'The persisted double-elimination topology has ambiguous Series numbering.',
|
||||
};
|
||||
}
|
||||
seenBracketNumbers.add(bracketNumber);
|
||||
const gameCount = positiveInteger(bracketMatch.gameCount) ?? 1;
|
||||
if (
|
||||
gameNumber >= nextGameNumber &&
|
||||
gameNumber < nextGameNumber + gameCount
|
||||
) {
|
||||
const series = graph.find(
|
||||
(candidate) => candidate.code === bracketMatch.bracketMatchId,
|
||||
);
|
||||
const ordinal = gameNumber - nextGameNumber + 1;
|
||||
const slot = series?.gameSlots.find(
|
||||
(candidate) => candidate.ordinal === ordinal,
|
||||
);
|
||||
return series && slot
|
||||
? { series, slot }
|
||||
: {
|
||||
error:
|
||||
'The persisted double-elimination GameSlot has no Competition target.',
|
||||
};
|
||||
}
|
||||
nextGameNumber += gameCount;
|
||||
}
|
||||
return {
|
||||
error:
|
||||
'The global game number is outside the persisted double-elimination topology.',
|
||||
};
|
||||
}
|
||||
|
||||
function assignmentMappingNotFound(
|
||||
params: {
|
||||
code: LegacyTournamentCodeInput;
|
||||
@@ -1662,7 +2029,6 @@ function buildAssignments(
|
||||
facts: CompetitionMigrationFact[],
|
||||
graph: SeriesDefinition[],
|
||||
teamIds: ReadonlyMap<number, string>,
|
||||
warnings: CompetitionMigrationIssue[],
|
||||
reasons: CompetitionMigrationIssue[],
|
||||
): CompetitionMigrationAssignment[] {
|
||||
const result: CompetitionMigrationAssignment[] = [];
|
||||
@@ -1698,19 +2064,47 @@ function buildAssignments(
|
||||
continue;
|
||||
}
|
||||
const { series, slot } = resolution;
|
||||
if (code.state === 'used' && !gameFact) {
|
||||
warnings.push(
|
||||
const acceptedGame =
|
||||
gameFact ??
|
||||
facts.find(
|
||||
(fact): fact is MigrationGameAcceptedFact =>
|
||||
fact.type === 'game-accepted' && fact.gameSlotId === slot.id,
|
||||
);
|
||||
if (code.state === 'used' && !acceptedGame) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'USED_CODE_WITHOUT_ACCEPTED_GAME',
|
||||
'A used TournamentCode has no accepted legacy game evidence.',
|
||||
'A used TournamentCode must target an accepted legacy game.',
|
||||
{ tournamentCodeId, gameSlotId: slot.id },
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const reservedAt = normalizeDate(
|
||||
code.reservedAt,
|
||||
normalizeDate(code.usedAt, sourceFallbackDate(input)),
|
||||
if (
|
||||
code.riotMatchId &&
|
||||
acceptedGame &&
|
||||
!acceptedGameHasRiotIdentity(acceptedGame, code.riotMatchId)
|
||||
) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'TOURNAMENT_CODE_RIOT_EVIDENCE_CONFLICT',
|
||||
'TournamentCode Riot identity conflicts with the accepted game in its target slot.',
|
||||
{
|
||||
tournamentCodeId,
|
||||
gameSlotId: slot.id,
|
||||
riotMatchId: code.riotMatchId,
|
||||
},
|
||||
),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const timestamps = tournamentCodeTimestamps(
|
||||
input,
|
||||
code,
|
||||
tournamentCodeId,
|
||||
reasons,
|
||||
);
|
||||
if (!timestamps) continue;
|
||||
result.push({
|
||||
id: stableId(
|
||||
competitionId,
|
||||
@@ -1722,13 +2116,7 @@ function buildAssignments(
|
||||
gameSlotId: slot.id,
|
||||
tournamentCodeId,
|
||||
state: code.state,
|
||||
reservedAt,
|
||||
...(code.usedAt
|
||||
? { usedAt: normalizeDate(code.usedAt, reservedAt) }
|
||||
: {}),
|
||||
...(code.releasedAt
|
||||
? { releasedAt: normalizeDate(code.releasedAt, reservedAt) }
|
||||
: {}),
|
||||
...timestamps,
|
||||
...(code.riotMatchId ? { riotMatchId: code.riotMatchId } : {}),
|
||||
commandId: stableId(
|
||||
competitionId,
|
||||
@@ -1764,6 +2152,88 @@ function buildAssignments(
|
||||
return result.sort((left, right) => left.id.localeCompare(right.id));
|
||||
}
|
||||
|
||||
function acceptedGameHasRiotIdentity(
|
||||
fact: MigrationGameAcceptedFact,
|
||||
riotMatchId: string,
|
||||
): boolean {
|
||||
return (
|
||||
(fact.evidence.type === 'riot' &&
|
||||
fact.evidence.riotMatchId === riotMatchId) ||
|
||||
(fact.evidence.type === 'legacy' &&
|
||||
fact.evidence.legacyReference.endsWith(`:${riotMatchId}`))
|
||||
);
|
||||
}
|
||||
|
||||
function tournamentCodeTimestamps(
|
||||
input: LegacyMatchInput,
|
||||
code: LegacyTournamentCodeInput,
|
||||
tournamentCodeId: string,
|
||||
reasons: CompetitionMigrationIssue[],
|
||||
): Pick<
|
||||
CompetitionMigrationAssignment,
|
||||
'reservedAt' | 'usedAt' | 'releasedAt' | 'voidedAt'
|
||||
> | null {
|
||||
const raw = {
|
||||
createdAt: optionalDate(code.createdAt),
|
||||
reservedAt: optionalDate(code.reservedAt),
|
||||
usedAt: optionalDate(code.usedAt),
|
||||
releasedAt: optionalDate(code.releasedAt),
|
||||
voidedAt: optionalDate(code.voidedAt),
|
||||
updatedAt: optionalDate(code.updatedAt),
|
||||
};
|
||||
if (Object.values(raw).some((value) => value === null)) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'INVALID_TOURNAMENT_CODE_TIMELINE',
|
||||
'TournamentCode lifecycle contains an invalid timestamp.',
|
||||
{ tournamentCodeId },
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
const reservedAt =
|
||||
raw.reservedAt ??
|
||||
raw.createdAt ??
|
||||
raw.usedAt ??
|
||||
raw.releasedAt ??
|
||||
raw.voidedAt ??
|
||||
sourceFallbackDate(input);
|
||||
const usedAt = raw.usedAt ?? undefined;
|
||||
const releasedAt = raw.releasedAt ?? undefined;
|
||||
const voidedAt =
|
||||
raw.voidedAt ??
|
||||
(code.state === 'voided'
|
||||
? (raw.updatedAt ?? releasedAt ?? usedAt ?? reservedAt)
|
||||
: undefined);
|
||||
const ordered = [reservedAt, usedAt, releasedAt, voidedAt].filter(
|
||||
(value): value is string => value !== undefined,
|
||||
);
|
||||
if (ordered.some((value, index) => index > 0 && value < ordered[index - 1])) {
|
||||
reasons.push(
|
||||
issue(
|
||||
'INVALID_TOURNAMENT_CODE_TIMELINE',
|
||||
'TournamentCode lifecycle timestamps are not chronological.',
|
||||
{ tournamentCodeId },
|
||||
),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
reservedAt,
|
||||
...(usedAt ? { usedAt } : {}),
|
||||
...(releasedAt ? { releasedAt } : {}),
|
||||
...(voidedAt ? { voidedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function optionalDate(value: unknown): string | undefined | null {
|
||||
if (value === undefined || value === null || value === '') return undefined;
|
||||
const date =
|
||||
value instanceof Date ? value : new Date(value as string | number);
|
||||
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
function seriesCompletionDate(input: LegacyMatchInput, code?: string): string {
|
||||
const completedAt = input.doubleElimination?.bracketMatches?.find(
|
||||
(bracketMatch) => bracketMatch.bracketMatchId === code,
|
||||
|
||||
Reference in new issue
Block a user