feat: execute competition result commands atomically
This commit is contained in:
1 parent
3b274b4ec2
commit
0c31a78df0
3 files changed
+984
No files matched your search
@@ -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),
|
||||
},
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user