This commit is contained in:
dahyeon committed 2026-05-02 03:27:19 -07:00
1 parent 2379051196
commit 4baea89f89
6 files changed
+9834 -48

No files matched your search

+120 -24
View File
@@ -2,6 +2,7 @@ import {
BadRequestException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
@@ -13,13 +14,17 @@ import {
MatchParticipant,
MatchTeamMember,
Position,
RiotAccount,
TeamSide,
} 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';
const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
@@ -46,8 +51,15 @@ interface MarkSoldParams {
assignedPosition?: Position;
}
interface AuctionEnrichmentTarget {
userId: mongoose.Types.ObjectId;
puuid: string;
}
@Injectable()
export class AuctionService {
private readonly logger = new Logger(AuctionService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService,
@@ -101,32 +113,16 @@ export class AuctionService {
const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia';
const enrichTargets = basePlayerUsers
.map((user) => ({
userId: user._id,
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0])
?.puuid,
}))
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } =>
typeof target.puuid === 'string' && target.puuid.length > 0,
);
await runWithConcurrency(enrichTargets, 3, async (target) => {
await this.enrichmentService.enrichRiotAccount({
userId: target.userId,
puuid: target.puuid,
options: {
force: false,
platform,
region,
},
});
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 playerUsers = await UserModel.find({
_id: { $in: basePlayerUsers.map((user) => user._id) },
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u]));
const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = [];
@@ -182,6 +178,12 @@ export class AuctionService {
await match.save();
await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match);
this.enqueueBackgroundOrderEnrichment({
auctionId: auction._id,
targets: enrichTargets,
platform,
region,
});
return auction;
}
@@ -497,6 +499,100 @@ export class AuctionService {
await this.tournamentResultService.scheduleInitialPoll(match);
}
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 : 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.$.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 : 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(
side: TeamSide,
groupIndex: number,