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.
3416 lines
121 KiB
TypeScript
3416 lines
121 KiB
TypeScript
import {
|
|
BadRequestException,
|
|
ConflictException,
|
|
Injectable,
|
|
InternalServerErrorException,
|
|
Logger,
|
|
NotFoundException,
|
|
ServiceUnavailableException,
|
|
Optional,
|
|
} from '@nestjs/common';
|
|
import { randomUUID } from 'crypto';
|
|
import {
|
|
AuctionLifecycleLock,
|
|
AuctionLifecycleBusyError,
|
|
} from './auction-lifecycle-lock';
|
|
import { AUCTION_OPTIONAL_PROJECTION_FIELDS } from './auction-projection';
|
|
import { AuctionEventBusService } from './auction-event-bus.service';
|
|
import { performance } from 'perf_hooks';
|
|
import mongoose from 'mongoose';
|
|
import { ConnectionService } from '../global/database/connection.service';
|
|
import {
|
|
AuctionActionType,
|
|
AuctionChatMessage,
|
|
AuctionDocument,
|
|
AuctionPlayerSnapshot,
|
|
AuctionTeam,
|
|
AuctionTopTierThreshold,
|
|
MatchDocument,
|
|
MatchParticipant,
|
|
MatchTeamMember,
|
|
Position,
|
|
RiotAccount,
|
|
} from '../global/database/schema';
|
|
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
|
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
|
|
import { TournamentCodeService } from '../tournament-code/tournament-code.service';
|
|
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
|
import {
|
|
AuctionRedisCommandService,
|
|
type AuctionBidCommandResult,
|
|
} from './redis/auction-redis-command.service';
|
|
import { buildAuctionRedisKeys } from './redis/auction-redis.keys';
|
|
import {
|
|
buildAuctionRedisLiveStatePatchFromStructure,
|
|
buildAuctionRedisStructureState,
|
|
convertLegacyAuctionTeamsToRedisTeams,
|
|
stringifyAuctionRedisStructureState,
|
|
} from './redis/auction-redis-projection';
|
|
import { AuctionRedisService } from './redis/auction-redis.service';
|
|
import { AUCTION_CLEANUP_DURABILITY_SCRIPT } from './redis/auction-redis.cleanup';
|
|
import { AuctionRedisStateReaderService } from './redis/auction-redis-state-reader.service';
|
|
import { shouldHydrateRedisAuctionState } from './redis/auction-redis.state';
|
|
// [AUCTION-DEBUG] 경매 "중복 멤버" 조사용 임시 계측. 조사 종료 후 제거 대상.
|
|
import { recordNewRelicCustomEvent } from '../global/observability/new-relic';
|
|
|
|
const AUCTION_MAX_TEAM_SIZE = 5;
|
|
const AUCTION_MIN_BID_POINTS = 10;
|
|
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
|
|
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
|
|
const AUCTION_CHAT_MAX_MESSAGES = 200;
|
|
const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300;
|
|
const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24;
|
|
const AUCTION_MAX_STORED_BID_HISTORY_COUNT = 1000;
|
|
const AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT = 500;
|
|
const AUCTION_BID_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
|
const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
|
|
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
|
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
|
const AUCTION_HISTORY_LIST_LIMIT = 100;
|
|
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
|
|
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
|
|
|
|
interface StartAuctionParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
startAuctionRequestId: string;
|
|
actorUserId?: mongoose.Types.ObjectId;
|
|
captains: {
|
|
teamIndex: number;
|
|
userId: mongoose.Types.ObjectId;
|
|
initialTeamBidPointAmount?: number;
|
|
}[];
|
|
initialTeamBidPointAmount: number;
|
|
maximumBidRoundDurationSeconds: number;
|
|
bidRoundExtensionSeconds: number;
|
|
topTierAuctionPriorityThreshold: AuctionTopTierThreshold;
|
|
manualTopTierAuctionPriorityUserIds: mongoose.Types.ObjectId[];
|
|
}
|
|
|
|
interface PlaceBidParams {
|
|
clientObservedBidRoundId?: string;
|
|
matchId: mongoose.Types.ObjectId;
|
|
teamIndex: number;
|
|
amount: number;
|
|
bidRequestId?: string;
|
|
bidderUserId?: mongoose.Types.ObjectId;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
}
|
|
|
|
interface AuctionStructureActionRequestParams {
|
|
auctionActionRequestId?: string;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentAuctionPlayerOrderIndex?: number;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
clientObservedPhase?: string;
|
|
clientObservedRevision?: number;
|
|
shouldBroadcastStateAfterDurability?: boolean;
|
|
}
|
|
|
|
interface MarkSoldParams extends AuctionStructureActionRequestParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
assignedPosition?: Position;
|
|
}
|
|
|
|
interface ReservedRedisActionRequestContext {
|
|
actionRequest: {
|
|
observedProcessingLeaseVersion: number;
|
|
processingOwnerToken: string;
|
|
scopeKey: string;
|
|
};
|
|
auctionStateTransitionId: string;
|
|
expectedAuctionLifecycleId: string;
|
|
expectedCurrentAuctionPlayerOrderIndex?: number;
|
|
expectedCurrentBidRoundPlayerUserId?: string;
|
|
expectedPhase: string;
|
|
expectedRevision: number;
|
|
}
|
|
|
|
interface ReplayedRedisActionRequestContext {
|
|
currentServerTimestampMS: number;
|
|
replay: true;
|
|
requiresRefetch: boolean;
|
|
responseJson?: string;
|
|
revision?: number;
|
|
}
|
|
|
|
type RedisActionRequestContext =
|
|
| ReservedRedisActionRequestContext
|
|
| ReplayedRedisActionRequestContext;
|
|
|
|
interface AppendChatMessageParams {
|
|
matchId: mongoose.Types.ObjectId;
|
|
userId?: mongoose.Types.ObjectId;
|
|
displayName?: string;
|
|
message: string;
|
|
}
|
|
|
|
export interface AuctionHistoryView {
|
|
sequence: number;
|
|
action: AuctionActionType;
|
|
actionLabel: string;
|
|
takenAt: Date;
|
|
}
|
|
|
|
interface AuctionHistorySummaryRecord {
|
|
sequence: number;
|
|
action: AuctionActionType;
|
|
takenAt: Date;
|
|
}
|
|
|
|
interface AuctionHistoryListCacheEntry {
|
|
entries: AuctionHistoryView[];
|
|
expiresAtTimestampMS: number;
|
|
}
|
|
|
|
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
|
|
|
export interface AuctionBidDeltaResponse {
|
|
currentBidRoundId?: string;
|
|
auctionBidHistoryEntry: Record<string, unknown>;
|
|
auctionLifecycleId?: string;
|
|
bidServerTiming?: AuctionBidServerTiming;
|
|
bidRequestId: string;
|
|
currentBidRoundDeadlineTimestampMS: number;
|
|
currentHighestBidderTeamIndex: number;
|
|
currentHighestBidPointAmount: number;
|
|
currentServerTimestampMS: number;
|
|
revision: number;
|
|
}
|
|
|
|
export interface AuctionBidServerTiming {
|
|
fallbackFullStatePath?: boolean;
|
|
redisBidCommandDurationMS?: number;
|
|
redisBidContextReadDurationMS?: number;
|
|
serviceTotalDurationMS?: number;
|
|
}
|
|
|
|
export interface AuctionBidRejectDiagnostics {
|
|
currentBidRoundDeadlineTimestampMS?: number;
|
|
currentServerTimestampMS?: number;
|
|
}
|
|
|
|
interface AuctionEnrichmentTarget {
|
|
userId: mongoose.Types.ObjectId;
|
|
puuid: string;
|
|
}
|
|
|
|
function isMongoDuplicateKeyError(error: unknown): boolean {
|
|
return (
|
|
typeof error === 'object' &&
|
|
error !== null &&
|
|
Number((error as { code?: unknown }).code) === 11000
|
|
);
|
|
}
|
|
|
|
@Injectable()
|
|
export class AuctionService {
|
|
private readonly logger = new Logger(AuctionService.name);
|
|
private readonly auctionHistoryListCache = new Map<
|
|
string,
|
|
AuctionHistoryListCacheEntry
|
|
>();
|
|
|
|
constructor(
|
|
private readonly connectionService: ConnectionService,
|
|
private readonly enrichmentService: RiotAccountEnrichmentService,
|
|
private readonly tournamentCodeService: TournamentCodeService,
|
|
private readonly tournamentResultService: TournamentResultService,
|
|
private readonly auctionRedisService: AuctionRedisService,
|
|
private readonly auctionRedisCommandService: AuctionRedisCommandService,
|
|
private readonly auctionRedisStateReaderService: AuctionRedisStateReaderService,
|
|
@Optional()
|
|
private readonly auctionEventBusService?: AuctionEventBusService,
|
|
) {}
|
|
|
|
public async start(params: StartAuctionParams): Promise<AuctionDocument> {
|
|
return new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
params.matchId.toString(),
|
|
() => this.startLocked(params),
|
|
);
|
|
}
|
|
|
|
private async startLocked(
|
|
params: StartAuctionParams,
|
|
): Promise<AuctionDocument> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const UserModel = await this.connectionService.getModel('user');
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
const AuctionHistoryModel =
|
|
await this.connectionService.getModel('auctionHistory');
|
|
const CommunityModel = await this.connectionService.getModel('community');
|
|
|
|
const match = await MatchModel.findById(params.matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!match.communityId.equals(params.communityId)) {
|
|
throw new BadRequestException('Match does not belong to this community.');
|
|
}
|
|
|
|
const existing = await AuctionModel.findOne({ matchId: params.matchId });
|
|
if (existing) {
|
|
if (existing.startAuctionRequestId === params.startAuctionRequestId) {
|
|
return this.finishAuctionStartup(existing, match);
|
|
}
|
|
if (this.isRestartableResetRedisAuction(existing)) {
|
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
|
params.matchId.toString(),
|
|
existing.auctionLifecycleId,
|
|
);
|
|
await AuctionHistoryModel.deleteMany({ auctionId: existing._id });
|
|
await AuctionModel.deleteOne({ _id: existing._id });
|
|
} else if (this.isRedisResetStillApplying(existing)) {
|
|
throw new BadRequestException(
|
|
'Auction reset is still being applied. Please try again shortly.',
|
|
);
|
|
} else {
|
|
throw new BadRequestException('Auction already exists for this match.');
|
|
}
|
|
}
|
|
|
|
// No Mongo auction owns this match. Remove runtime left by an interrupted
|
|
// cancellation before creating a new lifecycle (under the lifecycle lock).
|
|
const orphanedRuntime =
|
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(
|
|
params.matchId.toString(),
|
|
);
|
|
if (orphanedRuntime?.auctionLifecycleId) {
|
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
|
params.matchId.toString(),
|
|
orphanedRuntime.auctionLifecycleId,
|
|
);
|
|
}
|
|
|
|
const activeParticipants = this.applyAuctionCut(match);
|
|
const desiredAuctionCount = activeParticipants.length;
|
|
if (desiredAuctionCount < 10) {
|
|
throw new BadRequestException(
|
|
'Not enough participants (need at least 10).',
|
|
);
|
|
}
|
|
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
|
|
if (params.captains.length !== expectedCaptainCount) {
|
|
throw new BadRequestException(
|
|
`Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`,
|
|
);
|
|
}
|
|
this.assertCaptainAssignments(
|
|
params.captains,
|
|
activeParticipants,
|
|
expectedCaptainCount,
|
|
);
|
|
const captainUserIds = params.captains.map((c) => c.userId);
|
|
|
|
const basePlayerUsers = await UserModel.find({
|
|
_id: {
|
|
$in: activeParticipants
|
|
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
|
|
.map((p) => p.userId),
|
|
},
|
|
});
|
|
const community = await CommunityModel.findById(match.communityId)
|
|
.select({ riotPlatform: 1, riotRegion: 1 })
|
|
.lean()
|
|
.exec();
|
|
const platform = community?.riotPlatform ?? 'kr';
|
|
const region = community?.riotRegion ?? 'asia';
|
|
|
|
const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
|
|
const enrichTargets = basePlayerUsers.flatMap((user) => {
|
|
const account =
|
|
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 }];
|
|
});
|
|
|
|
const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u]));
|
|
|
|
const nonCaptainPuuids = new Set<string>();
|
|
const order: AuctionPlayerSnapshot[] = [];
|
|
for (const participant of activeParticipants) {
|
|
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
|
|
continue;
|
|
}
|
|
const user = userById.get(participant.userId.toString());
|
|
if (!user) continue;
|
|
const primary =
|
|
user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0];
|
|
if (!primary) {
|
|
throw new BadRequestException(
|
|
`Participant ${user._id.toString()} has no Riot account.`,
|
|
);
|
|
}
|
|
if (nonCaptainPuuids.has(primary.puuid)) continue;
|
|
nonCaptainPuuids.add(primary.puuid);
|
|
order.push({
|
|
userId: user._id,
|
|
puuid: primary.puuid,
|
|
gameName: primary.gameName,
|
|
tagLine: primary.tagLine,
|
|
profileIconId: primary.profileIconId,
|
|
preferredPositions: participant.preferredPositions,
|
|
tiers: primary.tiers,
|
|
tierHistory: primary.tierHistory ?? [],
|
|
masteries: primary.championMasteries,
|
|
recentStatsSummary: primary.recentStatsSummary,
|
|
passCount: 0,
|
|
});
|
|
}
|
|
const shuffledOrder = this.shuffleAuctionPlayerOrder(order);
|
|
const prioritizedOrder = this.applyTopTierPriority(
|
|
shuffledOrder,
|
|
params.topTierAuctionPriorityThreshold,
|
|
params.manualTopTierAuctionPriorityUserIds,
|
|
);
|
|
|
|
const auctionId = new mongoose.Types.ObjectId();
|
|
const auctionStartedAtTimestampMS =
|
|
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
|
const startAuctionStateTransitionId = `start:${auctionId.toString()}:${params.startAuctionRequestId}`;
|
|
const auctionLifecycleId = `auction:${auctionId.toString()}:${params.startAuctionRequestId}`;
|
|
const legacyTeams = params.captains.map((c) => ({
|
|
teamIndex: c.teamIndex,
|
|
captainUserId: c.userId,
|
|
points: c.initialTeamBidPointAmount ?? params.initialTeamBidPointAmount,
|
|
members: [],
|
|
}));
|
|
const auctionTeams = convertLegacyAuctionTeamsToRedisTeams(legacyTeams);
|
|
const redisStructureInput = {
|
|
auctionPlayerOrder: prioritizedOrder,
|
|
auctionTeams,
|
|
bidRoundExtensionSeconds: params.bidRoundExtensionSeconds,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
initialTeamBidPointAmount: params.initialTeamBidPointAmount,
|
|
manualTopTierAuctionPriorityUserIds:
|
|
params.topTierAuctionPriorityThreshold === 'MANUAL'
|
|
? params.manualTopTierAuctionPriorityUserIds
|
|
: [],
|
|
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
|
passedAuctionPlayerQueue: [],
|
|
topTierAuctionPriorityThreshold: params.topTierAuctionPriorityThreshold,
|
|
};
|
|
const structureStateJson =
|
|
stringifyAuctionRedisStructureState(redisStructureInput);
|
|
const liveStatePatch =
|
|
buildAuctionRedisLiveStatePatchFromStructure(redisStructureInput);
|
|
let auction: AuctionDocument;
|
|
try {
|
|
auction = await AuctionModel.create({
|
|
_id: auctionId,
|
|
matchId: params.matchId,
|
|
phase: 'presenting',
|
|
revision: 1,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId,
|
|
lastAppliedAuctionStateTransitionId: startAuctionStateTransitionId,
|
|
currentAuctionHistorySequence: 1,
|
|
startAuctionRequestId: params.startAuctionRequestId,
|
|
startAuctionStateTransitionId,
|
|
auctionStartedAtTimestampMS,
|
|
auctionStartedByUserId: params.actorUserId,
|
|
matchSideEffectStatus: 'none',
|
|
matchSideEffectRevision: 0,
|
|
startupCompleted: false,
|
|
teams: legacyTeams,
|
|
order: prioritizedOrder,
|
|
passedQueue: [],
|
|
auctionRound: 1,
|
|
currentIndex: 0,
|
|
bids: [],
|
|
currentBid: 0,
|
|
maxTimerSeconds: params.maximumBidRoundDurationSeconds,
|
|
bidExtensionSeconds: params.bidRoundExtensionSeconds,
|
|
initialPoints: params.initialTeamBidPointAmount,
|
|
topTierThreshold: params.topTierAuctionPriorityThreshold,
|
|
manualTopTierUserIds:
|
|
params.topTierAuctionPriorityThreshold === 'MANUAL'
|
|
? params.manualTopTierAuctionPriorityUserIds
|
|
: [],
|
|
startedAt: new Date(auctionStartedAtTimestampMS),
|
|
auctionTeams,
|
|
auctionPlayerOrder: prioritizedOrder,
|
|
passedAuctionPlayerQueue: [],
|
|
currentAuctionRound: 1,
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
auctionBidHistory: [],
|
|
currentHighestBidPointAmount: 0,
|
|
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
|
bidRoundExtensionSeconds: params.bidRoundExtensionSeconds,
|
|
initialTeamBidPointAmount: params.initialTeamBidPointAmount,
|
|
topTierAuctionPriorityThreshold: params.topTierAuctionPriorityThreshold,
|
|
manualTopTierAuctionPriorityUserIds:
|
|
params.topTierAuctionPriorityThreshold === 'MANUAL'
|
|
? params.manualTopTierAuctionPriorityUserIds
|
|
: [],
|
|
});
|
|
} catch (error) {
|
|
if (!isMongoDuplicateKeyError(error)) throw error;
|
|
const raceWinner = await AuctionModel.findOne({
|
|
matchId: params.matchId,
|
|
});
|
|
if (raceWinner?.startAuctionRequestId === params.startAuctionRequestId) {
|
|
return this.finishAuctionStartup(raceWinner, match);
|
|
}
|
|
throw new BadRequestException('Auction already exists for this match.');
|
|
}
|
|
await this.recordSnapshot(auction, 'start');
|
|
const hydration = await this.auctionRedisCommandService.hydrateState(
|
|
params.matchId.toString(),
|
|
{
|
|
auctionHistorySequence: 1,
|
|
auctionLifecycleId,
|
|
maximumBidRoundDurationSeconds: params.maximumBidRoundDurationSeconds,
|
|
liveStatePatch,
|
|
matchId: params.matchId.toString(),
|
|
phase: 'presenting',
|
|
revision: 0,
|
|
structureStateJson,
|
|
},
|
|
);
|
|
if ('rejected' in hydration)
|
|
throw new ConflictException(
|
|
`Auction initialization failed: ${hydration.code}.`,
|
|
);
|
|
|
|
match.status = 'team-built';
|
|
await match.save();
|
|
auction.startupCompleted = true;
|
|
await AuctionModel.updateOne(
|
|
{ _id: auction._id },
|
|
{ $set: { startupCompleted: true } },
|
|
);
|
|
this.enqueueBackgroundOrderEnrichment({
|
|
auctionId: auction._id,
|
|
targets: enrichTargets,
|
|
platform,
|
|
region,
|
|
});
|
|
|
|
return auction;
|
|
}
|
|
|
|
private async finishAuctionStartup(
|
|
auction: AuctionDocument,
|
|
match: MatchDocument,
|
|
): Promise<AuctionDocument> {
|
|
// Documents predating the startup marker already completed the old path.
|
|
if (auction.startupCompleted !== false) return auction;
|
|
// Retry the original cut; recruiting may have changed since Mongo creation.
|
|
const roster = new Set([
|
|
...auction.teams.map((team) => team.captainUserId.toString()),
|
|
...auction.order.map((player) => player.userId.toString()),
|
|
]);
|
|
const participants = new Set(
|
|
match.participants.map((entry) => entry.userId.toString()),
|
|
);
|
|
if ([...roster].some((id) => !participants.has(id))) {
|
|
throw new ConflictException(
|
|
'Auction startup roster has changed. Cancel and restart the auction.',
|
|
);
|
|
}
|
|
const History = await this.connectionService.getModel('auctionHistory');
|
|
await History.updateOne(
|
|
{ auctionId: auction._id, sequence: 1 },
|
|
{
|
|
$setOnInsert: {
|
|
auctionId: auction._id,
|
|
matchId: auction.matchId,
|
|
sequence: 1,
|
|
action: 'start',
|
|
snapshotBefore: this.cloneJson(
|
|
typeof auction.toObject === 'function'
|
|
? auction.toObject()
|
|
: auction,
|
|
),
|
|
takenAt: auction.startedAt ?? new Date(),
|
|
},
|
|
},
|
|
{ upsert: true },
|
|
);
|
|
await this.hydrateRedisStateFromAuctionDocument(auction);
|
|
if (match.status === 'recruiting') {
|
|
match.participants.forEach((participant) => {
|
|
participant.excluded = !roster.has(participant.userId.toString());
|
|
});
|
|
match.status = 'team-built';
|
|
await match.save();
|
|
}
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
await AuctionModel.updateOne(
|
|
{ _id: auction._id },
|
|
{ $set: { startupCompleted: true } },
|
|
);
|
|
auction.startupCompleted = true;
|
|
return auction;
|
|
}
|
|
|
|
public async getByMatchId(
|
|
matchId: mongoose.Types.ObjectId,
|
|
): Promise<AuctionDocument> {
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
const auction = await AuctionModel.findOne({ matchId });
|
|
if (!auction) throw new NotFoundException('Auction not found.');
|
|
return auction;
|
|
}
|
|
|
|
public async getStateByMatchId(
|
|
matchId: mongoose.Types.ObjectId,
|
|
): Promise<AuctionStateResponse> {
|
|
for (let attempt = 0; ; attempt++) {
|
|
try {
|
|
return await this.getStateByMatchIdOnce(matchId);
|
|
} catch (error) {
|
|
if (!(error instanceof AuctionLifecycleBusyError)) throw error;
|
|
if (attempt >= 4)
|
|
throw new ServiceUnavailableException({
|
|
code: 'AUCTION_STATE_RECOVERING',
|
|
retryAfterMS: 500,
|
|
message: '경매 상태를 복구 중입니다. 잠시 후 다시 시도해 주세요.',
|
|
});
|
|
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
|
|
}
|
|
}
|
|
}
|
|
|
|
private async getStateByMatchIdOnce(
|
|
matchId: mongoose.Types.ObjectId,
|
|
): Promise<AuctionStateResponse> {
|
|
let auction = await this.getByMatchId(matchId);
|
|
if (!this.isRedisV1Auction(auction)) return auction;
|
|
|
|
if (auction.startupCompleted === false) {
|
|
auction = await new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
matchId.toString(),
|
|
async () => {
|
|
const current = await this.getByMatchId(matchId);
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
return this.finishAuctionStartup(current, match);
|
|
},
|
|
);
|
|
}
|
|
|
|
const redisState = await this.readRedisAuctionStateOrRehydrate(auction);
|
|
if (!redisState) return auction;
|
|
|
|
return {
|
|
...this.buildAuctionSnapshotFromRedisState(auction, redisState),
|
|
...redisState,
|
|
chatMessages: auction.chatMessages ?? [],
|
|
};
|
|
}
|
|
|
|
private async readRedisAuctionStateOrRehydrate(
|
|
auction: AuctionDocument,
|
|
): Promise<Record<string, unknown> | null> {
|
|
const matchId = auction.matchId.toString();
|
|
const mongoRevision = auction.revision ?? 0;
|
|
const mongoAuctionLifecycleId = auction.auctionLifecycleId;
|
|
if (!mongoAuctionLifecycleId) {
|
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
|
}
|
|
|
|
const liveIdentity =
|
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
|
|
// Completed runtimes expire after the retention period. Mongo remains the
|
|
// archive; viewing it must not create an immortal Redis runtime again.
|
|
if (!liveIdentity && auction.phase === 'complete') return null;
|
|
const shouldHydrate = shouldHydrateRedisAuctionState({
|
|
live: liveIdentity,
|
|
mongo: {
|
|
auctionLifecycleId: mongoAuctionLifecycleId,
|
|
revision: mongoRevision,
|
|
},
|
|
});
|
|
|
|
if (!shouldHydrate) {
|
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
|
}
|
|
|
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
matchId,
|
|
async () => {
|
|
const currentAuction = await this.getByMatchId(auction.matchId);
|
|
if (currentAuction.auctionLifecycleId !== mongoAuctionLifecycleId) {
|
|
throw new ConflictException(
|
|
'Auction lifecycle has changed. Refresh the auction.',
|
|
);
|
|
}
|
|
const currentLive =
|
|
await this.auctionRedisStateReaderService.readLiveStateIdentity(
|
|
matchId,
|
|
);
|
|
if (
|
|
currentLive?.auctionLifecycleId &&
|
|
currentLive.auctionLifecycleId !== mongoAuctionLifecycleId
|
|
) {
|
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
|
matchId,
|
|
currentLive.auctionLifecycleId,
|
|
);
|
|
}
|
|
await this.hydrateRedisStateFromAuctionDocument(currentAuction);
|
|
},
|
|
);
|
|
|
|
return this.auctionRedisStateReaderService.readAuctionStateView(matchId, {
|
|
shouldForceAuctionStateResync: true,
|
|
});
|
|
}
|
|
|
|
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
|
|
auction: AuctionDocument;
|
|
message: AuctionChatMessage;
|
|
}> {
|
|
const auction = await this.getByMatchId(params.matchId);
|
|
const messageText = this.normalizeChatMessage(params.message);
|
|
const message: AuctionChatMessage = {
|
|
id: randomUUID(),
|
|
userId: params.userId,
|
|
displayName: this.normalizeChatDisplayName(params.displayName),
|
|
message: messageText,
|
|
sentAt: new Date(),
|
|
};
|
|
|
|
auction.chatMessages ??= [];
|
|
auction.chatMessages.push(message);
|
|
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
|
|
if (overflow > 0) {
|
|
auction.chatMessages.splice(0, overflow);
|
|
}
|
|
|
|
await auction.save();
|
|
return { auction, message };
|
|
}
|
|
|
|
public async listHistory(params: {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
}): Promise<AuctionHistoryView[]> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const AuctionHistoryModel =
|
|
await this.connectionService.getModel('auctionHistory');
|
|
const match = await MatchModel.findById(params.matchId).select({
|
|
communityId: 1,
|
|
});
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!match.communityId.equals(params.communityId)) {
|
|
throw new BadRequestException('Match does not belong to this community.');
|
|
}
|
|
|
|
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
|
|
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
|
|
if (cachedHistory) return cachedHistory;
|
|
|
|
const entries = (await AuctionHistoryModel.find({ matchId: params.matchId })
|
|
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
|
|
.sort({ sequence: -1 })
|
|
.limit(AUCTION_HISTORY_LIST_LIMIT)
|
|
.lean()
|
|
.exec()) as AuctionHistorySummaryRecord[];
|
|
|
|
const history = entries.map((entry) => ({
|
|
sequence: entry.sequence,
|
|
action: entry.action,
|
|
actionLabel: this.formatHistoryActionLabel(entry.action),
|
|
takenAt: entry.takenAt,
|
|
}));
|
|
this.setCachedAuctionHistoryList(cacheKey, history);
|
|
return history;
|
|
}
|
|
|
|
private buildAuctionHistoryListCacheKey(params: {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
}): string {
|
|
return `${params.communityId.toString()}:${params.matchId.toString()}`;
|
|
}
|
|
|
|
private getCachedAuctionHistoryList(
|
|
cacheKey: string,
|
|
): AuctionHistoryView[] | null {
|
|
const cached = this.auctionHistoryListCache.get(cacheKey);
|
|
if (!cached) return null;
|
|
if (cached.expiresAtTimestampMS <= Date.now()) {
|
|
this.auctionHistoryListCache.delete(cacheKey);
|
|
return null;
|
|
}
|
|
return cached.entries;
|
|
}
|
|
|
|
private setCachedAuctionHistoryList(
|
|
cacheKey: string,
|
|
entries: AuctionHistoryView[],
|
|
): void {
|
|
if (
|
|
!this.auctionHistoryListCache.has(cacheKey) &&
|
|
this.auctionHistoryListCache.size >=
|
|
AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES
|
|
) {
|
|
const oldestKey = this.auctionHistoryListCache.keys().next().value as
|
|
| string
|
|
| undefined;
|
|
if (oldestKey) this.auctionHistoryListCache.delete(oldestKey);
|
|
}
|
|
this.auctionHistoryListCache.set(cacheKey, {
|
|
entries,
|
|
expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS,
|
|
});
|
|
}
|
|
|
|
public async openBidding(
|
|
matchId: mongoose.Types.ObjectId,
|
|
actionRequest: AuctionStructureActionRequestParams = {},
|
|
): Promise<AuctionStateResponse> {
|
|
const auction = await this.getByMatchId(matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.openRedisBidding(auction, actionRequest);
|
|
}
|
|
if (auction.phase !== 'presenting') {
|
|
throw new BadRequestException('Auction is not in presenting phase.');
|
|
}
|
|
await this.recordSnapshot(auction, 'open-bidding');
|
|
auction.phase = 'bidding';
|
|
auction.currentBid = 0;
|
|
auction.currentBidderTeamIndex = undefined;
|
|
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
|
|
await auction.save();
|
|
return auction;
|
|
}
|
|
|
|
public async placeBid(params: PlaceBidParams): Promise<AuctionStateResponse> {
|
|
this.assertValidBidPointAmount(params.amount);
|
|
const auction = await this.getByMatchId(params.matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.placeRedisBid(auction, params);
|
|
}
|
|
if (auction.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
const team = this.findAuctionTeamByIndex(auction, params.teamIndex);
|
|
if (!team) throw new BadRequestException('Unknown team.');
|
|
if (params.amount <= auction.currentBid) {
|
|
throw new BadRequestException('Bid must exceed current bid.');
|
|
}
|
|
if (params.amount > team.points) {
|
|
throw new BadRequestException('Bid exceeds team points.');
|
|
}
|
|
this.assertTeamHasSlot(team);
|
|
if (params.amount > this.calculateMaxBidForTeam(team)) {
|
|
throw new BadRequestException(
|
|
'Bid must reserve minimum points for remaining slots.',
|
|
);
|
|
}
|
|
// 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다.
|
|
|
|
await this.recordSnapshot(auction, 'bid', params.bidderUserId);
|
|
auction.currentBid = params.amount;
|
|
auction.currentBidderTeamIndex = params.teamIndex;
|
|
auction.currentDeadline = this.createDeadline(
|
|
this.resolveBidExtensionSeconds(auction),
|
|
);
|
|
auction.bids.push({
|
|
teamIndex: params.teamIndex,
|
|
amount: params.amount,
|
|
bidderUserId: team.captainUserId,
|
|
timestamp: new Date(),
|
|
});
|
|
await auction.save();
|
|
return auction;
|
|
}
|
|
|
|
public async placeBidDelta(
|
|
params: PlaceBidParams,
|
|
): Promise<AuctionBidDeltaResponse | AuctionStateResponse> {
|
|
this.assertValidBidPointAmount(params.amount);
|
|
const redisBidDelta =
|
|
await this.tryPlaceRedisBidDeltaFromRealtimeState(params);
|
|
if (redisBidDelta) return redisBidDelta;
|
|
|
|
const auction = await this.getByMatchId(params.matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.placeRedisBidDelta(auction, params);
|
|
}
|
|
return this.placeBid(params);
|
|
}
|
|
|
|
private async openRedisBidding(
|
|
auction: AuctionDocument,
|
|
actionRequestParams: AuctionStructureActionRequestParams,
|
|
): Promise<AuctionStateResponse> {
|
|
const matchId = auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
if (state.phase !== 'presenting') {
|
|
throw new BadRequestException('Auction is not in presenting phase.');
|
|
}
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action: 'open-bidding',
|
|
matchId,
|
|
params: actionRequestParams,
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const liveStatePatch = {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
phase: 'bidding',
|
|
};
|
|
return this.applyRedisStructureTransition({
|
|
action: 'open-bidding',
|
|
actionRequest,
|
|
auction,
|
|
deadline: {
|
|
durationSeconds: structureInput.maximumBidRoundDurationSeconds,
|
|
mode: 'set-relative',
|
|
},
|
|
expectedPhase: 'presenting',
|
|
liveStatePatch,
|
|
shouldBroadcastStateAfterDurability:
|
|
actionRequestParams.shouldBroadcastStateAfterDurability,
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private async placeRedisBid(
|
|
auction: AuctionDocument,
|
|
params: PlaceBidParams,
|
|
): Promise<AuctionStateResponse> {
|
|
const matchId = auction.matchId.toString();
|
|
await this.executeRedisBid(auction, params);
|
|
return this.requireRedisAuctionState(matchId);
|
|
}
|
|
|
|
private async placeRedisBidDelta(
|
|
auction: AuctionDocument,
|
|
params: PlaceBidParams,
|
|
): Promise<AuctionBidDeltaResponse> {
|
|
const serviceStartedAtMS = performance.now();
|
|
const { redisBidCommandDurationMS, result, state } =
|
|
await this.executeRedisBid(auction, params);
|
|
const bidDelta = this.buildBidDeltaFromRedisBidResult(state, result);
|
|
bidDelta.bidServerTiming = this.roundBidServerTiming({
|
|
fallbackFullStatePath: true,
|
|
redisBidCommandDurationMS,
|
|
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
|
});
|
|
this.logSlowBidTiming(auction.matchId.toString(), bidDelta.bidServerTiming);
|
|
return bidDelta;
|
|
}
|
|
|
|
private async tryPlaceRedisBidDeltaFromRealtimeState(
|
|
params: PlaceBidParams,
|
|
): Promise<AuctionBidDeltaResponse | null> {
|
|
const serviceStartedAtMS = performance.now();
|
|
const matchId = params.matchId.toString();
|
|
const bidContextReadStartedAtMS = performance.now();
|
|
const bidContext = await this.auctionRedisStateReaderService.readBidContext(
|
|
matchId,
|
|
params.teamIndex,
|
|
);
|
|
const redisBidContextReadDurationMS =
|
|
performance.now() - bidContextReadStartedAtMS;
|
|
if (!bidContext) return null;
|
|
if (bidContext.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
if (!bidContext.bidderTeamCaptainUserId) {
|
|
throw new BadRequestException('Unknown team.');
|
|
}
|
|
|
|
const auctionLifecycleId =
|
|
params.clientObservedAuctionLifecycleId ?? bidContext.auctionLifecycleId;
|
|
const currentBidRoundPlayerUserId =
|
|
params.clientObservedCurrentBidRoundPlayerUserId ??
|
|
bidContext.currentBidRoundPlayerUserId;
|
|
if (!auctionLifecycleId || !currentBidRoundPlayerUserId) {
|
|
throw new BadRequestException('Current bid round is not available.');
|
|
}
|
|
|
|
const redisBidCommandStartedAtMS = performance.now();
|
|
const result = await this.auctionRedisCommandService.placeBid(matchId, {
|
|
bidPointAmount: params.amount,
|
|
bidderTeamIndex: params.teamIndex,
|
|
bidderUserId: bidContext.bidderTeamCaptainUserId,
|
|
bidRequestId: params.bidRequestId ?? randomUUID(),
|
|
clientObservedBidRoundId: params.clientObservedBidRoundId,
|
|
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
|
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
|
matchId,
|
|
maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE,
|
|
maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT,
|
|
maximumStoredBidRequestResultCount:
|
|
AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT,
|
|
minimumBidPointReservePerRemainingAuctionTeamMemberSlot:
|
|
AUCTION_MIN_BID_POINTS,
|
|
minimumBidRequestResultReplayWindowMS:
|
|
AUCTION_BID_REQUEST_REPLAY_WINDOW_MS,
|
|
});
|
|
const redisBidCommandDurationMS =
|
|
performance.now() - redisBidCommandStartedAtMS;
|
|
if ('rejected' in result) {
|
|
const bidServerTiming = this.roundBidServerTiming({
|
|
redisBidCommandDurationMS,
|
|
redisBidContextReadDurationMS,
|
|
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
|
});
|
|
this.logSlowBidTiming(matchId, bidServerTiming);
|
|
throw this.createRedisBidRejectedException(result, bidServerTiming);
|
|
}
|
|
|
|
const bidDelta = this.buildBidDeltaFromRedisBidResult(
|
|
{ auctionLifecycleId: bidContext.auctionLifecycleId },
|
|
result,
|
|
);
|
|
bidDelta.bidServerTiming = this.roundBidServerTiming({
|
|
redisBidCommandDurationMS,
|
|
redisBidContextReadDurationMS,
|
|
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
|
});
|
|
this.logSlowBidTiming(matchId, bidDelta.bidServerTiming);
|
|
return bidDelta;
|
|
}
|
|
|
|
private async executeRedisBid(
|
|
auction: AuctionDocument,
|
|
params: PlaceBidParams,
|
|
): Promise<{
|
|
redisBidCommandDurationMS: number;
|
|
result: Extract<AuctionBidCommandResult, { ok: true }>;
|
|
state: Record<string, unknown>;
|
|
}> {
|
|
const serviceStartedAtMS = performance.now();
|
|
const matchId = auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
if (state.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
|
|
const auctionTeams = this.arrayFromState<Record<string, unknown>>(
|
|
state.auctionTeams,
|
|
);
|
|
const team = auctionTeams.find(
|
|
(entry) => Number(entry.teamIndex) === params.teamIndex,
|
|
);
|
|
if (!team) throw new BadRequestException('Unknown team.');
|
|
|
|
const auctionLifecycleId =
|
|
params.clientObservedAuctionLifecycleId ??
|
|
this.stringFromState(state.auctionLifecycleId);
|
|
const currentBidRoundPlayerUserId =
|
|
params.clientObservedCurrentBidRoundPlayerUserId ??
|
|
this.stringFromState(state.currentBidRoundPlayerUserId);
|
|
if (!auctionLifecycleId || !currentBidRoundPlayerUserId) {
|
|
throw new BadRequestException('Current bid round is not available.');
|
|
}
|
|
|
|
const redisBidCommandStartedAtMS = performance.now();
|
|
const result = await this.auctionRedisCommandService.placeBid(matchId, {
|
|
bidPointAmount: params.amount,
|
|
bidderTeamIndex: params.teamIndex,
|
|
bidderUserId: this.stringFromState(team.captainUserId),
|
|
bidRequestId: params.bidRequestId ?? randomUUID(),
|
|
clientObservedBidRoundId: params.clientObservedBidRoundId,
|
|
clientObservedAuctionLifecycleId: auctionLifecycleId,
|
|
clientObservedCurrentBidRoundPlayerUserId: currentBidRoundPlayerUserId,
|
|
matchId,
|
|
maximumAuctionTeamMemberCount: AUCTION_MAX_TEAM_SIZE,
|
|
maximumStoredAuctionBidHistoryCount: AUCTION_MAX_STORED_BID_HISTORY_COUNT,
|
|
maximumStoredBidRequestResultCount:
|
|
AUCTION_MAX_STORED_BID_REQUEST_RESULT_COUNT,
|
|
minimumBidPointReservePerRemainingAuctionTeamMemberSlot:
|
|
AUCTION_MIN_BID_POINTS,
|
|
minimumBidRequestResultReplayWindowMS:
|
|
AUCTION_BID_REQUEST_REPLAY_WINDOW_MS,
|
|
});
|
|
const redisBidCommandDurationMS =
|
|
performance.now() - redisBidCommandStartedAtMS;
|
|
if ('rejected' in result) {
|
|
const bidServerTiming = this.roundBidServerTiming({
|
|
fallbackFullStatePath: true,
|
|
redisBidCommandDurationMS,
|
|
serviceTotalDurationMS: performance.now() - serviceStartedAtMS,
|
|
});
|
|
this.logSlowBidTiming(matchId, bidServerTiming);
|
|
throw this.createRedisBidRejectedException(result, bidServerTiming);
|
|
}
|
|
|
|
return { redisBidCommandDurationMS, result, state };
|
|
}
|
|
|
|
private buildBidDeltaFromRedisBidResult(
|
|
state: Record<string, unknown>,
|
|
result: Extract<AuctionBidCommandResult, { ok: true }>,
|
|
): AuctionBidDeltaResponse {
|
|
return {
|
|
auctionBidHistoryEntry: result.auctionBidHistoryEntry,
|
|
currentBidRoundId:
|
|
typeof result.auctionBidHistoryEntry.bidRoundId === 'string'
|
|
? result.auctionBidHistoryEntry.bidRoundId
|
|
: undefined,
|
|
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
|
bidRequestId: result.bidRequestId,
|
|
currentBidRoundDeadlineTimestampMS:
|
|
result.currentBidRoundDeadlineTimestampMS,
|
|
currentHighestBidderTeamIndex: result.currentHighestBidderTeamIndex,
|
|
currentHighestBidPointAmount: result.currentHighestBidPointAmount,
|
|
currentServerTimestampMS: result.currentServerTimestampMS,
|
|
revision: result.revision,
|
|
};
|
|
}
|
|
|
|
private async markRedisSold(
|
|
auction: AuctionDocument,
|
|
params: MarkSoldParams,
|
|
): Promise<AuctionStateResponse> {
|
|
const matchId = auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
if (state.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
|
|
const currentBidPointAmount = this.numberFromState(
|
|
state.currentHighestBidPointAmount,
|
|
);
|
|
const winningTeamIndex = this.numberFromState(
|
|
state.currentHighestBidderTeamIndex,
|
|
-1,
|
|
);
|
|
if (winningTeamIndex < 1 || currentBidPointAmount <= 0) {
|
|
throw new BadRequestException('No bid to mark sold.');
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const currentPlayer =
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
];
|
|
if (!currentPlayer) throw new BadRequestException('No current player.');
|
|
|
|
const team = structureInput.auctionTeams.find(
|
|
(entry) => Number(entry.teamIndex) === winningTeamIndex,
|
|
);
|
|
if (!team) throw new BadRequestException('Winning team not found.');
|
|
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action: 'sold',
|
|
matchId,
|
|
params,
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
// [AUCTION-DEBUG] 중복 멤버 버그 스모킹건: 낙찰 직전, 이 선수가 이미 어느 팀에
|
|
// 들어있는지. (markRedisSold는 검사 없이 append하므로 true면 그대로 중복) — 제거 대상
|
|
const soldUserId = String(currentPlayer.userId);
|
|
const existingTeamIndex = structureInput.auctionTeams.find((entry) =>
|
|
(entry.members ?? []).some(
|
|
(member) => String(member.userId) === soldUserId,
|
|
),
|
|
)?.teamIndex;
|
|
recordNewRelicCustomEvent('AuctionServerSold', {
|
|
matchId,
|
|
auctionActionRequestId: params.auctionActionRequestId ?? null,
|
|
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
|
revision: this.numberFromState(state.revision),
|
|
currentAuctionPlayerOrderIndex:
|
|
structureInput.currentAuctionPlayerOrderIndex,
|
|
soldUserId,
|
|
winningTeamIndex,
|
|
currentBidPointAmount,
|
|
playerAlreadyInTeam: existingTeamIndex !== undefined,
|
|
existingTeamIndex:
|
|
existingTeamIndex !== undefined ? Number(existingTeamIndex) : -1,
|
|
totalAssignedMemberCount: structureInput.auctionTeams.reduce(
|
|
(sum, entry) => sum + (entry.members?.length ?? 0),
|
|
0,
|
|
),
|
|
});
|
|
|
|
const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position;
|
|
team.members = [
|
|
...(team.members ?? []),
|
|
{
|
|
userId: currentPlayer.userId,
|
|
assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID',
|
|
memberAcquisitionBidPointAmount: currentBidPointAmount,
|
|
},
|
|
];
|
|
team.remainingBidPointAmount =
|
|
Number(team.remainingBidPointAmount ?? 0) - currentBidPointAmount;
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'sold',
|
|
actionRequest,
|
|
auction,
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: 'bidding',
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
phase: 'sold',
|
|
},
|
|
shouldBroadcastStateAfterDurability:
|
|
params.shouldBroadcastStateAfterDurability,
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private async markRedisPassed(
|
|
auction: AuctionDocument,
|
|
actionRequestParams: AuctionStructureActionRequestParams,
|
|
): Promise<AuctionStateResponse> {
|
|
const matchId = auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
if (state.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
if (this.numberFromState(state.currentHighestBidPointAmount) > 0) {
|
|
throw new BadRequestException('Cannot pass a player with an active bid.');
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const currentPlayer =
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
];
|
|
if (!currentPlayer) throw new BadRequestException('No current player.');
|
|
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action: 'passed',
|
|
matchId,
|
|
params: actionRequestParams,
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
const passedPlayer: AuctionPlayerSnapshot = {
|
|
...this.cloneAuctionPlayerSnapshot(currentPlayer),
|
|
passCount: this.numberFromState(currentPlayer.passCount) + 1,
|
|
};
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
] = passedPlayer;
|
|
structureInput.passedAuctionPlayerQueue = [
|
|
...structureInput.passedAuctionPlayerQueue,
|
|
passedPlayer,
|
|
];
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'passed',
|
|
actionRequest,
|
|
auction,
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: 'bidding',
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
phase: 'passed',
|
|
},
|
|
shouldBroadcastStateAfterDurability:
|
|
actionRequestParams.shouldBroadcastStateAfterDurability,
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private async completeRedisExpirySold(
|
|
auction: AuctionDocument,
|
|
state: Record<string, unknown>,
|
|
): Promise<AuctionStateResponse> {
|
|
const currentBidPointAmount = this.numberFromState(
|
|
state.bidRoundExpiryWinningBidPointAmount,
|
|
);
|
|
const winningTeamIndex = this.numberFromState(
|
|
state.bidRoundExpiryWinningBidderTeamIndex,
|
|
-1,
|
|
);
|
|
if (winningTeamIndex < 1 || currentBidPointAmount <= 0) {
|
|
throw new BadRequestException('Prepared expiry has no winning bid.');
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const currentPlayer =
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
];
|
|
if (!currentPlayer) throw new BadRequestException('No current player.');
|
|
|
|
const team = structureInput.auctionTeams.find(
|
|
(entry) => Number(entry.teamIndex) === winningTeamIndex,
|
|
);
|
|
if (!team) throw new BadRequestException('Winning team not found.');
|
|
|
|
const preferredPrimary = currentPlayer.preferredPositions?.[0]?.position;
|
|
team.members = [
|
|
...(team.members ?? []),
|
|
{
|
|
userId: currentPlayer.userId,
|
|
assignedPosition: preferredPrimary ?? 'MID',
|
|
memberAcquisitionBidPointAmount: currentBidPointAmount,
|
|
},
|
|
];
|
|
team.remainingBidPointAmount =
|
|
Number(team.remainingBidPointAmount ?? 0) - currentBidPointAmount;
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'sold',
|
|
auction,
|
|
auctionStateTransitionId: this.stringFromState(
|
|
state.bidRoundExpiryAuctionStateTransitionId,
|
|
),
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: 'expiring',
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
phase: 'sold',
|
|
},
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private async completeRedisExpiryPassed(
|
|
auction: AuctionDocument,
|
|
state: Record<string, unknown>,
|
|
): Promise<AuctionStateResponse> {
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const currentPlayer =
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
];
|
|
if (!currentPlayer) throw new BadRequestException('No current player.');
|
|
|
|
const passedPlayer: AuctionPlayerSnapshot = {
|
|
...this.cloneAuctionPlayerSnapshot(currentPlayer),
|
|
passCount: this.numberFromState(currentPlayer.passCount) + 1,
|
|
};
|
|
structureInput.auctionPlayerOrder[
|
|
structureInput.currentAuctionPlayerOrderIndex
|
|
] = passedPlayer;
|
|
structureInput.passedAuctionPlayerQueue = [
|
|
...structureInput.passedAuctionPlayerQueue,
|
|
passedPlayer,
|
|
];
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'passed',
|
|
auction,
|
|
auctionStateTransitionId: this.stringFromState(
|
|
state.bidRoundExpiryAuctionStateTransitionId,
|
|
),
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: 'expiring',
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
phase: 'passed',
|
|
},
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private async advanceRedisAuction(
|
|
auction: AuctionDocument,
|
|
actionRequestParams: AuctionStructureActionRequestParams,
|
|
): Promise<AuctionStateResponse> {
|
|
const matchId = auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
if (state.phase !== 'sold' && state.phase !== 'passed') {
|
|
throw new BadRequestException('Cannot advance from current phase.');
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const nextIndex = structureInput.currentAuctionPlayerOrderIndex + 1;
|
|
let action: AuctionActionType = 'next';
|
|
let nextPhase = 'presenting';
|
|
|
|
if (nextIndex >= structureInput.auctionPlayerOrder.length) {
|
|
if (structureInput.passedAuctionPlayerQueue.length > 0) {
|
|
structureInput.auctionPlayerOrder = [
|
|
...structureInput.auctionPlayerOrder,
|
|
...structureInput.passedAuctionPlayerQueue.map((player) =>
|
|
this.cloneAuctionPlayerSnapshot(player),
|
|
),
|
|
];
|
|
structureInput.passedAuctionPlayerQueue = [];
|
|
structureInput.currentAuctionRound += 1;
|
|
structureInput.currentAuctionPlayerOrderIndex = nextIndex;
|
|
} else {
|
|
await this.assertCompleteAuctionRoster(
|
|
auction.matchId,
|
|
structureInput.auctionTeams,
|
|
);
|
|
action = 'complete';
|
|
nextPhase = 'complete';
|
|
}
|
|
} else {
|
|
structureInput.currentAuctionPlayerOrderIndex = nextIndex;
|
|
}
|
|
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action,
|
|
matchId,
|
|
params: actionRequestParams,
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
const completionTimestampMS =
|
|
action === 'complete'
|
|
? await this.auctionRedisService.getCurrentRedisTimestampMS()
|
|
: undefined;
|
|
return this.applyRedisStructureTransition({
|
|
action,
|
|
actionRequest,
|
|
auction,
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: String(state.phase),
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
auctionCompletedAtTimestampMS: completionTimestampMS,
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
phase: nextPhase,
|
|
},
|
|
shouldBroadcastStateAfterDurability:
|
|
actionRequestParams.shouldBroadcastStateAfterDurability,
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
public async markSold(params: MarkSoldParams): Promise<AuctionStateResponse> {
|
|
const auction = await this.getByMatchId(params.matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.markRedisSold(auction, params);
|
|
}
|
|
if (auction.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
if (!auction.currentBidderTeamIndex || auction.currentBid <= 0) {
|
|
throw new BadRequestException('No bid to mark sold.');
|
|
}
|
|
const team = this.findAuctionTeamByIndex(
|
|
auction,
|
|
auction.currentBidderTeamIndex,
|
|
);
|
|
if (!team) throw new BadRequestException('Winning team not found.');
|
|
this.assertTeamHasSlot(team);
|
|
|
|
const current = auction.order[auction.currentIndex];
|
|
if (!current) throw new BadRequestException('No current player.');
|
|
|
|
await this.recordSnapshot(auction, 'sold');
|
|
const preferredPrimary = current.preferredPositions[0]?.position;
|
|
team.members.push({
|
|
userId: current.userId,
|
|
assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID',
|
|
cost: auction.currentBid,
|
|
});
|
|
team.points -= auction.currentBid;
|
|
auction.phase = 'sold';
|
|
auction.currentDeadline = undefined;
|
|
await auction.save();
|
|
return auction;
|
|
}
|
|
|
|
public async markPassed(
|
|
matchId: mongoose.Types.ObjectId,
|
|
actionRequest: AuctionStructureActionRequestParams = {},
|
|
): Promise<AuctionStateResponse> {
|
|
const auction = await this.getByMatchId(matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.markRedisPassed(auction, actionRequest);
|
|
}
|
|
if (auction.phase !== 'bidding') {
|
|
throw new BadRequestException('Auction is not in bidding phase.');
|
|
}
|
|
if (auction.currentBid > 0) {
|
|
throw new BadRequestException('Cannot pass a player with an active bid.');
|
|
}
|
|
const current = auction.order[auction.currentIndex];
|
|
if (!current) throw new BadRequestException('No current player.');
|
|
|
|
await this.recordSnapshot(auction, 'passed');
|
|
current.passCount = (current.passCount ?? 0) + 1;
|
|
auction.passedQueue ??= [];
|
|
auction.passedQueue.push(this.cloneAuctionPlayerSnapshot(current));
|
|
auction.phase = 'passed';
|
|
auction.currentDeadline = undefined;
|
|
await auction.save();
|
|
return auction;
|
|
}
|
|
|
|
public async next(
|
|
matchId: mongoose.Types.ObjectId,
|
|
actionRequest: AuctionStructureActionRequestParams = {},
|
|
): Promise<AuctionStateResponse> {
|
|
const auction = await this.getByMatchId(matchId);
|
|
this.assertLiveAuctionOperationSupported(auction);
|
|
if (this.isRedisV1Auction(auction)) {
|
|
return this.advanceRedisAuction(auction, actionRequest);
|
|
}
|
|
if (auction.phase !== 'sold' && auction.phase !== 'passed') {
|
|
throw new BadRequestException('Cannot advance from current phase.');
|
|
}
|
|
const nextIndex = auction.currentIndex + 1;
|
|
const completesAuction =
|
|
nextIndex >= auction.order.length &&
|
|
(auction.passedQueue?.length ?? 0) === 0;
|
|
if (completesAuction) {
|
|
await this.assertCompleteAuctionRoster(matchId, auction.teams);
|
|
}
|
|
await this.recordSnapshot(auction, completesAuction ? 'complete' : 'next');
|
|
if (nextIndex >= auction.order.length) {
|
|
if ((auction.passedQueue?.length ?? 0) > 0) {
|
|
auction.order.push(
|
|
...auction.passedQueue.map((player) =>
|
|
this.cloneAuctionPlayerSnapshot(player),
|
|
),
|
|
);
|
|
auction.passedQueue = [];
|
|
auction.auctionRound = (auction.auctionRound ?? 1) + 1;
|
|
auction.currentIndex = nextIndex;
|
|
auction.phase = 'presenting';
|
|
auction.currentBid = 0;
|
|
auction.currentBidderTeamIndex = undefined;
|
|
} else {
|
|
auction.phase = 'complete';
|
|
auction.completedAt = new Date();
|
|
}
|
|
} else {
|
|
auction.currentIndex = nextIndex;
|
|
auction.phase = 'presenting';
|
|
auction.currentBid = 0;
|
|
auction.currentBidderTeamIndex = undefined;
|
|
}
|
|
auction.currentDeadline = undefined;
|
|
await auction.save();
|
|
if (auction.phase === 'complete') {
|
|
await this.syncMatchTeamsFromAuction(auction);
|
|
}
|
|
return auction;
|
|
}
|
|
|
|
public async completePreparedExpiry(
|
|
matchId: mongoose.Types.ObjectId,
|
|
): Promise<AuctionStateResponse | null> {
|
|
const auction = await this.getByMatchId(matchId);
|
|
if (!this.isRedisV1Auction(auction)) return null;
|
|
|
|
const state =
|
|
await this.auctionRedisStateReaderService.readAuctionStateView(
|
|
matchId.toString(),
|
|
{ includeInternalLiveStateFields: true },
|
|
);
|
|
if (!state || state.redisInternalPhase !== 'expiring') return null;
|
|
|
|
const decision = this.stringFromState(state.bidRoundExpiryDecision);
|
|
if (decision === 'sold') {
|
|
return this.completeRedisExpirySold(auction, state);
|
|
}
|
|
if (decision === 'passed') {
|
|
return this.completeRedisExpiryPassed(auction, state);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
public async reset(params: {
|
|
auctionActionRequestId?: string;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentAuctionPlayerOrderIndex?: number;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
clientObservedPhase?: string;
|
|
clientObservedRevision?: number;
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
}): Promise<void> {
|
|
let committed = false;
|
|
try {
|
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
params.matchId.toString(),
|
|
() =>
|
|
this.resetLocked(params, () => {
|
|
committed = true;
|
|
}),
|
|
);
|
|
} catch (error) {
|
|
if (!committed) throw error;
|
|
// A committed cancellation is successful even if lock renewal/teardown
|
|
// fails afterward. Cleanup is durably queued in the same Mongo transaction.
|
|
this.logger.warn(
|
|
`Auction cancellation committed; post-commit coordination failed: ${String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
private async resetLocked(
|
|
params: {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedRevision?: number;
|
|
},
|
|
onCommitted: () => void,
|
|
): Promise<void> {
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
const AuctionHistoryModel =
|
|
await this.connectionService.getModel('auctionHistory');
|
|
const AuctionSideEffectApplicationModel =
|
|
await this.connectionService.getModel('auctionSideEffectApplication');
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
|
|
const session = await this.connectionService.createSession();
|
|
if (!session) {
|
|
throw new InternalServerErrorException('Failed to start DB session.');
|
|
}
|
|
try {
|
|
session.startTransaction();
|
|
const auction = await AuctionModel.findOne({
|
|
matchId: params.matchId,
|
|
}).session(session);
|
|
if (!auction) {
|
|
// 이미 커밋된 취소의 재전송이면 성공으로 응답하고 남은 Redis 정리만 재시도한다.
|
|
const cancelledMatch = params.clientObservedAuctionLifecycleId
|
|
? await MatchModel.findById(params.matchId).session(session)
|
|
: null;
|
|
if (
|
|
!cancelledMatch ||
|
|
cancelledMatch.lastCancelledAuctionLifecycleId !==
|
|
params.clientObservedAuctionLifecycleId
|
|
) {
|
|
throw new NotFoundException('Auction not found.');
|
|
}
|
|
if (!cancelledMatch.communityId.equals(params.communityId)) {
|
|
throw new BadRequestException('Community mismatch.');
|
|
}
|
|
cancelledMatch.auctionCancellationCleanupPending = true;
|
|
cancelledMatch.auctionCancellationCleanupRetryAt = new Date();
|
|
await cancelledMatch.save({ session });
|
|
} else {
|
|
if (
|
|
this.isRedisV1Auction(auction) &&
|
|
(!params.clientObservedAuctionLifecycleId ||
|
|
params.clientObservedAuctionLifecycleId !==
|
|
auction.auctionLifecycleId)
|
|
) {
|
|
throw new ConflictException(
|
|
'Auction lifecycle has changed. Refresh before cancelling.',
|
|
);
|
|
}
|
|
|
|
const match = await MatchModel.findById(params.matchId).session(
|
|
session,
|
|
);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!match.communityId.equals(params.communityId)) {
|
|
throw new BadRequestException('Community mismatch.');
|
|
}
|
|
this.assertCompetitionLifecycleMutable(match, 'reset the auction');
|
|
|
|
if (this.isRedisV1Auction(auction)) {
|
|
// 같은 트랜잭션에서 취소 완료를 기록해, 재전송을 멱등 처리한다.
|
|
match.lastCancelledAuctionLifecycleId = auction.auctionLifecycleId;
|
|
match.auctionCancellationCleanupPending = true;
|
|
match.auctionCancellationCleanupRetryAt = new Date();
|
|
match.auctionCancellationCleanupAttempts = 0;
|
|
match.auctionCancellationCleanupError = undefined;
|
|
await this.resetMatchAfterAuctionCancellation(match, session);
|
|
await AuctionSideEffectApplicationModel.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);
|
|
if (match.status === 'team-built') {
|
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
|
match.status = 'recruiting';
|
|
match.teams = [];
|
|
match.tournamentCodeIds = [];
|
|
match.gameSchedule = [];
|
|
match.participants.forEach((participant) => {
|
|
participant.excluded = false;
|
|
});
|
|
match.teamBuiltAt = undefined;
|
|
match.result = undefined;
|
|
match.resultPollState = undefined;
|
|
await match.save({ session });
|
|
}
|
|
}
|
|
}
|
|
await session.commitTransaction();
|
|
onCommitted();
|
|
} catch (err) {
|
|
await session.abortTransaction();
|
|
throw err;
|
|
} finally {
|
|
await session.endSession();
|
|
}
|
|
}
|
|
|
|
public async retryPendingCancellations(batchLimit = 20): Promise<void> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const pending = await MatchModel.find({
|
|
auctionCancellationCleanupPending: true,
|
|
auctionCancellationCleanupRetryAt: { $lte: new Date() },
|
|
})
|
|
.sort({ auctionCancellationCleanupRetryAt: 1 })
|
|
.limit(batchLimit)
|
|
.lean()
|
|
.exec();
|
|
for (const match of pending) {
|
|
const lifecycle = match.lastCancelledAuctionLifecycleId;
|
|
if (!lifecycle) continue;
|
|
const filter = {
|
|
_id: match._id,
|
|
lastCancelledAuctionLifecycleId: lifecycle,
|
|
};
|
|
try {
|
|
await new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
match._id.toString(),
|
|
async () => {
|
|
// Compare-and-delete in Redis also protects a newly started lifecycle.
|
|
await this.clearRedisAuctionRuntimeForLifecycle(
|
|
match._id.toString(),
|
|
lifecycle,
|
|
);
|
|
const AuctionModel =
|
|
await this.connectionService.getModel('auction');
|
|
if (!(await AuctionModel.exists({ matchId: match._id }))) {
|
|
this.auctionEventBusService?.broadcastReset(
|
|
match._id.toString(),
|
|
lifecycle,
|
|
);
|
|
}
|
|
await MatchModel.updateOne(filter, {
|
|
$set: { auctionCancellationCleanupPending: false },
|
|
$unset: {
|
|
auctionCancellationCleanupRetryAt: '',
|
|
auctionCancellationCleanupError: '',
|
|
},
|
|
});
|
|
},
|
|
);
|
|
} catch (error) {
|
|
const attempts = (match.auctionCancellationCleanupAttempts ?? 0) + 1;
|
|
await MatchModel.updateOne(filter, {
|
|
$set: {
|
|
auctionCancellationCleanupPending: true,
|
|
auctionCancellationCleanupRetryAt: new Date(
|
|
Date.now() + Math.min(60000, 1000 * 2 ** Math.min(attempts, 6)),
|
|
),
|
|
auctionCancellationCleanupError: String(error).slice(0, 2000),
|
|
},
|
|
$inc: { auctionCancellationCleanupAttempts: 1 },
|
|
});
|
|
this.logger.warn(
|
|
`Auction cancellation cleanup will retry for ${match._id.toString()}: ${String(error)}`,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
public async undoTo(params: {
|
|
auctionActionRequestId?: string;
|
|
clientObservedAuctionLifecycleId?: string;
|
|
clientObservedCurrentAuctionPlayerOrderIndex?: number;
|
|
clientObservedCurrentBidRoundPlayerUserId?: string;
|
|
clientObservedPhase?: string;
|
|
clientObservedRevision?: number;
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
sequence: number;
|
|
}): Promise<AuctionStateResponse> {
|
|
return new AuctionLifecycleLock(this.auctionRedisService).run(
|
|
params.matchId.toString(),
|
|
() => this.undoToLocked(params),
|
|
);
|
|
}
|
|
|
|
private async undoToLocked(
|
|
params: AuctionStructureActionRequestParams & {
|
|
matchId: mongoose.Types.ObjectId;
|
|
communityId: mongoose.Types.ObjectId;
|
|
sequence: number;
|
|
},
|
|
): Promise<AuctionStateResponse> {
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
const AuctionHistoryModel =
|
|
await this.connectionService.getModel('auctionHistory');
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
|
|
const session = await this.connectionService.createSession();
|
|
if (!session) {
|
|
throw new InternalServerErrorException('Failed to start DB session.');
|
|
}
|
|
|
|
let redisUndoContext: {
|
|
state?: Record<string, unknown>;
|
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
|
auction: AuctionDocument;
|
|
snapshot: Record<string, unknown>;
|
|
targetHistorySequence: number;
|
|
undoingCompletedAuction: boolean;
|
|
} | null = null;
|
|
let restored: AuctionDocument | null = null;
|
|
|
|
try {
|
|
session.startTransaction();
|
|
const auction = await AuctionModel.findOne({
|
|
matchId: params.matchId,
|
|
}).session(session);
|
|
if (!auction) throw new NotFoundException('Auction not found.');
|
|
|
|
const match = await MatchModel.findById(params.matchId).session(session);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (!match.communityId.equals(params.communityId)) {
|
|
throw new BadRequestException('Community mismatch.');
|
|
}
|
|
|
|
const history = await AuctionHistoryModel.findOne({
|
|
auctionId: auction._id,
|
|
sequence: params.sequence,
|
|
})
|
|
.session(session)
|
|
.lean()
|
|
.exec();
|
|
if (!history) throw new NotFoundException('Auction history not found.');
|
|
|
|
const snapshot = history.snapshotBefore;
|
|
if (!snapshot || typeof snapshot !== 'object') {
|
|
throw new BadRequestException('Auction history snapshot is invalid.');
|
|
}
|
|
|
|
const liveState = this.isRedisV1Auction(auction)
|
|
? await this.requireRedisAuctionState(params.matchId.toString())
|
|
: undefined;
|
|
const undoingCompletedAuction = liveState
|
|
? liveState.phase === 'complete' && snapshot.phase !== 'complete'
|
|
: Boolean(auction.completedAt) && !('completedAt' in snapshot);
|
|
if (undoingCompletedAuction) {
|
|
this.assertCompetitionLifecycleMutable(
|
|
match,
|
|
'undo a completed auction',
|
|
);
|
|
}
|
|
if (this.isRedisV1Auction(auction)) {
|
|
redisUndoContext = {
|
|
state: liveState,
|
|
auction,
|
|
actionRequestParams: params,
|
|
snapshot: snapshot,
|
|
targetHistorySequence: params.sequence,
|
|
undoingCompletedAuction,
|
|
};
|
|
await session.commitTransaction();
|
|
} else {
|
|
if (undoingCompletedAuction) {
|
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
|
await this.tournamentResultService.cancelPolling(match, session);
|
|
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 session.commitTransaction();
|
|
restored = await AuctionModel.findById(auction._id);
|
|
if (!restored) throw new NotFoundException('Auction not found.');
|
|
}
|
|
} catch (err) {
|
|
await session.abortTransaction();
|
|
throw err;
|
|
} finally {
|
|
await session.endSession();
|
|
}
|
|
|
|
if (redisUndoContext) {
|
|
return this.undoRedisAuction(redisUndoContext);
|
|
}
|
|
if (!restored) throw new NotFoundException('Auction not found.');
|
|
return restored;
|
|
}
|
|
|
|
private async requireRedisAuctionState(
|
|
matchId: string,
|
|
): Promise<Record<string, unknown>> {
|
|
const state =
|
|
await this.auctionRedisStateReaderService.readAuctionStateView(matchId);
|
|
if (!state) {
|
|
throw new BadRequestException('Auction realtime state is not available.');
|
|
}
|
|
return state;
|
|
}
|
|
|
|
private async reserveRedisStructureActionRequest(params: {
|
|
action: AuctionActionType;
|
|
matchId: string;
|
|
params: AuctionStructureActionRequestParams;
|
|
state: Record<string, unknown>;
|
|
}): Promise<RedisActionRequestContext> {
|
|
const auctionActionRequestId =
|
|
params.params.auctionActionRequestId ?? randomUUID();
|
|
const expectedAuctionLifecycleId =
|
|
params.params.clientObservedAuctionLifecycleId ??
|
|
this.stringFromState(params.state.auctionLifecycleId);
|
|
const expectedRevision =
|
|
params.params.clientObservedRevision ??
|
|
this.numberFromState(params.state.revision);
|
|
const expectedPhase =
|
|
params.params.clientObservedPhase ??
|
|
this.stringFromState(params.state.phase);
|
|
const expectedCurrentBidRoundPlayerUserId =
|
|
params.params.clientObservedCurrentBidRoundPlayerUserId ??
|
|
this.stringFromState(params.state.currentBidRoundPlayerUserId) ??
|
|
undefined;
|
|
const expectedCurrentAuctionPlayerOrderIndex =
|
|
params.params.clientObservedCurrentAuctionPlayerOrderIndex ??
|
|
this.numberFromState(params.state.currentAuctionPlayerOrderIndex);
|
|
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,
|
|
},
|
|
);
|
|
|
|
if ('rejected' in reserved) {
|
|
throw new BadRequestException(
|
|
`Auction action request was rejected: ${reserved.code}.`,
|
|
);
|
|
}
|
|
if ('isReplay' in reserved) {
|
|
if (reserved.replayStatus === 'applied') {
|
|
return {
|
|
currentServerTimestampMS: reserved.currentServerTimestampMS,
|
|
replay: true,
|
|
requiresRefetch: reserved.requiresRefetch ?? true,
|
|
responseJson: reserved.responseJson,
|
|
revision: reserved.revision,
|
|
};
|
|
}
|
|
throw new BadRequestException(
|
|
`Auction action request was replayed as ${reserved.replayStatus}.`,
|
|
);
|
|
}
|
|
|
|
return {
|
|
actionRequest: {
|
|
observedProcessingLeaseVersion: reserved.observedProcessingLeaseVersion,
|
|
processingOwnerToken,
|
|
scopeKey: reserved.actionRequestScopeKey,
|
|
},
|
|
auctionStateTransitionId: reserved.auctionStateTransitionId,
|
|
expectedAuctionLifecycleId,
|
|
expectedCurrentAuctionPlayerOrderIndex,
|
|
expectedCurrentBidRoundPlayerUserId,
|
|
expectedPhase,
|
|
expectedRevision,
|
|
};
|
|
}
|
|
|
|
private isReplayedRedisActionRequestContext(
|
|
actionRequest: RedisActionRequestContext,
|
|
): actionRequest is ReplayedRedisActionRequestContext {
|
|
return 'replay' in actionRequest;
|
|
}
|
|
|
|
private async resolveReplayedRedisActionRequest(
|
|
matchId: string,
|
|
actionRequest: ReplayedRedisActionRequestContext,
|
|
): Promise<AuctionStateResponse> {
|
|
if (actionRequest.responseJson && !actionRequest.requiresRefetch) {
|
|
try {
|
|
return JSON.parse(actionRequest.responseJson) as Record<
|
|
string,
|
|
unknown
|
|
>;
|
|
} catch {
|
|
// Fall through to a full Redis read if a stored response is malformed.
|
|
}
|
|
}
|
|
return this.requireRedisAuctionState(matchId);
|
|
}
|
|
|
|
private async applyRedisStructureTransition(params: {
|
|
action: AuctionActionType;
|
|
auction: AuctionDocument;
|
|
actionRequest?: ReservedRedisActionRequestContext;
|
|
auctionStateTransitionId?: string;
|
|
deadline:
|
|
| { mode: 'none' }
|
|
| { mode: 'remove' }
|
|
| { durationSeconds: number; mode: 'set-relative' };
|
|
expectedPhase: string;
|
|
historyMutation?: Record<string, unknown>;
|
|
liveStatePatch: Record<
|
|
string,
|
|
string | number | boolean | null | undefined
|
|
>;
|
|
matchSideEffectMutation?: Record<string, unknown>;
|
|
shouldBroadcastStateAfterDurability?: boolean;
|
|
shouldResetBidRuntime?: boolean;
|
|
state: Record<string, unknown>;
|
|
structureInput: Parameters<typeof stringifyAuctionRedisStructureState>[0];
|
|
}): Promise<AuctionStateResponse> {
|
|
const matchId = params.auction.matchId.toString();
|
|
const auctionLifecycleId = this.stringFromState(
|
|
params.state.auctionLifecycleId,
|
|
);
|
|
const expectedRevision =
|
|
params.actionRequest?.expectedRevision ??
|
|
this.numberFromState(params.state.revision);
|
|
const expectedAuctionHistorySequence = this.numberFromState(
|
|
params.state.currentAuctionHistorySequence,
|
|
);
|
|
const auctionHistorySequence = expectedAuctionHistorySequence + 1;
|
|
const auctionStateTransitionId =
|
|
params.actionRequest?.auctionStateTransitionId ||
|
|
params.auctionStateTransitionId ||
|
|
`${params.action}:${auctionLifecycleId}:${randomUUID()}`;
|
|
const afterState = {
|
|
...params.state,
|
|
...buildAuctionRedisStructureState(params.structureInput),
|
|
...params.liveStatePatch,
|
|
currentAuctionHistorySequence: auctionHistorySequence,
|
|
lastAppliedAuctionStateTransitionId: auctionStateTransitionId,
|
|
revision: expectedRevision + 1,
|
|
currentBidRoundId:
|
|
params.deadline.mode === 'set-relative'
|
|
? auctionStateTransitionId
|
|
: params.state.currentBidRoundId,
|
|
currentBidRoundDeadlineTimestampMS:
|
|
params.deadline.mode === 'remove'
|
|
? 0
|
|
: params.state.currentBidRoundDeadlineTimestampMS,
|
|
};
|
|
const afterAuctionMongoProjection =
|
|
this.buildAuctionMongoProjectionFromState(params.auction, afterState);
|
|
const matchSideEffectMutation =
|
|
params.matchSideEffectMutation ??
|
|
(params.action === 'complete'
|
|
? { type: 'syncMatchTeamsAfterComplete' }
|
|
: { type: 'none' });
|
|
if (matchSideEffectMutation.type !== 'none') {
|
|
afterAuctionMongoProjection.matchSideEffectStatus = 'pending';
|
|
afterAuctionMongoProjection.matchSideEffectRevision =
|
|
Math.max(
|
|
params.auction.matchSideEffectRevision ?? 0,
|
|
this.numberFromState(params.state.matchSideEffectRevision),
|
|
) + 1;
|
|
afterAuctionMongoProjection.matchSideEffectError = undefined;
|
|
afterAuctionMongoProjection.matchSideEffectTransitionId =
|
|
auctionStateTransitionId;
|
|
params.liveStatePatch.matchSideEffectTransitionId =
|
|
auctionStateTransitionId;
|
|
params.liveStatePatch.matchSideEffectStatus = 'pending';
|
|
params.liveStatePatch.matchSideEffectRevision =
|
|
afterAuctionMongoProjection.matchSideEffectRevision as number;
|
|
}
|
|
|
|
const durabilityPayload = {
|
|
afterAuctionMongoProjection,
|
|
auctionActionType: params.action,
|
|
auctionHistorySequence,
|
|
auctionId: params.auction._id.toString(),
|
|
auctionLifecycleId,
|
|
auctionStateTransitionId,
|
|
historyMutation: params.historyMutation ?? { type: 'append' },
|
|
matchId,
|
|
matchSideEffectMutation,
|
|
revision: expectedRevision + 1,
|
|
snapshotBefore: this.buildAuctionSnapshotFromRedisState(
|
|
params.auction,
|
|
params.state,
|
|
),
|
|
};
|
|
const result = await this.auctionRedisCommandService.applyTransition(
|
|
matchId,
|
|
{
|
|
afterAuctionStructureStateJson: stringifyAuctionRedisStructureState(
|
|
params.structureInput,
|
|
),
|
|
auctionHistorySequence,
|
|
auctionLifecycleId:
|
|
params.actionRequest?.expectedAuctionLifecycleId ??
|
|
auctionLifecycleId,
|
|
auctionStateTransitionId,
|
|
broadcastStateRevision: expectedRevision + 1,
|
|
deadline: params.deadline,
|
|
durabilityPayloadJson: JSON.stringify(durabilityPayload),
|
|
expectedCurrentAuctionPlayerOrderIndex:
|
|
params.actionRequest?.expectedCurrentAuctionPlayerOrderIndex ??
|
|
params.structureInput.currentAuctionPlayerOrderIndex,
|
|
expectedCurrentBidRoundPlayerUserId:
|
|
params.actionRequest?.expectedCurrentBidRoundPlayerUserId ??
|
|
(params.expectedPhase === 'bidding'
|
|
? this.stringFromState(params.state.currentBidRoundPlayerUserId)
|
|
: undefined),
|
|
expectedAuctionHistorySequence,
|
|
expectedPhase:
|
|
params.actionRequest?.expectedPhase ?? params.expectedPhase,
|
|
expectedRevision,
|
|
liveStatePatch: params.liveStatePatch,
|
|
matchId,
|
|
shouldBroadcastState:
|
|
params.shouldBroadcastStateAfterDurability ?? true,
|
|
shouldResetBidRuntime: params.shouldResetBidRuntime,
|
|
actionRequest: params.actionRequest?.actionRequest,
|
|
},
|
|
);
|
|
// [AUCTION-DEBUG] 제거 대상. 모든 redis 전환(sold/undo/next/open-bidding/complete)의 백본 타임라인.
|
|
// auctionStateTransitionId = `${action}:${lifecycleId}:${auctionActionRequestId}`
|
|
// 라서 클라의 auctionActionRequestId와 조인된다.
|
|
recordNewRelicCustomEvent('AuctionServerTransition', {
|
|
matchId,
|
|
action: params.action,
|
|
auctionStateTransitionId,
|
|
auctionLifecycleId,
|
|
expectedRevision,
|
|
newRevision: 'rejected' in result ? -1 : expectedRevision + 1,
|
|
auctionHistorySequence,
|
|
currentAuctionPlayerOrderIndex:
|
|
params.structureInput.currentAuctionPlayerOrderIndex,
|
|
totalAssignedMemberCount: params.structureInput.auctionTeams.reduce(
|
|
(sum, entry) => sum + (entry.members?.length ?? 0),
|
|
0,
|
|
),
|
|
rejected: 'rejected' in result,
|
|
rejectionCode: 'rejected' in result ? result.code : null,
|
|
});
|
|
|
|
if ('rejected' in result) {
|
|
// 게이트웨이가 설명적 거부코드로 변환할 수 있도록 내부 code(예: CONFLICT)를
|
|
// 구조화해 던진다(message만 던지면 code 자리에 풀 문장이 들어가 매핑이 어렵다).
|
|
throw new BadRequestException({
|
|
code: result.code,
|
|
message: `Auction transition was rejected: ${result.code}.`,
|
|
});
|
|
}
|
|
|
|
return this.requireRedisAuctionState(matchId);
|
|
}
|
|
|
|
private async resetRedisAuction(params: {
|
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
|
auction: AuctionDocument;
|
|
}): Promise<AuctionStateResponse> {
|
|
const matchId = params.auction.matchId.toString();
|
|
const state = await this.requireRedisAuctionState(matchId);
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action: 'reset',
|
|
matchId,
|
|
params: params.actionRequestParams ?? {},
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
const currentStructureInput = this.buildRedisStructureInputFromState(state);
|
|
const resetStructureInput = {
|
|
...currentStructureInput,
|
|
auctionPlayerOrder: [],
|
|
auctionTeams: [],
|
|
currentAuctionPlayerOrderIndex: 0,
|
|
currentAuctionRound: 1,
|
|
passedAuctionPlayerQueue: [],
|
|
};
|
|
const clearedTeamLiveStatePatch: Record<string, number> = {};
|
|
for (const team of this.arrayFromState<Record<string, unknown>>(
|
|
state.auctionTeams,
|
|
)) {
|
|
const teamIndex = this.numberFromState(team.teamIndex);
|
|
if (teamIndex < 1) continue;
|
|
clearedTeamLiveStatePatch[`team:${teamIndex}:remainingBidPointAmount`] =
|
|
0;
|
|
clearedTeamLiveStatePatch[
|
|
`team:${teamIndex}:assignedAuctionTeamMemberCount`
|
|
] = 0;
|
|
}
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'reset',
|
|
actionRequest,
|
|
auction: params.auction,
|
|
deadline: { mode: 'remove' },
|
|
expectedPhase: String(state.phase),
|
|
historyMutation: {
|
|
resetMode: 'clear-history',
|
|
type: 'reset',
|
|
},
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(resetStructureInput),
|
|
...clearedTeamLiveStatePatch,
|
|
auctionCompletedAtTimestampMS: 0,
|
|
currentBidRoundDeadlineTimestampMS: 0,
|
|
currentBidRoundPlayerUserId: '',
|
|
currentHighestBidPointAmount: 0,
|
|
currentHighestBidderTeamIndex: -1,
|
|
matchSideEffectRevision:
|
|
Number(params.auction.matchSideEffectRevision ?? 0) + 1,
|
|
matchSideEffectStatus: 'pending',
|
|
phase: 'waiting',
|
|
},
|
|
matchSideEffectMutation: { type: 'resetMatchAfterAuctionReset' },
|
|
shouldResetBidRuntime: true,
|
|
state,
|
|
structureInput: resetStructureInput,
|
|
});
|
|
}
|
|
|
|
private async undoRedisAuction(params: {
|
|
state?: Record<string, unknown>;
|
|
actionRequestParams?: AuctionStructureActionRequestParams;
|
|
auction: AuctionDocument;
|
|
snapshot: Record<string, unknown>;
|
|
targetHistorySequence: number;
|
|
undoingCompletedAuction: boolean;
|
|
}): Promise<AuctionStateResponse> {
|
|
const matchId = params.auction.matchId.toString();
|
|
const state =
|
|
params.state ?? (await this.requireRedisAuctionState(matchId));
|
|
const actionRequest = await this.reserveRedisStructureActionRequest({
|
|
action: 'undo',
|
|
matchId,
|
|
params: params.actionRequestParams ?? {},
|
|
state,
|
|
});
|
|
if (this.isReplayedRedisActionRequestContext(actionRequest)) {
|
|
return this.resolveReplayedRedisActionRequest(matchId, actionRequest);
|
|
}
|
|
|
|
const structureInput = this.buildRedisStructureInputFromAuctionSnapshot(
|
|
params.snapshot,
|
|
);
|
|
const phase = this.stringFromState(params.snapshot.phase) || 'presenting';
|
|
const currentHighestBidderTeamIndex = this.numberFromState(
|
|
params.snapshot.currentHighestBidderTeamIndex ??
|
|
params.snapshot.currentBidderTeamIndex,
|
|
-1,
|
|
);
|
|
const currentHighestBidPointAmount = this.numberFromState(
|
|
params.snapshot.currentHighestBidPointAmount ??
|
|
params.snapshot.currentBid,
|
|
0,
|
|
);
|
|
|
|
// [AUCTION-DEBUG] 제거 대상. undo가 "어느 시점으로" 복원하는지 + 복원된 팀 구성. 라이브 revision과
|
|
// 복원 스냅샷 revision의 간격(restoredRevisionLag)이 사용자가 본 "2~3 뒤처짐".
|
|
// 이 이벤트 직후의 AuctionServerSold가 playerAlreadyInTeam:true면 "undo가 선수를
|
|
// 안 지운 채 재낙찰 → 중복"이 한 타임라인으로 증명된다.
|
|
const liveRevisionBeforeUndo = this.numberFromState(state.revision);
|
|
const restoredRevision = this.numberFromState(params.snapshot.revision);
|
|
const restoredMemberUserIds = structureInput.auctionTeams.flatMap((entry) =>
|
|
(entry.members ?? []).map((member) => String(member.userId)),
|
|
);
|
|
recordNewRelicCustomEvent('AuctionServerUndo', {
|
|
matchId,
|
|
auctionActionRequestId:
|
|
params.actionRequestParams?.auctionActionRequestId ?? null,
|
|
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
|
targetHistorySequence: params.targetHistorySequence,
|
|
liveRevisionBeforeUndo,
|
|
restoredRevision,
|
|
restoredRevisionLag: liveRevisionBeforeUndo - restoredRevision,
|
|
restoredHistorySequence: this.numberFromState(
|
|
params.snapshot.currentAuctionHistorySequence,
|
|
),
|
|
restoredPhase: phase,
|
|
restoredOrderIndex: structureInput.currentAuctionPlayerOrderIndex,
|
|
restoredAssignedMemberCount: restoredMemberUserIds.length,
|
|
restoredHasDuplicateMember:
|
|
restoredMemberUserIds.length !== new Set(restoredMemberUserIds).size,
|
|
undoingCompletedAuction: params.undoingCompletedAuction,
|
|
});
|
|
|
|
return this.applyRedisStructureTransition({
|
|
action: 'undo',
|
|
actionRequest,
|
|
auction: params.auction,
|
|
deadline:
|
|
phase === 'bidding'
|
|
? {
|
|
durationSeconds: structureInput.maximumBidRoundDurationSeconds,
|
|
mode: 'set-relative',
|
|
}
|
|
: { mode: 'remove' },
|
|
expectedPhase: String(state.phase),
|
|
historyMutation: {
|
|
targetHistorySequence: params.targetHistorySequence,
|
|
type: 'deleteAfterSequenceAndAppendUndo',
|
|
},
|
|
liveStatePatch: {
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
auctionCompletedAtTimestampMS:
|
|
phase === 'complete'
|
|
? this.numberFromState(
|
|
params.snapshot.auctionCompletedAtTimestampMS ??
|
|
params.snapshot.completedAt,
|
|
)
|
|
: 0,
|
|
currentHighestBidPointAmount,
|
|
currentHighestBidderTeamIndex,
|
|
phase,
|
|
},
|
|
matchSideEffectMutation: params.undoingCompletedAuction
|
|
? { type: 'undoCompletedAuctionSideEffects' }
|
|
: { type: 'none' },
|
|
state,
|
|
structureInput,
|
|
});
|
|
}
|
|
|
|
private buildRedisStructureInputFromState(
|
|
state: Record<string, unknown>,
|
|
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
|
return {
|
|
auctionPlayerOrder: this.cloneRedisStructureArray(
|
|
state.auctionPlayerOrder,
|
|
),
|
|
auctionTeams: this.cloneRedisStructureArray(state.auctionTeams),
|
|
bidRoundExtensionSeconds: this.numberFromState(
|
|
state.bidRoundExtensionSeconds,
|
|
5,
|
|
),
|
|
currentAuctionPlayerOrderIndex: this.numberFromState(
|
|
state.currentAuctionPlayerOrderIndex,
|
|
),
|
|
currentAuctionRound: this.numberFromState(state.currentAuctionRound, 1),
|
|
initialTeamBidPointAmount: this.numberFromState(
|
|
state.initialTeamBidPointAmount,
|
|
1000,
|
|
),
|
|
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
|
state.manualTopTierAuctionPriorityUserIds,
|
|
),
|
|
maximumBidRoundDurationSeconds: this.numberFromState(
|
|
state.maximumBidRoundDurationSeconds,
|
|
30,
|
|
),
|
|
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
|
state.passedAuctionPlayerQueue,
|
|
),
|
|
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
|
state.topTierAuctionPriorityThreshold,
|
|
)
|
|
? state.topTierAuctionPriorityThreshold
|
|
: 'NONE',
|
|
};
|
|
}
|
|
|
|
private buildRedisStructureInputFromAuctionSnapshot(
|
|
snapshot: Record<string, unknown>,
|
|
): Parameters<typeof stringifyAuctionRedisStructureState>[0] {
|
|
const legacyTeams = this.cloneRedisStructureArray(snapshot.teams);
|
|
const auctionTeams = this.cloneRedisStructureArray(snapshot.auctionTeams);
|
|
return {
|
|
auctionPlayerOrder: this.cloneRedisStructureArray(
|
|
snapshot.auctionPlayerOrder ?? snapshot.order,
|
|
),
|
|
auctionTeams:
|
|
auctionTeams.length > 0
|
|
? auctionTeams
|
|
: convertLegacyAuctionTeamsToRedisTeams(legacyTeams as never),
|
|
bidRoundExtensionSeconds: this.numberFromState(
|
|
snapshot.bidRoundExtensionSeconds ?? snapshot.bidExtensionSeconds,
|
|
5,
|
|
),
|
|
currentAuctionPlayerOrderIndex: this.numberFromState(
|
|
snapshot.currentAuctionPlayerOrderIndex ?? snapshot.currentIndex,
|
|
),
|
|
currentAuctionRound: this.numberFromState(
|
|
snapshot.currentAuctionRound ?? snapshot.auctionRound,
|
|
1,
|
|
),
|
|
initialTeamBidPointAmount: this.numberFromState(
|
|
snapshot.initialTeamBidPointAmount ?? snapshot.initialPoints,
|
|
1000,
|
|
),
|
|
manualTopTierAuctionPriorityUserIds: this.cloneRedisStructureArray(
|
|
snapshot.manualTopTierAuctionPriorityUserIds ??
|
|
snapshot.manualTopTierUserIds,
|
|
),
|
|
maximumBidRoundDurationSeconds: this.numberFromState(
|
|
snapshot.maximumBidRoundDurationSeconds ?? snapshot.maxTimerSeconds,
|
|
30,
|
|
),
|
|
passedAuctionPlayerQueue: this.cloneRedisStructureArray(
|
|
snapshot.passedAuctionPlayerQueue ?? snapshot.passedQueue,
|
|
),
|
|
topTierAuctionPriorityThreshold: this.isAuctionTopTierThreshold(
|
|
snapshot.topTierAuctionPriorityThreshold ?? snapshot.topTierThreshold,
|
|
)
|
|
? ((snapshot.topTierAuctionPriorityThreshold ??
|
|
snapshot.topTierThreshold) as never)
|
|
: 'NONE',
|
|
};
|
|
}
|
|
|
|
private buildAuctionSnapshotFromRedisState(
|
|
auction: AuctionDocument,
|
|
state: Record<string, unknown>,
|
|
): Record<string, unknown> {
|
|
const base =
|
|
typeof auction.toObject === 'function'
|
|
? (auction.toObject({ depopulate: true }) as Record<string, unknown>)
|
|
: (auction as unknown as Record<string, unknown>);
|
|
const snapshotBase = this.cloneJson(base);
|
|
for (const field of AUCTION_OPTIONAL_PROJECTION_FIELDS)
|
|
delete snapshotBase[field];
|
|
return {
|
|
...snapshotBase,
|
|
...this.buildAuctionMongoProjectionFromState(auction, state),
|
|
_id: auction._id,
|
|
matchId: auction.matchId,
|
|
chatMessages: auction.chatMessages ?? [],
|
|
};
|
|
}
|
|
|
|
private buildAuctionMongoProjectionFromState(
|
|
auction: AuctionDocument,
|
|
state: Record<string, unknown>,
|
|
): Record<string, unknown> {
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const currentHighestBidderTeamIndex = this.numberFromState(
|
|
state.currentHighestBidderTeamIndex,
|
|
-1,
|
|
);
|
|
const currentBidRoundDeadlineTimestampMS = this.numberFromState(
|
|
state.currentBidRoundDeadlineTimestampMS,
|
|
0,
|
|
);
|
|
const auctionBidHistory = this.arrayFromState<Record<string, unknown>>(
|
|
state.auctionBidHistory,
|
|
);
|
|
const phase = this.stringFromState(state.phase) || 'presenting';
|
|
const projection: Record<string, unknown> = {
|
|
currentBidRoundId: state.currentBidRoundId || undefined,
|
|
auctionBidHistory,
|
|
auctionCompletedAtTimestampMS:
|
|
phase === 'complete' &&
|
|
this.numberFromState(state.auctionCompletedAtTimestampMS) > 0
|
|
? this.numberFromState(state.auctionCompletedAtTimestampMS)
|
|
: undefined,
|
|
auctionEngineVersion: 'redis-v1',
|
|
auctionLifecycleId: this.stringFromState(state.auctionLifecycleId),
|
|
auctionPlayerOrder: structureInput.auctionPlayerOrder,
|
|
auctionRound: structureInput.currentAuctionRound,
|
|
auctionTeams: structureInput.auctionTeams,
|
|
bidExtensionSeconds: structureInput.bidRoundExtensionSeconds,
|
|
bidRoundExtensionSeconds: structureInput.bidRoundExtensionSeconds,
|
|
bids: auctionBidHistory.map((bid) => ({
|
|
amount: this.numberFromState(bid.bidPointAmount),
|
|
bidderUserId: bid.bidderUserId,
|
|
teamIndex: this.numberFromState(bid.bidderTeamIndex),
|
|
timestamp: new Date(this.numberFromState(bid.bidPlacedAtTimestampMS)),
|
|
})),
|
|
completedAt:
|
|
phase === 'complete' &&
|
|
this.numberFromState(state.auctionCompletedAtTimestampMS) > 0
|
|
? new Date(this.numberFromState(state.auctionCompletedAtTimestampMS))
|
|
: undefined,
|
|
currentAuctionHistorySequence: this.numberFromState(
|
|
state.currentAuctionHistorySequence,
|
|
),
|
|
currentAuctionPlayerOrderIndex:
|
|
structureInput.currentAuctionPlayerOrderIndex,
|
|
currentAuctionRound: structureInput.currentAuctionRound,
|
|
currentBid: this.numberFromState(state.currentHighestBidPointAmount),
|
|
currentBidRoundDeadlineTimestampMS:
|
|
currentBidRoundDeadlineTimestampMS > 0
|
|
? currentBidRoundDeadlineTimestampMS
|
|
: undefined,
|
|
currentBidderTeamIndex:
|
|
currentHighestBidderTeamIndex > 0
|
|
? currentHighestBidderTeamIndex
|
|
: undefined,
|
|
currentDeadline:
|
|
currentBidRoundDeadlineTimestampMS > 0
|
|
? new Date(currentBidRoundDeadlineTimestampMS)
|
|
: undefined,
|
|
currentHighestBidPointAmount: this.numberFromState(
|
|
state.currentHighestBidPointAmount,
|
|
),
|
|
currentHighestBidderTeamIndex:
|
|
currentHighestBidderTeamIndex > 0
|
|
? currentHighestBidderTeamIndex
|
|
: undefined,
|
|
currentIndex: structureInput.currentAuctionPlayerOrderIndex,
|
|
initialPoints: structureInput.initialTeamBidPointAmount,
|
|
initialTeamBidPointAmount: structureInput.initialTeamBidPointAmount,
|
|
lastAppliedAuctionStateTransitionId: this.stringFromState(
|
|
state.lastAppliedAuctionStateTransitionId,
|
|
),
|
|
manualTopTierAuctionPriorityUserIds:
|
|
structureInput.manualTopTierAuctionPriorityUserIds,
|
|
manualTopTierUserIds: structureInput.manualTopTierAuctionPriorityUserIds,
|
|
matchId: auction.matchId,
|
|
maxTimerSeconds: structureInput.maximumBidRoundDurationSeconds,
|
|
maximumBidRoundDurationSeconds:
|
|
structureInput.maximumBidRoundDurationSeconds,
|
|
order: structureInput.auctionPlayerOrder,
|
|
passedAuctionPlayerQueue: structureInput.passedAuctionPlayerQueue,
|
|
passedQueue: structureInput.passedAuctionPlayerQueue,
|
|
phase,
|
|
revision: this.numberFromState(state.revision),
|
|
teams: this.convertRedisTeamsToLegacyTeams(structureInput.auctionTeams),
|
|
topTierAuctionPriorityThreshold:
|
|
structureInput.topTierAuctionPriorityThreshold,
|
|
topTierThreshold: structureInput.topTierAuctionPriorityThreshold,
|
|
};
|
|
|
|
return this.dropUndefinedProjectionFields(projection);
|
|
}
|
|
|
|
private convertRedisTeamsToLegacyTeams(
|
|
auctionTeams: Parameters<
|
|
typeof stringifyAuctionRedisStructureState
|
|
>[0]['auctionTeams'],
|
|
): AuctionTeam[] {
|
|
return auctionTeams.map((team) => ({
|
|
captainUserId: team.captainUserId,
|
|
members: (team.members ?? []).map((member) => ({
|
|
assignedPosition: member.assignedPosition,
|
|
cost: member.memberAcquisitionBidPointAmount,
|
|
userId: member.userId,
|
|
})),
|
|
points: team.remainingBidPointAmount,
|
|
teamIndex: team.teamIndex,
|
|
}));
|
|
}
|
|
|
|
private dropUndefinedProjectionFields(
|
|
projection: Record<string, unknown>,
|
|
): Record<string, unknown> {
|
|
return Object.fromEntries(
|
|
Object.entries(projection).filter(([, value]) => value !== undefined),
|
|
);
|
|
}
|
|
|
|
private arrayFromState<T = never>(value: unknown): T[] {
|
|
return Array.isArray(value) ? (value as T[]) : [];
|
|
}
|
|
|
|
private cloneRedisStructureArray<T = never>(value: unknown): T[] {
|
|
// 구조 전환 핸들러가 이 작업본을 변이하므로 snapshotBefore 원본과 참조를 공유하면 안 된다.
|
|
// structuredClone은 ObjectId를 [object Object]로 망가뜨리므로, 코드베이스 관행대로
|
|
// JSON 클론으로 깊은 복사 + ObjectId/Date 정규화를 함께 수행한다.
|
|
return this.cloneJson(this.arrayFromState<T>(value));
|
|
}
|
|
|
|
private cloneJson<T>(value: T): T {
|
|
return JSON.parse(JSON.stringify(value)) as T;
|
|
}
|
|
|
|
private numberFromState(value: unknown, fallback = 0): number {
|
|
const parsed = Number(value);
|
|
return Number.isFinite(parsed) ? parsed : fallback;
|
|
}
|
|
|
|
private stringFromState(value: unknown): string {
|
|
return typeof value === 'string' ? value : (value?.toString() ?? '');
|
|
}
|
|
|
|
private isAuctionTopTierThreshold(
|
|
value: unknown,
|
|
): value is AuctionTopTierThreshold {
|
|
return (
|
|
value === 'NONE' ||
|
|
value === 'EMERALD' ||
|
|
value === 'DIAMOND' ||
|
|
value === 'MASTER' ||
|
|
value === 'MANUAL'
|
|
);
|
|
}
|
|
|
|
private formatRedisBidRejectCode(code: string): string {
|
|
switch (code) {
|
|
case 'BID_CLIENT_UPDATE_REQUIRED':
|
|
return '경매 화면이 업데이트되었습니다. 새로고침한 뒤 다시 입찰해 주세요.';
|
|
case 'PHASE':
|
|
return 'Auction is not in bidding phase.';
|
|
case 'STALE_BID_ROUND':
|
|
return 'Bid round has already changed.';
|
|
case 'EXPIRED':
|
|
return 'Bid deadline has already expired.';
|
|
case 'TOO_LOW':
|
|
return 'Bid must exceed current bid.';
|
|
case 'UNKNOWN_TEAM':
|
|
return 'Unknown team.';
|
|
case 'FULL':
|
|
return 'Team already has maximum members.';
|
|
case 'INSUFFICIENT':
|
|
return 'Bid must reserve minimum points for remaining slots.';
|
|
case 'DUPLICATE_REQUEST_CONFLICT':
|
|
return 'Bid request conflicts with an earlier request.';
|
|
default:
|
|
return `Bid was rejected: ${code}.`;
|
|
}
|
|
}
|
|
|
|
private createRedisBidRejectedException(
|
|
result: Extract<AuctionBidCommandResult, { rejected: true }>,
|
|
bidServerTiming?: AuctionBidServerTiming,
|
|
): BadRequestException {
|
|
const message = this.formatRedisBidRejectCode(result.code);
|
|
const bidDiagnostics: AuctionBidRejectDiagnostics = {
|
|
currentBidRoundDeadlineTimestampMS:
|
|
result.currentBidRoundDeadlineTimestampMS,
|
|
currentServerTimestampMS: result.currentServerTimestampMS,
|
|
};
|
|
return new BadRequestException({
|
|
bidDiagnostics,
|
|
...(bidServerTiming ? { bidServerTiming } : {}),
|
|
code: result.code,
|
|
message,
|
|
});
|
|
}
|
|
|
|
private roundBidServerTiming(
|
|
timing: AuctionBidServerTiming,
|
|
): AuctionBidServerTiming {
|
|
return Object.fromEntries(
|
|
Object.entries(timing).map(([key, value]) => [
|
|
key,
|
|
typeof value === 'number' ? Math.round(value * 10) / 10 : value,
|
|
]),
|
|
) as AuctionBidServerTiming;
|
|
}
|
|
|
|
private logSlowBidTiming(
|
|
matchId: string,
|
|
timing: AuctionBidServerTiming,
|
|
): void {
|
|
const serviceTotalDurationMS = timing.serviceTotalDurationMS ?? 0;
|
|
if (serviceTotalDurationMS < 250) return;
|
|
this.logger.warn(
|
|
`Auction bid latency match=${matchId} service=${serviceTotalDurationMS}ms context=${timing.redisBidContextReadDurationMS ?? 0}ms redisBid=${timing.redisBidCommandDurationMS ?? 0}ms fallback=${timing.fallbackFullStatePath ? '1' : '0'}`,
|
|
);
|
|
}
|
|
|
|
private applyTopTierPriority(
|
|
order: AuctionPlayerSnapshot[],
|
|
threshold: AuctionTopTierThreshold,
|
|
manualTopTierUserIds: mongoose.Types.ObjectId[],
|
|
): AuctionPlayerSnapshot[] {
|
|
if (threshold === 'NONE') return order;
|
|
if (threshold === 'MANUAL') {
|
|
const manualIds = new Set(
|
|
manualTopTierUserIds.map((userId) => userId.toString()),
|
|
);
|
|
if (manualIds.size === 0) return order;
|
|
const selected = order.filter((snap) =>
|
|
manualIds.has(snap.userId.toString()),
|
|
);
|
|
const rest = order.filter(
|
|
(snap) => !manualIds.has(snap.userId.toString()),
|
|
);
|
|
return [...selected, ...rest];
|
|
}
|
|
|
|
const ranks = [
|
|
'IRON',
|
|
'BRONZE',
|
|
'SILVER',
|
|
'GOLD',
|
|
'PLATINUM',
|
|
'EMERALD',
|
|
'DIAMOND',
|
|
'MASTER',
|
|
'GRANDMASTER',
|
|
'CHALLENGER',
|
|
];
|
|
const cutoff = ranks.indexOf(threshold);
|
|
const score = (snap: AuctionPlayerSnapshot) => {
|
|
const solo = snap.tiers.find(
|
|
(tier) => tier.queueType === 'RANKED_SOLO_5x5',
|
|
);
|
|
if (!solo) return -1;
|
|
const tierIdx = ranks.indexOf(solo.tier);
|
|
if (tierIdx < cutoff) return -1;
|
|
const rankBonus =
|
|
({ 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
|
|
);
|
|
};
|
|
|
|
const top = order
|
|
.filter((snap) => score(snap) >= 0)
|
|
.sort((left, right) => score(right) - score(left));
|
|
const rest = order.filter((snap) => score(snap) < 0);
|
|
return [...top, ...rest];
|
|
}
|
|
|
|
private shuffleAuctionPlayerOrder(
|
|
order: AuctionPlayerSnapshot[],
|
|
): AuctionPlayerSnapshot[] {
|
|
const shuffled = [...order];
|
|
for (let index = shuffled.length - 1; index > 0; index -= 1) {
|
|
const swapIndex = Math.floor(Math.random() * (index + 1));
|
|
[shuffled[index], shuffled[swapIndex]] = [
|
|
shuffled[swapIndex],
|
|
shuffled[index],
|
|
];
|
|
}
|
|
return shuffled;
|
|
}
|
|
|
|
private cloneAuctionPlayerSnapshot(
|
|
player: AuctionPlayerSnapshot,
|
|
): AuctionPlayerSnapshot {
|
|
return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot;
|
|
}
|
|
|
|
private normalizeChatMessage(message: string): string {
|
|
const normalized = message.trim();
|
|
if (!normalized) {
|
|
throw new BadRequestException('Chat message is required.');
|
|
}
|
|
if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) {
|
|
throw new BadRequestException(
|
|
`Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`,
|
|
);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
private normalizeChatDisplayName(displayName: string | undefined): string {
|
|
const normalized = displayName?.trim() || '관전자';
|
|
const chars = Array.from(normalized);
|
|
if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) {
|
|
return normalized;
|
|
}
|
|
return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join('');
|
|
}
|
|
|
|
private async recordSnapshot(
|
|
auction: AuctionDocument,
|
|
action: AuctionActionType,
|
|
actorUserId?: mongoose.Types.ObjectId,
|
|
): Promise<void> {
|
|
const AuctionHistoryModel =
|
|
await this.connectionService.getModel('auctionHistory');
|
|
const latest = await AuctionHistoryModel.findOne({ auctionId: auction._id })
|
|
.sort({ sequence: -1 })
|
|
.select({ sequence: 1 })
|
|
.lean()
|
|
.exec();
|
|
const snapshotBefore =
|
|
typeof auction.toObject === 'function'
|
|
? auction.toObject({ depopulate: true })
|
|
: auction;
|
|
|
|
await AuctionHistoryModel.create({
|
|
auctionId: auction._id,
|
|
matchId: auction.matchId,
|
|
sequence: (latest?.sequence ?? 0) + 1,
|
|
action,
|
|
actorUserId,
|
|
snapshotBefore: this.cloneJson(snapshotBefore),
|
|
takenAt: new Date(),
|
|
});
|
|
}
|
|
|
|
private formatHistoryActionLabel(action: AuctionActionType): string {
|
|
switch (action) {
|
|
case 'start':
|
|
return '경매 시작';
|
|
case 'open-bidding':
|
|
return '입찰 열기';
|
|
case 'bid':
|
|
return '입찰';
|
|
case 'sold':
|
|
return '낙찰 처리';
|
|
case 'passed':
|
|
return '유찰';
|
|
case 'next':
|
|
return '다음 선수';
|
|
case 'complete':
|
|
return '경매 완료';
|
|
case 'reset':
|
|
return '경매 초기화';
|
|
case 'undo':
|
|
return '되돌리기';
|
|
default:
|
|
return action;
|
|
}
|
|
}
|
|
|
|
private applyAuctionCut(match: {
|
|
participants: MatchParticipant[];
|
|
}): MatchParticipant[] {
|
|
const ordered = [...match.participants].sort(
|
|
(left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(),
|
|
);
|
|
const desiredAuctionCount = Math.floor(ordered.length / 10) * 10;
|
|
const activeIds = new Set(
|
|
ordered
|
|
.slice(0, desiredAuctionCount)
|
|
.map((participant) => participant.userId.toString()),
|
|
);
|
|
match.participants.forEach((participant) => {
|
|
participant.excluded = !activeIds.has(participant.userId.toString());
|
|
});
|
|
return ordered.slice(0, desiredAuctionCount);
|
|
}
|
|
|
|
private async assertCompleteAuctionRoster(
|
|
matchId: mongoose.Types.ObjectId,
|
|
teams: Array<{
|
|
captainUserId: mongoose.Types.ObjectId;
|
|
members: Array<{ userId: mongoose.Types.ObjectId }>;
|
|
}>,
|
|
): Promise<void> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
|
|
// The queue can contain reauction entries or be corrupted; use the original roster.
|
|
const expectedIds = match.participants
|
|
.filter((participant) => !participant.excluded)
|
|
.map((participant) => participant.userId.toString());
|
|
const expected = new Set(expectedIds);
|
|
const assignedIds = teams.flatMap((team) => [
|
|
team.captainUserId.toString(),
|
|
...team.members.map((member) => member.userId.toString()),
|
|
]);
|
|
const assigned = new Set(assignedIds);
|
|
const missingUserIds = expectedIds.filter((id) => !assigned.has(id));
|
|
const unexpectedUserIds = [...assigned].filter((id) => !expected.has(id));
|
|
if (
|
|
expected.size === 0 ||
|
|
expected.size !== expectedIds.length ||
|
|
assigned.size !== assignedIds.length ||
|
|
missingUserIds.length > 0 ||
|
|
unexpectedUserIds.length > 0
|
|
) {
|
|
this.logger.error({
|
|
event: 'auction_roster_validation_failed',
|
|
matchId: matchId.toString(),
|
|
expectedCount: expectedIds.length,
|
|
assignedCount: assignedIds.length,
|
|
assignedUniqueCount: assigned.size,
|
|
missingUserIds,
|
|
unexpectedUserIds,
|
|
});
|
|
throw new BadRequestException({
|
|
code: 'AUCTION_ROSTER_INVALID',
|
|
message: 'Auction roster validation failed.',
|
|
});
|
|
}
|
|
}
|
|
|
|
private assertCaptainAssignments(
|
|
captains: StartAuctionParams['captains'],
|
|
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
|
|
expectedCaptainCount: number,
|
|
): void {
|
|
const activeUserIds = new Set(
|
|
activeParticipants.map((participant) => participant.userId.toString()),
|
|
);
|
|
const captainUserIds = new Set<string>();
|
|
const teamIndexes = new Set<number>();
|
|
|
|
for (const captain of captains) {
|
|
const userId = captain.userId.toString();
|
|
if (!activeUserIds.has(userId)) {
|
|
throw new BadRequestException(
|
|
'All captains must be active participants of the match.',
|
|
);
|
|
}
|
|
if (captainUserIds.has(userId)) {
|
|
throw new BadRequestException('Captains must be different users.');
|
|
}
|
|
captainUserIds.add(userId);
|
|
|
|
if (
|
|
!Number.isInteger(captain.teamIndex) ||
|
|
captain.teamIndex < 1 ||
|
|
captain.teamIndex > expectedCaptainCount
|
|
) {
|
|
throw new BadRequestException('Captain teamIndex is out of range.');
|
|
}
|
|
if (teamIndexes.has(captain.teamIndex)) {
|
|
throw new BadRequestException('Duplicate captain team assignment.');
|
|
}
|
|
teamIndexes.add(captain.teamIndex);
|
|
}
|
|
|
|
for (let teamIndex = 1; teamIndex <= expectedCaptainCount; teamIndex += 1) {
|
|
if (!teamIndexes.has(teamIndex)) {
|
|
throw new BadRequestException('Each teamIndex needs one captain.');
|
|
}
|
|
}
|
|
}
|
|
|
|
private findAuctionTeamByIndex(
|
|
auction: AuctionDocument,
|
|
teamIndex: number,
|
|
): AuctionTeam | undefined {
|
|
return auction.teams.find((team) => team.teamIndex === teamIndex);
|
|
}
|
|
|
|
private createDeadline(secondsFromNow: number): Date {
|
|
return new Date(Date.now() + secondsFromNow * 1000);
|
|
}
|
|
|
|
private resolveBidExtensionSeconds(auction: AuctionDocument): number {
|
|
const maxTimerSeconds = Math.max(5, auction.maxTimerSeconds ?? 30);
|
|
const bidExtensionSeconds = Math.max(0, auction.bidExtensionSeconds ?? 5);
|
|
const minimumRemainingSeconds = Math.min(
|
|
maxTimerSeconds,
|
|
bidExtensionSeconds,
|
|
);
|
|
|
|
if (!auction.currentDeadline) {
|
|
return maxTimerSeconds;
|
|
}
|
|
|
|
const remainingSeconds = Math.ceil(
|
|
(auction.currentDeadline.getTime() - Date.now()) / 1000,
|
|
);
|
|
return Math.min(
|
|
maxTimerSeconds,
|
|
Math.max(minimumRemainingSeconds, remainingSeconds),
|
|
);
|
|
}
|
|
|
|
private assertTeamHasSlot(team: AuctionTeam): void {
|
|
if (this.countTeamMembersIncludingCaptain(team) >= AUCTION_MAX_TEAM_SIZE) {
|
|
throw new BadRequestException('Team already has maximum members.');
|
|
}
|
|
}
|
|
|
|
private assertValidBidPointAmount(amount: number): void {
|
|
if (!Number.isInteger(amount) || amount <= 0) {
|
|
throw new BadRequestException('Bid amount must be a positive integer.');
|
|
}
|
|
}
|
|
|
|
private calculateMaxBidForTeam(team: AuctionTeam): number {
|
|
const remainingSlotsAfterCurrentBid = Math.max(
|
|
0,
|
|
AUCTION_MAX_TEAM_SIZE - this.countTeamMembersIncludingCaptain(team) - 1,
|
|
);
|
|
const reservedPoints =
|
|
remainingSlotsAfterCurrentBid * AUCTION_MIN_BID_POINTS;
|
|
return Math.max(0, team.points - reservedPoints);
|
|
}
|
|
|
|
private countTeamMembersIncludingCaptain(team: AuctionTeam): number {
|
|
const userIds = new Set<string>([team.captainUserId.toString()]);
|
|
for (const member of team.members) {
|
|
userIds.add(member.userId.toString());
|
|
}
|
|
return userIds.size;
|
|
}
|
|
|
|
private isRedisV1Auction(auction: AuctionDocument): boolean {
|
|
return auction.auctionEngineVersion === 'redis-v1';
|
|
}
|
|
|
|
private assertCompetitionLifecycleMutable(
|
|
match: Pick<MatchDocument, 'competitionId'>,
|
|
action: string,
|
|
): void {
|
|
if (match.competitionId) {
|
|
throw new ConflictException(
|
|
`Cannot ${action} after the immutable Competition has been created. Create a new Match instead.`,
|
|
);
|
|
}
|
|
}
|
|
|
|
private isRestartableResetRedisAuction(auction: AuctionDocument): boolean {
|
|
return (
|
|
this.isRedisV1Auction(auction) &&
|
|
auction.phase === 'waiting' &&
|
|
auction.matchSideEffectStatus === 'completed'
|
|
);
|
|
}
|
|
|
|
private isRedisResetStillApplying(auction: AuctionDocument): boolean {
|
|
return (
|
|
this.isRedisV1Auction(auction) &&
|
|
auction.phase === 'waiting' &&
|
|
auction.matchSideEffectStatus !== 'completed'
|
|
);
|
|
}
|
|
|
|
private async resetMatchAfterAuctionCancellation(
|
|
match: MatchDocument,
|
|
session: mongoose.ClientSession,
|
|
): Promise<void> {
|
|
await this.tournamentCodeService.releaseFromMatch(match, session);
|
|
await this.tournamentResultService.cancelPolling(match, session);
|
|
match.status = 'recruiting';
|
|
match.teams = [];
|
|
match.tournamentCodeIds = [];
|
|
match.gameSchedule = [];
|
|
match.participants.forEach((participant) => {
|
|
participant.excluded = false;
|
|
});
|
|
match.teamBuiltAt = undefined;
|
|
match.result = undefined;
|
|
match.resultPollState = undefined;
|
|
await match.save({ session });
|
|
}
|
|
|
|
private assertLiveAuctionOperationSupported(auction: AuctionDocument): void {
|
|
if (auction.startupCompleted === false) {
|
|
throw new ConflictException(
|
|
'Auction startup is not complete. Refresh to resume initialization.',
|
|
);
|
|
}
|
|
if (auction.auctionEngineVersion && !this.isRedisV1Auction(auction)) {
|
|
throw new BadRequestException(
|
|
'Legacy auction live operations are not supported.',
|
|
);
|
|
}
|
|
}
|
|
|
|
private async syncMatchTeamsFromAuction(
|
|
auction: AuctionDocument,
|
|
): Promise<void> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(auction.matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (match.competitionId) {
|
|
await this.tournamentResultService.scheduleInitialPoll(match);
|
|
return;
|
|
}
|
|
|
|
const participantByUserId = new Map(
|
|
match.participants.map((participant) => [
|
|
participant.userId.toString(),
|
|
participant,
|
|
]),
|
|
);
|
|
|
|
const matchTeams = auction.teams.map((team) => {
|
|
const captain = participantByUserId.get(team.captainUserId.toString());
|
|
const members: MatchTeamMember[] = [
|
|
{
|
|
userId: team.captainUserId,
|
|
assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID',
|
|
cost: 0,
|
|
},
|
|
...team.members
|
|
.filter((member) => !member.userId.equals(team.captainUserId))
|
|
.map((member) => ({
|
|
userId: member.userId,
|
|
assignedPosition: member.assignedPosition,
|
|
cost: member.cost,
|
|
})),
|
|
];
|
|
|
|
return {
|
|
teamIndex: team.teamIndex,
|
|
name: this.resolveTeamName(team.teamIndex),
|
|
captainUserId: team.captainUserId,
|
|
members,
|
|
};
|
|
});
|
|
if (matchTeams.length === 0) {
|
|
throw new Error(
|
|
`Auction completed without teams for match ${match._id.toString()}.`,
|
|
);
|
|
}
|
|
const finalizedAt = match.teamBuiltAt ?? new Date();
|
|
match.teams = matchTeams;
|
|
match.status = 'team-built';
|
|
match.teamBuiltAt = undefined;
|
|
await match.save();
|
|
const preparedMatch =
|
|
(await this.tournamentCodeService.reserveForMatch(match)) ?? match;
|
|
preparedMatch.teamBuiltAt = finalizedAt;
|
|
await preparedMatch.save();
|
|
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
|
|
}
|
|
|
|
private async syncMatchTeamsFromRedisAuctionState(
|
|
auction: AuctionDocument,
|
|
state: Record<string, unknown>,
|
|
): Promise<void> {
|
|
const MatchModel = await this.connectionService.getModel('match');
|
|
const match = await MatchModel.findById(auction.matchId);
|
|
if (!match) throw new NotFoundException('Match not found.');
|
|
if (match.competitionId) {
|
|
await this.tournamentResultService.scheduleInitialPoll(match);
|
|
return;
|
|
}
|
|
|
|
const participantByUserId = new Map(
|
|
match.participants.map((participant) => [
|
|
participant.userId.toString(),
|
|
participant,
|
|
]),
|
|
);
|
|
const structureInput = this.buildRedisStructureInputFromState(state);
|
|
const teams = this.convertRedisTeamsToLegacyTeams(
|
|
structureInput.auctionTeams,
|
|
);
|
|
|
|
const matchTeams = teams.map((team) => {
|
|
const captain = participantByUserId.get(team.captainUserId.toString());
|
|
const members: MatchTeamMember[] = [
|
|
{
|
|
userId: team.captainUserId,
|
|
assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID',
|
|
cost: 0,
|
|
},
|
|
...team.members
|
|
.filter(
|
|
(member) =>
|
|
member.userId.toString() !== team.captainUserId.toString(),
|
|
)
|
|
.map((member) => ({
|
|
userId: member.userId,
|
|
assignedPosition: member.assignedPosition,
|
|
cost: member.cost,
|
|
})),
|
|
];
|
|
|
|
return {
|
|
teamIndex: team.teamIndex,
|
|
name: this.resolveTeamName(team.teamIndex),
|
|
captainUserId: team.captainUserId,
|
|
members,
|
|
};
|
|
});
|
|
if (matchTeams.length === 0) {
|
|
throw new Error(
|
|
`Redis auction completed without teams for match ${match._id.toString()}.`,
|
|
);
|
|
}
|
|
const finalizedAt = match.teamBuiltAt ?? new Date();
|
|
match.teams = matchTeams;
|
|
match.status = 'team-built';
|
|
match.teamBuiltAt = undefined;
|
|
await match.save();
|
|
const preparedMatch =
|
|
(await this.tournamentCodeService.reserveForMatch(match)) ?? match;
|
|
preparedMatch.teamBuiltAt = finalizedAt;
|
|
await preparedMatch.save();
|
|
await this.tournamentResultService.scheduleInitialPoll(preparedMatch);
|
|
}
|
|
|
|
private async hydrateRedisStateFromAuctionDocument(
|
|
auction: AuctionDocument,
|
|
): Promise<void> {
|
|
const auctionTeams =
|
|
auction.auctionTeams && auction.auctionTeams.length > 0
|
|
? auction.auctionTeams
|
|
: convertLegacyAuctionTeamsToRedisTeams(auction.teams ?? []);
|
|
const structureInput = {
|
|
auctionPlayerOrder: auction.auctionPlayerOrder ?? auction.order ?? [],
|
|
auctionTeams,
|
|
bidRoundExtensionSeconds:
|
|
auction.bidRoundExtensionSeconds ?? auction.bidExtensionSeconds ?? 5,
|
|
currentAuctionPlayerOrderIndex:
|
|
auction.currentAuctionPlayerOrderIndex ?? auction.currentIndex ?? 0,
|
|
currentAuctionRound:
|
|
auction.currentAuctionRound ?? auction.auctionRound ?? 1,
|
|
initialTeamBidPointAmount:
|
|
auction.initialTeamBidPointAmount ?? auction.initialPoints ?? 1000,
|
|
manualTopTierAuctionPriorityUserIds:
|
|
auction.manualTopTierAuctionPriorityUserIds ??
|
|
auction.manualTopTierUserIds ??
|
|
[],
|
|
maximumBidRoundDurationSeconds:
|
|
auction.maximumBidRoundDurationSeconds ?? auction.maxTimerSeconds ?? 30,
|
|
passedAuctionPlayerQueue:
|
|
auction.passedAuctionPlayerQueue ?? auction.passedQueue ?? [],
|
|
topTierAuctionPriorityThreshold:
|
|
auction.topTierAuctionPriorityThreshold ??
|
|
auction.topTierThreshold ??
|
|
'NONE',
|
|
};
|
|
const hydration = await this.auctionRedisCommandService.hydrateState(
|
|
auction.matchId.toString(),
|
|
{
|
|
auctionHistorySequence: auction.currentAuctionHistorySequence ?? 0,
|
|
auctionLifecycleId:
|
|
auction.auctionLifecycleId ??
|
|
`auction:${auction._id.toString()}:rehydrated`,
|
|
liveStatePatch: {
|
|
currentBidRoundId: auction.phase === 'bidding' ? randomUUID() : '',
|
|
matchSideEffectTransitionId: auction.matchSideEffectTransitionId,
|
|
matchSideEffectRevision: auction.matchSideEffectRevision,
|
|
matchSideEffectStatus: auction.matchSideEffectStatus,
|
|
...buildAuctionRedisLiveStatePatchFromStructure(structureInput),
|
|
currentHighestBidPointAmount:
|
|
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
|
currentHighestBidderTeamIndex:
|
|
auction.currentHighestBidderTeamIndex ??
|
|
auction.currentBidderTeamIndex ??
|
|
-1,
|
|
},
|
|
maximumBidRoundDurationSeconds:
|
|
structureInput.maximumBidRoundDurationSeconds,
|
|
matchId: auction.matchId.toString(),
|
|
phase: auction.phase,
|
|
revision: auction.revision ?? 0,
|
|
structureStateJson: stringifyAuctionRedisStructureState(structureInput),
|
|
},
|
|
);
|
|
if ('rejected' in hydration)
|
|
throw new ConflictException(
|
|
`Auction recovery failed: ${hydration.code}.`,
|
|
);
|
|
}
|
|
|
|
private async clearRedisAuctionRuntimeForLifecycle(
|
|
matchId: string,
|
|
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], KEYS[12])",
|
|
'return 1',
|
|
].join('\n'),
|
|
'12',
|
|
keys.liveStateKey,
|
|
keys.deadlineQueueKey,
|
|
keys.structureStateKey,
|
|
keys.appliedTransitionIdsKey,
|
|
keys.bidHistoryKey,
|
|
keys.bidRequestResultsKey,
|
|
keys.bidRequestResultOrderKey,
|
|
keys.actionRequestResultsKey,
|
|
keys.actionRequestResultOrderKey,
|
|
keys.rehydrateLockKey,
|
|
keys.stateTransitionLockKey,
|
|
keys.rejectedBidRequestResultOrderKey,
|
|
matchId,
|
|
expectedAuctionLifecycleId ?? '',
|
|
]);
|
|
if (Number(cleared) !== 1) return;
|
|
await this.clearRedisDurabilityPayloadsForLifecycle(
|
|
keys,
|
|
expectedAuctionLifecycleId,
|
|
);
|
|
}
|
|
|
|
private async clearRedisDurabilityPayloadsForLifecycle(
|
|
keys: ReturnType<typeof buildAuctionRedisKeys>,
|
|
expectedAuctionLifecycleId?: string,
|
|
): Promise<void> {
|
|
let cursor = '0';
|
|
do {
|
|
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) : [];
|
|
if (payloadKeys.length === 0) continue;
|
|
|
|
await this.auctionRedisService.evalScript(
|
|
AUCTION_CLEANUP_DURABILITY_SCRIPT,
|
|
[
|
|
keys.durabilityRetryQueueKey,
|
|
keys.durabilityDeadLetterQueueKey,
|
|
...payloadKeys,
|
|
],
|
|
[expectedAuctionLifecycleId ?? ''],
|
|
);
|
|
} while (cursor !== '0');
|
|
}
|
|
|
|
private enqueueBackgroundOrderEnrichment(params: {
|
|
auctionId: mongoose.Types.ObjectId;
|
|
targets: AuctionEnrichmentTarget[];
|
|
platform: RiotPlatformRoute;
|
|
region: RiotRegionalRoute;
|
|
}): void {
|
|
if (params.targets.length === 0) return;
|
|
|
|
// 경매 시작 UX를 막지 않도록 Riot 최신화는 뒤에서 1명씩 천천히 수행한다.
|
|
void this.refreshOrderSnapshotsFromRiot(params).catch((error: unknown) => {
|
|
this.logger.warn(
|
|
`Auction background Riot refresh failed for ${params.auctionId.toString()}: ${
|
|
error instanceof Error ? error.message : String(error)
|
|
}`,
|
|
);
|
|
});
|
|
}
|
|
|
|
private async refreshOrderSnapshotsFromRiot(params: {
|
|
auctionId: mongoose.Types.ObjectId;
|
|
targets: AuctionEnrichmentTarget[];
|
|
platform: RiotPlatformRoute;
|
|
region: RiotRegionalRoute;
|
|
}): Promise<void> {
|
|
const AuctionModel = await this.connectionService.getModel('auction');
|
|
|
|
this.logger.debug(
|
|
`Refreshing Riot snapshots for ${params.targets.length} auction players in background.`,
|
|
);
|
|
|
|
await runWithConcurrency(
|
|
params.targets,
|
|
AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY,
|
|
async (target) => {
|
|
try {
|
|
const result = await this.enrichmentService.enrichRiotAccount({
|
|
userId: target.userId,
|
|
puuid: target.puuid,
|
|
options: {
|
|
force: false,
|
|
platform: params.platform,
|
|
region: params.region,
|
|
},
|
|
});
|
|
const account = result.account;
|
|
if (!account) return;
|
|
|
|
await AuctionModel.updateOne(
|
|
{
|
|
_id: params.auctionId,
|
|
'order.userId': target.userId,
|
|
},
|
|
{
|
|
$set: {
|
|
'order.$.gameName': account.gameName,
|
|
'order.$.tagLine': account.tagLine,
|
|
'order.$.profileIconId': account.profileIconId,
|
|
'order.$.tiers': account.tiers,
|
|
'order.$.tierHistory': account.tierHistory ?? [],
|
|
'order.$.masteries': account.championMasteries,
|
|
'order.$.recentStatsSummary': account.recentStatsSummary,
|
|
updatedAt: new Date(),
|
|
},
|
|
},
|
|
).exec();
|
|
} catch (error: unknown) {
|
|
this.logger.warn(
|
|
`Failed to refresh auction Riot snapshot for ${target.puuid}: ${
|
|
error instanceof Error ? error.message : String(error)
|
|
}`,
|
|
);
|
|
}
|
|
},
|
|
);
|
|
}
|
|
|
|
private wasRecentlyRefreshed(account: RiotAccount, cutoff: number): boolean {
|
|
return this.getLatestRefreshAt(account) >= cutoff;
|
|
}
|
|
|
|
private getLatestRefreshAt(account: RiotAccount): number {
|
|
const timestamps = [
|
|
account.lastRefreshRequestedAt,
|
|
account.recentStatsFetchedAt,
|
|
account.championMasteriesFetchedAt,
|
|
account.matchIdsFetchedAt,
|
|
...account.tiers.map((tier) => tier.fetchedAt),
|
|
];
|
|
|
|
return timestamps.reduce((latest, value) => {
|
|
const timestamp = value instanceof Date ? value.getTime() : 0;
|
|
return Math.max(latest, timestamp);
|
|
}, 0);
|
|
}
|
|
|
|
private resolveTeamName(teamIndex: number): string {
|
|
return `${teamIndex}팀`;
|
|
}
|
|
}
|
|
|
|
async function runWithConcurrency<T>(
|
|
items: T[],
|
|
concurrency: number,
|
|
worker: (item: T) => Promise<void>,
|
|
): Promise<void> {
|
|
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);
|
|
}
|
|
},
|
|
);
|
|
|
|
await Promise.allSettled(runners);
|
|
}
|