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

@@ -34,6 +34,7 @@ describe('AuctionService', () => {
function createFullTeam(side: 'blue' | 'red') {
return {
side,
groupIndex: 1,
captainUserId: new mongoose.Types.ObjectId(),
points: 100,
members: Array.from({ length: 4 }, () => ({
@@ -62,6 +63,7 @@ describe('AuctionService', () => {
service.placeBid({
matchId,
side: 'blue',
groupIndex: 1,
amount: 20,
}),
).rejects.toThrow('Team already has maximum members.');
@@ -177,6 +179,7 @@ describe('AuctionService', () => {
expect(match.teams).toEqual([
{
side: 'blue',
groupIndex: 1,
name: '블루팀',
captainUserId: blueCaptainId,
members: [
@@ -194,6 +197,7 @@ describe('AuctionService', () => {
},
{
side: 'red',
groupIndex: 1,
name: '레드팀',
captainUserId: redCaptainId,
members: [
@@ -230,10 +234,12 @@ describe('AuctionService', () => {
teams: [
{
side: 'blue',
groupIndex: 1,
name: '블루팀',
members: [],
},
],
participants: [],
save: jest.fn().mockResolvedValue(undefined),
};
const auctionFindOneQuery = {
+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,
@@ -67,30 +67,38 @@ export class RiotRecentMatchesService {
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => {
const dto = await this.matchService.getMatch(matchId, { region });
if (dto.info.queueId !== queueId) {
try {
const dto = await this.matchService.getMatch(matchId, { region });
if (dto.info.queueId !== queueId) {
this.logger.warn(
`Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`,
);
return;
}
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
} catch (error: unknown) {
this.logger.warn(
`Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`,
`Skipping Riot match ${matchId} while syncing ${params.puuid}: ${
error instanceof Error ? error.message : error
}`,
);
return;
}
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $setOnInsert: payload },
{ upsert: true },
).exec();
});
return this.loadFromDb({ puuid: params.puuid, limit, queueId });
+2
View File
@@ -118,6 +118,7 @@ export function useMatch(matchId: string | undefined, communityId = DEFAULT_COMM
export function useAuction(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
options: { refetchInterval?: number | false } = {},
) {
return useQuery({
queryKey: ['auction', communityId, matchId ?? null],
@@ -128,6 +129,7 @@ export function useAuction(
),
enabled: Boolean(communityId && matchId),
retry: false,
refetchInterval: options.refetchInterval,
});
}
+26 -3
View File
@@ -20,7 +20,12 @@ import {
profileIconUrl,
} from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league';
import type { ApiRiotLaneStats, Position, TeamSide } from '../api/types';
import type {
ApiAuction,
ApiRiotLaneStats,
Position,
TeamSide,
} from '../api/types';
type CaptainRole = {
side: TeamSide;
@@ -46,6 +51,22 @@ function isCurrentBidder(
);
}
function getAuctionUpdatedAt(auction: ApiAuction | null | undefined) {
if (!auction) return 0;
return Date.parse(auction.updatedAt ?? auction.createdAt ?? '') || 0;
}
function pickLatestAuction(
socketAuction: ApiAuction | null,
queryAuction: ApiAuction | undefined,
) {
if (!socketAuction) return queryAuction ?? null;
if (!queryAuction) return socketAuction;
return getAuctionUpdatedAt(queryAuction) > getAuctionUpdatedAt(socketAuction)
? queryAuction
: socketAuction;
}
const AUCTION_MAX_TEAM_SIZE = 5;
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
const POSITION_TO_RIOT_LANE = {
@@ -554,7 +575,9 @@ export default function AuctionPage() {
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null;
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID, {
refetchInterval: 5000,
});
const socket = useAuctionSocket(id);
const captainSide = useDevCaptainSide();
const [captainGroupIndex, setCaptainGroupIndex] = useState(1);
@@ -566,7 +589,7 @@ export default function AuctionPage() {
return () => window.clearInterval(timer);
}, []);
const liveAuction = socket.auction ?? auctionQuery.data ?? null;
const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const auctionState =
liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now))