fix: prevent empty-team auction completion state

This commit is contained in:
dahyeon committed 2026-06-25 05:26:09 -07:00
1 parent 2984bd1604
commit ab721873f3
6 files changed
+748 -452

No files matched your search

@@ -92,7 +92,10 @@ describe('auction durability projection helpers', () => {
it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: false },
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
{
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
])('decides whether projection can apply %#', ({ current, expected }) => {
expect(shouldApplyAuctionProjection(current, payload)).toBe(expected);
});
@@ -100,14 +103,23 @@ describe('auction durability projection helpers', () => {
it.each([
{ current: { auctionLifecycleId: 'life-1', revision: 8 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 9 }, expected: true },
{ current: { auctionLifecycleId: 'life-1', revision: 10 }, expected: false },
{ current: { auctionLifecycleId: 'new-life', revision: 1 }, expected: false },
{
current: { auctionLifecycleId: 'life-1', revision: 10 },
expected: false,
},
{
current: { auctionLifecycleId: 'new-life', revision: 1 },
expected: false,
},
{ current: {}, expected: false },
])('decides whether a durability payload can be processed %#', ({ current, expected }) => {
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
expected,
);
});
])(
'decides whether a durability payload can be processed %#',
({ current, expected }) => {
expect(shouldProcessAuctionDurabilityPayload(current, payload)).toBe(
expected,
);
},
);
it('reads due durability payload keys from Redis', async () => {
const sendCommand = jest.fn().mockResolvedValue(['payload-1']);
@@ -333,7 +345,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -404,7 +419,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(session),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return { findById: auctionFindById, updateOne: auctionUpdateOne };
@@ -613,7 +631,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = (
scheduler as unknown as {
@@ -649,7 +669,9 @@ describe('auction durability projection helpers', () => {
.spyOn(scheduler, 'processDueDurabilityPayloads')
.mockResolvedValue({ applied: 0, failed: 0, skipped: 0 });
await (scheduler as unknown as { safeTick: () => Promise<void> }).safeTick();
await (
scheduler as unknown as { safeTick: () => Promise<void> }
).safeTick();
const auctionRedisService = (
scheduler as unknown as {
@@ -747,7 +769,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
@@ -829,26 +852,18 @@ describe('auction durability projection helpers', () => {
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
});
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
1,
'match-1',
{
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 2000,
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
},
);
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(
2,
'match-1',
{
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 3000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
},
);
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(1, 'match-1', {
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 2000,
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
});
expect(broadcastMatchSideEffect).toHaveBeenNthCalledWith(2, 'match-1', {
auctionLifecycleId: 'life-1',
currentServerTimestampMS: 3000,
matchSideEffectRevision: 3,
matchSideEffectStatus: 'completed',
});
expect(sendCommand).toHaveBeenCalledWith([
'EVAL',
expect.stringContaining("redis.call('EXPIRE'"),
@@ -870,6 +885,101 @@ describe('auction durability projection helpers', () => {
]);
});
it('fails sync match teams side effect when the completed projection has no teams', async () => {
const completePayload = {
...payload,
afterAuctionMongoProjection: {
auctionTeams: [],
matchSideEffectRevision: 1,
phase: 'complete',
revision: 10,
},
auctionActionType: 'complete',
matchSideEffectMutation: { type: 'syncMatchTeamsAfterComplete' },
revision: 10,
} as const;
const match = {
participants: [],
save: jest.fn().mockResolvedValue(undefined),
status: 'team-built',
teamBuiltAt: undefined,
teams: [],
};
const historyUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
});
const auctionUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ modifiedCount: 1 }),
});
const auctionFindOneAndUpdate = jest
.fn()
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 2,
matchSideEffectStatus: 'processing',
}),
})
.mockReturnValueOnce({
exec: jest.fn().mockResolvedValue({
auctionLifecycleId: 'life-1',
matchSideEffectRevision: 3,
matchSideEffectStatus: 'failed',
}),
});
const sideEffectUpdateOne = jest.fn().mockReturnValue({
exec: jest.fn().mockResolvedValue({ matchedCount: 1, modifiedCount: 1 }),
});
const reserveForMatch = jest.fn().mockResolvedValue(match);
const scheduleInitialPoll = jest.fn().mockResolvedValue(null);
const mirrorMatchSideEffectStatus = jest.fn().mockResolvedValue(true);
const broadcastMatchSideEffect = jest.fn();
const scheduler = new AuctionDurabilityScheduler(
{
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') return { updateOne: historyUpdateOne };
if (name === 'auction') {
return {
findOneAndUpdate: auctionFindOneAndUpdate,
updateOne: auctionUpdateOne,
};
}
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
{
getCurrentRedisTimestampMS: jest
.fn()
.mockResolvedValueOnce(2000)
.mockResolvedValueOnce(3000),
raw: jest.fn().mockReturnValue({ sendCommand: jest.fn() }),
} as never,
{ reserveForMatch } as never,
{ scheduleInitialPoll } as never,
{ mirrorMatchSideEffectStatus } as never,
{ broadcastMatchSideEffect } as never,
);
await expect(
scheduler.applyDurabilityPayload(completePayload),
).rejects.toThrow('produced no match teams');
expect(match.save).not.toHaveBeenCalled();
expect(reserveForMatch).not.toHaveBeenCalled();
expect(scheduleInitialPoll).not.toHaveBeenCalled();
expect(mirrorMatchSideEffectStatus).toHaveBeenLastCalledWith(
expect.objectContaining({
matchSideEffectStatus: 'failed',
}),
);
});
it('applies reset match side effect after durable projection', async () => {
const resetPayload = {
...payload,
@@ -943,7 +1053,10 @@ describe('auction durability projection helpers', () => {
createSession: jest.fn().mockResolvedValue(null),
getModel: jest.fn((name: string) => {
if (name === 'auctionHistory') {
return { deleteMany: historyDeleteMany, updateOne: historyUpdateOne };
return {
deleteMany: historyDeleteMany,
updateOne: historyUpdateOne,
};
}
if (name === 'auction') {
return {
@@ -955,7 +1068,8 @@ describe('auction durability projection helpers', () => {
if (name === 'auctionSideEffectApplication') {
return { updateOne: sideEffectUpdateOne };
}
if (name === 'match') return { findById: jest.fn().mockReturnValue(match) };
if (name === 'match')
return { findById: jest.fn().mockReturnValue(match) };
return {};
}),
} as never,
@@ -985,7 +1099,10 @@ describe('auction durability projection helpers', () => {
teams: [],
tournamentCodeIds: [],
});
expect(match.participants).toEqual([{ excluded: false }, { excluded: false }]);
expect(match.participants).toEqual([
{ excluded: false },
{ excluded: false },
]);
expect(match.save).toHaveBeenCalledTimes(1);
expect(sideEffectUpdateOne).toHaveBeenCalledWith(
expect.objectContaining({
@@ -128,15 +128,17 @@ export class AuctionDurabilityScheduler
currentRedisTimestampMS: number,
batchLimit: number,
): Promise<string[]> {
const reply = await this.auctionRedisService.raw().sendCommand([
'ZRANGEBYSCORE',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'ZRANGEBYSCORE',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
'-inf',
String(currentRedisTimestampMS),
'LIMIT',
'0',
String(batchLimit),
]);
return Array.isArray(reply) ? reply.map(String) : [];
}
@@ -168,12 +170,11 @@ export class AuctionDurabilityScheduler
await this.clearDurabilityPayload(payloadKey);
} catch (error) {
failed += 1;
const failureDisposition =
await this.recordDurabilityPayloadFailure(
payloadKey,
currentRedisTimestampMS,
error,
);
const failureDisposition = await this.recordDurabilityPayloadFailure(
payloadKey,
currentRedisTimestampMS,
error,
);
this.logger.warn(
`Auction durability payload failed for ${payloadKey} (${failureDisposition}): ${
error instanceof Error ? error.message : error
@@ -195,7 +196,9 @@ export class AuctionDurabilityScheduler
const payloadJson = hash.payloadJson;
if (!payloadJson) return null;
const payload = JSON.parse(payloadJson) as AuctionDurabilityPayload;
const committedAtRedisTimestampMS = Number(hash.committedAtRedisTimestampMS);
const committedAtRedisTimestampMS = Number(
hash.committedAtRedisTimestampMS,
);
if (Number.isFinite(committedAtRedisTimestampMS)) {
payload.committedAtRedisTimestampMS = committedAtRedisTimestampMS;
}
@@ -223,12 +226,15 @@ export class AuctionDurabilityScheduler
try {
session?.startTransaction();
if (typeof AuctionModel.findById === 'function') {
const currentProjection = await readAuctionProjectionIdentityForMutation(
AuctionModel,
payload.auctionId,
session,
);
if (!shouldProcessAuctionDurabilityPayload(currentProjection, payload)) {
const currentProjection =
await readAuctionProjectionIdentityForMutation(
AuctionModel,
payload.auctionId,
session,
);
if (
!shouldProcessAuctionDurabilityPayload(currentProjection, payload)
) {
if (session) await session.commitTransaction();
return;
}
@@ -370,15 +376,17 @@ export class AuctionDurabilityScheduler
);
if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload,
status: 'processing',
});
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
{
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload,
status: 'processing',
},
);
if (!processingDelta) return;
let expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision;
@@ -396,11 +404,18 @@ export class AuctionDurabilityScheduler
teamBuiltAt?: Date;
teams: ReturnType<typeof buildMatchTeamsFromProjection>;
} | null;
if (!match) throw new Error(`Match not found: ${String(payload.matchId)}`);
match.teams = buildMatchTeamsFromProjection(
if (!match)
throw new Error(`Match not found: ${String(payload.matchId)}`);
const matchTeams = buildMatchTeamsFromProjection(
payload.afterAuctionMongoProjection,
match,
);
if (matchTeams.length === 0) {
throw new Error(
`Auction complete side effect produced no match teams for match ${String(payload.matchId)}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
@@ -553,15 +568,18 @@ export class AuctionDurabilityScheduler
);
if (!hasMatchedDocument(leaseResult)) return;
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus({
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ?? 0,
),
payload: params.payload,
status: 'processing',
});
const processingDelta = await this.persistAndBroadcastMatchSideEffectStatus(
{
AuctionModel,
currentServerTimestampMS: currentRedisTimestampMS,
expectedMatchSideEffectRevision: Number(
params.payload.afterAuctionMongoProjection.matchSideEffectRevision ??
0,
),
payload: params.payload,
status: 'processing',
},
);
if (!processingDelta) return;
let expectedMatchSideEffectRevision =
processingDelta.matchSideEffectRevision;
@@ -605,7 +623,8 @@ export class AuctionDurabilityScheduler
} catch (error) {
const failureTimestampMS =
await this.auctionRedisService.getCurrentRedisTimestampMS();
const errorMessage = error instanceof Error ? error.message : String(error);
const errorMessage =
error instanceof Error ? error.message : String(error);
await execMaybe(
AuctionSideEffectApplicationModel.updateOne(
identity as never,
@@ -658,7 +677,9 @@ export class AuctionDurabilityScheduler
payload: AuctionDurabilityPayload;
session: mongoose.ClientSession | null | undefined;
}): Promise<void> {
const mutation = parseAuctionHistoryMutation(params.payload.historyMutation);
const mutation = parseAuctionHistoryMutation(
params.payload.historyMutation,
);
if (isDestructiveHistoryMutation(mutation)) {
if (mutation.type === 'deleteAfterSequenceAndAppendUndo') {
if (!params.AuctionHistoryModel.deleteMany) {
@@ -689,7 +710,9 @@ export class AuctionDurabilityScheduler
}
}
const historyOperation = buildAuctionHistoryUpsert(params.payload).updateOne;
const historyOperation = buildAuctionHistoryUpsert(
params.payload,
).updateOne;
await execMaybe(
params.AuctionHistoryModel.updateOne(
historyOperation.filter as never,
@@ -731,7 +754,9 @@ export class AuctionDurabilityScheduler
: {}),
matchSideEffectStatus: params.status,
},
...(params.errorMessage ? {} : { $unset: { matchSideEffectError: '' } }),
...(params.errorMessage
? {}
: { $unset: { matchSideEffectError: '' } }),
} as never,
{
projection: {
@@ -742,13 +767,11 @@ export class AuctionDurabilityScheduler
returnDocument: 'after',
} as never,
),
)) as
| {
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
}
| null;
)) as {
auctionLifecycleId?: string;
matchSideEffectRevision?: number;
matchSideEffectStatus?: AuctionMatchSideEffectStatus;
} | null;
if (!updatedAuction?.auctionLifecycleId) return null;
const delta = buildMatchSideEffectDelta({
@@ -815,12 +838,14 @@ export class AuctionDurabilityScheduler
payloadKey: string,
retryAtRedisTimestampMS: number,
): Promise<void> {
await this.auctionRedisService.raw().sendCommand([
'ZADD',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
String(retryAtRedisTimestampMS),
payloadKey,
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZADD',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
String(retryAtRedisTimestampMS),
payloadKey,
]);
}
private async recordDurabilityPayloadFailure(
@@ -829,43 +854,44 @@ export class AuctionDurabilityScheduler
error: unknown,
): Promise<'dead-lettered' | 'requeued'> {
const errorMessage = formatErrorMessageForRedis(error);
const attemptReply = await this.auctionRedisService.raw().sendCommand([
'HINCRBY',
payloadKey,
'attempts',
'1',
]);
const attemptReply = await this.auctionRedisService
.raw()
.sendCommand(['HINCRBY', payloadKey, 'attempts', '1']);
const attempts = Number(attemptReply);
await this.auctionRedisService.raw().sendCommand([
'HSET',
payloadKey,
'lastError',
errorMessage,
'lastFailedAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'HSET',
payloadKey,
'lastError',
errorMessage,
'lastFailedAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
if (
Number.isFinite(attempts) &&
attempts >= AUCTION_DURABILITY_MAX_ATTEMPTS
) {
await this.auctionRedisService.raw().sendCommand([
'ZREM',
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
payloadKey,
]);
await this.auctionRedisService.raw().sendCommand([
'HSET',
payloadKey,
'deadLetteredAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService.raw().sendCommand([
'ZADD',
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
String(currentRedisTimestampMS),
payloadKey,
]);
await this.auctionRedisService
.raw()
.sendCommand(['ZREM', AUCTION_DURABILITY_RETRY_QUEUE_KEY, payloadKey]);
await this.auctionRedisService
.raw()
.sendCommand([
'HSET',
payloadKey,
'deadLetteredAtRedisTimestampMS',
String(currentRedisTimestampMS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZADD',
AUCTION_DURABILITY_DEAD_LETTER_QUEUE_KEY,
String(currentRedisTimestampMS),
payloadKey,
]);
return 'dead-lettered';
}
@@ -881,38 +907,40 @@ export class AuctionDurabilityScheduler
): Promise<void> {
const matchId = String(payload.matchId);
const keys = buildAuctionRedisKeys(matchId);
await this.auctionRedisService.raw().sendCommand([
'EVAL',
[
"local expectedAuctionLifecycleId = ARGV[2]",
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
"if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
' return 0',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
'for index = 1, #KEYS do',
' if index ~= 2 then',
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
' end',
'end',
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
payload.auctionLifecycleId,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
]);
await this.auctionRedisService
.raw()
.sendCommand([
'EVAL',
[
'local expectedAuctionLifecycleId = ARGV[2]',
"local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
'if currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
' return 0',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
'for index = 1, #KEYS do',
' if index ~= 2 then',
" redis.call('EXPIRE', KEYS[index], ARGV[3])",
' end',
'end',
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
payload.auctionLifecycleId,
String(AUCTION_REDIS_COMPLETED_RETAIN_SECONDS),
]);
}
}
@@ -961,7 +989,9 @@ export function parseAuctionHistoryMutation(
}
if (record.type === 'reset') {
const resetMode =
record.resetMode === 'preserve-audit' ? 'preserve-audit' : 'clear-history';
record.resetMode === 'preserve-audit'
? 'preserve-audit'
: 'clear-history';
return { resetMode, type: 'reset' };
}
return { type: 'append' };
@@ -1055,7 +1085,10 @@ export function buildSideEffectApplicationUpsert(
payload: AuctionDurabilityPayload,
mutation: ParsedMatchSideEffectMutation,
) {
const identity = buildSideEffectApplicationIdentityFromPayload(payload, mutation);
const identity = buildSideEffectApplicationIdentityFromPayload(
payload,
mutation,
);
return {
filter: identity,
update: {
@@ -1100,7 +1133,12 @@ function buildSideEffectApplicationIdentityFromPayload(
function hashStableJson(value: unknown): string {
return createHash('sha256')
.update(JSON.stringify(value, Object.keys(value as Record<string, unknown>).sort()))
.update(
JSON.stringify(
value,
Object.keys(value as Record<string, unknown>).sort(),
),
)
.digest('hex');
}
@@ -1140,13 +1178,16 @@ function buildMatchTeamsFromProjection(
const members: MatchTeamMember[] = [
{
assignedPosition:
(captain?.preferredPositions?.[0]?.position as Position | undefined) ??
'MID',
(captain?.preferredPositions?.[0]?.position as
| Position
| undefined) ?? 'MID',
cost: 0,
userId: captainUserId,
},
...rawMembers
.filter((member) => member.userId?.toString() !== captainUserId.toString())
.filter(
(member) => member.userId?.toString() !== captainUserId.toString(),
)
.map((member) => ({
assignedPosition: (member.assignedPosition ?? 'MID') as Position,
cost: Number(member.memberAcquisitionBidPointAmount ?? 0),
@@ -1198,7 +1239,9 @@ function calculateDurabilityRetryDelayMS(attempts: number): number {
);
}
async function execMaybe<T>(queryOrPromise: Promise<T> | { exec(): Promise<T> }) {
async function execMaybe<T>(
queryOrPromise: Promise<T> | { exec(): Promise<T> },
) {
if (
queryOrPromise &&
typeof (queryOrPromise as { exec?: unknown }).exec === 'function'
@@ -158,11 +158,12 @@ describe('AuctionService', () => {
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, auctionRedisService } = createService({
auction: {
findOne: auctionFindOne,
},
});
const { service, auctionRedisCommandService, auctionRedisService } =
createService({
auction: {
findOne: auctionFindOne,
},
});
await expect(
service.placeBid({
@@ -266,7 +267,7 @@ describe('AuctionService', () => {
});
expect(match.status).toBe('team-built');
expect(match.teamBuiltAt).toBeInstanceOf(Date);
expect(match.teamBuiltAt).toBeUndefined();
expect(match.save).toHaveBeenCalledTimes(1);
expect(tournamentCodeService.reserveForMatch).not.toHaveBeenCalled();
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
@@ -542,44 +543,45 @@ describe('AuctionService', () => {
}));
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({
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(null),
exec: jest.fn().mockResolvedValue({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
}),
}),
}),
}),
},
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,
@@ -800,7 +802,9 @@ describe('AuctionService', () => {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(null);
auctionRedisStateReaderService.readLiveStateIdentity.mockResolvedValue(
null,
);
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
redisState,
);
@@ -870,12 +874,15 @@ describe('AuctionService', () => {
phase: 'bidding',
revision: 2,
};
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(presentingState)
.mockResolvedValueOnce(biddingState);
@@ -973,12 +980,15 @@ describe('AuctionService', () => {
currentHighestBidPointAmount: 120,
revision: 3,
};
const { service, auctionRedisCommandService, auctionRedisStateReaderService } =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
const {
service,
auctionRedisCommandService,
auctionRedisStateReaderService,
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(biddingState)
.mockResolvedValueOnce(afterBidState);
@@ -1189,15 +1199,14 @@ describe('AuctionService', () => {
auctionRedisStateReaderService,
tournamentCodeService,
tournamentResultService,
} =
createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
match: {
findById: jest.fn().mockResolvedValue(match),
},
});
} = createService({
auction: {
findOne: jest.fn().mockResolvedValue(auction),
},
match: {
findById: jest.fn().mockResolvedValue(match),
},
});
auctionRedisStateReaderService.readAuctionStateView
.mockResolvedValueOnce(soldState)
.mockResolvedValueOnce(completeState);
@@ -1377,8 +1386,7 @@ describe('AuctionService', () => {
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(),
(player: { userId: mongoose.Types.ObjectId }) => player.userId.toString(),
);
expect(auctionOrder).not.toEqual(signupOrder);
@@ -1647,9 +1655,7 @@ describe('AuctionService', () => {
amount: 20,
});
expect(auction.currentDeadline).toEqual(
new Date(now.getTime() + 12000),
);
expect(auction.currentDeadline).toEqual(new Date(now.getTime() + 12000));
expect(auction.save).toHaveBeenCalledTimes(1);
});
@@ -2151,21 +2157,25 @@ describe('AuctionService', () => {
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),
},
});
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(
@@ -2261,23 +2271,27 @@ describe('AuctionService', () => {
}),
};
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),
}),
},
});
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)
@@ -2298,7 +2312,9 @@ describe('AuctionService', () => {
).resolves.toBe(restoredRedisState);
expect(auctionReplaceOne).not.toHaveBeenCalled();
expect(auctionRedisCommandService.reserveActionRequest).toHaveBeenCalledWith(
expect(
auctionRedisCommandService.reserveActionRequest,
).toHaveBeenCalledWith(
matchId.toString(),
expect.objectContaining({
auctionActionRequestId: '00000000-0000-4000-8000-000000000070',
@@ -2319,9 +2335,7 @@ describe('AuctionService', () => {
durationSeconds: 30,
mode: 'set-relative',
});
const durabilityPayload = JSON.parse(
transitionInput.durabilityPayloadJson,
);
const durabilityPayload = JSON.parse(transitionInput.durabilityPayloadJson);
expect(durabilityPayload).toMatchObject({
auctionActionType: 'undo',
historyMutation: {
+211 -173
View File
@@ -230,7 +230,9 @@ export class AuctionService {
const activeParticipants = this.applyAuctionCut(match);
const desiredAuctionCount = activeParticipants.length;
if (desiredAuctionCount < 10) {
throw new BadRequestException('Not enough participants (need at least 10).');
throw new BadRequestException(
'Not enough participants (need at least 10).',
);
}
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
if (params.captains.length !== expectedCaptainCount) {
@@ -262,7 +264,8 @@ export class AuctionService {
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
const enrichTargets = basePlayerUsers.flatMap((user) => {
const account =
user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0];
user.riotAccounts.find((entry) => entry.isPrimary) ??
user.riotAccounts[0];
if (!account?.puuid) return [];
if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
return [{ userId: user._id, puuid: account.puuid }];
@@ -316,8 +319,7 @@ export class AuctionService {
const legacyTeams = params.captains.map((c) => ({
teamIndex: c.teamIndex,
captainUserId: c.userId,
points:
c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
members: [],
}));
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
@@ -391,26 +393,30 @@ export class AuctionService {
});
} catch (error) {
if (!isMongoDuplicateKeyError(error)) throw error;
const raceWinner = await AuctionModel.findOne({ matchId: params.matchId });
const raceWinner = await AuctionModel.findOne({
matchId: params.matchId,
});
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
return raceWinner;
}
throw new BadRequestException('Auction already exists for this match.');
}
await this.recordSnapshot(auction, 'start');
await this.auctionRedisCommandService.hydrateState(params.matchId.toString(), {
auctionHistorySequence: 1,
auctionLifecycleId,
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
liveStatePatch,
matchId: params.matchId.toString(),
phase: 'presenting',
revision: 0,
structureStateJson,
});
await this.auctionRedisCommandService.hydrateState(
params.matchId.toString(),
{
auctionHistorySequence: 1,
auctionLifecycleId,
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
liveStatePatch,
matchId: params.matchId.toString(),
phase: 'presenting',
revision: 0,
structureStateJson,
},
);
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
this.enqueueBackgroundOrderEnrichment({
auctionId: auction._id,
@@ -624,9 +630,8 @@ export class AuctionService {
params: PlaceBidParams,
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
this.assertValidBidPointAmount(params.amount);
const redisBidDelta = await this.tryPlaceRedisBidDeltaFromRealtimeState(
params,
);
const redisBidDelta =
await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
if (redisBidDelta) return redisBidDelta;
const auction = await this.getByMatchId(params.matchId);
@@ -712,11 +717,10 @@ export class AuctionService {
const serviceStartedAtMS = performance.now();
const matchId = params.matchId.toString();
const bidContextReadStartedAtMS = performance.now();
const bidContext =
await this.auctionRedisStateReaderService.readBidContext(
matchId,
params.teamIndex,
);
const bidContext = await this.auctionRedisStateReaderService.readBidContext(
matchId,
params.teamIndex,
);
const redisBidContextReadDurationMS =
performance.now() - bidContextReadStartedAtMS;
if (!bidContext) return null;
@@ -1321,12 +1325,10 @@ export class AuctionService {
if (!session) {
throw new InternalServerErrorException('Failed to start DB session.');
}
let redisRuntimeToClear:
| {
auctionLifecycleId?: string;
matchId: string;
}
| null = null;
let redisRuntimeToClear: {
auctionLifecycleId?: string;
matchId: string;
} | null = null;
try {
session.startTransaction();
const auction = await AuctionModel.findOne({
@@ -1349,15 +1351,15 @@ export class AuctionService {
await AuctionSideEffectApplicationModel.deleteMany({
auctionId: auction._id,
}).session(session);
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
session,
);
await AuctionHistoryModel.deleteMany({
auctionId: auction._id,
}).session(session);
await auction.deleteOne({ session });
} else {
await auction.deleteOne({ session });
await AuctionHistoryModel.deleteMany({ auctionId: auction._id }).session(
session,
);
await AuctionHistoryModel.deleteMany({
auctionId: auction._id,
}).session(session);
if (match.status === 'team-built') {
await this.tournamentCodeService.releaseFromMatch(match);
match.status = 'recruiting';
@@ -1410,15 +1412,13 @@ export class AuctionService {
throw new InternalServerErrorException('Failed to start DB session.');
}
let redisUndoContext:
| {
actionRequestParams?: AuctionStructureActionRequestParams;
auction: AuctionDocument;
snapshot: Record<string, unknown>;
targetHistorySequence: number;
undoingCompletedAuction: boolean;
}
| null = null;
let redisUndoContext: {
actionRequestParams?: AuctionStructureActionRequestParams;
auction: AuctionDocument;
snapshot: Record<string, unknown>;
targetHistorySequence: number;
undoingCompletedAuction: boolean;
} | null = null;
let restored: AuctionDocument | null = null;
try {
@@ -1460,27 +1460,27 @@ export class AuctionService {
};
await session.commitTransaction();
} else {
if (undoingCompletedAuction) {
await this.tournamentCodeService.releaseFromMatch(match);
await this.tournamentResultService.cancelPolling(match);
match.status = 'team-built';
match.result = undefined;
await match.save({ session });
}
if (undoingCompletedAuction) {
await this.tournamentCodeService.releaseFromMatch(match);
await this.tournamentResultService.cancelPolling(match);
match.status = 'team-built';
match.result = undefined;
await match.save({ session });
}
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
session,
}).exec();
await AuctionHistoryModel.deleteMany({
auctionId: auction._id,
sequence: { $gt: params.sequence },
})
.session(session)
.exec();
await AuctionModel.replaceOne({ _id: auction._id }, snapshot, {
session,
}).exec();
await AuctionHistoryModel.deleteMany({
auctionId: auction._id,
sequence: { $gt: params.sequence },
})
.session(session)
.exec();
await session.commitTransaction();
restored = await AuctionModel.findById(auction._id);
if (!restored) throw new NotFoundException('Auction not found.');
await session.commitTransaction();
restored = await AuctionModel.findById(auction._id);
if (!restored) throw new NotFoundException('Auction not found.');
}
} catch (err) {
await session.abortTransaction();
@@ -1534,28 +1534,27 @@ export class AuctionService {
const processingOwnerToken = randomUUID();
const auctionStateTransitionId = `${params.action}:${expectedAuctionLifecycleId}:${auctionActionRequestId}`;
const reserved =
await this.auctionRedisCommandService.reserveActionRequest(
params.matchId,
{
auctionActionRequestId,
auctionActionType: params.action,
auctionStateTransitionId,
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
expectedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
expectedCurrentBidRoundPlayerUserId,
clientObservedPhase: expectedPhase,
clientObservedRevision: expectedRevision,
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
maximumStoredAuctionActionRequestResultCount:
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
minimumAuctionActionRequestResultReplayWindowMS:
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
processingOwnerToken,
},
);
const reserved = await this.auctionRedisCommandService.reserveActionRequest(
params.matchId,
{
auctionActionRequestId,
auctionActionType: params.action,
auctionStateTransitionId,
clientObservedAuctionLifecycleId: expectedAuctionLifecycleId,
clientObservedCurrentAuctionPlayerOrderIndex:
expectedCurrentAuctionPlayerOrderIndex,
clientObservedCurrentBidRoundPlayerUserId:
expectedCurrentBidRoundPlayerUserId,
clientObservedPhase: expectedPhase,
clientObservedRevision: expectedRevision,
leaseDurationMS: AUCTION_ACTION_REQUEST_LEASE_DURATION_MS,
maximumStoredAuctionActionRequestResultCount:
AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT,
minimumAuctionActionRequestResultReplayWindowMS:
AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS,
processingOwnerToken,
},
);
if ('rejected' in reserved) {
throw new BadRequestException(
@@ -1579,8 +1578,7 @@ export class AuctionService {
return {
actionRequest: {
observedProcessingLeaseVersion:
reserved.observedProcessingLeaseVersion,
observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
processingOwnerToken,
scopeKey: reserved.actionRequestScopeKey,
},
@@ -1627,7 +1625,10 @@ export class AuctionService {
| { durationSeconds: number; mode: 'set-relative' };
expectedPhase: string;
historyMutation?: Record<string, unknown>;
liveStatePatch: Record<string, string | number | boolean | null | undefined>;
liveStatePatch: Record<
string,
string | number | boolean | null | undefined
>;
matchSideEffectMutation?: Record<string, unknown>;
shouldBroadcastStateAfterDurability?: boolean;
shouldResetBidRuntime?: boolean;
@@ -1644,8 +1645,7 @@ export class AuctionService {
const expectedAuctionHistorySequence = this.numberFromState(
params.state.currentAuctionHistorySequence,
);
const auctionHistorySequence =
expectedAuctionHistorySequence + 1;
const auctionHistorySequence = expectedAuctionHistorySequence + 1;
const auctionStateTransitionId =
params.actionRequest?.auctionStateTransitionId ||
params.auctionStateTransitionId ||
@@ -1695,7 +1695,8 @@ export class AuctionService {
),
auctionHistorySequence,
auctionLifecycleId:
params.actionRequest?.expectedAuctionLifecycleId ?? auctionLifecycleId,
params.actionRequest?.expectedAuctionLifecycleId ??
auctionLifecycleId,
auctionStateTransitionId,
broadcastStateRevision: expectedRevision + 1,
deadline: params.deadline,
@@ -1709,7 +1710,8 @@ export class AuctionService {
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
: undefined),
expectedAuctionHistorySequence,
expectedPhase: params.actionRequest?.expectedPhase ?? params.expectedPhase,
expectedPhase:
params.actionRequest?.expectedPhase ?? params.expectedPhase,
expectedRevision,
liveStatePatch: params.liveStatePatch,
matchId,
@@ -1762,9 +1764,8 @@ export class AuctionService {
)) {
const teamIndex = this.numberFromState(team.teamIndex);
if (teamIndex < 1) continue;
clearedTeamLiveStatePatch[
`team:${teamIndex}:remainingBidPointAmount`
] = 0;
clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
0;
clearedTeamLiveStatePatch[
`team:${teamIndex}:assignedAuctionTeamMemberCount`
] = 0;
@@ -1829,7 +1830,8 @@ export class AuctionService {
-1,
);
const currentHighestBidPointAmount = this.numberFromState(
params.snapshot.currentHighestBidPointAmount ?? params.snapshot.currentBid,
params.snapshot.currentHighestBidPointAmount ??
params.snapshot.currentBid,
0,
);
@@ -1898,10 +1900,11 @@ export class AuctionService {
passedAuctionPlayerQueue: this.arrayFromState(
state.passedAuctionPlayerQueue,
),
topTierAuctionPriorityThreshold:
this.isAuctionTopTierThreshold(state.topTierAuctionPriorityThreshold)
? state.topTierAuctionPriorityThreshold
: 'NONE',
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
state.topTierAuctionPriorityThreshold,
)
? state.topTierAuctionPriorityThreshold
: 'NONE',
};
}
@@ -1913,9 +1916,10 @@ export class AuctionService {
auctionPlayerOrder: this.arrayFromState(
snapshot.auctionPlayerOrder ?? snapshot.order,
),
auctionTeams: this.arrayFromState(snapshot.auctionTeams).length > 0
? this.arrayFromState(snapshot.auctionTeams)
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
auctionTeams:
this.arrayFromState(snapshot.auctionTeams).length > 0
? this.arrayFromState(snapshot.auctionTeams)
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
bidRoundExtensionSeconds: this.numberFromState(
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
5,
@@ -1945,8 +1949,8 @@ export class AuctionService {
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
)
? (snapshot.topTierAuctionPriorityThreshold ??
snapshot.topTierThreshold) as never
? ((snapshot.topTierAuctionPriorityThreshold ??
snapshot.topTierThreshold) as never)
: 'NONE',
};
}
@@ -2064,7 +2068,9 @@ export class AuctionService {
}
private convertRedisTeamsToLegacyTeams(
auctionTeams: Parameters<typeof stringifyAuctionRedisStructureState>[0]['auctionTeams'],
auctionTeams: Parameters<
typeof stringifyAuctionRedisStructureState
>[0]['auctionTeams'],
): AuctionTeam[] {
return auctionTeams.map((team) => ({
captainUserId: team.captainUserId as mongoose.Types.ObjectId,
@@ -2096,7 +2102,7 @@ export class AuctionService {
}
private stringFromState(value: unknown): string {
return typeof value === 'string' ? value : value?.toString() ?? '';
return typeof value === 'string' ? value : (value?.toString() ?? '');
}
private isAuctionTopTierThreshold(
@@ -2218,7 +2224,9 @@ export class AuctionService {
({ I: 4, II: 3, III: 2, IV: 1, '': 0 } as Record<string, number>)[
solo.rank
] ?? 0;
return tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001;
return (
tierIdx * 1000 + rankBonus * 100 + (solo.leaguePoints ?? 0) * 0.001
);
};
const top = order
@@ -2507,7 +2515,7 @@ export class AuctionService {
]),
);
match.teams = auction.teams.map((team) => {
const matchTeams = auction.teams.map((team) => {
const captain = participantByUserId.get(team.captainUserId.toString());
const members: MatchTeamMember[] = [
{
@@ -2531,6 +2539,12 @@ export class AuctionService {
members,
};
});
if (matchTeams.length === 0) {
throw new Error(
`Auction completed without teams for match ${match._id.toString()}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
@@ -2557,7 +2571,7 @@ export class AuctionService {
structureInput.auctionTeams,
);
match.teams = teams.map((team) => {
const matchTeams = teams.map((team) => {
const captain = participantByUserId.get(team.captainUserId.toString());
const members: MatchTeamMember[] = [
{
@@ -2566,7 +2580,10 @@ export class AuctionService {
cost: 0,
},
...team.members
.filter((member) => member.userId.toString() !== team.captainUserId.toString())
.filter(
(member) =>
member.userId.toString() !== team.captainUserId.toString(),
)
.map((member) => ({
userId: member.userId,
assignedPosition: member.assignedPosition,
@@ -2581,6 +2598,12 @@ export class AuctionService {
members,
};
});
if (matchTeams.length === 0) {
throw new Error(
`Redis auction completed without teams for match ${match._id.toString()}.`,
);
}
match.teams = matchTeams;
match.status = 'team-built';
match.teamBuiltAt = match.teamBuiltAt ?? new Date();
await match.save();
@@ -2602,7 +2625,8 @@ export class AuctionService {
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
currentAuctionPlayerOrderIndex:
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
currentAuctionRound: auction.currentAuctionRound ?? auction.auctionRound ?? 1,
currentAuctionRound:
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
initialTeamBidPointAmount:
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
manualTopTierAuctionPriorityUserIds:
@@ -2614,7 +2638,9 @@ export class AuctionService {
passedAuctionPlayerQueue:
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
topTierAuctionPriorityThreshold:
auction.topTierAuctionPriorityThreshold ?? auction.topTierThreshold ?? 'NONE',
auction.topTierAuctionPriorityThreshold ??
auction.topTierThreshold ??
'NONE',
};
await this.auctionRedisCommandService.hydrateState(
auction.matchId.toString(),
@@ -2647,35 +2673,37 @@ export class AuctionService {
expectedAuctionLifecycleId?: string,
): Promise<void> {
const keys = buildAuctionRedisKeys(matchId);
const cleared = await this.auctionRedisService.raw().sendCommand([
'EVAL',
[
"local expectedAuctionLifecycleId = ARGV[2]",
"if expectedAuctionLifecycleId ~= '' then",
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
" if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then",
" return 0",
' end',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
expectedAuctionLifecycleId ?? '',
]);
const cleared = await this.auctionRedisService
.raw()
.sendCommand([
'EVAL',
[
'local expectedAuctionLifecycleId = ARGV[2]',
"if expectedAuctionLifecycleId ~= '' then",
" local currentAuctionLifecycleId = redis.call('HGET', KEYS[1], 'auctionLifecycleId')",
' if currentAuctionLifecycleId and currentAuctionLifecycleId ~= expectedAuctionLifecycleId then',
' return 0',
' end',
'end',
"redis.call('ZREM', KEYS[2], ARGV[1])",
"redis.call('DEL', KEYS[1], KEYS[3], KEYS[4], KEYS[5], KEYS[6], KEYS[7], KEYS[8], KEYS[9], KEYS[10], KEYS[11])",
'return 1',
].join('\n'),
'11',
keys.liveStateKey,
keys.deadlineQueueKey,
keys.structureStateKey,
keys.appliedTransitionIdsKey,
keys.bidHistoryKey,
keys.bidRequestResultsKey,
keys.bidRequestResultOrderKey,
keys.actionRequestResultsKey,
keys.actionRequestResultOrderKey,
keys.rehydrateLockKey,
keys.stateTransitionLockKey,
matchId,
expectedAuctionLifecycleId ?? '',
]);
if (Number(cleared) !== 1) return;
await this.clearRedisDurabilityPayloadsForLifecycle(
keys,
@@ -2689,14 +2717,16 @@ export class AuctionService {
): Promise<void> {
let cursor = '0';
do {
const reply = await this.auctionRedisService.raw().sendCommand([
'SCAN',
cursor,
'MATCH',
`${keys.durabilityPayloadKeyPrefix}*`,
'COUNT',
'100',
]);
const reply = await this.auctionRedisService
.raw()
.sendCommand([
'SCAN',
cursor,
'MATCH',
`${keys.durabilityPayloadKeyPrefix}*`,
'COUNT',
'100',
]);
if (!Array.isArray(reply) || reply.length < 2) return;
cursor = String(reply[0]);
const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : [];
@@ -2714,20 +2744,23 @@ export class AuctionService {
);
if (payloadKeysToDelete.length === 0) continue;
await this.auctionRedisService.raw().sendCommand([
'ZREM',
keys.durabilityRetryQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService.raw().sendCommand([
'ZREM',
keys.durabilityDeadLetterQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService.raw().sendCommand([
'DEL',
...payloadKeysToDelete,
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZREM',
keys.durabilityRetryQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService
.raw()
.sendCommand([
'ZREM',
keys.durabilityDeadLetterQueueKey,
...payloadKeysToDelete,
]);
await this.auctionRedisService
.raw()
.sendCommand(['DEL', ...payloadKeysToDelete]);
} while (cursor !== '0');
}
@@ -2742,7 +2775,9 @@ export class AuctionService {
const payload = JSON.parse(payloadValue) as Record<string, unknown>;
return payload.auctionLifecycleId === expectedAuctionLifecycleId;
} catch {
this.logger.warn(`Failed to parse auction durability payload ${payloadKey}.`);
this.logger.warn(
`Failed to parse auction durability payload ${payloadKey}.`,
);
return false;
}
}
@@ -2855,13 +2890,16 @@ async function runWithConcurrency<T>(
if (items.length === 0) return;
const queue = [...items];
const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
});
const runners = Array.from(
{ length: Math.min(concurrency, queue.length) },
async () => {
while (queue.length > 0) {
const item = queue.shift();
if (item === undefined) return;
await worker(item);
}
},
);
await Promise.allSettled(runners);
}