release/86 #2
No files matched your search
@@ -0,0 +1,191 @@
|
||||
import {
|
||||
assertReversalPreview,
|
||||
buildReversalFacts,
|
||||
previewSeriesReversal,
|
||||
} from './competition-reversal';
|
||||
|
||||
describe('Competition reversal planning', () => {
|
||||
const graph = [
|
||||
series('series-parent', [team('team-8'), team('team-3')]),
|
||||
series('series-child', [winner('series-parent'), loser('series-parent')]),
|
||||
];
|
||||
const facts = [
|
||||
accepted('fact-parent', 'series-parent', 'slot-parent', 'team-8', 'team-3'),
|
||||
accepted('fact-child', 'series-child', 'slot-child', 'team-8', 'team-3'),
|
||||
];
|
||||
const assignments = [
|
||||
assignment('assignment-parent', 'series-parent', 'slot-parent', 'used'),
|
||||
assignment('assignment-child', 'series-child', 'slot-child', 'reserved'),
|
||||
];
|
||||
|
||||
it('rejects strict reversal when a descendant has result activity', () => {
|
||||
expect(() =>
|
||||
previewSeriesReversal({
|
||||
competitionId: 'competition-1',
|
||||
revision: 2,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'strict',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
}),
|
||||
).toThrow(
|
||||
expect.objectContaining({ code: 'REVERSAL_DESCENDANT_ACTIVITY' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('builds a deterministic cascade impact from graph descendants', () => {
|
||||
const first = previewSeriesReversal({
|
||||
competitionId: 'competition-1',
|
||||
revision: 2,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'cascade',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
});
|
||||
const second = previewSeriesReversal({
|
||||
competitionId: 'competition-1',
|
||||
revision: 2,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'cascade',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
});
|
||||
|
||||
expect(second).toEqual(first);
|
||||
expect(first).toEqual({
|
||||
sourceRevision: 2,
|
||||
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
impact: {
|
||||
seriesIds: ['series-parent', 'series-child'],
|
||||
factIds: ['fact-parent', 'fact-child'],
|
||||
gameSlotIds: ['slot-parent', 'slot-child'],
|
||||
teamIds: ['team-3', 'team-8'],
|
||||
releasesReservedCodes: 1,
|
||||
voidsUsedCodes: 1,
|
||||
requiresStatsRebuild: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a stale or changed preview before emitting reversal facts', () => {
|
||||
const preview = previewSeriesReversal({
|
||||
competitionId: 'competition-1',
|
||||
revision: 2,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'cascade',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
});
|
||||
|
||||
expect(() =>
|
||||
assertReversalPreview(
|
||||
{
|
||||
competitionId: 'competition-1',
|
||||
revision: 3,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'cascade',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
},
|
||||
preview.impactHash,
|
||||
),
|
||||
).toThrow(expect.objectContaining({ code: 'REVERSAL_PREVIEW_STALE' }));
|
||||
});
|
||||
|
||||
it('emits one append-only reversal fact for every active result fact', () => {
|
||||
const preview = previewSeriesReversal({
|
||||
competitionId: 'competition-1',
|
||||
revision: 2,
|
||||
seriesId: 'series-parent',
|
||||
mode: 'cascade',
|
||||
graph,
|
||||
facts,
|
||||
assignments,
|
||||
});
|
||||
|
||||
expect(
|
||||
buildReversalFacts({
|
||||
preview,
|
||||
facts,
|
||||
competitionId: 'competition-1',
|
||||
commandId: 'command-reverse',
|
||||
nextRevision: 3,
|
||||
actor: { type: 'user', userId: 'admin-1' },
|
||||
reason: '잘못 수집된 게임',
|
||||
occurredAt: new Date('2026-07-12T01:00:00.000Z'),
|
||||
}),
|
||||
).toEqual([
|
||||
expect.objectContaining({
|
||||
type: 'game-voided',
|
||||
gameAcceptedFactId: 'fact-parent',
|
||||
revision: 3,
|
||||
ordinalWithinRevision: 1,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: 'game-voided',
|
||||
gameAcceptedFactId: 'fact-child',
|
||||
revision: 3,
|
||||
ordinalWithinRevision: 2,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
function series(id: string, sources: Array<Record<string, unknown>>) {
|
||||
return {
|
||||
id,
|
||||
stage: { type: 'upper' as const, displayOrder: 1 },
|
||||
slots: [
|
||||
{ position: 'A' as const, source: sources[0] },
|
||||
{ position: 'B' as const, source: sources[1] },
|
||||
],
|
||||
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
|
||||
gameSlots: [{ id: id.replace('series', 'slot'), seriesId: id, ordinal: 1 }],
|
||||
};
|
||||
}
|
||||
|
||||
function team(teamId: string) {
|
||||
return { type: 'team', teamId };
|
||||
}
|
||||
|
||||
function winner(seriesId: string) {
|
||||
return { type: 'series-outcome', seriesId, select: 'winner' };
|
||||
}
|
||||
|
||||
function loser(seriesId: string) {
|
||||
return { type: 'series-outcome', seriesId, select: 'loser' };
|
||||
}
|
||||
|
||||
function accepted(
|
||||
id: string,
|
||||
seriesId: string,
|
||||
gameSlotId: string,
|
||||
winnerTeamId: string,
|
||||
loserTeamId: string,
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
type: 'game-accepted',
|
||||
seriesId,
|
||||
gameSlotId,
|
||||
mapping: {
|
||||
blueTeamId: winnerTeamId,
|
||||
redTeamId: loserTeamId,
|
||||
winnerTeamId,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function assignment(
|
||||
id: string,
|
||||
seriesId: string,
|
||||
gameSlotId: string,
|
||||
state: 'reserved' | 'used',
|
||||
) {
|
||||
return { id, seriesId, gameSlotId, state };
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
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],
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user