Files
lolympus-tournament-support/apps/api/src/modules/competition/competition-command.service.ts
T

1063 lines
31 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { createHash } from 'node:crypto';
import mongoose from 'mongoose';
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;
const COMMAND_TRANSACTION_ATTEMPTS = 3;
export type CompetitionCommandActor =
| { type: 'system' }
| { type: 'user'; userId: PersistenceId }
| { type: 'migration'; migrationRunId: string };
export interface AcceptGameCommand {
competitionId: PersistenceId;
expectedRevision: number;
idempotencyKey: string;
actor: CompetitionCommandActor;
occurredAt?: Date;
gameId: PersistenceId;
seriesId: PersistenceId;
gameSlotId: PersistenceId;
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;
};
}
export type SeriesAdjudicationDecision =
| {
type: 'walkover' | 'forfeit' | 'administrative';
winnerTeamId: PersistenceId;
}
| { type: 'administrative-draw' };
export interface AdjudicateSeriesCommand {
competitionId: PersistenceId;
expectedRevision: number;
idempotencyKey: string;
actor: CompetitionCommandActor;
occurredAt?: Date;
seriesId: PersistenceId;
decision: SeriesAdjudicationDecision;
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;
revision: number;
replayed: boolean;
}
interface CommandEnvelope {
type: 'accept-game' | 'adjudicate-series' | 'reverse-series';
competitionId: PersistenceId;
expectedRevision: number;
idempotencyKey: string;
actor: CompetitionCommandActor;
occurredAt?: Date;
payload: Readonly<Record<string, unknown>>;
}
interface AssignmentRecord {
seriesId: PersistenceId;
gameSlotId: PersistenceId;
tournamentCodeId: PersistenceId;
state: string;
}
@Injectable()
export class CompetitionCommandService {
constructor(private readonly connectionService: ConnectionService) {}
public acceptGame(
command: AcceptGameCommand,
): Promise<CompetitionCommandResult> {
return this.runCommand({
type: 'accept-game',
competitionId: command.competitionId,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
actor: command.actor,
occurredAt: command.occurredAt,
payload: {
gameId: command.gameId,
seriesId: command.seriesId,
gameSlotId: command.gameSlotId,
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 }
: {}),
},
});
}
public adjudicateSeries(
command: AdjudicateSeriesCommand,
): Promise<CompetitionCommandResult> {
return this.runCommand({
type: 'adjudicate-series',
competitionId: command.competitionId,
expectedRevision: command.expectedRevision,
idempotencyKey: command.idempotencyKey,
actor: command.actor,
occurredAt: command.occurredAt,
payload: {
seriesId: command.seriesId,
decision: command.decision,
reason: command.reason.trim(),
},
});
}
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() as Promise<AssignmentRecord[]>,
]);
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();
}
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= COMMAND_TRANSACTION_ATTEMPTS;
attempt += 1
) {
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() as Promise<AssignmentRecord[]>,
]);
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,
},
},
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
if (!updated) throw staleRevisionError(command.expectedRevision);
await this.applyReversalAssignments(
command.competitionId,
competition.matchId,
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);
if (
attempt < COMMAND_TRANSACTION_ATTEMPTS &&
isRetryableCommandTransactionError(error)
) {
lastRetryableError = error;
continue;
}
throw error;
} finally {
await session.endSession();
}
}
throw lastRetryableError;
}
private async runCommand(
command: CommandEnvelope,
): Promise<CompetitionCommandResult> {
validateEnvelope(command);
let lastRetryableError: unknown;
for (
let attempt = 1;
attempt <= COMMAND_TRANSACTION_ATTEMPTS;
attempt += 1
) {
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 =
await this.connectionService.getModel('competition');
const FactModel =
await this.connectionService.getModel('competitionFact');
const OutboxModel =
await this.connectionService.getModel('competitionOutbox');
const requestHash = requestHashFor(command);
const commandId = commandIdFor(command);
const competitionId = command.competitionId;
const receipt = await OutboxModel.findOne({
competitionId,
idempotencyKey: command.idempotencyKey,
})
.session(session)
.lean()
.exec();
if (receipt) {
const replay = await this.replay(
CompetitionModel,
competitionId,
requestHash,
receipt,
session,
);
await session.commitTransaction();
return replay;
}
const competition = await CompetitionModel.findById(competitionId)
.session(session)
.lean()
.exec();
if (!competition) {
throw new CompetitionCommandError(
'COMPETITION_NOT_FOUND',
'Competition not found.',
404,
{ competitionId: idString(competitionId) },
);
}
assertExpectedRevision(competition.revision, command.expectedRevision);
const existingFacts = await FactModel.find({ competitionId })
.sort({ revision: 1, ordinalWithinRevision: 1 })
.session(session)
.lean()
.exec();
const nextRevision = command.expectedRevision + 1;
const recordedAt = new Date();
const fact = buildFact(
command,
commandId,
requestHash,
nextRevision,
recordedAt,
);
const projection = projectCompetition({
competitionId: idString(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, fact].map(factForProjection),
});
await FactModel.insertMany([fact], { session });
const updated = await CompetitionModel.findOneAndUpdate(
{ _id: competitionId, revision: command.expectedRevision },
{
$inc: { revision: 1 },
$set: {
projection,
projectorVersion: competition.projectorVersion,
phase: projection.phase,
},
},
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
if (!updated) {
throw staleRevisionError(command.expectedRevision);
}
await this.applyTournamentCode(command, commandId, recordedAt, session);
await OutboxModel.insertMany(
[
buildOutbox(
competitionId,
command,
commandId,
requestHash,
nextRevision,
fact,
projection,
updated,
recordedAt,
),
],
{ session },
);
await session.commitTransaction();
return {
competition: updated,
commandId,
revision: nextRevision,
replayed: false,
};
} catch (error) {
await session.abortTransaction().catch(() => undefined);
if (
attempt < COMMAND_TRANSACTION_ATTEMPTS &&
isRetryableCommandTransactionError(error)
) {
lastRetryableError = error;
continue;
}
throw error;
} finally {
await session.endSession();
}
}
throw lastRetryableError;
}
private async replay(
CompetitionModel: mongoose.Model<Competition>,
competitionId: PersistenceId,
requestHash: string,
receipt: Pick<
CompetitionOutbox,
'requestHash' | 'idempotencyKey' | 'commandId' | 'revision' | 'payload'
>,
session: mongoose.ClientSession,
): Promise<CompetitionCommandResult> {
if (receipt.requestHash !== requestHash) {
throw new CompetitionCommandError(
'IDEMPOTENCY_KEY_CONFLICT',
'The Idempotency-Key was already used for a different command payload.',
409,
{ idempotencyKey: receipt.idempotencyKey },
);
}
const competition = await CompetitionModel.findById(competitionId)
.session(session)
.lean()
.exec();
if (!competition) {
throw new CompetitionCommandError(
'COMPETITION_NOT_FOUND',
'Competition not found.',
404,
{ competitionId: idString(competitionId) },
);
}
const responseSnapshot = receipt.payload;
const replayCompetition = {
...competition,
revision: receipt.revision,
projection: responseSnapshot.projection,
phase: responseSnapshot.phase,
...(responseSnapshot.updatedAt === undefined
? {}
: { updatedAt: responseSnapshot.updatedAt }),
};
return {
competition: replayCompetition,
commandId: receipt.commandId,
revision: receipt.revision,
replayed: true,
};
}
private async applyTournamentCode(
command: CommandEnvelope,
commandId: string,
recordedAt: Date,
session: mongoose.ClientSession,
): Promise<void> {
const tournamentCode = command.payload.tournamentCode as
| { tournamentCodeId: PersistenceId; riotMatchId: string }
| undefined;
if (!tournamentCode) return;
const AssignmentModel = (await this.connectionService.getModel(
'tournamentCodeAssignment',
)) as mongoose.Model<any>;
const assignmentResult = await AssignmentModel.updateOne(
{
competitionId: command.competitionId,
seriesId: command.payload.seriesId,
gameSlotId: command.payload.gameSlotId,
tournamentCodeId: tournamentCode.tournamentCodeId,
state: 'reserved',
},
{
$set: {
state: 'used',
usedAt: recordedAt,
riotMatchId: tournamentCode.riotMatchId,
commandId,
},
},
{ session },
);
if (assignmentResult.modifiedCount !== 1) {
throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId);
}
const TournamentCodeModel = (await this.connectionService.getModel(
'tournamentCode',
)) as mongoose.Model<any>;
const codeResult = await TournamentCodeModel.updateOne(
{ _id: tournamentCode.tournamentCodeId, state: 'reserved' },
{
$set: {
state: 'used',
usedAt: recordedAt,
riotMatchId: tournamentCode.riotMatchId,
},
},
{ session },
);
if (codeResult.modifiedCount !== 1) {
throw tournamentCodeConflict(command, tournamentCode.tournamentCodeId);
}
}
private async applyReversalAssignments(
competitionId: PersistenceId,
matchId: PersistenceId,
preview: SeriesReversalPreview,
assignments: AssignmentRecord[],
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 },
);
const MatchModel = (await this.connectionService.getModel(
'match',
)) as mongoose.Model<any>;
await MatchModel.updateOne(
{ _id: matchId },
{ $pull: { tournamentCodeIds: { $in: codeIds } } },
{ session },
);
}
}
function validateEnvelope(command: CommandEnvelope): void {
if (
!Number.isInteger(command.expectedRevision) ||
command.expectedRevision < 0 ||
command.idempotencyKey.trim().length === 0 ||
command.idempotencyKey.length > 200 ||
((command.type === 'adjudicate-series' ||
command.type === 'reverse-series') &&
String(command.payload.reason).trim().length === 0)
) {
throw invalidCommandError();
}
}
function assertExpectedRevision(actual: number, expected: number): void {
if (actual !== expected) {
throw staleRevisionError(expected, actual);
}
}
function staleRevisionError(
expectedRevision: number,
actualRevision?: number,
): CompetitionCommandError {
return new CompetitionCommandError(
'STALE_COMPETITION_REVISION',
'Competition changed after the caller read it.',
412,
{
expectedRevision,
...(actualRevision === undefined ? {} : { actualRevision }),
},
);
}
function buildFact(
command: CommandEnvelope,
commandId: string,
requestHash: string,
revision: number,
recordedAt: Date,
): Readonly<Record<string, unknown>> {
const factId = deterministicObjectId(commandId, 'fact', 1);
const common = {
_id: factId,
competitionId: command.competitionId,
revision,
ordinalWithinRevision: 1,
commandId,
idempotencyKey: command.idempotencyKey,
requestHash,
schemaVersion: 1,
actor: command.actor,
occurredAt: command.occurredAt ?? recordedAt,
recordedAt,
};
if (command.type === 'accept-game') {
return {
...common,
type: 'game-accepted',
gameId: command.payload.gameId,
seriesId: command.payload.seriesId,
gameSlotId: command.payload.gameSlotId,
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 }),
};
}
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(
competitionId: PersistenceId,
command: CommandEnvelope,
commandId: string,
requestHash: string,
revision: number,
fact:
| Readonly<Record<string, unknown>>
| readonly Readonly<Record<string, unknown>>[],
projection: unknown,
updatedCompetition: unknown,
recordedAt: Date,
): Readonly<Record<string, unknown>> {
const facts: readonly Readonly<Record<string, unknown>>[] = Array.isArray(
fact,
)
? fact
: [fact];
return {
eventId: `${commandId}:competition-projected`,
competitionId,
revision,
commandId,
idempotencyKey: command.idempotencyKey,
requestHash,
type: 'competition.projection-updated',
payload: {
competitionId: idString(competitionId),
sourceRevision: revision,
factIds: facts.map((entry) => idString(entry._id as PersistenceId)),
projection,
phase:
isRecord(projection) && typeof projection.phase === 'string'
? projection.phase
: undefined,
updatedAt: isRecord(updatedCompetition)
? updatedCompetition.updatedAt
: undefined,
},
state: 'pending',
attemptCount: 0,
availableAt: recordedAt,
};
}
function factForProjection(
fact: Readonly<Record<string, unknown>>,
): Readonly<Record<string, unknown>> {
const plain = toPlain(fact) as Readonly<Record<string, unknown>>;
const sourceId = fact.id ?? fact._id;
return {
...plain,
id: idString(sourceId as PersistenceId),
};
}
function requestHashFor(command: CommandEnvelope): string {
return sha256({
type: command.type,
competitionId: command.competitionId,
actor: command.actor,
payload: command.payload,
});
}
function commandIdFor(command: CommandEnvelope): string {
return `cmpcmd_${sha256({
competitionId: command.competitionId,
idempotencyKey: command.idempotencyKey,
}).slice(0, 32)}`;
}
function deterministicObjectId(
commandId: string,
entity: string,
ordinal: number,
): mongoose.Types.ObjectId {
return new mongoose.Types.ObjectId(
sha256([commandId, entity, ordinal]).slice(0, 24),
);
}
function sha256(value: unknown): string {
return createHash('sha256').update(canonicalJson(value)).digest('hex');
}
function canonicalJson(value: unknown): string {
return JSON.stringify(toCanonical(value));
}
function toCanonical(value: unknown): unknown {
if (value instanceof mongoose.Types.ObjectId) return value.toHexString();
if (value instanceof Date) return value.toISOString();
if (Array.isArray(value)) return value.map(toCanonical);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value as Readonly<Record<string, unknown>>)
.filter(([, child]) => child !== undefined)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, child]) => [key, toCanonical(child)]),
);
}
return value;
}
function toPlain(value: unknown): unknown {
return toCanonical(value);
}
function isRecord(value: unknown): value is Readonly<Record<string, unknown>> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function idString(value: PersistenceId): string {
return value instanceof mongoose.Types.ObjectId
? value.toHexString()
: String(value);
}
function tournamentCodeConflict(
command: CommandEnvelope,
tournamentCodeId: PersistenceId,
): CompetitionCommandError {
return new CompetitionCommandError(
'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT',
'The Tournament Code assignment is no longer reserved for this GameSlot.',
409,
{
competitionId: idString(command.competitionId),
gameSlotId: idString(command.payload.gameSlotId as PersistenceId),
tournamentCodeId: idString(tournamentCodeId),
},
);
}
function reversalInput(
competition: Pick<Competition, 'revision' | 'seriesGraph'>,
command: PreviewSeriesReversalCommand,
facts: readonly unknown[],
assignments: readonly AssignmentRecord[],
) {
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'],
},
matchId: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$matchId'],
},
gameNumber: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$gameNumber'],
},
bracketMatchId: {
$cond: [
{ $eq: ['$state', 'reserved'] },
'$$REMOVE',
'$bracketMatchId',
],
},
reservedAt: {
$cond: [{ $eq: ['$state', 'reserved'] }, '$$REMOVE', '$reservedAt'],
},
},
},
];
}
function persistenceObjectId(value: PersistenceId): PersistenceId {
if (value instanceof mongoose.Types.ObjectId) return value;
return mongoose.isValidObjectId(value)
? new mongoose.Types.ObjectId(value)
: value;
}
function isRetryableCommandTransactionError(error: unknown): boolean {
const candidate = error as {
code?: number;
codeName?: string;
hasErrorLabel?: (label: string) => boolean;
};
return Boolean(
candidate?.code === 11_000 ||
candidate?.code === 112 ||
candidate?.codeName === 'WriteConflict' ||
candidate?.hasErrorLabel?.('TransientTransactionError') ||
candidate?.hasErrorLabel?.('UnknownTransactionCommitResult'),
);
}
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,
);
}