.
This commit is contained in:
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 = {
|
||||
|
||||
@@ -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 });
|
||||
|
||||
Reference in new issue
Block a user