feat: expose revision-safe competition API

This commit is contained in:
dahyeon committed 2026-07-12 19:34:15 +00:00
1 parent f3286e7fd1
commit 55e5b8df70
11 files changed
+2443 -19

No files matched your search

@@ -5,6 +5,13 @@ import { ConnectionService } from '../global/database/connection.service';
import type { Competition, CompetitionOutbox } from './competition.schema';
import { CompetitionCommandError } from './competition.errors';
import { projectCompetition } from './domain/competition-projector';
import {
assertReversalPreview,
buildReversalFacts,
previewSeriesReversal as planSeriesReversal,
type SeriesReversalMode,
type SeriesReversalPreview,
} from './domain/competition-reversal';
type PersistenceId = string | mongoose.Types.ObjectId;
@@ -25,6 +32,9 @@ export interface AcceptGameCommand {
ordinal: number;
evidence: Readonly<Record<string, unknown>>;
mapping: Readonly<Record<string, unknown>>;
startedAt?: Date;
durationSeconds?: number;
participants?: readonly Readonly<Record<string, unknown>>[];
tournamentCode?: {
tournamentCodeId: PersistenceId;
riotMatchId: string;
@@ -49,6 +59,21 @@ export interface AdjudicateSeriesCommand {
reason: string;
}
export interface PreviewSeriesReversalCommand {
competitionId: PersistenceId;
expectedRevision: number;
seriesId: PersistenceId;
mode: SeriesReversalMode;
}
export interface ReverseSeriesCommand extends PreviewSeriesReversalCommand {
idempotencyKey: string;
actor: CompetitionCommandActor;
occurredAt?: Date;
reason: string;
impactHash: string;
}
export interface CompetitionCommandResult {
competition: unknown;
commandId: string;
@@ -57,7 +82,7 @@ export interface CompetitionCommandResult {
}
interface CommandEnvelope {
type: 'accept-game' | 'adjudicate-series';
type: 'accept-game' | 'adjudicate-series' | 'reverse-series';
competitionId: PersistenceId;
expectedRevision: number;
idempotencyKey: string;
@@ -87,6 +112,11 @@ export class CompetitionCommandService {
ordinal: command.ordinal,
evidence: command.evidence,
mapping: command.mapping,
...(command.startedAt ? { startedAt: command.startedAt } : {}),
...(command.durationSeconds === undefined
? {}
: { durationSeconds: command.durationSeconds }),
...(command.participants ? { participants: command.participants } : {}),
...(command.tournamentCode
? { tournamentCode: command.tournamentCode }
: {}),
@@ -112,6 +142,214 @@ export class CompetitionCommandService {
});
}
public async previewSeriesReversal(
command: PreviewSeriesReversalCommand,
): Promise<SeriesReversalPreview> {
if (
!Number.isInteger(command.expectedRevision) ||
command.expectedRevision < 0
) {
throw invalidCommandError();
}
const CompetitionModel =
await this.connectionService.getModel('competition');
const competition = await CompetitionModel.findById(command.competitionId)
.lean()
.exec();
if (!competition) throw competitionNotFound(command.competitionId);
assertExpectedRevision(competition.revision, command.expectedRevision);
const [FactModel, AssignmentModel] = await Promise.all([
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('tournamentCodeAssignment'),
]);
const [facts, assignments] = await Promise.all([
FactModel.find({ competitionId: command.competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.lean()
.exec(),
AssignmentModel.find({ competitionId: command.competitionId })
.lean()
.exec(),
]);
const revisionCheck = await CompetitionModel.findById(command.competitionId)
.lean()
.exec();
if (!revisionCheck) throw competitionNotFound(command.competitionId);
assertExpectedRevision(revisionCheck.revision, command.expectedRevision);
return planSeriesReversal(
reversalInput(competition, command, facts, assignments),
);
}
public async reverseSeries(
command: ReverseSeriesCommand,
): Promise<CompetitionCommandResult> {
const envelope: CommandEnvelope = {
type: 'reverse-series',
competitionId: command.competitionId,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
actor: command.actor,
occurredAt: command.occurredAt,
payload: {
seriesId: command.seriesId,
mode: command.mode,
reason: command.reason.trim(),
impactHash: command.impactHash,
},
};
validateEnvelope(envelope);
if (!/^[a-f0-9]{64}$/.test(command.impactHash)) {
throw invalidCommandError();
}
const session = await this.connectionService.createSession();
if (!session) {
throw new CompetitionCommandError(
'COMPETITION_TRANSACTION_UNAVAILABLE',
'A MongoDB transaction is required for Competition commands.',
500,
);
}
try {
session.startTransaction();
const [CompetitionModel, FactModel, OutboxModel, AssignmentModel] =
await Promise.all([
this.connectionService.getModel('competition'),
this.connectionService.getModel('competitionFact'),
this.connectionService.getModel('competitionOutbox'),
this.connectionService.getModel('tournamentCodeAssignment'),
]);
const requestHash = requestHashFor(envelope);
const commandId = commandIdFor(envelope);
const receipt = await OutboxModel.findOne({
competitionId: command.competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
command.competitionId,
requestHash,
receipt,
session,
);
await session.commitTransaction();
return replay;
}
const competition = await CompetitionModel.findById(command.competitionId)
.session(session)
.lean()
.exec();
if (!competition) throw competitionNotFound(command.competitionId);
assertExpectedRevision(competition.revision, command.expectedRevision);
const [existingFacts, assignments] = await Promise.all([
FactModel.find({ competitionId: command.competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec(),
AssignmentModel.find({ competitionId: command.competitionId })
.session(session)
.lean()
.exec(),
]);
const input = reversalInput(
competition,
command,
existingFacts,
assignments,
);
const preview = assertReversalPreview(input, command.impactHash);
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const occurredAt = command.occurredAt ?? recordedAt;
const rawFacts = buildReversalFacts({
preview,
facts: input.facts,
competitionId: idString(command.competitionId),
commandId,
nextRevision,
actor: toPlain(command.actor) as Readonly<Record<string, unknown>>,
reason: command.reason.trim(),
occurredAt,
});
const reversalFacts = rawFacts.map((rawFact) =>
persistenceReversalFact(rawFact, command, commandId, requestHash),
);
const projection = projectCompetition({
competitionId: idString(command.competitionId),
revision: nextRevision,
projectorVersion: competition.projectorVersion,
teams: toPlain(competition.teams) as never,
format: toPlain(competition.format) as never,
seriesGraph: toPlain(competition.seriesGraph) as never,
facts: [...existingFacts, ...reversalFacts].map(factForProjection),
});
await FactModel.insertMany(reversalFacts, { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: command.competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
)
.lean()
.exec();
if (!updated) throw staleRevisionError(command.expectedRevision);
await this.applyReversalAssignments(
command.competitionId,
preview,
assignments,
commandId,
recordedAt,
session,
);
await OutboxModel.insertMany(
[
buildOutbox(
command.competitionId,
envelope,
commandId,
requestHash,
nextRevision,
reversalFacts,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
throw error;
} finally {
await session.endSession();
}
}
private async runCommand(
command: CommandEnvelope,
): Promise<CompetitionCommandResult> {
@@ -347,6 +585,53 @@ export class CompetitionCommandService {
throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId);
}
}
private async applyReversalAssignments(
competitionId: PersistenceId,
preview: SeriesReversalPreview,
assignments: Array<Record<string, any>>,
commandId: string,
recordedAt: Date,
session: mongoose.ClientSession,
): Promise<void> {
const impactedSlotIds = new Set(preview.impact.gameSlotIds);
const impacted = assignments.filter(
(assignment) =>
impactedSlotIds.has(idString(assignment.gameSlotId)) &&
(assignment.state === 'reserved' || assignment.state === 'used'),
);
if (impacted.length === 0) return;
const gameSlotIds = impacted.map(({ gameSlotId }) =>
persistenceObjectId(gameSlotId),
);
const codeIds = impacted.map(({ tournamentCodeId }) =>
persistenceObjectId(tournamentCodeId),
);
const AssignmentModel = (await this.connectionService.getModel(
'tournamentCodeAssignment',
)) as mongoose.Model<any>;
await AssignmentModel.updateMany(
{
competitionId,
gameSlotId: { $in: gameSlotIds },
state: { $in: ['reserved', 'used'] },
},
reversalStatePipeline(recordedAt, commandId),
{ session },
);
const TournamentCodeModel = (await this.connectionService.getModel(
'tournamentCode',
)) as mongoose.Model<any>;
await TournamentCodeModel.updateMany(
{
_id: { $in: codeIds },
state: { $in: ['reserved', 'used'] },
},
tournamentCodeReversalStatePipeline(recordedAt),
{ session },
);
}
}
function validateEnvelope(command: CommandEnvelope): void {
@@ -355,14 +640,11 @@ function validateEnvelope(command: CommandEnvelope): void {
command.expectedRevision < 0 ||
command.idempotencyKey.trim().length === 0 ||
command.idempotencyKey.length > 200 ||
(command.type === 'adjudicate-series' &&
((command.type === 'adjudicate-series' ||
command.type === 'reverse-series') &&
String(command.payload.reason).trim().length === 0)
) {
throw new CompetitionCommandError(
'INVALID_COMPETITION_COMMAND',
'Expected revision and a non-empty Idempotency-Key are required.',
422,
);
throw invalidCommandError();
}
}
@@ -419,16 +701,29 @@ function buildFact(
ordinal: command.payload.ordinal,
evidence: command.payload.evidence,
mapping: command.payload.mapping,
...(command.payload.startedAt === undefined
? {}
: { startedAt: command.payload.startedAt }),
...(command.payload.durationSeconds === undefined
? {}
: { durationSeconds: command.payload.durationSeconds }),
...(command.payload.participants === undefined
? {}
: { participants: command.payload.participants }),
};
}
return {
...common,
type: 'series-adjudicated',
seriesId: command.payload.seriesId,
decision: command.payload.decision,
reason: command.payload.reason,
};
if (command.type === 'adjudicate-series') {
return {
...common,
type: 'series-adjudicated',
seriesId: command.payload.seriesId,
decision: command.payload.decision,
reason: command.payload.reason,
};
}
throw invalidCommandError();
}
function buildOutbox(
@@ -437,11 +732,14 @@ function buildOutbox(
commandId: string,
requestHash: string,
revision: number,
fact: Readonly<Record<string, unknown>>,
fact:
| Readonly<Record<string, unknown>>
| readonly Readonly<Record<string, unknown>>[],
projection: unknown,
updatedCompetition: unknown,
recordedAt: Date,
): Readonly<Record<string, unknown>> {
const facts = Array.isArray(fact) ? fact : [fact];
return {
eventId: `${commandId}:competition-projected`,
competitionId,
@@ -453,7 +751,7 @@ function buildOutbox(
payload: {
competitionId: idString(competitionId),
sourceRevision: revision,
factIds: [idString(fact._id as PersistenceId)],
factIds: facts.map((entry) => idString(entry._id as PersistenceId)),
projection,
phase:
isRecord(projection) && typeof projection.phase === 'string'
@@ -558,3 +856,122 @@ function tournamentCodeConflict(
},
);
}
function reversalInput(
competition: Pick<Competition, 'revision' | 'seriesGraph'>,
command: PreviewSeriesReversalCommand,
facts: readonly unknown[],
assignments: readonly Record<string, any>[],
) {
return {
competitionId: idString(command.competitionId),
revision: competition.revision,
seriesId: idString(command.seriesId),
mode: command.mode,
graph: toPlain(competition.seriesGraph) as never,
facts: facts.map((fact) =>
factForProjection(fact as Readonly<Record<string, unknown>>),
),
assignments: assignments.map((assignment) => ({
seriesId: idString(assignment.seriesId),
gameSlotId: idString(assignment.gameSlotId),
state: String(assignment.state),
})),
};
}
function persistenceReversalFact(
rawFact: Record<string, unknown>,
command: ReverseSeriesCommand,
commandId: string,
requestHash: string,
): Readonly<Record<string, unknown>> {
const { id, ...fields } = rawFact;
return {
...fields,
_id: persistenceObjectId(id as PersistenceId),
competitionId: command.competitionId,
commandId,
idempotencyKey: command.idempotencyKey,
requestHash,
...(fields.gameAcceptedFactId === undefined
? {}
: {
gameAcceptedFactId: persistenceObjectId(
fields.gameAcceptedFactId as PersistenceId,
),
}),
...(fields.adjudicationFactId === undefined
? {}
: {
adjudicationFactId: persistenceObjectId(
fields.adjudicationFactId as PersistenceId,
),
}),
};
}
function reversalStatePipeline(
recordedAt: Date,
commandId?: string,
): mongoose.PipelineStage[] {
return [
{
$set: {
state: {
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
},
releasedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$$REMOVE'],
},
voidedAt: {
$cond: [{ $eq: ['$state', 'used'] }, recordedAt, '$$REMOVE'],
},
...(commandId ? { commandId } : {}),
},
},
];
}
function tournamentCodeReversalStatePipeline(
recordedAt: Date,
): mongoose.PipelineStage[] {
return [
{
$set: {
state: {
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
},
releasedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, recordedAt, '$releasedAt'],
},
},
},
];
}
function persistenceObjectId(value: PersistenceId): PersistenceId {
if (value instanceof mongoose.Types.ObjectId) return value;
return mongoose.isValidObjectId(value)
? new mongoose.Types.ObjectId(value)
: value;
}
function competitionNotFound(
competitionId: PersistenceId,
): CompetitionCommandError {
return new CompetitionCommandError(
'COMPETITION_NOT_FOUND',
'Competition not found.',
404,
{ competitionId: idString(competitionId) },
);
}
function invalidCommandError(): CompetitionCommandError {
return new CompetitionCommandError(
'INVALID_COMPETITION_COMMAND',
'Expected revision, valid payload, and a non-empty Idempotency-Key are required.',
422,
);
}