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') { function createFullTeam(side: 'blue' | 'red') {
return { return {
side, side,
groupIndex: 1,
captainUserId: new mongoose.Types.ObjectId(), captainUserId: new mongoose.Types.ObjectId(),
points: 100, points: 100,
members: Array.from({ length: 4 }, () => ({ members: Array.from({ length: 4 }, () => ({
@@ -62,6 +63,7 @@ describe('AuctionService', () => {
service.placeBid({ service.placeBid({
matchId, matchId,
side: 'blue', side: 'blue',
groupIndex: 1,
amount: 20, amount: 20,
}), }),
).rejects.toThrow('Team already has maximum members.'); ).rejects.toThrow('Team already has maximum members.');
@@ -177,6 +179,7 @@ describe('AuctionService', () => {
expect(match.teams).toEqual([ expect(match.teams).toEqual([
{ {
side: 'blue', side: 'blue',
groupIndex: 1,
name: '블루팀', name: '블루팀',
captainUserId: blueCaptainId, captainUserId: blueCaptainId,
members: [ members: [
@@ -194,6 +197,7 @@ describe('AuctionService', () => {
}, },
{ {
side: 'red', side: 'red',
groupIndex: 1,
name: '레드팀', name: '레드팀',
captainUserId: redCaptainId, captainUserId: redCaptainId,
members: [ members: [
@@ -230,10 +234,12 @@ describe('AuctionService', () => {
teams: [ teams: [
{ {
side: 'blue', side: 'blue',
groupIndex: 1,
name: '블루팀', name: '블루팀',
members: [], members: [],
}, },
], ],
participants: [],
save: jest.fn().mockResolvedValue(undefined), save: jest.fn().mockResolvedValue(undefined),
}; };
const auctionFindOneQuery = { const auctionFindOneQuery = {
+120 -24
View File
@@ -2,6 +2,7 @@ import {
BadRequestException, BadRequestException,
Injectable, Injectable,
InternalServerErrorException, InternalServerErrorException,
Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import mongoose from 'mongoose'; import mongoose from 'mongoose';
@@ -13,13 +14,17 @@ import {
MatchParticipant, MatchParticipant,
MatchTeamMember, MatchTeamMember,
Position, Position,
RiotAccount,
TeamSide, TeamSide,
} from '../global/database/schema'; } from '../global/database/schema';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; 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 { TournamentCodeService } from '../tournament-code/tournament-code.service';
import { TournamentResultService } from '../tournament-result/tournament-result.service'; import { TournamentResultService } from '../tournament-result/tournament-result.service';
const AUCTION_MAX_TEAM_SIZE = 5; const AUCTION_MAX_TEAM_SIZE = 5;
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
interface StartAuctionParams { interface StartAuctionParams {
matchId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId;
@@ -46,8 +51,15 @@ interface MarkSoldParams {
assignedPosition?: Position; assignedPosition?: Position;
} }
interface AuctionEnrichmentTarget {
userId: mongoose.Types.ObjectId;
puuid: string;
}
@Injectable() @Injectable()
export class AuctionService { export class AuctionService {
private readonly logger = new Logger(AuctionService.name);
constructor( constructor(
private readonly connectionService: ConnectionService, private readonly connectionService: ConnectionService,
private readonly enrichmentService: RiotAccountEnrichmentService, private readonly enrichmentService: RiotAccountEnrichmentService,
@@ -101,32 +113,16 @@ export class AuctionService {
const platform = community?.riotPlatform ?? 'kr'; const platform = community?.riotPlatform ?? 'kr';
const region = community?.riotRegion ?? 'asia'; const region = community?.riotRegion ?? 'asia';
const enrichTargets = basePlayerUsers const enrichCooldownCutoff = Date.now() - AUCTION_ENRICHMENT_COOLDOWN_MS;
.map((user) => ({ const enrichTargets = basePlayerUsers.flatMap((user) => {
userId: user._id, const account =
puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0]) user.riotAccounts.find((entry) => entry.isPrimary) ?? user.riotAccounts[0];
?.puuid, if (!account?.puuid) return [];
})) if (this.wasRecentlyRefreshed(account, enrichCooldownCutoff)) return [];
.filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } => return [{ userId: user._id, puuid: account.puuid }];
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 playerUsers = await UserModel.find({ const userById = new Map(basePlayerUsers.map((u) => [u._id.toString(), u]));
_id: { $in: basePlayerUsers.map((user) => user._id) },
});
const userById = new Map(playerUsers.map((u) => [u._id.toString(), u]));
const nonCaptainPuuids = new Set<string>(); const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = []; const order: AuctionPlayerSnapshot[] = [];
@@ -182,6 +178,12 @@ export class AuctionService {
await match.save(); await match.save();
await this.tournamentCodeService.reserveForMatch(match); await this.tournamentCodeService.reserveForMatch(match);
await this.tournamentResultService.scheduleInitialPoll(match); await this.tournamentResultService.scheduleInitialPoll(match);
this.enqueueBackgroundOrderEnrichment({
auctionId: auction._id,
targets: enrichTargets,
platform,
region,
});
return auction; return auction;
} }
@@ -497,6 +499,100 @@ export class AuctionService {
await this.tournamentResultService.scheduleInitialPoll(match); 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( private resolveTeamName(
side: TeamSide, side: TeamSide,
groupIndex: number, groupIndex: number,
@@ -67,30 +67,38 @@ export class RiotRecentMatchesService {
const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId)); const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId));
await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => { await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => {
const dto = await this.matchService.getMatch(matchId, { region }); try {
if (dto.info.queueId !== queueId) { 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( 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 }); 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( export function useAuction(
matchId: string | undefined, matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID, communityId = DEFAULT_COMMUNITY_ID,
options: { refetchInterval?: number | false } = {},
) { ) {
return useQuery({ return useQuery({
queryKey: ['auction', communityId, matchId ?? null], queryKey: ['auction', communityId, matchId ?? null],
@@ -128,6 +129,7 @@ export function useAuction(
), ),
enabled: Boolean(communityId && matchId), enabled: Boolean(communityId && matchId),
retry: false, retry: false,
refetchInterval: options.refetchInterval,
}); });
} }
+26 -3
View File
@@ -20,7 +20,12 @@ import {
profileIconUrl, profileIconUrl,
} from '../lib/ddragon'; } from '../lib/ddragon';
import { positionIcon, positionLabel } from '../lib/league'; 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 = { type CaptainRole = {
side: TeamSide; 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 AUCTION_MAX_TEAM_SIZE = 5;
const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; const LANE_ROWS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
const POSITION_TO_RIOT_LANE = { const POSITION_TO_RIOT_LANE = {
@@ -554,7 +575,9 @@ export default function AuctionPage() {
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID, (membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
)?.user ?? null; )?.user ?? null;
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID); 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 socket = useAuctionSocket(id);
const captainSide = useDevCaptainSide(); const captainSide = useDevCaptainSide();
const [captainGroupIndex, setCaptainGroupIndex] = useState(1); const [captainGroupIndex, setCaptainGroupIndex] = useState(1);
@@ -566,7 +589,7 @@ export default function AuctionPage() {
return () => window.clearInterval(timer); return () => window.clearInterval(timer);
}, []); }, []);
const liveAuction = socket.auction ?? auctionQuery.data ?? null; const liveAuction = pickLatestAuction(socket.auction, auctionQuery.data);
const auctionState = const auctionState =
liveAuction && matchQuery.data liveAuction && matchQuery.data
? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now)) ? mapApiAuctionToAuctionState(liveAuction, matchQuery.data, new Date(now))
+9651
View File
File diff suppressed because it is too large. Load diff