Serialize lifecycle changes and make cancellation, deadlines, and match side effects recoverable and idempotent. Archive accepted bids durably, quarantine invalid payloads, and preserve compatibility with empty round IDs. Synchronize HTTP polling and socket state with scoped resync events. Add cancellation cleanup index migration and regression coverage. Validated with 744 API tests, 65 Redis integration tests, and 28 Mongo integration tests.
2921 lines
90 KiB
TypeScript
2921 lines
90 KiB
TypeScript
import mongoose from 'mongoose';
|
|
import { AuctionService } from './auction.service';
|
|
|
|
describe('AuctionService', () => {
|
|
function requireRecord(
|
|
value: unknown,
|
|
label: string,
|
|
): Record<string, unknown> {
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
throw new Error(`${label} must be an object.`);
|
|
}
|
|
return value as Record<string, unknown>;
|
|
}
|
|
|
|
function requireArray(value: unknown, label: string): unknown[] {
|
|
if (!Array.isArray(value)) {
|
|
throw new Error(`${label} must be an array.`);
|
|
}
|
|
return value as unknown[];
|
|
}
|
|
|
|
function parseJsonRecord(value: unknown, label: string) {
|
|
if (typeof value !== 'string') {
|
|
throw new Error(`${label} must be a JSON string.`);
|
|
}
|
|
return requireRecord(JSON.parse(value) as unknown, label);
|
|
}
|
|
|
|
function createService(models: Record<string, unknown>) {
|
|
const auctionHistoryModel = {
|
|
findOne: jest.fn().mockReturnValue({
|
|
sort: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue(null),
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
create: jest.fn().mockResolvedValue(undefined),
|
|
deleteMany: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(undefined),
|
|
}),
|
|
};
|
|
const allModels = {
|
|
auctionHistory: auctionHistoryModel,
|
|
...models,
|
|
auction: {
|
|
updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }),
|
|
...((models.auction as object) ?? {}),
|
|
},
|
|
};
|
|
const connectionService = {
|
|
getModel: jest.fn((name: string) => allModels[name]),
|
|
createSession: jest.fn(),
|
|
};
|
|
const enrichmentService = {
|
|
enrichRiotAccount: jest.fn(),
|
|
};
|
|
const tournamentCodeService = {
|
|
reserveForMatch: jest.fn().mockResolvedValue(undefined),
|
|
releaseFromMatch: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const tournamentResultService = {
|
|
scheduleInitialPoll: jest.fn().mockResolvedValue(null),
|
|
cancelPolling: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auctionRedisService = {
|
|
acquireTokenLock: jest.fn().mockResolvedValue(true),
|
|
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1780000000000),
|
|
releaseTokenLock: jest.fn().mockResolvedValue(true),
|
|
raw: jest.fn().mockReturnValue({
|
|
sendCommand: jest.fn().mockResolvedValue(1),
|
|
}),
|
|
};
|
|
const auctionRedisCommandService = {
|
|
applyTransition: jest.fn().mockResolvedValue({
|
|
auctionStateTransitionId: 'transition-1',
|
|
currentServerTimestampMS: 1780000000000,
|
|
ok: true,
|
|
revision: 2,
|
|
}),
|
|
reserveActionRequest: jest.fn().mockImplementation(
|
|
async (
|
|
_matchId: string,
|
|
input: {
|
|
auctionActionRequestId: string;
|
|
auctionStateTransitionId: string;
|
|
clientObservedAuctionLifecycleId: string;
|
|
},
|
|
) => ({
|
|
actionRequestScopeKey: `${input.clientObservedAuctionLifecycleId}:${input.auctionActionRequestId}`,
|
|
auctionStateTransitionId: input.auctionStateTransitionId,
|
|
currentServerTimestampMS: 1780000000000,
|
|
newAuctionLifecycleId: '',
|
|
observedProcessingLeaseVersion: 1,
|
|
reserved: true,
|
|
wasLeaseExpired: false,
|
|
}),
|
|
),
|
|
hydrateState: jest.fn().mockResolvedValue({
|
|
currentServerTimestampMS: 1780000000000,
|
|
hydrated: true,
|
|
revision: 1,
|
|
}),
|
|
placeBid: jest.fn().mockResolvedValue({
|
|
auctionBidHistoryEntry: { bidPointAmount: 20 },
|
|
bidRequestId: 'bid-1',
|
|
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
|
currentHighestBidderTeamIndex: 1,
|
|
currentHighestBidPointAmount: 20,
|
|
currentServerTimestampMS: 1780000000000,
|
|
ok: true,
|
|
revision: 3,
|
|
}),
|
|
};
|
|
const auctionRedisStateReaderService = {
|
|
readLiveStateIdentity: jest.fn().mockResolvedValue({
|
|
auctionLifecycleId: 'life-1',
|
|
revision: 1,
|
|
}),
|
|
readBidContext: jest.fn().mockResolvedValue(null),
|
|
readAuctionStateView: jest.fn().mockResolvedValue(null),
|
|
};
|
|
|
|
return {
|
|
service: new AuctionService(
|
|
connectionService as never,
|
|
enrichmentService as never,
|
|
tournamentCodeService as never,
|
|
tournamentResultService as never,
|
|
auctionRedisService as never,
|
|
auctionRedisCommandService as never,
|
|
auctionRedisStateReaderService as never,
|
|
),
|
|
connectionService,
|
|
tournamentCodeService,
|
|
tournamentResultService,
|
|
auctionHistoryModel,
|
|
auctionRedisCommandService,
|
|
auctionRedisService,
|
|
auctionRedisStateReaderService,
|
|
};
|
|
}
|
|
|
|
function createFullTeam(teamIndex: number) {
|
|
return {
|
|
teamIndex,
|
|
captainUserId: new mongoose.Types.ObjectId(),
|
|
points: 100,
|
|
members: Array.from({ length: 4 }, () => ({
|
|
userId: new mongoose.Types.ObjectId(),
|
|
assignedPosition: 'MID',
|
|
cost: 10,
|
|
})),
|
|
};
|
|
}
|
|
|
|
afterEach(() => {
|
|
jest.restoreAllMocks();
|
|
jest.useRealTimers();
|
|
});
|
|
|
|
it('rejects live operations for migrated legacy auctions', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
auctionEngineVersion: 'legacy-renamed',
|
|
matchId,
|
|
phase: 'bidding',
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.placeBid({
|
|
amount: 10,
|
|
matchId,
|
|
teamIndex: 1,
|
|
}),
|
|
).rejects.toThrow('Legacy auction live operations are not supported.');
|
|
});
|
|
|
|
it('rejects non-positive or fractional bid amounts before loading auction state', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auctionFindOne = jest.fn();
|
|
const { service, auctionRedisCommandService } = createService({
|
|
auction: {
|
|
findOne: auctionFindOne,
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.placeBid({
|
|
amount: 0,
|
|
matchId,
|
|
teamIndex: 1,
|
|
}),
|
|
).rejects.toThrow('Bid amount must be a positive integer.');
|
|
await expect(
|
|
service.placeBid({
|
|
amount: 10.5,
|
|
matchId,
|
|
teamIndex: 1,
|
|
}),
|
|
).rejects.toThrow('Bid amount must be a positive integer.');
|
|
expect(auctionFindOne).not.toHaveBeenCalled();
|
|
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('lists auction history with a summary projection and short local cache', async () => {
|
|
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const match = {
|
|
communityId: {
|
|
equals: jest.fn((value) => value.toString() === communityId.toString()),
|
|
},
|
|
};
|
|
const historyRows = [
|
|
{
|
|
action: 'sold',
|
|
sequence: 4,
|
|
takenAt: new Date('2026-06-26T00:00:00.000Z'),
|
|
},
|
|
{
|
|
action: 'open-bidding',
|
|
sequence: 3,
|
|
takenAt: new Date('2026-06-26T00:00:01.000Z'),
|
|
},
|
|
];
|
|
const historyExec = jest.fn().mockResolvedValue(historyRows);
|
|
const historyLean = jest.fn().mockReturnValue({ exec: historyExec });
|
|
const historyLimit = jest.fn().mockReturnValue({ lean: historyLean });
|
|
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
|
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
|
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
|
const { service } = createService({
|
|
auctionHistory: {
|
|
find: historyFind,
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockResolvedValue(match),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.listHistory({ matchId, communityId }),
|
|
).resolves.toEqual([
|
|
{
|
|
action: 'sold',
|
|
actionLabel: '낙찰 처리',
|
|
sequence: 4,
|
|
takenAt: historyRows[0].takenAt,
|
|
},
|
|
{
|
|
action: 'open-bidding',
|
|
actionLabel: '입찰 열기',
|
|
sequence: 3,
|
|
takenAt: historyRows[1].takenAt,
|
|
},
|
|
]);
|
|
await service.listHistory({ matchId, communityId });
|
|
|
|
expect(historyFind).toHaveBeenCalledTimes(1);
|
|
expect(historySelect).toHaveBeenCalledWith({
|
|
_id: 0,
|
|
action: 1,
|
|
sequence: 1,
|
|
takenAt: 1,
|
|
});
|
|
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
|
expect(historyLimit).toHaveBeenCalledWith(100);
|
|
|
|
nowSpy.mockReturnValue(3101);
|
|
await service.listHistory({ matchId, communityId });
|
|
expect(historyFind).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
toObject: jest.fn().mockReturnValue({ matchId }),
|
|
};
|
|
const { service, tournamentCodeService, tournamentResultService } =
|
|
createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(null),
|
|
create: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000001',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{ teamIndex: 2, userId: userIds[1] },
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
});
|
|
|
|
expect(match.status).toBe('team-built');
|
|
expect(match.teamBuiltAt).toBeUndefined();
|
|
expect(match.save).toHaveBeenCalledTimes(1);
|
|
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
|
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('creates redis-v1 auction fields and bootstraps Redis state when starting', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
|
_id: payload._id,
|
|
matchId,
|
|
...payload,
|
|
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
|
}));
|
|
const { service, auctionRedisCommandService, auctionRedisService } =
|
|
createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(null),
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000011',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{
|
|
teamIndex: 2,
|
|
userId: userIds[1],
|
|
initialTeamBidPointAmount: 1200,
|
|
},
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
});
|
|
|
|
const createdPayload = auctionCreate.mock.calls[0][0];
|
|
expect(auctionRedisService.getCurrentRedisTimestampMS).toHaveBeenCalled();
|
|
expect(createdPayload).toMatchObject({
|
|
auctionEngineVersion: 'redis-v1',
|
|
currentAuctionHistorySequence: 1,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
currentHighestBidPointAmount: 0,
|
|
initialTeamBidPointAmount: 1000,
|
|
matchSideEffectRevision: 0,
|
|
matchSideEffectStatus: 'none',
|
|
phase: 'presenting',
|
|
revision: 1,
|
|
});
|
|
expect(createdPayload.auctionTeams).toEqual([
|
|
expect.objectContaining({
|
|
remainingBidPointAmount: 1000,
|
|
teamIndex: 1,
|
|
}),
|
|
expect.objectContaining({
|
|
remainingBidPointAmount: 1200,
|
|
teamIndex: 2,
|
|
}),
|
|
]);
|
|
expect(createdPayload.auctionStartedAtTimestampMS).toBe(1780000000000);
|
|
expect(createdPayload.startedAt).toEqual(new Date(1780000000000));
|
|
expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
auctionHistorySequence: 1,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
matchId: matchId.toString(),
|
|
phase: 'presenting',
|
|
revision: 0,
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('replays start when the same startAuctionRequestId already created the auction', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const existingAuction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000010',
|
|
};
|
|
const auctionCreate = jest.fn();
|
|
const { service } = createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue({
|
|
_id: matchId,
|
|
communityId,
|
|
}),
|
|
},
|
|
user: {
|
|
find: jest.fn(),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(existingAuction),
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn(),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000010',
|
|
captains: [],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
}),
|
|
).resolves.toBe(existingAuction);
|
|
expect(auctionCreate).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects start while a redis reset side effect is still applying', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const existingAuction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
auctionEngineVersion: 'redis-v1',
|
|
matchSideEffectStatus: 'pending',
|
|
phase: 'waiting',
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000020',
|
|
};
|
|
const auctionCreate = jest.fn();
|
|
const { service } = createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue({
|
|
_id: matchId,
|
|
communityId,
|
|
}),
|
|
},
|
|
user: {
|
|
find: jest.fn(),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(existingAuction),
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn(),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000021',
|
|
captains: [],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
}),
|
|
).rejects.toThrow('Auction reset is still being applied.');
|
|
expect(auctionCreate).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('removes a completed redis reset auction before starting again', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const oldAuctionId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const existingAuction = {
|
|
_id: oldAuctionId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: 'old-life-1',
|
|
matchSideEffectStatus: 'completed',
|
|
phase: 'waiting',
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000022',
|
|
};
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
|
_id: payload._id,
|
|
matchId,
|
|
...payload,
|
|
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
|
}));
|
|
const auctionDeleteOne = jest.fn().mockResolvedValue({ deletedCount: 1 });
|
|
const historyDeleteMany = jest.fn().mockResolvedValue({ deletedCount: 2 });
|
|
const { service, auctionRedisCommandService, auctionRedisService } =
|
|
createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
create: auctionCreate,
|
|
deleteOne: auctionDeleteOne,
|
|
findOne: jest.fn().mockResolvedValue(existingAuction),
|
|
},
|
|
auctionHistory: {
|
|
create: jest.fn().mockResolvedValue(undefined),
|
|
deleteMany: historyDeleteMany,
|
|
findOne: jest.fn().mockReturnValue({
|
|
sort: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue(null),
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000023',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{ teamIndex: 2, userId: userIds[1] },
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
});
|
|
|
|
expect(historyDeleteMany).toHaveBeenCalledWith({ auctionId: oldAuctionId });
|
|
expect(auctionDeleteOne).toHaveBeenCalledWith({ _id: oldAuctionId });
|
|
expect(auctionRedisService.raw().sendCommand).toHaveBeenCalledWith([
|
|
'EVAL',
|
|
expect.stringContaining('currentAuctionLifecycleId'),
|
|
'12',
|
|
`auction:${matchId.toString()}:liveAuctionState`,
|
|
'auction:bidRoundDeadlineQueue',
|
|
`auction:${matchId.toString()}:auctionStructureState`,
|
|
`auction:${matchId.toString()}:appliedAuctionStateTransitionIds`,
|
|
`auction:${matchId.toString()}:auctionBidHistory`,
|
|
`auction:${matchId.toString()}:bidRequestResults`,
|
|
`auction:${matchId.toString()}:bidRequestResultOrder`,
|
|
`auction:${matchId.toString()}:auctionActionRequestResults`,
|
|
`auction:${matchId.toString()}:auctionActionRequestResultOrder`,
|
|
`auction:${matchId.toString()}:rehydrateLock`,
|
|
`auction:${matchId.toString()}:auctionStateTransitionLock`,
|
|
`auction:${matchId.toString()}:rejectedBidRequestResultOrder`,
|
|
matchId.toString(),
|
|
'old-life-1',
|
|
]);
|
|
expect(auctionCreate).toHaveBeenCalledTimes(1);
|
|
expect(auctionRedisCommandService.hydrateState).toHaveBeenCalled();
|
|
});
|
|
|
|
it('replays start after a concurrent create wins with the same request id', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const raceWinner = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000012',
|
|
};
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auctionFindOne = jest
|
|
.fn()
|
|
.mockResolvedValueOnce(null)
|
|
.mockResolvedValueOnce(raceWinner);
|
|
const auctionCreate = jest.fn().mockRejectedValue({ code: 11000 });
|
|
const { service, auctionRedisCommandService } = createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
findOne: auctionFindOne,
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000012',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{ teamIndex: 2, userId: userIds[1] },
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
}),
|
|
).resolves.toBe(raceWinner);
|
|
|
|
expect(auctionCreate).toHaveBeenCalledTimes(1);
|
|
expect(auctionRedisCommandService.hydrateState).not.toHaveBeenCalled();
|
|
expect(match.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('reads Redis state view for redis-v1 auctions', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
chatMessages: [{ id: 'chat-1' }],
|
|
toObject: jest.fn().mockReturnValue({
|
|
matchId,
|
|
phase: 'presenting',
|
|
revision: 1,
|
|
}),
|
|
};
|
|
const { service, auctionRedisStateReaderService } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue({
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
currentServerTimestampMS: 1000,
|
|
});
|
|
|
|
await expect(service.getStateByMatchId(matchId)).resolves.toMatchObject({
|
|
chatMessages: [{ id: 'chat-1' }],
|
|
currentServerTimestampMS: 1000,
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
});
|
|
expect(
|
|
auctionRedisStateReaderService.readAuctionStateView,
|
|
).toHaveBeenCalledWith(matchId.toString());
|
|
});
|
|
|
|
it('rehydrates Redis state from Mongo projection when live state is missing', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const playerUserId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: 'life-1',
|
|
phase: 'presenting',
|
|
revision: 4,
|
|
currentAuctionHistorySequence: 3,
|
|
auctionTeams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: captainUserId.toString(),
|
|
remainingBidPointAmount: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
auctionPlayerOrder: [{ userId: playerUserId.toString() }],
|
|
passedAuctionPlayerQueue: [],
|
|
currentAuctionRound: 1,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
initialTeamBidPointAmount: 1000,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
chatMessages: [],
|
|
toObject: jest.fn().mockReturnValue({
|
|
matchId,
|
|
phase: 'presenting',
|
|
revision: 4,
|
|
}),
|
|
};
|
|
const redisState = {
|
|
auctionLifecycleId: 'life-1',
|
|
phase: 'presenting',
|
|
revision: 5,
|
|
shouldForceAuctionStateResync: true,
|
|
};
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
|
|
null,
|
|
);
|
|
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
|
redisState,
|
|
);
|
|
|
|
await expect(service.getStateByMatchId(matchId)).resolves.toMatchObject({
|
|
phase: 'presenting',
|
|
revision: 5,
|
|
shouldForceAuctionStateResync: true,
|
|
});
|
|
expect(auctionRedisService.acquireTokenLock).toHaveBeenCalledWith(
|
|
`auction:${matchId.toString()}:lifecycleMutationLock`,
|
|
expect.any(String),
|
|
30000,
|
|
);
|
|
expect(auctionRedisCommandService.hydrateState).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
auctionLifecycleId: 'life-1',
|
|
phase: 'presenting',
|
|
revision: 4,
|
|
}),
|
|
);
|
|
expect(
|
|
auctionRedisStateReaderService.readAuctionStateView,
|
|
).toHaveBeenCalledWith(matchId.toString(), {
|
|
shouldForceAuctionStateResync: true,
|
|
});
|
|
});
|
|
|
|
it('opens bidding through Redis for redis-v1 auctions', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
};
|
|
const presentingState = {
|
|
auctionLifecycleId: 'life-1',
|
|
auctionTeams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: new mongoose.Types.ObjectId().toString(),
|
|
remainingBidPointAmount: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
auctionPlayerOrder: [
|
|
{
|
|
userId: new mongoose.Types.ObjectId().toString(),
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
},
|
|
],
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 1,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
passedAuctionPlayerQueue: [],
|
|
phase: 'presenting',
|
|
revision: 1,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const biddingState = {
|
|
...presentingState,
|
|
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
};
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readAuctionStateView
|
|
.mockResolvedValueOnce(presentingState)
|
|
.mockResolvedValueOnce(biddingState);
|
|
|
|
await expect(
|
|
service.openBidding(matchId, {
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000060',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedPhase: 'presenting',
|
|
clientObservedRevision: 1,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
});
|
|
expect(
|
|
auctionRedisCommandService.reserveActionRequest,
|
|
).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000060',
|
|
auctionActionType: 'open-bidding',
|
|
auctionStateTransitionId:
|
|
'open-bidding:life-1:00000000-0000-4000-8000-000000000060',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedPhase: 'presenting',
|
|
clientObservedRevision: 1,
|
|
}),
|
|
);
|
|
expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
actionRequest: expect.objectContaining({
|
|
observedProcessingLeaseVersion: 1,
|
|
scopeKey: 'life-1:00000000-0000-4000-8000-000000000060',
|
|
}),
|
|
auctionStateTransitionId:
|
|
'open-bidding:life-1:00000000-0000-4000-8000-000000000060',
|
|
deadline: { durationSeconds: 30, mode: 'set-relative' },
|
|
expectedPhase: 'presenting',
|
|
expectedRevision: 1,
|
|
liveStatePatch: expect.objectContaining({
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
phase: 'bidding',
|
|
'team:1:assignedAuctionTeamMemberCount': 1,
|
|
'team:1:remainingBidPointAmount': 1000,
|
|
}),
|
|
}),
|
|
);
|
|
const transitionInput =
|
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
|
expect(
|
|
parseJsonRecord(
|
|
transitionInput.durabilityPayloadJson,
|
|
'durabilityPayloadJson',
|
|
),
|
|
).toMatchObject({
|
|
afterAuctionMongoProjection: expect.objectContaining({
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
}),
|
|
auctionActionType: 'open-bidding',
|
|
historyMutation: { type: 'append' },
|
|
matchSideEffectMutation: { type: 'none' },
|
|
snapshotBefore: expect.objectContaining({
|
|
phase: 'presenting',
|
|
}),
|
|
});
|
|
});
|
|
|
|
it('places bids through Redis for redis-v1 auctions', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const playerUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
};
|
|
const biddingState = {
|
|
auctionLifecycleId: 'life-1',
|
|
auctionTeams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: captainUserId.toString(),
|
|
remainingBidPointAmount: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
currentBidRoundPlayerUserId: playerUserId.toString(),
|
|
phase: 'bidding',
|
|
revision: 2,
|
|
};
|
|
const afterBidState = {
|
|
...biddingState,
|
|
currentHighestBidderTeamIndex: 1,
|
|
currentHighestBidPointAmount: 120,
|
|
revision: 3,
|
|
};
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readAuctionStateView
|
|
.mockResolvedValueOnce(biddingState)
|
|
.mockResolvedValueOnce(afterBidState);
|
|
|
|
await expect(
|
|
service.placeBid({
|
|
amount: 120,
|
|
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
|
matchId,
|
|
teamIndex: 1,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
currentHighestBidderTeamIndex: 1,
|
|
currentHighestBidPointAmount: 120,
|
|
revision: 3,
|
|
});
|
|
expect(auctionRedisCommandService.placeBid).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
bidPointAmount: 120,
|
|
bidderTeamIndex: 1,
|
|
bidderUserId: captainUserId.toString(),
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(),
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('keeps Redis sold snapshotBefore isolated from the sold structure mutation', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const playerUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
auctionEngineVersion: 'redis-v1',
|
|
matchId,
|
|
matchSideEffectRevision: 0,
|
|
};
|
|
const biddingState = {
|
|
auctionBidHistory: [],
|
|
auctionLifecycleId: 'life-1',
|
|
auctionPlayerOrder: [
|
|
{
|
|
userId: playerUserId.toString(),
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
},
|
|
],
|
|
auctionTeams: [
|
|
{
|
|
captainUserId: captainUserId.toString(),
|
|
members: [],
|
|
remainingBidPointAmount: 1000,
|
|
teamIndex: 1,
|
|
},
|
|
],
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 3,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
currentBidRoundPlayerUserId: playerUserId.toString(),
|
|
currentHighestBidPointAmount: 120,
|
|
currentHighestBidderTeamIndex: 1,
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
passedAuctionPlayerQueue: [],
|
|
phase: 'bidding',
|
|
revision: 4,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const soldState = {
|
|
...biddingState,
|
|
auctionTeams: [
|
|
{
|
|
...biddingState.auctionTeams[0],
|
|
members: [
|
|
{
|
|
assignedPosition: 'MID',
|
|
memberAcquisitionBidPointAmount: 120,
|
|
userId: playerUserId.toString(),
|
|
},
|
|
],
|
|
remainingBidPointAmount: 880,
|
|
},
|
|
],
|
|
currentAuctionHistorySequence: 4,
|
|
currentHighestBidPointAmount: 120,
|
|
phase: 'sold',
|
|
revision: 5,
|
|
};
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readAuctionStateView
|
|
.mockResolvedValueOnce(biddingState)
|
|
.mockResolvedValueOnce(soldState);
|
|
|
|
await expect(
|
|
service.markSold({
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000061',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedCurrentBidRoundPlayerUserId: playerUserId.toString(),
|
|
clientObservedPhase: 'bidding',
|
|
clientObservedRevision: 4,
|
|
matchId,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
phase: 'sold',
|
|
revision: 5,
|
|
});
|
|
|
|
const transitionInput =
|
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
|
const durabilityPayload = parseJsonRecord(
|
|
transitionInput.durabilityPayloadJson,
|
|
'durabilityPayloadJson',
|
|
);
|
|
const snapshotBefore = requireRecord(
|
|
durabilityPayload.snapshotBefore,
|
|
'snapshotBefore',
|
|
);
|
|
const snapshotBeforeTeams = requireArray(
|
|
snapshotBefore.auctionTeams,
|
|
'snapshotBefore.auctionTeams',
|
|
);
|
|
const snapshotBeforeTeam = requireRecord(
|
|
snapshotBeforeTeams[0],
|
|
'snapshotBefore.auctionTeams[0]',
|
|
);
|
|
const afterAuctionMongoProjection = requireRecord(
|
|
durabilityPayload.afterAuctionMongoProjection,
|
|
'afterAuctionMongoProjection',
|
|
);
|
|
const projectedTeams = requireArray(
|
|
afterAuctionMongoProjection.auctionTeams,
|
|
'afterAuctionMongoProjection.auctionTeams',
|
|
);
|
|
const projectedTeam = requireRecord(
|
|
projectedTeams[0],
|
|
'afterAuctionMongoProjection.auctionTeams[0]',
|
|
);
|
|
expect(snapshotBefore).toMatchObject({
|
|
phase: 'bidding',
|
|
revision: 4,
|
|
});
|
|
expect(snapshotBeforeTeam.members).toEqual([]);
|
|
expect(projectedTeam.members).toEqual([
|
|
expect.objectContaining({
|
|
memberAcquisitionBidPointAmount: 120,
|
|
userId: playerUserId.toString(),
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it('returns bid deltas without re-reading the full Redis state', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const playerUserId = new mongoose.Types.ObjectId();
|
|
const biddingContext = {
|
|
auctionLifecycleId: 'life-1',
|
|
bidderTeamCaptainUserId: captainUserId.toString(),
|
|
currentBidRoundPlayerUserId: playerUserId.toString(),
|
|
phase: 'bidding',
|
|
};
|
|
const auctionBidHistoryEntry = {
|
|
bidderTeamIndex: 1,
|
|
bidderUserId: captainUserId.toString(),
|
|
bidPlacedAtTimestampMS: 1780000000000,
|
|
bidPointAmount: 120,
|
|
};
|
|
const {
|
|
connectionService,
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({});
|
|
auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce(
|
|
biddingContext,
|
|
);
|
|
auctionRedisCommandService.placeBid.mockResolvedValueOnce({
|
|
auctionBidHistoryEntry,
|
|
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
|
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
|
currentHighestBidderTeamIndex: 1,
|
|
currentHighestBidPointAmount: 120,
|
|
currentServerTimestampMS: 1780000000000,
|
|
ok: true,
|
|
revision: 3,
|
|
});
|
|
|
|
await expect(
|
|
service.placeBidDelta({
|
|
amount: 120,
|
|
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
|
matchId,
|
|
teamIndex: 1,
|
|
}),
|
|
).resolves.toEqual(
|
|
expect.objectContaining({
|
|
auctionBidHistoryEntry,
|
|
auctionLifecycleId: 'life-1',
|
|
bidRequestId: '00000000-0000-4000-8000-000000000050',
|
|
bidServerTiming: expect.objectContaining({
|
|
redisBidCommandDurationMS: expect.any(Number),
|
|
redisBidContextReadDurationMS: expect.any(Number),
|
|
serviceTotalDurationMS: expect.any(Number),
|
|
}),
|
|
currentBidRoundDeadlineTimestampMS: 1780000030000,
|
|
currentHighestBidderTeamIndex: 1,
|
|
currentHighestBidPointAmount: 120,
|
|
currentServerTimestampMS: 1780000000000,
|
|
revision: 3,
|
|
}),
|
|
);
|
|
expect(
|
|
auctionRedisStateReaderService.readAuctionStateView,
|
|
).not.toHaveBeenCalled();
|
|
expect(connectionService.getModel).not.toHaveBeenCalledWith('auction');
|
|
});
|
|
|
|
it('includes redis bid diagnostics and timing on realtime bid rejection', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const playerUserId = new mongoose.Types.ObjectId();
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({});
|
|
auctionRedisStateReaderService.readBidContext.mockResolvedValueOnce({
|
|
auctionLifecycleId: 'life-1',
|
|
bidderTeamCaptainUserId: captainUserId.toString(),
|
|
currentBidRoundPlayerUserId: playerUserId.toString(),
|
|
phase: 'bidding',
|
|
});
|
|
auctionRedisCommandService.placeBid.mockResolvedValueOnce({
|
|
bidRequestId: 'bid-1',
|
|
code: 'EXPIRED',
|
|
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
|
currentServerTimestampMS: 1780000003000,
|
|
rejected: true,
|
|
});
|
|
|
|
try {
|
|
await service.placeBidDelta({
|
|
amount: 120,
|
|
bidRequestId: 'bid-1',
|
|
matchId,
|
|
teamIndex: 1,
|
|
});
|
|
throw new Error('Expected bid rejection.');
|
|
} catch (error) {
|
|
const response = (error as { getResponse: () => unknown }).getResponse();
|
|
expect(response).toEqual(
|
|
expect.objectContaining({
|
|
bidDiagnostics: {
|
|
currentBidRoundDeadlineTimestampMS: 1780000002500,
|
|
currentServerTimestampMS: 1780000003000,
|
|
},
|
|
bidServerTiming: expect.objectContaining({
|
|
redisBidCommandDurationMS: expect.any(Number),
|
|
redisBidContextReadDurationMS: expect.any(Number),
|
|
serviceTotalDurationMS: expect.any(Number),
|
|
}),
|
|
code: 'EXPIRED',
|
|
message: 'Bid deadline has already expired.',
|
|
}),
|
|
);
|
|
}
|
|
});
|
|
|
|
describe('redis next safety', () => {
|
|
function createFortyPlayerAuction() {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const participantIds = Array.from(
|
|
{ length: 40 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: 'life-1',
|
|
};
|
|
const state = {
|
|
auctionLifecycleId: 'life-1',
|
|
auctionTeams: participantIds
|
|
.slice(0, 8)
|
|
.map((captainUserId, index) => ({
|
|
teamIndex: index + 1,
|
|
captainUserId: captainUserId.toString(),
|
|
remainingBidPointAmount: 960,
|
|
members: participantIds
|
|
.slice(8 + index * 4, 12 + index * 4)
|
|
.map((userId) => ({
|
|
userId: userId.toString(),
|
|
assignedPosition: 'MID',
|
|
memberAcquisitionBidPointAmount: 10,
|
|
})),
|
|
})),
|
|
auctionPlayerOrder: participantIds.slice(8).map((userId) => ({
|
|
userId: userId.toString(),
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
passCount: 0,
|
|
})),
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 121,
|
|
currentAuctionPlayerOrderIndex: 31,
|
|
currentAuctionRound: 1,
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 15,
|
|
passedAuctionPlayerQueue: [] as Array<{
|
|
userId: string;
|
|
preferredPositions: Array<{ position: string; priority: number }>;
|
|
passCount: number;
|
|
}>,
|
|
phase: 'sold',
|
|
revision: 479,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const match = {
|
|
_id: matchId,
|
|
participants: participantIds.map((userId) => ({
|
|
userId,
|
|
excluded: false,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
})),
|
|
status: 'team-built',
|
|
teams: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const dependencies = createService({
|
|
auction: { findOne: jest.fn().mockResolvedValue(auction) },
|
|
match: { findById: jest.fn().mockResolvedValue(match) },
|
|
});
|
|
dependencies.auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
|
state,
|
|
);
|
|
dependencies.auctionRedisCommandService.applyTransition.mockImplementation(
|
|
async (_matchId: string, input: Record<string, unknown>) => {
|
|
Object.assign(
|
|
state,
|
|
parseJsonRecord(
|
|
input.afterAuctionStructureStateJson,
|
|
'afterAuctionStructureStateJson',
|
|
),
|
|
input.liveStatePatch,
|
|
{
|
|
revision: Number(input.expectedRevision) + 1,
|
|
currentAuctionHistorySequence: input.auctionHistorySequence,
|
|
},
|
|
);
|
|
return {
|
|
auctionStateTransitionId: String(input.auctionStateTransitionId),
|
|
currentServerTimestampMS: 1780000000000,
|
|
ok: true,
|
|
revision: state.revision,
|
|
};
|
|
},
|
|
);
|
|
return { ...dependencies, matchId, match, state, participantIds };
|
|
}
|
|
|
|
it.each([12, 31])(
|
|
'rejects next for a presenting player at index %i without skipping or completing',
|
|
async (index) => {
|
|
const { service, matchId, state, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.phase = 'presenting';
|
|
state.currentAuctionPlayerOrderIndex = index;
|
|
const before = structuredClone(state);
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Cannot advance from current phase.',
|
|
);
|
|
|
|
expect(state).toEqual(before);
|
|
expect(
|
|
auctionRedisCommandService.reserveActionRequest,
|
|
).not.toHaveBeenCalled();
|
|
expect(
|
|
auctionRedisCommandService.applyTransition,
|
|
).not.toHaveBeenCalled();
|
|
},
|
|
);
|
|
|
|
it('rejects completion when only 39 of the 40 participants are assigned', async () => {
|
|
const { service, matchId, state, match, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.auctionTeams[6].members.pop();
|
|
const before = structuredClone(state);
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Auction roster validation failed.',
|
|
);
|
|
|
|
expect(state).toEqual(before);
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
expect(match.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('checks original eligible participants even if a missing player also disappeared from the order', async () => {
|
|
const { service, matchId, state, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
const missingPlayer = state.auctionTeams[6].members.pop()!;
|
|
state.auctionPlayerOrder = state.auctionPlayerOrder.filter(
|
|
(player) => player.userId !== missingPlayer.userId,
|
|
);
|
|
state.currentAuctionPlayerOrderIndex =
|
|
state.auctionPlayerOrder.length - 1;
|
|
const before = structuredClone(state);
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Auction roster validation failed.',
|
|
);
|
|
|
|
expect(state).toEqual(before);
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects a duplicate assignment even when the assigned count still equals 40', async () => {
|
|
const { service, matchId, state, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.auctionTeams[0].members[0].userId =
|
|
state.auctionTeams[1].members[0].userId;
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Auction roster validation failed.',
|
|
);
|
|
|
|
expect(state.phase).toBe('sold');
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects duplicate captain membership even when every expected user is present', async () => {
|
|
const { service, matchId, state, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.auctionTeams[0].members.push({
|
|
userId: state.auctionTeams[0].captainUserId,
|
|
assignedPosition: 'MID',
|
|
memberAcquisitionBidPointAmount: 10,
|
|
});
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Auction roster validation failed.',
|
|
);
|
|
|
|
expect(state.phase).toBe('sold');
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects an unexpected assigned user even when all 40 assignments are unique', async () => {
|
|
const { service, matchId, state, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.auctionTeams[0].members[0].userId =
|
|
new mongoose.Types.ObjectId().toString();
|
|
|
|
await expect(service.next(matchId)).rejects.toThrow(
|
|
'Auction roster validation failed.',
|
|
);
|
|
|
|
expect(state.phase).toBe('sold');
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('completes all 40 eligible participants once, allowing repeat order entries after passes and excluding cut participants', async () => {
|
|
const { service, matchId, state, match, auctionRedisCommandService } =
|
|
createFortyPlayerAuction();
|
|
state.auctionPlayerOrder.push({
|
|
...state.auctionPlayerOrder[12],
|
|
passCount: 1,
|
|
});
|
|
state.currentAuctionPlayerOrderIndex =
|
|
state.auctionPlayerOrder.length - 1;
|
|
state.currentAuctionRound = 2;
|
|
match.participants.push({
|
|
userId: new mongoose.Types.ObjectId(),
|
|
excluded: true,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
});
|
|
|
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
|
phase: 'complete',
|
|
revision: 480,
|
|
});
|
|
|
|
expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes(
|
|
1,
|
|
);
|
|
expect(state.auctionTeams).toHaveLength(8);
|
|
expect(
|
|
state.auctionTeams.every((team) => team.members.length === 4),
|
|
).toBe(true);
|
|
expect(match.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(['sold', 'passed'])(
|
|
'advances a nonterminal %s player without demanding a completed roster',
|
|
async (phase) => {
|
|
const { service, matchId, state } = createFortyPlayerAuction();
|
|
state.phase = phase;
|
|
state.currentAuctionPlayerOrderIndex = 12;
|
|
state.auctionTeams.forEach((team) => {
|
|
team.members = [];
|
|
});
|
|
|
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
|
phase: 'presenting',
|
|
currentAuctionPlayerOrderIndex: 13,
|
|
});
|
|
},
|
|
);
|
|
|
|
it('requeues passed players for another round without completing an incomplete roster', async () => {
|
|
const { service, matchId, state } = createFortyPlayerAuction();
|
|
state.phase = 'passed';
|
|
state.auctionTeams[7].members.pop();
|
|
state.passedAuctionPlayerQueue.push({
|
|
...state.auctionPlayerOrder[31],
|
|
passCount: 1,
|
|
});
|
|
|
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
|
phase: 'presenting',
|
|
currentAuctionPlayerOrderIndex: 32,
|
|
currentAuctionRound: 2,
|
|
passedAuctionPlayerQueue: [],
|
|
});
|
|
expect(state.auctionPlayerOrder).toHaveLength(33);
|
|
});
|
|
});
|
|
|
|
it('syncs match teams when a redis-v1 auction completes', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const memberUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
};
|
|
const soldState = {
|
|
auctionLifecycleId: 'life-1',
|
|
auctionTeams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: captainUserId.toString(),
|
|
remainingBidPointAmount: 970,
|
|
members: [
|
|
{
|
|
userId: memberUserId.toString(),
|
|
assignedPosition: 'ADC',
|
|
memberAcquisitionBidPointAmount: 30,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
auctionPlayerOrder: [{ userId: memberUserId.toString() }],
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 2,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
passedAuctionPlayerQueue: [],
|
|
phase: 'sold',
|
|
revision: 3,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const completeState = {
|
|
...soldState,
|
|
auctionCompletedAtTimestampMS: 1780000100000,
|
|
phase: 'complete',
|
|
revision: 4,
|
|
};
|
|
const match = {
|
|
participants: [
|
|
{
|
|
userId: captainUserId,
|
|
preferredPositions: [{ position: 'TOP', priority: 1 }],
|
|
},
|
|
{
|
|
userId: memberUserId,
|
|
preferredPositions: [{ position: 'ADC', priority: 1 }],
|
|
},
|
|
],
|
|
status: 'team-built',
|
|
teams: [],
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const {
|
|
service,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
tournamentCodeService,
|
|
tournamentResultService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
});
|
|
auctionRedisStateReaderService.readAuctionStateView
|
|
.mockResolvedValueOnce(soldState)
|
|
.mockResolvedValueOnce(completeState);
|
|
|
|
await expect(service.next(matchId)).resolves.toMatchObject({
|
|
phase: 'complete',
|
|
revision: 4,
|
|
});
|
|
const [, transitionInput] =
|
|
auctionRedisCommandService.applyTransition.mock.calls.at(-1) ?? [];
|
|
expect(
|
|
parseJsonRecord(
|
|
transitionInput.durabilityPayloadJson,
|
|
'durabilityPayloadJson',
|
|
),
|
|
).toMatchObject({
|
|
afterAuctionMongoProjection: {
|
|
matchSideEffectStatus: 'pending',
|
|
phase: 'complete',
|
|
},
|
|
auctionActionType: 'complete',
|
|
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
|
|
});
|
|
expect(match.teams).toEqual([]);
|
|
expect(match.save).not.toHaveBeenCalled();
|
|
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
|
|
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('appends a chat message and keeps only the latest 200 messages', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const userId = new mongoose.Types.ObjectId();
|
|
const oldMessages = Array.from({ length: 200 }, (_, index) => ({
|
|
id: `old-${index}`,
|
|
displayName: 'Old',
|
|
message: `old message ${index}`,
|
|
sentAt: new Date(index),
|
|
}));
|
|
const auction = {
|
|
matchId,
|
|
chatMessages: oldMessages,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
const appended = await service.appendChatMessage({
|
|
matchId,
|
|
userId,
|
|
displayName: ' Captain One ',
|
|
message: ' 좋은 픽입니다 ',
|
|
});
|
|
|
|
expect(appended.message).toMatchObject({
|
|
userId,
|
|
displayName: 'Captain One',
|
|
message: '좋은 픽입니다',
|
|
});
|
|
expect(appended.message.id).toHaveLength(36);
|
|
expect(appended.message.sentAt).toBeInstanceOf(Date);
|
|
expect(auction.chatMessages).toHaveLength(200);
|
|
expect(auction.chatMessages[0].id).toBe('old-1');
|
|
expect(auction.chatMessages.at(-1)).toBe(appended.message);
|
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('rejects blank and overly long chat messages', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
matchId,
|
|
chatMessages: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.appendChatMessage({
|
|
matchId,
|
|
displayName: 'Spectator',
|
|
message: ' ',
|
|
}),
|
|
).rejects.toThrow('Chat message is required.');
|
|
await expect(
|
|
service.appendChatMessage({
|
|
matchId,
|
|
displayName: 'Spectator',
|
|
message: 'a'.repeat(301),
|
|
}),
|
|
).rejects.toThrow('Chat message must be 300 characters or less.');
|
|
expect(auction.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('randomizes the non-captain player order when starting an auction', async () => {
|
|
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0);
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
|
}));
|
|
const { service } = createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(null),
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000002',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{ teamIndex: 2, userId: userIds[1] },
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
});
|
|
|
|
const signupOrder = userIds.slice(2).map((userId) => userId.toString());
|
|
const auctionOrder = auctionCreate.mock.calls[0][0].order.map(
|
|
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
|
|
);
|
|
|
|
expect(auctionOrder).not.toEqual(signupOrder);
|
|
expect([...auctionOrder].sort()).toEqual([...signupOrder].sort());
|
|
expect(randomSpy).toHaveBeenCalled();
|
|
});
|
|
|
|
it('includes tier history in auction player snapshots when starting an auction', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const userIds = Array.from(
|
|
{ length: 10 },
|
|
() => new mongoose.Types.ObjectId(),
|
|
);
|
|
const participants = userIds.map((userId, index) => ({
|
|
userId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
joinedAt: new Date(index),
|
|
excluded: false,
|
|
}));
|
|
const match = {
|
|
_id: matchId,
|
|
communityId,
|
|
participants,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const tierHistory = [
|
|
{
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'GOLD',
|
|
rank: 'II',
|
|
leaguePoints: 42,
|
|
wins: 30,
|
|
losses: 24,
|
|
recordedAt: new Date('2026-05-01T00:00:00.000Z'),
|
|
},
|
|
{
|
|
queueType: 'RANKED_SOLO_5x5',
|
|
tier: 'PLATINUM',
|
|
rank: 'IV',
|
|
leaguePoints: 15,
|
|
wins: 34,
|
|
losses: 27,
|
|
recordedAt: new Date('2026-05-08T00:00:00.000Z'),
|
|
},
|
|
];
|
|
const users = userIds.slice(2).map((userId, index) => ({
|
|
_id: userId,
|
|
riotAccounts: [
|
|
{
|
|
puuid: `puuid-${index}`,
|
|
gameName: `Player${index}`,
|
|
tagLine: 'KR1',
|
|
profileIconId: index,
|
|
tiers: [],
|
|
tierHistory: index === 0 ? tierHistory : [],
|
|
championMasteries: [],
|
|
recentStatsSummary: undefined,
|
|
lastRefreshRequestedAt: new Date(),
|
|
isPrimary: true,
|
|
},
|
|
],
|
|
}));
|
|
const auctionCreate = jest.fn().mockImplementation(async (payload) => ({
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
toObject: jest.fn().mockReturnValue({ matchId, ...payload }),
|
|
}));
|
|
const { service } = createService({
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
user: {
|
|
find: jest.fn().mockResolvedValue(users),
|
|
},
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(null),
|
|
create: auctionCreate,
|
|
},
|
|
community: {
|
|
findById: jest.fn().mockReturnValue({
|
|
select: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
riotPlatform: 'kr',
|
|
riotRegion: 'asia',
|
|
}),
|
|
}),
|
|
}),
|
|
}),
|
|
},
|
|
});
|
|
|
|
await service.start({
|
|
matchId,
|
|
communityId,
|
|
startAuctionRequestId: '00000000-0000-4000-8000-000000000003',
|
|
captains: [
|
|
{ teamIndex: 1, userId: userIds[0] },
|
|
{ teamIndex: 2, userId: userIds[1] },
|
|
],
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
bidRoundExtensionSeconds: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
manualTopTierAuctionPriorityUserIds: [],
|
|
});
|
|
|
|
const firstPlayerSnapshot = auctionCreate.mock.calls[0][0].order.find(
|
|
(player: { userId: mongoose.Types.ObjectId }) =>
|
|
player.userId.equals(userIds[2]),
|
|
);
|
|
|
|
expect(firstPlayerSnapshot).toMatchObject({
|
|
userId: userIds[2],
|
|
tierHistory,
|
|
});
|
|
});
|
|
|
|
it('rejects bids when the team already has 5 members including captain', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
phase: 'bidding',
|
|
teams: [createFullTeam(1), createFullTeam(2)],
|
|
currentBid: 10,
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.placeBid({
|
|
matchId,
|
|
teamIndex: 1,
|
|
amount: 20,
|
|
}),
|
|
).rejects.toThrow('Team already has maximum members.');
|
|
expect(auction.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('rejects bids that do not reserve minimum points for remaining team slots', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'bidding',
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: new mongoose.Types.ObjectId(),
|
|
points: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
currentBid: 100,
|
|
currentDeadline: new Date(),
|
|
maxTimerSeconds: 30,
|
|
bidExtensionSeconds: 5,
|
|
bids: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await expect(
|
|
service.placeBid({
|
|
matchId,
|
|
teamIndex: 1,
|
|
amount: 980,
|
|
}),
|
|
).rejects.toThrow('Bid must reserve minimum points for remaining slots.');
|
|
expect(auction.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('allows bids up to the maximum after reserving minimum points', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'bidding',
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId,
|
|
points: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
currentBid: 100,
|
|
currentDeadline: new Date(),
|
|
maxTimerSeconds: 30,
|
|
bidExtensionSeconds: 5,
|
|
bids: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await service.placeBid({
|
|
matchId,
|
|
teamIndex: 1,
|
|
amount: 970,
|
|
});
|
|
|
|
expect(auction.currentBid).toBe(970);
|
|
expect(auction).toHaveProperty('currentBidderTeamIndex', 1);
|
|
expect(auction.bids).toEqual([
|
|
expect.objectContaining({
|
|
teamIndex: 1,
|
|
amount: 970,
|
|
bidderUserId: captainUserId,
|
|
}),
|
|
]);
|
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('extends a short bid deadline using the configured bid extension seconds', async () => {
|
|
const now = new Date('2026-05-02T00:00:00.000Z');
|
|
jest.useFakeTimers().setSystemTime(now);
|
|
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainUserId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'bidding',
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId,
|
|
points: 1000,
|
|
members: [],
|
|
},
|
|
],
|
|
currentBid: 10,
|
|
currentDeadline: new Date(now.getTime() + 2000),
|
|
maxTimerSeconds: 30,
|
|
bidExtensionSeconds: 12,
|
|
bids: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await service.placeBid({
|
|
matchId,
|
|
teamIndex: 1,
|
|
amount: 20,
|
|
});
|
|
|
|
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
|
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('rejects sold confirmation when the winning team is already full', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
phase: 'bidding',
|
|
currentBidderTeamIndex: 1,
|
|
currentBid: 20,
|
|
currentIndex: 0,
|
|
order: [
|
|
{
|
|
userId: new mongoose.Types.ObjectId(),
|
|
preferredPositions: [{ position: 'ADC', priority: 1 }],
|
|
},
|
|
],
|
|
teams: [createFullTeam(1), createFullTeam(2)],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await expect(service.markSold({ matchId })).rejects.toThrow(
|
|
'Team already has maximum members.',
|
|
);
|
|
expect(auction.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('marks a zero-bid player as passed and queues them for another round', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const playerId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'bidding',
|
|
currentBid: 0,
|
|
currentIndex: 0,
|
|
auctionRound: 1,
|
|
order: [
|
|
{
|
|
userId: playerId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
passCount: 0,
|
|
},
|
|
],
|
|
passedQueue: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await service.markPassed(matchId);
|
|
|
|
expect(auction.phase).toBe('passed');
|
|
expect(auction.order[0].passCount).toBe(1);
|
|
expect(auction.passedQueue).toHaveLength(1);
|
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('queues zero-bid passes after the first auction round', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const playerId = new mongoose.Types.ObjectId();
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'bidding',
|
|
currentBid: 0,
|
|
currentIndex: 0,
|
|
auctionRound: 2,
|
|
order: [
|
|
{
|
|
userId: playerId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
passCount: 1,
|
|
},
|
|
],
|
|
passedQueue: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await service.markPassed(matchId);
|
|
|
|
expect(auction.phase).toBe('passed');
|
|
expect(auction.order[0].passCount).toBe(2);
|
|
expect(auction.passedQueue).toHaveLength(1);
|
|
expect(auction.passedQueue[0]).toMatchObject({
|
|
userId: playerId.toString(),
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
passCount: 2,
|
|
});
|
|
});
|
|
|
|
it('requeues second-pass players instead of force-assigning them', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const captainOneId = new mongoose.Types.ObjectId();
|
|
const captainTwoId = new mongoose.Types.ObjectId();
|
|
const passedPlayerId = new mongoose.Types.ObjectId();
|
|
const passedPlayer = {
|
|
userId: passedPlayerId,
|
|
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
|
passCount: 2,
|
|
};
|
|
const auction = {
|
|
_id: new mongoose.Types.ObjectId(),
|
|
matchId,
|
|
phase: 'passed',
|
|
currentIndex: 0,
|
|
auctionRound: 2,
|
|
order: [passedPlayer],
|
|
passedQueue: [passedPlayer],
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: captainOneId,
|
|
points: 10,
|
|
members: [],
|
|
},
|
|
{
|
|
teamIndex: 2,
|
|
captainUserId: captainTwoId,
|
|
points: 50,
|
|
members: [],
|
|
},
|
|
],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
toObject: jest.fn().mockReturnValue({ _id: 'auction', matchId }),
|
|
};
|
|
const { service } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
});
|
|
|
|
await service.next(matchId);
|
|
|
|
expect(auction.phase).toBe('presenting');
|
|
expect(auction.auctionRound).toBe(3);
|
|
expect(auction.currentIndex).toBe(1);
|
|
expect(auction.order).toHaveLength(2);
|
|
expect(auction.order[1]).toMatchObject({
|
|
userId: passedPlayerId.toString(),
|
|
preferredPositions: [{ position: 'SUP', priority: 1 }],
|
|
passCount: 2,
|
|
});
|
|
expect(auction.passedQueue).toEqual([]);
|
|
expect(auction.teams[0].members).toEqual([]);
|
|
expect(auction.teams[1].members).toEqual([]);
|
|
expect(auction.teams[0].points).toBe(10);
|
|
expect(auction.teams[1].points).toBe(50);
|
|
});
|
|
|
|
it('syncs completed auction teams into the match document', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const blueCaptainId = new mongoose.Types.ObjectId();
|
|
const redCaptainId = new mongoose.Types.ObjectId();
|
|
const blueMemberId = new mongoose.Types.ObjectId();
|
|
const redMemberId = new mongoose.Types.ObjectId();
|
|
|
|
const auction = {
|
|
matchId,
|
|
phase: 'sold',
|
|
currentIndex: 1,
|
|
order: [{ userId: blueMemberId }, { userId: redMemberId }],
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
captainUserId: blueCaptainId,
|
|
points: 970,
|
|
members: [
|
|
{
|
|
userId: blueMemberId,
|
|
assignedPosition: 'ADC',
|
|
cost: 30,
|
|
},
|
|
],
|
|
},
|
|
{
|
|
teamIndex: 2,
|
|
captainUserId: redCaptainId,
|
|
points: 940,
|
|
members: [
|
|
{
|
|
userId: redMemberId,
|
|
assignedPosition: 'JGL',
|
|
cost: 60,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const match = {
|
|
participants: [
|
|
{
|
|
userId: blueCaptainId,
|
|
preferredPositions: [{ position: 'TOP', priority: 1 }],
|
|
},
|
|
{
|
|
userId: redCaptainId,
|
|
preferredPositions: [{ position: 'MID', priority: 1 }],
|
|
},
|
|
{
|
|
userId: blueMemberId,
|
|
preferredPositions: [{ position: 'ADC', priority: 1 }],
|
|
},
|
|
{
|
|
userId: redMemberId,
|
|
preferredPositions: [{ position: 'JGL', priority: 1 }],
|
|
},
|
|
],
|
|
status: 'team-built',
|
|
teams: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const { service, tournamentCodeService, tournamentResultService } =
|
|
createService({
|
|
auction: {
|
|
findOne: jest.fn().mockResolvedValue(auction),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockResolvedValue(match),
|
|
},
|
|
});
|
|
tournamentCodeService.reserveForMatch.mockImplementation((candidate) => {
|
|
expect(candidate.teamBuiltAt).toBeUndefined();
|
|
return Promise.resolve(candidate);
|
|
});
|
|
|
|
await service.next(matchId);
|
|
|
|
expect(auction.phase).toBe('complete');
|
|
expect(auction).toHaveProperty('completedAt', expect.any(Date));
|
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
|
expect(match.save).toHaveBeenCalledTimes(2);
|
|
expect(match.teams).toEqual([
|
|
{
|
|
teamIndex: 1,
|
|
name: '1팀',
|
|
captainUserId: blueCaptainId,
|
|
members: [
|
|
{
|
|
userId: blueCaptainId,
|
|
assignedPosition: 'TOP',
|
|
cost: 0,
|
|
},
|
|
{
|
|
userId: blueMemberId,
|
|
assignedPosition: 'ADC',
|
|
cost: 30,
|
|
},
|
|
],
|
|
},
|
|
{
|
|
teamIndex: 2,
|
|
name: '2팀',
|
|
captainUserId: redCaptainId,
|
|
members: [
|
|
{
|
|
userId: redCaptainId,
|
|
assignedPosition: 'MID',
|
|
cost: 0,
|
|
},
|
|
{
|
|
userId: redMemberId,
|
|
assignedPosition: 'JGL',
|
|
cost: 60,
|
|
},
|
|
],
|
|
},
|
|
]);
|
|
expect(tournamentCodeService.reserveForMatch).toHaveBeenCalledWith(match);
|
|
expect(tournamentResultService.scheduleInitialPoll).toHaveBeenCalledWith(
|
|
match,
|
|
);
|
|
});
|
|
|
|
it('clears match teams when resetting an auction', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auction = {
|
|
deleteOne: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const match = {
|
|
communityId,
|
|
status: 'team-built',
|
|
teams: [
|
|
{
|
|
teamIndex: 1,
|
|
name: '1팀',
|
|
members: [],
|
|
},
|
|
],
|
|
tournamentCodeIds: [new mongoose.Types.ObjectId()],
|
|
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
|
|
participants: [],
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auctionFindOneQuery = {
|
|
session: jest.fn().mockResolvedValue(auction),
|
|
};
|
|
const matchFindByIdQuery = {
|
|
session: jest.fn().mockResolvedValue(match),
|
|
};
|
|
const { service, connectionService } = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
|
},
|
|
});
|
|
connectionService.createSession.mockResolvedValue(session);
|
|
|
|
await service.reset({ matchId, communityId });
|
|
|
|
expect(match.status).toBe('recruiting');
|
|
expect(match.teams).toEqual([]);
|
|
expect(match.tournamentCodeIds).toEqual([]);
|
|
expect(match.gameSchedule).toEqual([]);
|
|
expect(match.save).toHaveBeenCalledWith({ session });
|
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('rejects auction reset after Competition bootstrap', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auction = {
|
|
deleteOne: jest.fn(),
|
|
};
|
|
const match = {
|
|
communityId,
|
|
competitionId: new mongoose.Types.ObjectId(),
|
|
status: 'team-built',
|
|
teams: [{ teamIndex: 1 }],
|
|
tournamentCodeIds: [],
|
|
gameSchedule: [],
|
|
participants: [],
|
|
save: jest.fn(),
|
|
};
|
|
const { service, connectionService, tournamentCodeService } = createService(
|
|
{
|
|
auction: {
|
|
findOne: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(auction),
|
|
}),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(match),
|
|
}),
|
|
},
|
|
},
|
|
);
|
|
connectionService.createSession.mockResolvedValue(session);
|
|
|
|
await expect(service.reset({ matchId, communityId })).rejects.toThrow(
|
|
'immutable Competition',
|
|
);
|
|
|
|
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
|
expect(session.commitTransaction).not.toHaveBeenCalled();
|
|
expect(auction.deleteOne).not.toHaveBeenCalled();
|
|
expect(tournamentCodeService.releaseFromMatch).not.toHaveBeenCalled();
|
|
expect(match.save).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('fully deletes redis-v1 auction data when cancelling an auction', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const auctionId = new mongoose.Types.ObjectId();
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auction = {
|
|
_id: auctionId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: 'life-1',
|
|
matchId,
|
|
matchSideEffectRevision: 0,
|
|
deleteOne: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const match = {
|
|
gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }],
|
|
communityId,
|
|
status: 'team-built',
|
|
teams: [{ teamIndex: 1 }],
|
|
tournamentCodeIds: [new mongoose.Types.ObjectId()],
|
|
participants: [{ excluded: true }, { excluded: false }],
|
|
result: { games: [] },
|
|
resultPollState: { state: 'polling' },
|
|
teamBuiltAt: new Date(),
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const sideEffectDeleteMany = jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(undefined),
|
|
});
|
|
const {
|
|
service,
|
|
connectionService,
|
|
tournamentCodeService,
|
|
tournamentResultService,
|
|
auctionHistoryModel,
|
|
auctionRedisCommandService,
|
|
auctionRedisService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(auction),
|
|
}),
|
|
},
|
|
auctionSideEffectApplication: {
|
|
deleteMany: sideEffectDeleteMany,
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(match),
|
|
}),
|
|
},
|
|
});
|
|
connectionService.createSession.mockResolvedValue(session);
|
|
const redisClient = auctionRedisService.raw();
|
|
redisClient.sendCommand
|
|
.mockResolvedValueOnce(1)
|
|
.mockResolvedValueOnce(['0', []]);
|
|
|
|
await service.reset({
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000080',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedCurrentBidRoundPlayerUserId: 'player-1',
|
|
clientObservedPhase: 'bidding',
|
|
clientObservedRevision: 4,
|
|
matchId,
|
|
communityId,
|
|
});
|
|
|
|
expect(
|
|
auctionRedisCommandService.reserveActionRequest,
|
|
).not.toHaveBeenCalled();
|
|
expect(auctionRedisCommandService.applyTransition).not.toHaveBeenCalled();
|
|
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(
|
|
match,
|
|
session,
|
|
);
|
|
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(
|
|
match,
|
|
session,
|
|
);
|
|
expect(match).toMatchObject({
|
|
gameSchedule: [],
|
|
result: undefined,
|
|
resultPollState: undefined,
|
|
status: 'recruiting',
|
|
teamBuiltAt: undefined,
|
|
teams: [],
|
|
tournamentCodeIds: [],
|
|
});
|
|
expect(match.participants).toEqual([
|
|
{ excluded: false },
|
|
{ excluded: false },
|
|
]);
|
|
expect(match.save).toHaveBeenCalledWith({ session });
|
|
expect(sideEffectDeleteMany).toHaveBeenCalledWith({ auctionId });
|
|
expect(auctionHistoryModel.deleteMany).toHaveBeenCalledWith({
|
|
auctionId,
|
|
});
|
|
expect(auction.deleteOne).toHaveBeenCalledWith({ session });
|
|
expect(redisClient.sendCommand).not.toHaveBeenCalled();
|
|
expect(match).toMatchObject({
|
|
lastCancelledAuctionLifecycleId: 'life-1',
|
|
auctionCancellationCleanupPending: true,
|
|
auctionCancellationCleanupRetryAt: expect.any(Date),
|
|
});
|
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('undoes to a history snapshot and releases resources when leaving complete', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const auctionId = new mongoose.Types.ObjectId();
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auction = {
|
|
_id: auctionId,
|
|
matchId,
|
|
completedAt: new Date(),
|
|
};
|
|
const snapshot = {
|
|
_id: auctionId.toString(),
|
|
matchId: matchId.toString(),
|
|
phase: 'bidding',
|
|
order: [],
|
|
teams: [],
|
|
};
|
|
const restored = { _id: auctionId, phase: 'bidding' };
|
|
const match = {
|
|
communityId,
|
|
status: 'finished',
|
|
result: { games: [] },
|
|
save: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auctionFindOneQuery = {
|
|
session: jest.fn().mockResolvedValue(auction),
|
|
};
|
|
const matchFindByIdQuery = {
|
|
session: jest.fn().mockResolvedValue(match),
|
|
};
|
|
const historyFindOneQuery = {
|
|
session: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
auctionId,
|
|
matchId,
|
|
sequence: 3,
|
|
snapshotBefore: snapshot,
|
|
}),
|
|
}),
|
|
}),
|
|
};
|
|
const historyDeleteManyQuery = {
|
|
session: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue(undefined),
|
|
}),
|
|
};
|
|
const auctionReplaceOne = jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue(undefined),
|
|
});
|
|
const {
|
|
service,
|
|
connectionService,
|
|
tournamentCodeService,
|
|
tournamentResultService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockReturnValue(auctionFindOneQuery),
|
|
replaceOne: auctionReplaceOne,
|
|
findById: jest.fn().mockResolvedValue(restored),
|
|
},
|
|
auctionHistory: {
|
|
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
|
deleteMany: jest.fn().mockReturnValue(historyDeleteManyQuery),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue(matchFindByIdQuery),
|
|
},
|
|
});
|
|
connectionService.createSession.mockResolvedValue(session);
|
|
|
|
await expect(
|
|
service.undoTo({ matchId, communityId, sequence: 3 }),
|
|
).resolves.toBe(restored);
|
|
|
|
expect(tournamentCodeService.releaseFromMatch).toHaveBeenCalledWith(
|
|
match,
|
|
session,
|
|
);
|
|
expect(tournamentResultService.cancelPolling).toHaveBeenCalledWith(
|
|
match,
|
|
session,
|
|
);
|
|
expect(match.status).toBe('team-built');
|
|
expect(match.result).toBeUndefined();
|
|
expect(auctionReplaceOne).toHaveBeenCalledWith(
|
|
{ _id: auctionId },
|
|
snapshot,
|
|
{ session },
|
|
);
|
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('uses Redis transition when undoing a redis-v1 auction', async () => {
|
|
const matchId = new mongoose.Types.ObjectId();
|
|
const communityId = new mongoose.Types.ObjectId();
|
|
const auctionId = new mongoose.Types.ObjectId();
|
|
const session = {
|
|
startTransaction: jest.fn(),
|
|
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
|
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
|
endSession: jest.fn().mockResolvedValue(undefined),
|
|
};
|
|
const auction = {
|
|
_id: auctionId,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: 'life-1',
|
|
completedAt: new Date(),
|
|
matchId,
|
|
matchSideEffectRevision: 0,
|
|
};
|
|
const snapshot = {
|
|
_id: auctionId.toString(),
|
|
auctionLifecycleId: 'life-1',
|
|
auctionPlayerOrder: [{ userId: 'player-1', passCount: 0 }],
|
|
auctionTeams: [],
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 3,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
initialTeamBidPointAmount: 1000,
|
|
matchId: matchId.toString(),
|
|
maximumBidRoundDurationSeconds: 30,
|
|
passedAuctionPlayerQueue: [],
|
|
phase: 'bidding',
|
|
revision: 4,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const match = {
|
|
communityId,
|
|
};
|
|
const currentRedisState = {
|
|
auctionLifecycleId: 'life-1',
|
|
auctionPlayerOrder: [{ userId: 'player-2', passCount: 0 }],
|
|
auctionTeams: [],
|
|
bidRoundExtensionSeconds: 5,
|
|
currentAuctionHistorySequence: 5,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
currentBidRoundPlayerUserId: 'player-2',
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
initialTeamBidPointAmount: 1000,
|
|
maximumBidRoundDurationSeconds: 30,
|
|
passedAuctionPlayerQueue: [],
|
|
phase: 'complete',
|
|
revision: 5,
|
|
topTierAuctionPriorityThreshold: 'NONE',
|
|
};
|
|
const restoredRedisState = {
|
|
...snapshot,
|
|
currentServerTimestampMS: 1780000000000,
|
|
phase: 'bidding',
|
|
revision: 6,
|
|
};
|
|
const historyFindOneQuery = {
|
|
session: jest.fn().mockReturnValue({
|
|
lean: jest.fn().mockReturnValue({
|
|
exec: jest.fn().mockResolvedValue({
|
|
auctionId,
|
|
matchId,
|
|
sequence: 3,
|
|
snapshotBefore: snapshot,
|
|
}),
|
|
}),
|
|
}),
|
|
};
|
|
const auctionReplaceOne = jest.fn();
|
|
const {
|
|
service,
|
|
connectionService,
|
|
auctionRedisCommandService,
|
|
auctionRedisStateReaderService,
|
|
} = createService({
|
|
auction: {
|
|
findOne: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(auction),
|
|
}),
|
|
replaceOne: auctionReplaceOne,
|
|
},
|
|
auctionHistory: {
|
|
findOne: jest.fn().mockReturnValue(historyFindOneQuery),
|
|
},
|
|
match: {
|
|
findById: jest.fn().mockReturnValue({
|
|
session: jest.fn().mockResolvedValue(match),
|
|
}),
|
|
},
|
|
});
|
|
connectionService.createSession.mockResolvedValue(session);
|
|
auctionRedisStateReaderService.readAuctionStateView
|
|
.mockResolvedValueOnce(currentRedisState)
|
|
.mockResolvedValueOnce(restoredRedisState);
|
|
|
|
await expect(
|
|
service.undoTo({
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedCurrentBidRoundPlayerUserId: 'player-2',
|
|
clientObservedPhase: 'complete',
|
|
clientObservedRevision: 5,
|
|
matchId,
|
|
communityId,
|
|
sequence: 3,
|
|
}),
|
|
).resolves.toBe(restoredRedisState);
|
|
|
|
expect(auctionReplaceOne).not.toHaveBeenCalled();
|
|
expect(
|
|
auctionRedisCommandService.reserveActionRequest,
|
|
).toHaveBeenCalledWith(
|
|
matchId.toString(),
|
|
expect.objectContaining({
|
|
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
|
|
auctionStateTransitionId:
|
|
'undo:life-1:00000000-0000-4000-8000-000000000070',
|
|
clientObservedAuctionLifecycleId: 'life-1',
|
|
clientObservedCurrentAuctionPlayerOrderIndex: 0,
|
|
clientObservedCurrentBidRoundPlayerUserId: 'player-2',
|
|
clientObservedPhase: 'complete',
|
|
clientObservedRevision: 5,
|
|
}),
|
|
);
|
|
expect(auctionRedisCommandService.applyTransition).toHaveBeenCalledTimes(1);
|
|
const transitionInput =
|
|
auctionRedisCommandService.applyTransition.mock.calls[0][1];
|
|
expect(transitionInput.expectedPhase).toBe('complete');
|
|
expect(transitionInput.deadline).toEqual({
|
|
durationSeconds: 30,
|
|
mode: 'set-relative',
|
|
});
|
|
const durabilityPayload = parseJsonRecord(
|
|
transitionInput.durabilityPayloadJson,
|
|
'durabilityPayloadJson',
|
|
);
|
|
expect(durabilityPayload).toMatchObject({
|
|
auctionActionType: 'undo',
|
|
historyMutation: {
|
|
targetHistorySequence: 3,
|
|
type: 'deleteAfterSequenceAndAppendUndo',
|
|
},
|
|
matchSideEffectMutation: {
|
|
type: 'undoCompletedAuctionSideEffects',
|
|
},
|
|
});
|
|
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|