feat: execute competition result commands atomically

This commit is contained in:
dahyeon committed 2026-07-12 19:08:18 +00:00
1 parent 3b274b4ec2
commit 0c31a78df0
3 files changed
+984

No files matched your search

@@ -0,0 +1,401 @@
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionCommandService } from './competition-command.service';
import { projectCompetition } from './domain/competition-projector';
jest.mock('./domain/competition-projector', () => ({
projectCompetition: jest.fn(),
}));
const mockedProjectCompetition = jest.mocked(projectCompetition);
describe('CompetitionCommandService', () => {
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-12T10:00:00.000Z'));
mockedProjectCompetition.mockReset();
mockedProjectCompetition.mockReturnValue(PROJECTION as never);
});
afterEach(() => {
jest.useRealTimers();
});
it('rejects a stale expected revision and aborts without writing', async () => {
const harness = createHarness({ competitionRevision: 8 });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
details: { expectedRevision: 7, actualRevision: 8 },
},
);
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
expect(harness.session.endSession).toHaveBeenCalledTimes(1);
});
it('uses the expected revision in the persistence CAS and aborts a lost race', async () => {
const harness = createHarness({ casResult: null });
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'STALE_COMPETITION_REVISION',
httpStatus: 412,
},
);
const [casFilter, casUpdate, casOptions] = harness.competitionModel
.findOneAndUpdate.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $inc: Record<string, unknown>; $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(casFilter).toEqual({ _id: COMPETITION_ID, revision: 7 });
expect(casUpdate).toMatchObject({
$inc: { revision: 1 },
$set: { projection: PROJECTION },
});
expect(casOptions).toMatchObject({ new: true, session: harness.session });
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
});
it('replays an exact Idempotency-Key request without appending a second fact', async () => {
const harness = createHarness();
let storedReceipt: Record<string, unknown> | null = null;
harness.outboxModel.findOne.mockImplementation(() =>
queryResult(storedReceipt),
);
harness.outboxModel.insertMany.mockImplementation(
([receipt]: Array<Record<string, unknown>>) => {
storedReceipt = receipt;
return Promise.resolve([receipt]);
},
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = acceptGameCommand();
const first = await service.acceptGame(command);
const replay = await service.acceptGame(command);
expect(first).toMatchObject({ revision: 8, replayed: false });
expect(replay).toMatchObject({
commandId: first.commandId,
revision: 8,
replayed: true,
});
expect(replay.competition).toEqual(first.competition);
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledTimes(1);
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
expect(mockedProjectCompetition).toHaveBeenCalledTimes(1);
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(2);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('rejects the same Idempotency-Key when its payload hash differs', async () => {
const harness = createHarness();
harness.outboxModel.findOne.mockReturnValue(
queryResult({
idempotencyKey: 'riot:KR_7000000001',
requestHash: 'a-different-payload-hash',
commandId: 'cmpcmd_original',
revision: 8,
}),
);
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
await expect(service.acceptGame(acceptGameCommand())).rejects.toMatchObject(
{
code: 'IDEMPOTENCY_KEY_CONFLICT',
httpStatus: 409,
},
);
expect(harness.competitionModel.findById).not.toHaveBeenCalled();
expect(harness.factModel.insertMany).not.toHaveBeenCalled();
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
});
it('atomically accepts a code-backed game, projects it, and enqueues an event', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const command = {
...acceptGameCommand(),
tournamentCode: {
tournamentCodeId: TOURNAMENT_CODE_ID,
riotMatchId: 'KR_7000000001',
},
};
const result = await service.acceptGame(command);
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.session.startTransaction).toHaveBeenCalledTimes(1);
const [insertedFacts, factOptions] = harness.factModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(insertedFacts).toHaveLength(1);
expect(insertedFacts[0]).toMatchObject({
type: 'game-accepted',
revision: 8,
ordinalWithinRevision: 1,
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
});
expect(factOptions).toEqual({ session: harness.session });
const projectionInput = mockedProjectCompetition.mock.calls[0][0];
const projectedFact = projectionInput.facts[0] as Record<string, unknown>;
const projectedMapping = projectedFact.mapping as Record<string, unknown>;
expect(projectionInput.competitionId).toBe(COMPETITION_ID.toHexString());
expect(projectionInput.revision).toBe(8);
expect(typeof projectedFact.id).toBe('string');
expect(projectedFact).toMatchObject({
type: 'game-accepted',
seriesId: SERIES_ID.toHexString(),
});
expect(projectedMapping.winnerTeamId).toBe(TEAM_A_ID.toHexString());
const [assignmentFilter, assignmentUpdate, assignmentOptions] = harness
.assignmentModel.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(assignmentFilter).toMatchObject({
competitionId: COMPETITION_ID,
gameSlotId: GAME_SLOT_ID,
tournamentCodeId: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(assignmentUpdate.$set.state).toBe('used');
expect(assignmentOptions).toEqual({ session: harness.session });
const [codeFilter, codeUpdate, codeOptions] = harness.tournamentCodeModel
.updateOne.mock.calls[0] as unknown as [
Record<string, unknown>,
{ $set: Record<string, unknown> },
Record<string, unknown>,
];
expect(codeFilter).toEqual({
_id: TOURNAMENT_CODE_ID,
state: 'reserved',
});
expect(codeUpdate.$set.state).toBe('used');
expect(codeOptions).toEqual({ session: harness.session });
const [outboxRecords, outboxOptions] = harness.outboxModel.insertMany.mock
.calls[0] as unknown as [
Array<Record<string, unknown>>,
Record<string, unknown>,
];
expect(outboxRecords).toHaveLength(1);
expect(outboxRecords[0]).toMatchObject({
revision: 8,
type: 'competition.projection-updated',
state: 'pending',
payload: { projection: PROJECTION },
});
expect(outboxOptions).toEqual({ session: harness.session });
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
expect(harness.session.abortTransaction).not.toHaveBeenCalled();
});
it('appends an administrative adjudication through the same command runner', async () => {
const harness = createHarness();
const service = new CompetitionCommandService(
harness.connectionService as ConnectionService,
);
const result = await service.adjudicateSeries({
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'admin:series:walkover:1',
actor: { type: 'user', userId: USER_ID },
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
});
expect(result).toMatchObject({ revision: 8, replayed: false });
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
[
expect.objectContaining({
type: 'series-adjudicated',
seriesId: SERIES_ID,
decision: { type: 'walkover', winnerTeamId: TEAM_B_ID },
reason: 'Opponent did not appear before the deadline.',
}),
],
{ session: harness.session },
);
expect(harness.assignmentModel.updateOne).not.toHaveBeenCalled();
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
});
});
const COMPETITION_ID = new Types.ObjectId('64b000000000000000000001');
const SERIES_ID = new Types.ObjectId('64b000000000000000000002');
const GAME_SLOT_ID = new Types.ObjectId('64b000000000000000000003');
const GAME_ID = new Types.ObjectId('64b000000000000000000004');
const TEAM_A_ID = new Types.ObjectId('64b000000000000000000005');
const TEAM_B_ID = new Types.ObjectId('64b000000000000000000006');
const USER_ID = new Types.ObjectId('64b000000000000000000007');
const TOURNAMENT_CODE_ID = new Types.ObjectId('64b000000000000000000008');
const PROJECTION = {
sourceRevision: 8,
projectorVersion: 1,
phase: 'running',
formatType: 'paired-series',
series: [],
games: [],
gameSlots: [],
rounds: [],
connectors: [],
};
function acceptGameCommand() {
return {
competitionId: COMPETITION_ID,
expectedRevision: 7,
idempotencyKey: 'riot:KR_7000000001',
actor: { type: 'system' as const },
occurredAt: new Date('2026-07-12T09:59:00.000Z'),
gameId: GAME_ID,
seriesId: SERIES_ID,
gameSlotId: GAME_SLOT_ID,
ordinal: 1,
evidence: {
type: 'riot' as const,
riotMatchId: 'KR_7000000001',
payloadHash: 'sha256:riot-payload',
},
mapping: {
mappingVersion: 1,
confidence: 1,
blueTeamId: TEAM_A_ID,
redTeamId: TEAM_B_ID,
winnerTeamId: TEAM_A_ID,
participantAssignments: [],
},
};
}
function createHarness(
options: {
competitionRevision?: number;
casResult?: Record<string, unknown> | null;
} = {},
) {
const session = {
startTransaction: jest.fn(),
commitTransaction: jest.fn().mockResolvedValue(undefined),
abortTransaction: jest.fn().mockResolvedValue(undefined),
endSession: jest.fn().mockResolvedValue(undefined),
};
const competition = competitionDocument(options.competitionRevision ?? 7);
const competitionModel = {
findById: jest.fn().mockReturnValue(queryResult(competition)),
findOneAndUpdate: jest
.fn()
.mockReturnValue(
queryResult(
options.casResult === undefined
? competitionDocument(8, PROJECTION)
: options.casResult,
),
),
};
const factModel = {
find: jest.fn().mockReturnValue(queryResult([])),
insertMany: jest.fn().mockResolvedValue([]),
};
const outboxModel = {
findOne: jest.fn().mockReturnValue(queryResult(null)),
insertMany: jest.fn().mockResolvedValue([]),
};
const assignmentModel = {
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
};
const tournamentCodeModel = {
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
};
const models: Record<string, unknown> = {
competition: competitionModel,
competitionFact: factModel,
competitionOutbox: outboxModel,
tournamentCodeAssignment: assignmentModel,
tournamentCode: tournamentCodeModel,
};
const connectionService = {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
};
return {
session,
competitionModel,
factModel,
outboxModel,
assignmentModel,
tournamentCodeModel,
connectionService,
};
}
function competitionDocument(revision: number, projection = PROJECTION) {
return {
_id: COMPETITION_ID,
matchId: new Types.ObjectId('64b000000000000000000010'),
communityId: new Types.ObjectId('64b000000000000000000011'),
schemaVersion: 1,
projectorVersion: 1,
revision,
phase: 'running',
teams: [
{ teamId: TEAM_A_ID, displayOrder: 1, seedNumber: 1 },
{ teamId: TEAM_B_ID, displayOrder: 2, seedNumber: 2 },
],
format: {
type: 'paired-series',
rule: { type: 'first-to', winsRequired: 2, maxGames: 3 },
},
seriesGraph: [],
projection,
};
}
function queryResult<T>(value: T) {
const query = {
session: jest.fn(),
sort: jest.fn(),
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.session.mockReturnValue(query);
query.sort.mockReturnValue(query);
query.lean.mockReturnValue(query);
return query;
}
@@ -0,0 +1,560 @@
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';
type PersistenceId = string | mongoose.Types.ObjectId;
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>>;
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 CompetitionCommandResult {
competition: unknown;
commandId: string;
revision: number;
replayed: boolean;
}
interface CommandEnvelope {
type: 'accept-game' | 'adjudicate-series';
competitionId: PersistenceId;
expectedRevision: number;
idempotencyKey: string;
actor: CompetitionCommandActor;
occurredAt?: Date;
payload: Readonly<Record<string, unknown>>;
}
@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.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(),
},
});
}
private async runCommand(
command: CommandEnvelope,
): Promise<CompetitionCommandResult> {
validateEnvelope(command);
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,
},
},
{ new: true, 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);
throw error;
} finally {
await session.endSession();
}
}
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);
}
}
}
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' &&
String(command.payload.reason).trim().length === 0)
) {
throw new CompetitionCommandError(
'INVALID_COMPETITION_COMMAND',
'Expected revision and a non-empty Idempotency-Key are required.',
422,
);
}
}
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,
};
}
return {
...common,
type: 'series-adjudicated',
seriesId: command.payload.seriesId,
decision: command.payload.decision,
reason: command.payload.reason,
};
}
function buildOutbox(
competitionId: PersistenceId,
command: CommandEnvelope,
commandId: string,
requestHash: string,
revision: number,
fact: Readonly<Record<string, unknown>>,
projection: unknown,
updatedCompetition: unknown,
recordedAt: Date,
): Readonly<Record<string, unknown>> {
return {
eventId: `${commandId}:competition-projected`,
competitionId,
revision,
commandId,
idempotencyKey: command.idempotencyKey,
requestHash,
type: 'competition.projection-updated',
payload: {
competitionId: idString(competitionId),
sourceRevision: revision,
factIds: [idString(fact._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),
},
);
}
@@ -0,0 +1,23 @@
export type CompetitionCommandErrorCode =
| 'COMPETITION_NOT_FOUND'
| 'COMPETITION_TRANSACTION_UNAVAILABLE'
| 'IDEMPOTENCY_KEY_CONFLICT'
| 'INVALID_COMPETITION_COMMAND'
| 'STALE_COMPETITION_REVISION'
| 'TOURNAMENT_CODE_ASSIGNMENT_CONFLICT';
/**
* Transport-neutral command failure. Controllers may translate `httpStatus`
* directly while command handlers remain usable by jobs and migrations.
*/
export class CompetitionCommandError extends Error {
constructor(
public readonly code: CompetitionCommandErrorCode,
message: string,
public readonly httpStatus: 404 | 409 | 412 | 422 | 500,
public readonly details?: Readonly<Record<string, unknown>>,
) {
super(message);
this.name = 'CompetitionCommandError';
}
}