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,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;
|
||||
}
|
||||
Reference in new issue
Block a user