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

+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);
}