363 lines
9.8 KiB
TypeScript
363 lines
9.8 KiB
TypeScript
import { createHash } from 'node:crypto';
|
|
|
|
export type SeriesReversalMode = 'strict' | 'cascade';
|
|
|
|
interface ReversalGraphSeries {
|
|
id: string;
|
|
slots: ReadonlyArray<{
|
|
source: Readonly<{
|
|
type?: unknown;
|
|
seriesId?: unknown;
|
|
}>;
|
|
}>;
|
|
}
|
|
|
|
interface ReversalFactBase {
|
|
id: string;
|
|
type: string;
|
|
seriesId?: string;
|
|
}
|
|
|
|
interface AcceptedGameFact extends ReversalFactBase {
|
|
type: 'game-accepted';
|
|
seriesId: string;
|
|
gameSlotId: string;
|
|
mapping: {
|
|
blueTeamId: string;
|
|
redTeamId: string;
|
|
winnerTeamId: string;
|
|
};
|
|
}
|
|
|
|
interface AdjudicatedFact extends ReversalFactBase {
|
|
type: 'series-adjudicated';
|
|
seriesId: string;
|
|
decision:
|
|
| { type: string; winnerTeamId?: string }
|
|
| { type: 'administrative-draw' };
|
|
}
|
|
|
|
interface VoidedGameFact extends ReversalFactBase {
|
|
type: 'game-voided';
|
|
gameAcceptedFactId: string;
|
|
}
|
|
|
|
interface ReversedAdjudicationFact extends ReversalFactBase {
|
|
type: 'adjudication-reversed';
|
|
adjudicationFactId: string;
|
|
}
|
|
|
|
type ReversalFact =
|
|
| AcceptedGameFact
|
|
| AdjudicatedFact
|
|
| VoidedGameFact
|
|
| ReversedAdjudicationFact;
|
|
|
|
interface ReversalAssignment {
|
|
seriesId: string;
|
|
gameSlotId: string;
|
|
state: 'reserved' | 'used' | 'released' | 'voided' | string;
|
|
}
|
|
|
|
export interface ReversalPreviewInput {
|
|
competitionId: string;
|
|
revision: number;
|
|
seriesId: string;
|
|
mode: SeriesReversalMode;
|
|
graph: readonly ReversalGraphSeries[];
|
|
facts: readonly unknown[];
|
|
assignments: readonly ReversalAssignment[];
|
|
}
|
|
|
|
export interface SeriesReversalImpact {
|
|
seriesIds: string[];
|
|
factIds: string[];
|
|
gameSlotIds: string[];
|
|
teamIds: string[];
|
|
releasesReservedCodes: number;
|
|
voidsUsedCodes: number;
|
|
requiresStatsRebuild: boolean;
|
|
}
|
|
|
|
export interface SeriesReversalPreview {
|
|
sourceRevision: number;
|
|
impactHash: string;
|
|
impact: SeriesReversalImpact;
|
|
}
|
|
|
|
export class CompetitionReversalError extends Error {
|
|
constructor(
|
|
public readonly code:
|
|
| 'REVERSAL_SERIES_NOT_FOUND'
|
|
| 'REVERSAL_NO_ACTIVE_RESULT'
|
|
| 'REVERSAL_DESCENDANT_ACTIVITY'
|
|
| 'REVERSAL_PREVIEW_STALE'
|
|
| 'REVERSAL_REASON_REQUIRED',
|
|
message: string,
|
|
public readonly details?: Readonly<Record<string, unknown>>,
|
|
) {
|
|
super(message);
|
|
this.name = 'CompetitionReversalError';
|
|
}
|
|
}
|
|
|
|
/** Calculate the exact immutable facts and code assignments affected by a reversal. */
|
|
export function previewSeriesReversal(
|
|
input: ReversalPreviewInput,
|
|
): SeriesReversalPreview {
|
|
const seriesOrder = affectedSeries(input.graph, input.seriesId);
|
|
const facts = normalizeReversalFacts(input.facts);
|
|
const active = activeResultFacts(facts);
|
|
const affectedSet = new Set(seriesOrder);
|
|
const descendantSet = new Set(seriesOrder.slice(1));
|
|
const descendantActivity = active.filter((fact) =>
|
|
descendantSet.has(fact.seriesId),
|
|
);
|
|
const descendantUsedAssignments = input.assignments.filter(
|
|
(assignment) =>
|
|
descendantSet.has(assignment.seriesId) && assignment.state === 'used',
|
|
);
|
|
|
|
if (
|
|
input.mode === 'strict' &&
|
|
(descendantActivity.length > 0 || descendantUsedAssignments.length > 0)
|
|
) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_DESCENDANT_ACTIVITY',
|
|
'A descendant Series has result or used-code activity. Preview a cascade reversal.',
|
|
{
|
|
seriesIds: [
|
|
...new Set([
|
|
...descendantActivity.map(({ seriesId }) => seriesId),
|
|
...descendantUsedAssignments.map(({ seriesId }) => seriesId),
|
|
]),
|
|
],
|
|
},
|
|
);
|
|
}
|
|
|
|
const selectedFacts = active.filter(
|
|
(fact) =>
|
|
fact.seriesId === input.seriesId ||
|
|
(input.mode === 'cascade' && descendantSet.has(fact.seriesId)),
|
|
);
|
|
if (!selectedFacts.some(({ seriesId }) => seriesId === input.seriesId)) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_NO_ACTIVE_RESULT',
|
|
`Series ${input.seriesId} has no active result to reverse.`,
|
|
{ seriesId: input.seriesId },
|
|
);
|
|
}
|
|
|
|
const factOrder = new Map(
|
|
seriesOrder.map((seriesId, index) => [seriesId, index]),
|
|
);
|
|
selectedFacts.sort(
|
|
(left, right) =>
|
|
factOrder.get(left.seriesId)! - factOrder.get(right.seriesId)!,
|
|
);
|
|
const assignments = input.assignments.filter((assignment) =>
|
|
affectedSet.has(assignment.seriesId),
|
|
);
|
|
const teamIds = new Set<string>();
|
|
const gameSlotIds = new Set<string>();
|
|
for (const fact of selectedFacts) {
|
|
if (fact.type === 'game-accepted') {
|
|
gameSlotIds.add(fact.gameSlotId);
|
|
teamIds.add(fact.mapping.blueTeamId);
|
|
teamIds.add(fact.mapping.redTeamId);
|
|
} else if ('winnerTeamId' in fact.decision && fact.decision.winnerTeamId) {
|
|
teamIds.add(fact.decision.winnerTeamId);
|
|
}
|
|
}
|
|
for (const assignment of assignments) gameSlotIds.add(assignment.gameSlotId);
|
|
|
|
const impact: SeriesReversalImpact = {
|
|
seriesIds: seriesOrder,
|
|
factIds: selectedFacts.map(({ id }) => id),
|
|
gameSlotIds: [...gameSlotIds].sort(),
|
|
teamIds: [...teamIds].sort(),
|
|
releasesReservedCodes: assignments.filter(
|
|
({ state }) => state === 'reserved',
|
|
).length,
|
|
voidsUsedCodes: assignments.filter(({ state }) => state === 'used').length,
|
|
requiresStatsRebuild: selectedFacts.some(
|
|
({ type }) => type === 'game-accepted',
|
|
),
|
|
};
|
|
return {
|
|
sourceRevision: input.revision,
|
|
impactHash: hashImpact(input, impact),
|
|
impact,
|
|
};
|
|
}
|
|
|
|
export function assertReversalPreview(
|
|
input: ReversalPreviewInput,
|
|
expectedImpactHash: string,
|
|
): SeriesReversalPreview {
|
|
const current = previewSeriesReversal(input);
|
|
if (current.impactHash !== expectedImpactHash) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_PREVIEW_STALE',
|
|
'The Competition changed after the reversal preview.',
|
|
{ sourceRevision: input.revision },
|
|
);
|
|
}
|
|
return current;
|
|
}
|
|
|
|
export function buildReversalFacts(input: {
|
|
preview: SeriesReversalPreview;
|
|
facts: readonly unknown[];
|
|
competitionId: string;
|
|
commandId: string;
|
|
nextRevision: number;
|
|
actor: Readonly<Record<string, unknown>>;
|
|
reason: string;
|
|
occurredAt: Date;
|
|
}): Array<Record<string, unknown>> {
|
|
if (!input.reason.trim()) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_REASON_REQUIRED',
|
|
'A reversal reason is required.',
|
|
);
|
|
}
|
|
const byId = new Map(
|
|
normalizeReversalFacts(input.facts).map((fact) => [fact.id, fact]),
|
|
);
|
|
const causationId = deterministicId(
|
|
input.competitionId,
|
|
input.commandId,
|
|
'reversal',
|
|
);
|
|
|
|
return input.preview.impact.factIds.map((factId, index) => {
|
|
const target = byId.get(factId);
|
|
if (!target) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_PREVIEW_STALE',
|
|
`Fact ${factId} no longer matches the preview.`,
|
|
);
|
|
}
|
|
const common = {
|
|
id: deterministicId(input.competitionId, input.commandId, factId),
|
|
competitionId: input.competitionId,
|
|
revision: input.nextRevision,
|
|
ordinalWithinRevision: index + 1,
|
|
commandId: input.commandId,
|
|
schemaVersion: 1,
|
|
actor: input.actor,
|
|
occurredAt: input.occurredAt,
|
|
recordedAt: input.occurredAt,
|
|
causationId,
|
|
reason: input.reason,
|
|
};
|
|
return target.type === 'game-accepted'
|
|
? {
|
|
...common,
|
|
type: 'game-voided',
|
|
gameAcceptedFactId: target.id,
|
|
}
|
|
: {
|
|
...common,
|
|
type: 'adjudication-reversed',
|
|
adjudicationFactId: target.id,
|
|
};
|
|
});
|
|
}
|
|
|
|
function affectedSeries(
|
|
graph: readonly ReversalGraphSeries[],
|
|
sourceSeriesId: string,
|
|
): string[] {
|
|
if (!graph.some(({ id }) => id === sourceSeriesId)) {
|
|
throw new CompetitionReversalError(
|
|
'REVERSAL_SERIES_NOT_FOUND',
|
|
`Series ${sourceSeriesId} does not exist.`,
|
|
);
|
|
}
|
|
const affected = new Set([sourceSeriesId]);
|
|
let changed = true;
|
|
while (changed) {
|
|
changed = false;
|
|
for (const definition of graph) {
|
|
if (affected.has(definition.id)) continue;
|
|
if (
|
|
definition.slots.some(({ source }) =>
|
|
typeof source.seriesId === 'string'
|
|
? affected.has(source.seriesId)
|
|
: false,
|
|
)
|
|
) {
|
|
affected.add(definition.id);
|
|
changed = true;
|
|
}
|
|
}
|
|
}
|
|
return graph.filter(({ id }) => affected.has(id)).map(({ id }) => id);
|
|
}
|
|
|
|
function normalizeReversalFacts(facts: readonly unknown[]): ReversalFact[] {
|
|
return facts.filter((fact): fact is ReversalFact => {
|
|
if (!isRecord(fact) || typeof fact.id !== 'string') return false;
|
|
return (
|
|
fact.type === 'game-accepted' ||
|
|
fact.type === 'series-adjudicated' ||
|
|
fact.type === 'game-voided' ||
|
|
fact.type === 'adjudication-reversed'
|
|
);
|
|
});
|
|
}
|
|
|
|
function activeResultFacts(
|
|
facts: readonly ReversalFact[],
|
|
): Array<AcceptedGameFact | AdjudicatedFact> {
|
|
const voided = new Set(
|
|
facts
|
|
.filter((fact): fact is VoidedGameFact => fact.type === 'game-voided')
|
|
.map(({ gameAcceptedFactId }) => gameAcceptedFactId),
|
|
);
|
|
const reversed = new Set(
|
|
facts
|
|
.filter(
|
|
(fact): fact is ReversedAdjudicationFact =>
|
|
fact.type === 'adjudication-reversed',
|
|
)
|
|
.map(({ adjudicationFactId }) => adjudicationFactId),
|
|
);
|
|
return facts.filter(
|
|
(fact): fact is AcceptedGameFact | AdjudicatedFact =>
|
|
(fact.type === 'game-accepted' && !voided.has(fact.id)) ||
|
|
(fact.type === 'series-adjudicated' && !reversed.has(fact.id)),
|
|
);
|
|
}
|
|
|
|
function hashImpact(
|
|
input: ReversalPreviewInput,
|
|
impact: SeriesReversalImpact,
|
|
): string {
|
|
return createHash('sha256')
|
|
.update(
|
|
JSON.stringify({
|
|
competitionId: input.competitionId,
|
|
sourceRevision: input.revision,
|
|
seriesId: input.seriesId,
|
|
mode: input.mode,
|
|
impact,
|
|
}),
|
|
)
|
|
.digest('hex');
|
|
}
|
|
|
|
function deterministicId(...parts: string[]): string {
|
|
return createHash('sha256')
|
|
.update(JSON.stringify(parts))
|
|
.digest('hex')
|
|
.slice(0, 24);
|
|
}
|
|
|
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === 'object' && value !== null;
|
|
}
|