Files
lolympus-tournament-support/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts
T

233 lines
7.2 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import mongoose from 'mongoose';
import { Logger } from '@nestjs/common';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { MatchStatsService } from '../community-stats/match-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner';
import { CompetitionOutboxProcessor } from './competition-outbox.processor';
describe('CompetitionOutboxProcessor', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('leases a projection event and applies idempotent downstream effects', async () => {
const competitionId = new mongoose.Types.ObjectId();
const matchId = new mongoose.Types.ObjectId();
const communityId = new mongoose.Types.ObjectId();
const eventId = new mongoose.Types.ObjectId();
const event = {
_id: eventId,
competitionId,
revision: 7,
type: 'competition.projection-updated',
state: 'pending',
attemptCount: 1,
};
const publish = jest.fn(() => executable({ matchedCount: 1 }));
const claim = jest
.fn()
.mockReturnValueOnce(leanExecutable(event))
.mockReturnValueOnce(leanExecutable(null));
const matchUpdate = jest.fn(() => executable({ matchedCount: 1 }));
const models = {
competitionOutbox: {
findOneAndUpdate: claim,
updateOne: publish,
},
competition: {
findById: jest.fn(() =>
leanExecutable({
_id: competitionId,
matchId,
communityId,
revision: 8,
phase: 'completed',
teams: [],
projection: {
phase: 'completed',
series: [],
gameSlots: [],
games: [{ evidence: { type: 'riot', riotMatchId: 'KR_1' } }],
},
}),
),
},
match: {
findById: jest.fn(() =>
leanExecutable({ status: 'in-progress', resultPollState: {} }),
),
updateOne: matchUpdate,
},
};
const connection = {
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as unknown as ConnectionService;
const provisionReadyAssignments = jest.fn().mockResolvedValue({});
const provisioner = {
provisionReadyAssignments,
} as unknown as jest.Mocked<CompetitionAssignmentProvisioner>;
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
const stats = {
buildAndUpsert,
} as unknown as jest.Mocked<MatchStatsService>;
const invalidateCommunity = jest.fn().mockResolvedValue(undefined);
const communityStats = {
invalidateCommunity,
} as unknown as jest.Mocked<CommunityStatsService>;
const processor = new CompetitionOutboxProcessor(
connection,
provisioner,
stats,
communityStats,
);
await expect(processor.drainOnce()).resolves.toBe(1);
expect(provisionReadyAssignments).toHaveBeenCalledWith({
matchId,
competition: expect.objectContaining({
competitionId: competitionId.toString(),
revision: 8,
}),
});
expect(matchUpdate).toHaveBeenCalledWith(
{ _id: matchId },
{
$set: expect.objectContaining({
status: 'finished',
'resultPollState.matchedCount': 1,
'resultPollState.state': 'complete',
}),
},
);
expect(buildAndUpsert).toHaveBeenCalledWith(matchId, {
sourceRevision: 8,
});
expect(invalidateCommunity).toHaveBeenCalledWith(communityId);
expect(publish).toHaveBeenCalledWith(
{ _id: eventId, state: 'pending', attemptCount: 1 },
expect.objectContaining({
$set: expect.objectContaining({ state: 'published' }),
}),
);
});
it('marks a leased event failed and retryable when effects cannot run', async () => {
const event = {
_id: new mongoose.Types.ObjectId(),
competitionId: new mongoose.Types.ObjectId(),
revision: 2,
type: 'competition.projection-updated',
state: 'pending',
attemptCount: 3,
};
const updateOne = jest.fn(() => executable({ matchedCount: 1 }));
const models = {
competitionOutbox: {
findOneAndUpdate: jest
.fn()
.mockReturnValueOnce(leanExecutable(event))
.mockReturnValueOnce(leanExecutable(null)),
updateOne,
},
competition: {
findById: jest.fn(() => leanExecutable(null)),
},
match: {},
};
const processor = new CompetitionOutboxProcessor(
{
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as unknown as ConnectionService,
{ provisionReadyAssignments: jest.fn() } as never,
{ buildAndUpsert: jest.fn() } as never,
{ invalidateCommunity: jest.fn() } as never,
);
await expect(processor.drainOnce()).resolves.toBe(1);
expect(updateOne).toHaveBeenCalledWith(
{ _id: event._id, state: 'pending', attemptCount: 3 },
{
$set: expect.objectContaining({
state: 'failed',
lastError: 'Competition no longer exists.',
availableAt: expect.any(Date),
}),
},
);
});
it('dead-letters a poison event after the delivery attempt limit', async () => {
const event = {
_id: new mongoose.Types.ObjectId(),
competitionId: new mongoose.Types.ObjectId(),
revision: 2,
type: 'competition.projection-updated',
state: 'pending',
attemptCount: 10,
};
const updateOne = jest.fn(() => executable({ matchedCount: 1 }));
const models = {
competitionOutbox: {
findOneAndUpdate: jest
.fn()
.mockReturnValueOnce(leanExecutable(event))
.mockReturnValueOnce(leanExecutable(null)),
updateOne,
},
competition: {
findById: jest.fn(() => leanExecutable(null)),
},
match: {},
};
const errorLog = jest
.spyOn(Logger.prototype, 'error')
.mockImplementation(() => undefined);
const processor = new CompetitionOutboxProcessor(
{
getModel: jest.fn((name: keyof typeof models) =>
Promise.resolve(models[name]),
),
} as unknown as ConnectionService,
{ provisionReadyAssignments: jest.fn() } as never,
{ buildAndUpsert: jest.fn() } as never,
{ invalidateCommunity: jest.fn() } as never,
);
await expect(processor.drainOnce()).resolves.toBe(1);
expect(updateOne).toHaveBeenCalledWith(
{ _id: event._id, state: 'pending', attemptCount: 10 },
{
$set: {
state: 'dead-letter',
lastError: 'Competition no longer exists.',
},
},
);
expect(errorLog).toHaveBeenCalledWith(
expect.stringContaining('moved to dead-letter after 10 attempts'),
);
});
});
function leanExecutable<T>(value: T) {
const query = {
lean: jest.fn(),
exec: jest.fn().mockResolvedValue(value),
};
query.lean.mockReturnValue(query);
return query;
}
function executable<T>(value: T) {
return { exec: jest.fn().mockResolvedValue(value) };
}