788 lines
26 KiB
TypeScript
788 lines
26 KiB
TypeScript
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({
|
|
returnDocument: 'after',
|
|
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('replays a concurrently committed identical command after a duplicate-key race', async () => {
|
|
const harness = createHarness();
|
|
let committedReceipt: Record<string, unknown> | null = null;
|
|
harness.outboxModel.findOne.mockImplementation(() =>
|
|
queryResult(committedReceipt),
|
|
);
|
|
harness.factModel.insertMany.mockImplementationOnce(
|
|
async ([fact]: Array<Record<string, unknown>>) => {
|
|
committedReceipt = {
|
|
competitionId: COMPETITION_ID,
|
|
idempotencyKey: fact.idempotencyKey,
|
|
requestHash: fact.requestHash,
|
|
commandId: fact.commandId,
|
|
revision: fact.revision,
|
|
payload: {
|
|
projection: PROJECTION,
|
|
phase: PROJECTION.phase,
|
|
},
|
|
};
|
|
throw Object.assign(new Error('duplicate command fact'), {
|
|
code: 11_000,
|
|
});
|
|
},
|
|
);
|
|
const service = new CompetitionCommandService(
|
|
harness.connectionService as ConnectionService,
|
|
);
|
|
|
|
await expect(
|
|
service.acceptGame(acceptGameCommand()),
|
|
).resolves.toMatchObject({
|
|
revision: 8,
|
|
replayed: true,
|
|
});
|
|
|
|
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
|
|
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(1);
|
|
expect(harness.competitionModel.findOneAndUpdate).not.toHaveBeenCalled();
|
|
expect(harness.outboxModel.insertMany).not.toHaveBeenCalled();
|
|
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
|
|
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
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,
|
|
startedAt: new Date('2026-07-12T09:30:00.000Z'),
|
|
durationSeconds: 1_800,
|
|
participants: [
|
|
{
|
|
userId: USER_ID.toHexString(),
|
|
teamId: TEAM_A_ID.toHexString(),
|
|
side: 'blue',
|
|
},
|
|
],
|
|
});
|
|
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);
|
|
});
|
|
|
|
it('previews a strict or cascade reversal against the requested revision', async () => {
|
|
const reversal = reversalFixture();
|
|
const harness = createHarness({
|
|
competition: reversal.competition,
|
|
facts: reversal.facts,
|
|
assignments: reversal.assignments,
|
|
});
|
|
const service = new CompetitionCommandService(
|
|
harness.connectionService as ConnectionService,
|
|
);
|
|
|
|
const preview = await service.previewSeriesReversal({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 7,
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'cascade',
|
|
});
|
|
|
|
expect(preview).toMatchObject({
|
|
sourceRevision: 7,
|
|
impactHash: expect.stringMatching(/^[a-f0-9]{64}$/),
|
|
impact: {
|
|
seriesIds: [
|
|
reversal.parentSeriesId.toHexString(),
|
|
reversal.childSeriesId.toHexString(),
|
|
],
|
|
factIds: [
|
|
reversal.parentFactId.toHexString(),
|
|
reversal.childFactId.toHexString(),
|
|
],
|
|
releasesReservedCodes: 1,
|
|
voidsUsedCodes: 1,
|
|
},
|
|
});
|
|
});
|
|
|
|
it('rejects a reversal preview at a stale revision', async () => {
|
|
const reversal = reversalFixture();
|
|
const harness = createHarness({ competition: reversal.competition });
|
|
const service = new CompetitionCommandService(
|
|
harness.connectionService as ConnectionService,
|
|
);
|
|
|
|
await expect(
|
|
service.previewSeriesReversal({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 6,
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'strict',
|
|
}),
|
|
).rejects.toMatchObject({
|
|
code: 'STALE_COMPETITION_REVISION',
|
|
httpStatus: 412,
|
|
});
|
|
});
|
|
|
|
it('hash-confirms and atomically appends cascade reversal facts', async () => {
|
|
const reversal = reversalFixture();
|
|
const harness = createHarness({
|
|
competition: reversal.competition,
|
|
facts: reversal.facts,
|
|
assignments: reversal.assignments,
|
|
});
|
|
const service = new CompetitionCommandService(
|
|
harness.connectionService as ConnectionService,
|
|
);
|
|
const preview = await service.previewSeriesReversal({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 7,
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'cascade',
|
|
});
|
|
|
|
const result = await service.reverseSeries({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 7,
|
|
idempotencyKey: 'admin:reverse:1',
|
|
actor: { type: 'user', userId: USER_ID },
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'cascade',
|
|
reason: 'Wrong result ingestion',
|
|
impactHash: preview.impactHash,
|
|
});
|
|
|
|
expect(result).toMatchObject({ revision: 8, replayed: false });
|
|
expect(harness.factModel.insertMany).toHaveBeenCalledWith(
|
|
[
|
|
expect.objectContaining({
|
|
_id: expect.any(Types.ObjectId),
|
|
type: 'game-voided',
|
|
gameAcceptedFactId: reversal.parentFactId,
|
|
revision: 8,
|
|
ordinalWithinRevision: 1,
|
|
reason: 'Wrong result ingestion',
|
|
}),
|
|
expect.objectContaining({
|
|
_id: expect.any(Types.ObjectId),
|
|
type: 'game-voided',
|
|
gameAcceptedFactId: reversal.childFactId,
|
|
revision: 8,
|
|
ordinalWithinRevision: 2,
|
|
}),
|
|
],
|
|
{ session: harness.session },
|
|
);
|
|
expect(harness.assignmentModel.updateMany).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
competitionId: COMPETITION_ID,
|
|
gameSlotId: {
|
|
$in: expect.arrayContaining([
|
|
reversal.parentGameSlotId,
|
|
reversal.childGameSlotId,
|
|
]),
|
|
},
|
|
}),
|
|
expect.any(Array),
|
|
{ session: harness.session },
|
|
);
|
|
expect(harness.tournamentCodeModel.updateMany).toHaveBeenCalled();
|
|
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
|
|
{ _id: reversal.competition.matchId },
|
|
{
|
|
$pull: {
|
|
tournamentCodeIds: {
|
|
$in: [reversal.parentCodeId, reversal.childCodeId],
|
|
},
|
|
},
|
|
},
|
|
{ session: harness.session },
|
|
);
|
|
const [, codeReversalPipeline] = harness.tournamentCodeModel.updateMany.mock
|
|
.calls[0] as unknown as [
|
|
Record<string, unknown>,
|
|
Array<Record<string, any>>,
|
|
];
|
|
expect(codeReversalPipeline[0].$set).toMatchObject({
|
|
state: {
|
|
$cond: [{ $eq: ['$state', 'reserved'] }, 'released', 'voided'],
|
|
},
|
|
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'],
|
|
},
|
|
});
|
|
expect(harness.competitionModel.findOneAndUpdate).toHaveBeenCalledWith(
|
|
{ _id: COMPETITION_ID, revision: 7 },
|
|
expect.objectContaining({ $inc: { revision: 1 } }),
|
|
expect.objectContaining({ session: harness.session }),
|
|
);
|
|
expect(harness.outboxModel.insertMany).toHaveBeenCalledTimes(1);
|
|
expect(harness.session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('retries a cascade reversal after a transient transaction conflict', async () => {
|
|
const reversal = reversalFixture();
|
|
const harness = createHarness({
|
|
competition: reversal.competition,
|
|
facts: reversal.facts,
|
|
assignments: reversal.assignments,
|
|
});
|
|
harness.factModel.insertMany
|
|
.mockRejectedValueOnce(
|
|
Object.assign(new Error('write conflict'), {
|
|
code: 112,
|
|
codeName: 'WriteConflict',
|
|
}),
|
|
)
|
|
.mockResolvedValueOnce([]);
|
|
const service = new CompetitionCommandService(
|
|
harness.connectionService as ConnectionService,
|
|
);
|
|
const preview = await service.previewSeriesReversal({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 7,
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'cascade',
|
|
});
|
|
|
|
await expect(
|
|
service.reverseSeries({
|
|
competitionId: COMPETITION_ID,
|
|
expectedRevision: 7,
|
|
idempotencyKey: 'admin:reverse:transient-retry',
|
|
actor: { type: 'user', userId: USER_ID },
|
|
seriesId: reversal.parentSeriesId,
|
|
mode: 'cascade',
|
|
reason: 'Wrong result ingestion',
|
|
impactHash: preview.impactHash,
|
|
}),
|
|
).resolves.toMatchObject({ revision: 8, replayed: false });
|
|
|
|
expect(harness.connectionService.createSession).toHaveBeenCalledTimes(2);
|
|
expect(harness.factModel.insertMany).toHaveBeenCalledTimes(2);
|
|
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
|
|
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: [],
|
|
},
|
|
startedAt: new Date('2026-07-12T09:30:00.000Z'),
|
|
durationSeconds: 1_800,
|
|
participants: [
|
|
{
|
|
userId: USER_ID.toHexString(),
|
|
teamId: TEAM_A_ID.toHexString(),
|
|
side: 'blue',
|
|
},
|
|
],
|
|
};
|
|
}
|
|
|
|
function createHarness(
|
|
options: {
|
|
competitionRevision?: number;
|
|
casResult?: Record<string, unknown> | null;
|
|
competition?: Record<string, unknown>;
|
|
facts?: Array<Record<string, unknown>>;
|
|
assignments?: Array<Record<string, unknown>>;
|
|
} = {},
|
|
) {
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const competition =
|
|
options.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(options.facts ?? [])),
|
|
insertMany: jest.fn().mockResolvedValue([]),
|
|
};
|
|
const outboxModel = {
|
|
findOne: jest.fn().mockReturnValue(queryResult(null)),
|
|
insertMany: jest.fn().mockResolvedValue([]),
|
|
};
|
|
const assignmentModel = {
|
|
find: jest.fn().mockReturnValue(queryResult(options.assignments ?? [])),
|
|
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
|
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
|
|
};
|
|
const tournamentCodeModel = {
|
|
updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
|
|
updateMany: jest.fn().mockResolvedValue({ modifiedCount: 2 }),
|
|
};
|
|
const matchModel = {
|
|
updateOne: jest
|
|
.fn()
|
|
.mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
|
|
};
|
|
const models: Record<string, unknown> = {
|
|
competition: competitionModel,
|
|
competitionFact: factModel,
|
|
competitionOutbox: outboxModel,
|
|
tournamentCodeAssignment: assignmentModel,
|
|
tournamentCode: tournamentCodeModel,
|
|
match: matchModel,
|
|
};
|
|
const connectionService = {
|
|
createSession: jest.fn().mockResolvedValue(session),
|
|
getModel: jest.fn((name: string) => Promise.resolve(models[name])),
|
|
};
|
|
|
|
return {
|
|
session,
|
|
competitionModel,
|
|
factModel,
|
|
outboxModel,
|
|
assignmentModel,
|
|
tournamentCodeModel,
|
|
matchModel,
|
|
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;
|
|
}
|
|
|
|
function reversalFixture() {
|
|
const parentSeriesId = new Types.ObjectId('64b000000000000000000021');
|
|
const childSeriesId = new Types.ObjectId('64b000000000000000000022');
|
|
const parentFactId = new Types.ObjectId('64b000000000000000000023');
|
|
const childFactId = new Types.ObjectId('64b000000000000000000024');
|
|
const parentGameSlotId = new Types.ObjectId('64b000000000000000000025');
|
|
const childGameSlotId = new Types.ObjectId('64b000000000000000000026');
|
|
const parentCodeId = new Types.ObjectId('64b000000000000000000027');
|
|
const childCodeId = new Types.ObjectId('64b000000000000000000028');
|
|
const series = (
|
|
id: Types.ObjectId,
|
|
sourceA: Record<string, unknown>,
|
|
sourceB: Record<string, unknown>,
|
|
) => ({
|
|
id: id.toHexString(),
|
|
stage: { type: 'upper', displayOrder: 1 },
|
|
slots: [
|
|
{ position: 'A', source: sourceA },
|
|
{ position: 'B', source: sourceB },
|
|
],
|
|
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
|
|
gameSlots: [],
|
|
});
|
|
const accepted = (
|
|
_id: Types.ObjectId,
|
|
seriesId: Types.ObjectId,
|
|
gameSlotId: Types.ObjectId,
|
|
) => ({
|
|
_id,
|
|
competitionId: COMPETITION_ID,
|
|
type: 'game-accepted',
|
|
revision: 1,
|
|
ordinalWithinRevision: 1,
|
|
commandId: `command-${_id.toHexString()}`,
|
|
idempotencyKey: `key-${_id.toHexString()}`,
|
|
requestHash: `hash-${_id.toHexString()}`,
|
|
schemaVersion: 1,
|
|
actor: { type: 'system' },
|
|
occurredAt: new Date('2026-07-12T00:00:00.000Z'),
|
|
recordedAt: new Date('2026-07-12T00:00:00.000Z'),
|
|
gameId: new Types.ObjectId(),
|
|
seriesId,
|
|
gameSlotId,
|
|
ordinal: 1,
|
|
evidence: { type: 'legacy', legacyReference: 'legacy' },
|
|
mapping: {
|
|
blueTeamId: TEAM_A_ID,
|
|
redTeamId: TEAM_B_ID,
|
|
winnerTeamId: TEAM_A_ID,
|
|
},
|
|
});
|
|
return {
|
|
parentSeriesId,
|
|
childSeriesId,
|
|
parentFactId,
|
|
childFactId,
|
|
parentGameSlotId,
|
|
childGameSlotId,
|
|
parentCodeId,
|
|
childCodeId,
|
|
competition: {
|
|
...competitionDocument(7),
|
|
seriesGraph: [
|
|
series(
|
|
parentSeriesId,
|
|
{ type: 'team', teamId: TEAM_A_ID.toHexString() },
|
|
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
|
|
),
|
|
series(
|
|
childSeriesId,
|
|
{
|
|
type: 'series-outcome',
|
|
seriesId: parentSeriesId.toHexString(),
|
|
select: 'winner',
|
|
},
|
|
{ type: 'team', teamId: TEAM_B_ID.toHexString() },
|
|
),
|
|
],
|
|
},
|
|
facts: [
|
|
accepted(parentFactId, parentSeriesId, parentGameSlotId),
|
|
accepted(childFactId, childSeriesId, childGameSlotId),
|
|
],
|
|
assignments: [
|
|
{
|
|
competitionId: COMPETITION_ID,
|
|
seriesId: parentSeriesId,
|
|
gameSlotId: parentGameSlotId,
|
|
tournamentCodeId: parentCodeId,
|
|
state: 'used',
|
|
},
|
|
{
|
|
competitionId: COMPETITION_ID,
|
|
seriesId: childSeriesId,
|
|
gameSlotId: childGameSlotId,
|
|
tournamentCodeId: childCodeId,
|
|
state: 'reserved',
|
|
},
|
|
],
|
|
};
|
|
}
|