feat(app): add stats and admin tools
This commit is contained in:
1 parent
efa133a1a2
commit
c8cca3fc43
35 files changed
+6875
No files matched your search
@@ -0,0 +1,59 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
|
||||
const COMMUNITY_STATS_TTL_SECONDS = 5 * 60;
|
||||
const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
@Injectable()
|
||||
export class CommunityStatsCacheService {
|
||||
private readonly logger = new Logger(CommunityStatsCacheService.name);
|
||||
|
||||
constructor(private readonly garnetService: GarnetService) {}
|
||||
|
||||
public get<T>(key: string): Promise<T | null> {
|
||||
return this.garnetService.getJson<T>(key);
|
||||
}
|
||||
|
||||
public set(
|
||||
key: string,
|
||||
value: unknown,
|
||||
ttlSeconds = COMMUNITY_STATS_TTL_SECONDS,
|
||||
): Promise<void> {
|
||||
return this.garnetService.setJson(key, value, ttlSeconds);
|
||||
}
|
||||
|
||||
public setDetail(key: string, value: unknown): Promise<void> {
|
||||
return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS);
|
||||
}
|
||||
|
||||
public async invalidateCommunity(communityId: string): Promise<number> {
|
||||
const prefix = `riot:communitystats:`;
|
||||
const match = `${prefix}*${communityId}*`;
|
||||
const client = this.garnetService.raw();
|
||||
let cursor = '0';
|
||||
let deleted = 0;
|
||||
|
||||
do {
|
||||
const reply = (await client.sendCommand([
|
||||
'SCAN',
|
||||
cursor,
|
||||
'MATCH',
|
||||
match,
|
||||
'COUNT',
|
||||
'100',
|
||||
])) as [string, string[]];
|
||||
cursor = reply[0];
|
||||
const keys = reply[1] ?? [];
|
||||
if (keys.length > 0) {
|
||||
deleted += await client.del(keys);
|
||||
}
|
||||
} while (cursor !== '0');
|
||||
|
||||
if (deleted > 0) {
|
||||
this.logger.debug(
|
||||
`Invalidated ${deleted} community stats cache keys for ${communityId}.`,
|
||||
);
|
||||
}
|
||||
return deleted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Controller, Get, Param, Query } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import { CommunityStatsService } from './community-stats.service';
|
||||
import type { CommunityStatsFilters } from './community-stats.types';
|
||||
|
||||
@Controller('communities/:communityId')
|
||||
export class CommunityStatsController {
|
||||
constructor(private readonly communityStatsService: CommunityStatsService) {}
|
||||
|
||||
@Get('internal-stats/matches')
|
||||
@AllowPublicAccess()
|
||||
public getMatches(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('seasonId') seasonId?: string,
|
||||
@Query('from') from?: string,
|
||||
@Query('to') to?: string,
|
||||
@Query('championId') championId?: string,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.communityStatsService.getMatches({
|
||||
communityId,
|
||||
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
||||
});
|
||||
}
|
||||
|
||||
@Get('internal-stats/leaderboard')
|
||||
@AllowPublicAccess()
|
||||
public getLeaderboard(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('seasonId') seasonId?: string,
|
||||
@Query('from') from?: string,
|
||||
@Query('to') to?: string,
|
||||
@Query('championId') championId?: string,
|
||||
) {
|
||||
return this.communityStatsService.getLeaderboard({
|
||||
communityId,
|
||||
filters: this.toFilters({ seasonId, from, to, championId }),
|
||||
});
|
||||
}
|
||||
|
||||
@Get('internal-stats/team-insights')
|
||||
@AllowPublicAccess()
|
||||
public getTeamInsights(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('seasonId') seasonId?: string,
|
||||
@Query('from') from?: string,
|
||||
@Query('to') to?: string,
|
||||
@Query('championId') championId?: string,
|
||||
) {
|
||||
return this.communityStatsService.getTeamInsights({
|
||||
communityId,
|
||||
filters: this.toFilters({ seasonId, from, to, championId }),
|
||||
});
|
||||
}
|
||||
|
||||
@Get('internal-stats/match/:matchId')
|
||||
@AllowPublicAccess()
|
||||
public getMatchDetail(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
return this.communityStatsService.getMatchDetail({ communityId, matchId });
|
||||
}
|
||||
|
||||
@Get('users/:userId/internal-history')
|
||||
@AllowPublicAccess()
|
||||
public getUserInternalHistory(
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId,
|
||||
@Query('seasonId') seasonId?: string,
|
||||
@Query('from') from?: string,
|
||||
@Query('to') to?: string,
|
||||
@Query('championId') championId?: string,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
return this.communityStatsService.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }),
|
||||
});
|
||||
}
|
||||
|
||||
private toFilters(params: {
|
||||
seasonId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
championId?: string;
|
||||
cursor?: string;
|
||||
limit?: string;
|
||||
}): CommunityStatsFilters {
|
||||
return {
|
||||
seasonId: params.seasonId,
|
||||
from: params.from,
|
||||
to: params.to,
|
||||
championId: this.toNumber(params.championId),
|
||||
cursor: this.toNumber(params.cursor),
|
||||
limit: this.toNumber(params.limit),
|
||||
};
|
||||
}
|
||||
|
||||
private toNumber(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||
import { CommunityStatsController } from './community-stats.controller';
|
||||
import { CommunityStatsService } from './community-stats.service';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
|
||||
@Module({
|
||||
controllers: [CommunityStatsController],
|
||||
providers: [
|
||||
CommunityStatsService,
|
||||
CommunityStatsCacheService,
|
||||
MatchStatsFragmentBuilder,
|
||||
MatchStatsRepository,
|
||||
MatchStatsService,
|
||||
],
|
||||
exports: [CommunityStatsService, MatchStatsService],
|
||||
})
|
||||
export class CommunityStatsModule {}
|
||||
@@ -0,0 +1,992 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { CommunityDocument, RiotLane } from '../global/database/schema';
|
||||
import type {
|
||||
HistorySeasonDto,
|
||||
RecentMatchView,
|
||||
} from '../match-history/match-history.types';
|
||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||
import type {
|
||||
CommunityStatsFilters,
|
||||
InternalMatchCardView,
|
||||
InternalMatchDetailResponse,
|
||||
InternalMatchListResponse,
|
||||
LeaderboardChampionStats,
|
||||
LeaderboardResponse,
|
||||
LeaderboardRow,
|
||||
LeaderHighlight,
|
||||
TeamInsightsResponse,
|
||||
UserInternalHistoryResponse,
|
||||
} from './community-stats.types';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
MATCH_STATS_BUILDER_VERSION,
|
||||
} from './match-stats.types';
|
||||
|
||||
const DEFAULT_LIST_LIMIT = 20;
|
||||
const MAX_LIST_LIMIT = 50;
|
||||
const MAX_MATCH_SCAN = 300;
|
||||
const MIN_HIGHLIGHT_GAMES = 5;
|
||||
|
||||
interface CommunityStatsContext {
|
||||
community: CommunityDocument;
|
||||
season: HistorySeasonDto;
|
||||
from: Date | null;
|
||||
to: Date | null;
|
||||
}
|
||||
|
||||
interface BaseDataset {
|
||||
season: HistorySeasonDto;
|
||||
matches: InternalMatchCardView[];
|
||||
records: InternalRecord[];
|
||||
detailsByMatchId: Map<string, InternalGameDetail[]>;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CommunityStatsService {
|
||||
private readonly logger = new Logger(CommunityStatsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly cacheService: CommunityStatsCacheService,
|
||||
private readonly matchStatsRepository: MatchStatsRepository,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async getMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<InternalMatchListResponse> {
|
||||
const key = this.cacheKey('matches', params.communityId, params.filters);
|
||||
const cached = await this.cacheService.get<InternalMatchListResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const limit = this.clampLimit(
|
||||
params.filters.limit,
|
||||
DEFAULT_LIST_LIMIT,
|
||||
MAX_LIST_LIMIT,
|
||||
);
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const filtered = params.filters.championId
|
||||
? dataset.matches.filter((match) =>
|
||||
dataset.records.some(
|
||||
(record) =>
|
||||
record.matchId === match.matchId &&
|
||||
record.championId === params.filters.championId,
|
||||
),
|
||||
)
|
||||
: dataset.matches;
|
||||
const cursor = params.filters.cursor;
|
||||
const page = filtered
|
||||
.filter(
|
||||
(match) => !cursor || new Date(match.scheduledAt).getTime() < cursor,
|
||||
)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const response: InternalMatchListResponse = {
|
||||
matches: visible,
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime()
|
||||
: null,
|
||||
season: dataset.season,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getLeaderboard(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<LeaderboardResponse> {
|
||||
const key = this.cacheKey(
|
||||
'leaderboard',
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached = await this.cacheService.get<LeaderboardResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||
const rows = this.buildLeaderboardRows(records);
|
||||
const response = { rows, season: dataset.season };
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getTeamInsights(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<TeamInsightsResponse> {
|
||||
const key = this.cacheKey(
|
||||
'teamInsights',
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const records = this.applyChampionFilter(dataset.records, params.filters);
|
||||
const rows = this.buildLeaderboardRows(records);
|
||||
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
|
||||
const blueGames = gameDetails.length;
|
||||
const redGames = gameDetails.length;
|
||||
const blueWins = gameDetails.filter(
|
||||
(game) => game.winnerSide === 'blue',
|
||||
).length;
|
||||
const redWins = gameDetails.filter(
|
||||
(game) => game.winnerSide === 'red',
|
||||
).length;
|
||||
|
||||
const response: TeamInsightsResponse = {
|
||||
season: dataset.season,
|
||||
sideWinRate: {
|
||||
blue: this.percent(blueWins, blueGames),
|
||||
red: this.percent(redWins, redGames),
|
||||
bluePicks: blueGames,
|
||||
redPicks: redGames,
|
||||
},
|
||||
topKda: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort((left, right) => right.kda - left.kda)[0],
|
||||
'kda',
|
||||
),
|
||||
mostKills: this.toHighlight(
|
||||
rows.sort((left, right) => right.totalKills - left.totalKills)[0],
|
||||
'totalKills',
|
||||
),
|
||||
topTeamGpm: this.toSingleGameHighlight(
|
||||
records.sort((left, right) => right.gpm - left.gpm)[0],
|
||||
'gpm',
|
||||
),
|
||||
topKillParticipation: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.avgKillParticipation - left.avgKillParticipation,
|
||||
)[0],
|
||||
'avgKillParticipation',
|
||||
),
|
||||
bestFarm: this.toHighlight(
|
||||
rows
|
||||
.filter((row) => row.games >= MIN_HIGHLIGHT_GAMES)
|
||||
.sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0],
|
||||
'avgCsPerMin',
|
||||
),
|
||||
minGamesThreshold: MIN_HIGHLIGHT_GAMES,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getMatchDetail(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
}): Promise<InternalMatchDetailResponse> {
|
||||
const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`;
|
||||
const cached =
|
||||
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||
seasonId: 'all',
|
||||
});
|
||||
const match = dataset.matches.find(
|
||||
(item) => item.matchId === params.matchId.toString(),
|
||||
);
|
||||
if (!match) throw new NotFoundException('Internal match not found.');
|
||||
const response: InternalMatchDetailResponse = {
|
||||
match,
|
||||
games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map(
|
||||
(game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
teams: game.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
side: team.side,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
participants: team.participants.map((record) => ({
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
teamIndex: record.teamIndex,
|
||||
side: record.side,
|
||||
teamPosition: record.teamPosition,
|
||||
championId: record.championId,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
cs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
gold: record.gold,
|
||||
gpm: record.gpm,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageShare: record.damageShare,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
win: record.win,
|
||||
})),
|
||||
})),
|
||||
}),
|
||||
),
|
||||
};
|
||||
await this.cacheService.setDetail(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public async getUserInternalHistory(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
filters: CommunityStatsFilters;
|
||||
}): Promise<UserInternalHistoryResponse> {
|
||||
const key = this.cacheKey(
|
||||
`userInternal:${params.userId.toString()}`,
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const cached =
|
||||
await this.cacheService.get<UserInternalHistoryResponse>(key);
|
||||
if (cached) return cached;
|
||||
|
||||
const dataset = await this.buildBaseDataset(
|
||||
params.communityId,
|
||||
params.filters,
|
||||
);
|
||||
const allUserRecords = dataset.records
|
||||
.filter((record) => record.userId === params.userId.toString())
|
||||
.sort((left, right) => right.gameCreation - left.gameCreation);
|
||||
const records = this.applyChampionFilter(allUserRecords, params.filters);
|
||||
const limit = this.clampLimit(params.filters.limit, 30, 50);
|
||||
const cursor = params.filters.cursor;
|
||||
const page = records
|
||||
.filter((record) => !cursor || record.gameCreation < cursor)
|
||||
.slice(0, limit + 1);
|
||||
const visible = page.slice(0, limit);
|
||||
const response: UserInternalHistoryResponse = {
|
||||
season: dataset.season,
|
||||
championStats: this.buildUserChampionStats(
|
||||
allUserRecords,
|
||||
dataset.season,
|
||||
),
|
||||
summary: this.buildUserSummary(records, visible.length || limit),
|
||||
matches: visible.map((record) => this.toRecentMatchView(record, dataset)),
|
||||
nextCursor:
|
||||
page.length > limit
|
||||
? (visible[visible.length - 1]?.gameCreation ?? null)
|
||||
: null,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
return response;
|
||||
}
|
||||
|
||||
public invalidateCommunity(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
return this.cacheService.invalidateCommunity(communityId.toString());
|
||||
}
|
||||
|
||||
private async buildBaseDataset(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): Promise<BaseDataset> {
|
||||
const context = await this.resolveContext(communityId, filters);
|
||||
let fragments = await this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
const rebuilt = await this.rebuildMissingOrStaleFragments(communityId);
|
||||
if (rebuilt > 0) {
|
||||
fragments = await this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
});
|
||||
}
|
||||
|
||||
const cards: InternalMatchCardView[] = [];
|
||||
const records: InternalRecord[] = [];
|
||||
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
|
||||
|
||||
for (const fragment of fragments) {
|
||||
const filteredGames = (fragment.gameDetails as InternalGameDetail[])
|
||||
.filter((game) => this.isGameInRange(game.gameCreation, context))
|
||||
.sort((left, right) => left.gameNumber - right.gameNumber);
|
||||
if (filteredGames.length === 0) continue;
|
||||
|
||||
const card = this.adjustCardForRange(
|
||||
fragment.matchCard as unknown as InternalMatchCardView,
|
||||
filteredGames,
|
||||
);
|
||||
cards.push(card);
|
||||
detailsByMatchId.set(fragment.matchId.toString(), filteredGames);
|
||||
|
||||
const allowedGameNumbers = new Set(
|
||||
filteredGames.map((game) => game.gameNumber),
|
||||
);
|
||||
records.push(
|
||||
...(fragment.records as InternalRecord[]).filter((record) =>
|
||||
allowedGameNumbers.has(record.gameNumber),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
season: context.season,
|
||||
matches: cards,
|
||||
records,
|
||||
detailsByMatchId,
|
||||
};
|
||||
}
|
||||
|
||||
private async rebuildMissingOrStaleFragments(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<number> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const [matches, fragments] = await Promise.all([
|
||||
MatchModel.find({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(MAX_MATCH_SCAN)
|
||||
.select({ _id: 1 })
|
||||
.exec(),
|
||||
this.matchStatsRepository.findByCommunity({
|
||||
communityId,
|
||||
limit: MAX_MATCH_SCAN,
|
||||
}),
|
||||
]);
|
||||
const fragmentByMatchId = new Map(
|
||||
fragments.map((fragment) => [fragment.matchId.toString(), fragment]),
|
||||
);
|
||||
let rebuilt = 0;
|
||||
|
||||
for (const match of matches) {
|
||||
const fragment = fragmentByMatchId.get(match._id.toString());
|
||||
if (fragment && fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
rebuilt += 1;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Failed to build match stats fragment for ${match._id.toString()}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return rebuilt;
|
||||
}
|
||||
|
||||
private adjustCardForRange(
|
||||
card: InternalMatchCardView,
|
||||
filteredGames: InternalGameDetail[],
|
||||
): InternalMatchCardView {
|
||||
const allowedGameNumbers = new Set(
|
||||
filteredGames.map((game) => game.gameNumber),
|
||||
);
|
||||
const games = card.games.filter((game) =>
|
||||
allowedGameNumbers.has(game.gameNumber),
|
||||
);
|
||||
const seriesResults = this.rebuildSeriesResults(games);
|
||||
return {
|
||||
...card,
|
||||
games,
|
||||
seriesResults,
|
||||
winnerTeamIndex: this.resolveWinnerTeamIndex(seriesResults),
|
||||
};
|
||||
}
|
||||
|
||||
private rebuildSeriesResults(
|
||||
games: InternalMatchCardView['games'],
|
||||
): InternalMatchCardView['seriesResults'] {
|
||||
const bySeries = new Map<
|
||||
string,
|
||||
InternalMatchCardView['seriesResults'][number]
|
||||
>();
|
||||
|
||||
for (const game of games) {
|
||||
if (game.winnerTeamIndex === null) continue;
|
||||
const teamAIndex = Math.min(game.blueTeamIndex, game.redTeamIndex);
|
||||
const teamBIndex = Math.max(game.blueTeamIndex, game.redTeamIndex);
|
||||
const key = `${teamAIndex}:${teamBIndex}`;
|
||||
const current = bySeries.get(key) ?? {
|
||||
teamAIndex,
|
||||
teamBIndex,
|
||||
teamAWins: 0,
|
||||
teamBWins: 0,
|
||||
};
|
||||
if (game.winnerTeamIndex === teamAIndex) current.teamAWins += 1;
|
||||
if (game.winnerTeamIndex === teamBIndex) current.teamBWins += 1;
|
||||
current.winnerTeamIndex =
|
||||
current.teamAWins > current.teamBWins
|
||||
? teamAIndex
|
||||
: current.teamBWins > current.teamAWins
|
||||
? teamBIndex
|
||||
: undefined;
|
||||
bySeries.set(key, current);
|
||||
}
|
||||
|
||||
return [...bySeries.values()].sort(
|
||||
(left, right) =>
|
||||
left.teamAIndex - right.teamAIndex ||
|
||||
left.teamBIndex - right.teamBIndex,
|
||||
);
|
||||
}
|
||||
|
||||
private resolveWinnerTeamIndex(
|
||||
seriesResults: InternalMatchCardView['seriesResults'],
|
||||
): number | undefined {
|
||||
const wins = new Map<number, number>();
|
||||
for (const series of seriesResults) {
|
||||
if (!series.winnerTeamIndex) continue;
|
||||
wins.set(
|
||||
series.winnerTeamIndex,
|
||||
(wins.get(series.winnerTeamIndex) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
return [...wins.entries()].sort(
|
||||
(left, right) => right[1] - left[1] || left[0] - right[0],
|
||||
)[0]?.[0];
|
||||
}
|
||||
|
||||
private async resolveContext(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): Promise<CommunityStatsContext> {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(communityId).exec();
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
const season = this.resolveSeason(community, filters.seasonId);
|
||||
const from = filters.from
|
||||
? new Date(filters.from)
|
||||
: season.startedAt
|
||||
? new Date(season.startedAt)
|
||||
: null;
|
||||
const to = filters.to ? new Date(filters.to) : null;
|
||||
if (from && Number.isNaN(from.getTime())) {
|
||||
throw new BadRequestException('Invalid from date.');
|
||||
}
|
||||
if (to && Number.isNaN(to.getTime())) {
|
||||
throw new BadRequestException('Invalid to date.');
|
||||
}
|
||||
return { community, season, from, to };
|
||||
}
|
||||
|
||||
private resolveSeason(
|
||||
community: CommunityDocument,
|
||||
seasonId?: string,
|
||||
): HistorySeasonDto {
|
||||
const seasons = this.resolveSeasons(community);
|
||||
if (seasonId === 'all') {
|
||||
return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null };
|
||||
}
|
||||
if (seasonId && seasonId !== 'current') {
|
||||
const selected = seasons.find((season) => season.id === seasonId);
|
||||
if (!selected) throw new BadRequestException('Invalid seasonId.');
|
||||
return selected;
|
||||
}
|
||||
return (
|
||||
seasons.find((season) => !season.endedAt) ??
|
||||
seasons[0] ?? {
|
||||
id: 'current',
|
||||
label: '현재 시즌',
|
||||
startedAt: community.seasonStartedAt?.toISOString() ?? null,
|
||||
endedAt: null,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] {
|
||||
const configured = community.seasons?.map((season) => ({
|
||||
id: season.id,
|
||||
label: season.label,
|
||||
startedAt: season.startedAt.toISOString(),
|
||||
endedAt: season.endedAt?.toISOString() ?? null,
|
||||
}));
|
||||
if (configured?.length) return configured;
|
||||
return [
|
||||
{
|
||||
id: 'current',
|
||||
label: '현재 시즌',
|
||||
startedAt: community.seasonStartedAt?.toISOString() ?? null,
|
||||
endedAt: null,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] {
|
||||
const byUser = new Map<string, InternalRecord[]>();
|
||||
for (const record of records) {
|
||||
byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]);
|
||||
}
|
||||
return [...byUser.entries()]
|
||||
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
);
|
||||
}
|
||||
|
||||
private toLeaderboardRow(
|
||||
userId: string,
|
||||
records: InternalRecord[],
|
||||
): LeaderboardRow {
|
||||
const first = records[0];
|
||||
const wins = records.filter((record) => record.win).length;
|
||||
const kills = this.sum(records, 'kills');
|
||||
const deaths = this.sum(records, 'deaths');
|
||||
const assists = this.sum(records, 'assists');
|
||||
const byLane: LeaderboardRow['byLane'] = {};
|
||||
for (const lane of [
|
||||
'TOP',
|
||||
'JUNGLE',
|
||||
'MIDDLE',
|
||||
'BOTTOM',
|
||||
'UTILITY',
|
||||
] as RiotLane[]) {
|
||||
const laneRecords = records.filter(
|
||||
(record) => record.teamPosition === lane,
|
||||
);
|
||||
if (laneRecords.length === 0) continue;
|
||||
byLane[lane] = {
|
||||
games: laneRecords.length,
|
||||
wins: laneRecords.filter((record) => record.win).length,
|
||||
kda: this.kda(
|
||||
this.sum(laneRecords, 'kills'),
|
||||
this.sum(laneRecords, 'deaths'),
|
||||
this.sum(laneRecords, 'assists'),
|
||||
),
|
||||
};
|
||||
}
|
||||
const championCounts = new Map<number, { games: number; wins: number }>();
|
||||
for (const record of records) {
|
||||
const current = championCounts.get(record.championId) ?? {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
};
|
||||
current.games += 1;
|
||||
current.wins += record.win ? 1 : 0;
|
||||
championCounts.set(record.championId, current);
|
||||
}
|
||||
|
||||
return {
|
||||
userId,
|
||||
summonerName: first?.summonerName ?? 'Unknown',
|
||||
profileIconId: first?.profileIconId ?? 0,
|
||||
games: records.length,
|
||||
wins,
|
||||
losses: records.length - wins,
|
||||
winRate: this.percent(wins, records.length),
|
||||
totalKills: kills,
|
||||
totalDeaths: deaths,
|
||||
totalAssists: assists,
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length),
|
||||
avgKillParticipation: this.average(
|
||||
this.sum(records, 'killParticipation'),
|
||||
records.length,
|
||||
),
|
||||
avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length),
|
||||
avgDamageShare: this.average(
|
||||
this.sum(records, 'damageShare'),
|
||||
records.length,
|
||||
),
|
||||
avgVisionScore: this.average(
|
||||
this.sum(records, 'visionScore'),
|
||||
records.length,
|
||||
),
|
||||
byLane,
|
||||
topChampions: [...championCounts.entries()]
|
||||
.map(([championId, stat]) => ({
|
||||
championId,
|
||||
games: stat.games,
|
||||
winRate: this.percent(stat.wins, stat.games),
|
||||
}))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
)
|
||||
.slice(0, 3),
|
||||
};
|
||||
}
|
||||
|
||||
private buildUserChampionStats(
|
||||
records: InternalRecord[],
|
||||
season: HistorySeasonDto,
|
||||
): LeaderboardChampionStats {
|
||||
const byChampion = new Map<number, InternalRecord[]>();
|
||||
for (const record of records) {
|
||||
byChampion.set(record.championId, [
|
||||
...(byChampion.get(record.championId) ?? []),
|
||||
record,
|
||||
]);
|
||||
}
|
||||
const champions = [...byChampion.entries()]
|
||||
.map(([championId, rows]) => this.toChampionRow(championId, rows))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
);
|
||||
const totals = this.toChampionRow(0, records);
|
||||
return {
|
||||
queueGroup: 'internal',
|
||||
rank: 'all',
|
||||
queueIds: [],
|
||||
season,
|
||||
lastFetchedAt: records[0]
|
||||
? new Date(records[0].gameCreation).toISOString()
|
||||
: null,
|
||||
champions,
|
||||
totals,
|
||||
};
|
||||
}
|
||||
|
||||
private toChampionRow(championId: number, rows: InternalRecord[]) {
|
||||
const wins = rows.filter((record) => record.win).length;
|
||||
const kills = this.sum(rows, 'kills');
|
||||
const deaths = this.sum(rows, 'deaths');
|
||||
const assists = this.sum(rows, 'assists');
|
||||
const gameMinutes = rows.reduce(
|
||||
(sum, record) => sum + Math.max(record.gameDuration / 60, 1),
|
||||
0,
|
||||
);
|
||||
return {
|
||||
championId,
|
||||
games: rows.length,
|
||||
wins,
|
||||
losses: rows.length - wins,
|
||||
winRate: this.percent(wins, rows.length),
|
||||
avgKills: this.average(kills, rows.length),
|
||||
avgDeaths: this.average(deaths, rows.length),
|
||||
avgAssists: this.average(assists, rows.length),
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
totalKills: kills,
|
||||
totalDeaths: deaths,
|
||||
totalAssists: assists,
|
||||
doubleKills: 0,
|
||||
tripleKills: 0,
|
||||
quadraKills: 0,
|
||||
pentaKills: 0,
|
||||
avgCs: this.average(this.sum(rows, 'cs'), rows.length),
|
||||
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
|
||||
};
|
||||
}
|
||||
|
||||
private buildUserSummary(
|
||||
records: InternalRecord[],
|
||||
requestedLimit: number,
|
||||
): UserInternalHistoryResponse['summary'] {
|
||||
const views = records.slice(0, requestedLimit);
|
||||
const wins = views.filter((record) => record.win).length;
|
||||
const kills = this.sum(views, 'kills');
|
||||
const deaths = this.sum(views, 'deaths');
|
||||
const assists = this.sum(views, 'assists');
|
||||
const best = views.reduce<InternalRecord | null>((bestRecord, record) => {
|
||||
if (!bestRecord) return record;
|
||||
return record.deaths === 0 || record.rating > bestRecord.rating
|
||||
? record
|
||||
: bestRecord;
|
||||
}, null);
|
||||
|
||||
return {
|
||||
windowSize: views.length,
|
||||
winRate: this.percent(wins, views.length),
|
||||
wins,
|
||||
losses: views.length - wins,
|
||||
streak: this.resolveStreak(views),
|
||||
kda: this.kda(kills, deaths, assists),
|
||||
avgKills: this.average(kills, views.length),
|
||||
avgDeaths: this.average(deaths, views.length),
|
||||
avgAssists: this.average(assists, views.length),
|
||||
bestRating: best
|
||||
? {
|
||||
rating: best.deaths === 0 ? 'Perfect' : best.rating,
|
||||
kills: best.kills,
|
||||
deaths: best.deaths,
|
||||
assists: best.assists,
|
||||
matchId: best.riotMatchId,
|
||||
}
|
||||
: null,
|
||||
positionRates: this.resolvePositionRates(views),
|
||||
topChampions: this.resolveTopChampions(views),
|
||||
lastFetchedAt: views[0]
|
||||
? new Date(views[0].gameCreation).toISOString()
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private toRecentMatchView(
|
||||
record: InternalRecord,
|
||||
dataset: BaseDataset,
|
||||
): RecentMatchView {
|
||||
const detail = dataset.detailsByMatchId
|
||||
.get(record.matchId)
|
||||
?.find((game) => game.riotMatchId === record.riotMatchId);
|
||||
return {
|
||||
matchId: record.riotMatchId,
|
||||
queueId: 0,
|
||||
queueLabel: '내전',
|
||||
gameCreation: record.gameCreation,
|
||||
gameDuration: record.gameDuration,
|
||||
win: record.win,
|
||||
remake: false,
|
||||
championId: record.championId,
|
||||
championLevel: record.championLevel,
|
||||
teamPosition: record.teamPosition,
|
||||
kills: record.kills,
|
||||
deaths: record.deaths,
|
||||
assists: record.assists,
|
||||
kda: this.kda(record.kills, record.deaths, record.assists),
|
||||
rating: record.rating,
|
||||
totalCs: record.cs,
|
||||
csPerMin: record.csPerMin,
|
||||
killParticipation: record.killParticipation,
|
||||
visionScore: record.visionScore,
|
||||
controlWardsBought: record.controlWardsBought,
|
||||
wardsPlaced: record.wardsPlaced,
|
||||
wardsKilled: record.wardsKilled,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageTaken: record.damageTaken,
|
||||
goldEarned: record.gold,
|
||||
items: record.items,
|
||||
trinket: record.trinket,
|
||||
summonerSpells: record.summonerSpells,
|
||||
perks: record.perks,
|
||||
teams: (detail?.teams ?? []).map((team) => ({
|
||||
side: team.side === 'blue' ? 100 : 200,
|
||||
win: team.win,
|
||||
objectives: team.objectives,
|
||||
participants: team.participants.map((participant) => ({
|
||||
puuid: participant.userId,
|
||||
gameName: participant.summonerName,
|
||||
tagLine: '',
|
||||
championId: participant.championId,
|
||||
championLevel: participant.championLevel,
|
||||
teamPosition: participant.teamPosition,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
items: participant.items,
|
||||
trinket: participant.trinket,
|
||||
summonerSpells: participant.summonerSpells,
|
||||
perks: participant.perks,
|
||||
totalCs: participant.cs,
|
||||
csPerMin: participant.csPerMin,
|
||||
goldEarned: participant.gold,
|
||||
damageDealtToChampions: participant.damageDealtToChampions,
|
||||
damageTaken: participant.damageTaken,
|
||||
visionScore: participant.visionScore,
|
||||
wardsPlaced: participant.wardsPlaced,
|
||||
wardsKilled: participant.wardsKilled,
|
||||
controlWardsBought: participant.controlWardsBought,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private applyChampionFilter(
|
||||
records: InternalRecord[],
|
||||
filters: CommunityStatsFilters,
|
||||
): InternalRecord[] {
|
||||
if (!filters.championId) return records;
|
||||
return records.filter((record) => record.championId === filters.championId);
|
||||
}
|
||||
|
||||
private isGameInRange(
|
||||
gameCreation: number,
|
||||
context: CommunityStatsContext,
|
||||
): boolean {
|
||||
if (context.from && gameCreation < context.from.getTime()) return false;
|
||||
if (context.to && gameCreation > context.to.getTime()) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private toHighlight(
|
||||
row: LeaderboardRow | undefined,
|
||||
field: keyof Pick<
|
||||
LeaderboardRow,
|
||||
'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin'
|
||||
>,
|
||||
): LeaderHighlight | null {
|
||||
if (!row) return null;
|
||||
return {
|
||||
metric: Number(row[field]),
|
||||
userId: row.userId,
|
||||
summonerName: row.summonerName,
|
||||
isSingleGame: false,
|
||||
};
|
||||
}
|
||||
|
||||
private toSingleGameHighlight(
|
||||
record: InternalRecord | undefined,
|
||||
field: keyof Pick<InternalRecord, 'gpm'>,
|
||||
): LeaderHighlight | null {
|
||||
if (!record) return null;
|
||||
return {
|
||||
metric: record[field],
|
||||
userId: record.userId,
|
||||
summonerName: record.summonerName,
|
||||
championId: record.championId,
|
||||
matchId: record.riotMatchId,
|
||||
isSingleGame: true,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveStreak(
|
||||
records: InternalRecord[],
|
||||
): UserInternalHistoryResponse['summary']['streak'] {
|
||||
if (records.length === 0) return null;
|
||||
const firstWin = records[0].win;
|
||||
let count = 0;
|
||||
for (const record of records) {
|
||||
if (record.win !== firstWin) break;
|
||||
count += 1;
|
||||
}
|
||||
return { type: firstWin ? 'win' : 'loss', count };
|
||||
}
|
||||
|
||||
private resolvePositionRates(
|
||||
records: InternalRecord[],
|
||||
): Partial<Record<RiotLane, number>> {
|
||||
const counts = new Map<string, number>();
|
||||
for (const record of records) {
|
||||
if (!record.teamPosition) continue;
|
||||
counts.set(
|
||||
record.teamPosition,
|
||||
(counts.get(record.teamPosition) ?? 0) + 1,
|
||||
);
|
||||
}
|
||||
return Object.fromEntries(
|
||||
[...counts.entries()].map(([lane, count]) => [
|
||||
lane,
|
||||
this.percent(count, records.length),
|
||||
]),
|
||||
) as Partial<Record<RiotLane, number>>;
|
||||
}
|
||||
|
||||
private resolveTopChampions(records: InternalRecord[]) {
|
||||
const byChampion = new Map<
|
||||
number,
|
||||
{ games: number; wins: number; rating: number }
|
||||
>();
|
||||
for (const record of records) {
|
||||
const current = byChampion.get(record.championId) ?? {
|
||||
games: 0,
|
||||
wins: 0,
|
||||
rating: 0,
|
||||
};
|
||||
current.games += 1;
|
||||
current.wins += record.win ? 1 : 0;
|
||||
current.rating += record.rating;
|
||||
byChampion.set(record.championId, current);
|
||||
}
|
||||
return [...byChampion.entries()]
|
||||
.map(([championId, stat]) => ({
|
||||
championId,
|
||||
games: stat.games,
|
||||
winRate: this.percent(stat.wins, stat.games),
|
||||
pickRate: this.percent(stat.games, records.length),
|
||||
avgRating: this.average(stat.rating, stat.games),
|
||||
}))
|
||||
.sort(
|
||||
(left, right) =>
|
||||
right.games - left.games || right.winRate - left.winRate,
|
||||
)
|
||||
.slice(0, 3);
|
||||
}
|
||||
|
||||
private cacheKey(
|
||||
scope: string,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
filters: CommunityStatsFilters,
|
||||
): string {
|
||||
return [
|
||||
'riot:communitystats',
|
||||
scope,
|
||||
communityId.toString(),
|
||||
filters.seasonId ?? 'current',
|
||||
filters.from ?? '',
|
||||
filters.to ?? '',
|
||||
filters.championId ?? '',
|
||||
filters.cursor ?? '',
|
||||
filters.limit ?? '',
|
||||
].join(':');
|
||||
}
|
||||
|
||||
private clampLimit(
|
||||
value: number | undefined,
|
||||
fallback: number,
|
||||
max: number,
|
||||
): number {
|
||||
if (!value || !Number.isFinite(value)) return fallback;
|
||||
return Math.max(1, Math.min(Math.floor(value), max));
|
||||
}
|
||||
|
||||
private sum<T extends keyof InternalRecord>(
|
||||
records: InternalRecord[],
|
||||
field: T,
|
||||
): number {
|
||||
return records.reduce((total, record) => {
|
||||
const value = record[field];
|
||||
return total + (typeof value === 'number' ? value : 0);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
private kda(kills: number, deaths: number, assists: number): number {
|
||||
return deaths === 0
|
||||
? kills + assists
|
||||
: this.round((kills + assists) / deaths);
|
||||
}
|
||||
|
||||
private percent(value: number, total: number): number {
|
||||
return total > 0 ? Math.round((value / total) * 100) : 0;
|
||||
}
|
||||
|
||||
private average(value: number, total: number): number {
|
||||
return total > 0 ? this.round(value / total) : 0;
|
||||
}
|
||||
|
||||
private round(value: number): number {
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import type { RiotLane, TeamSide } from '../global/database/schema';
|
||||
import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types';
|
||||
|
||||
export interface CommunityStatsFilters {
|
||||
seasonId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
championId?: number;
|
||||
cursor?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export interface InternalMatchListResponse {
|
||||
matches: InternalMatchCardView[];
|
||||
nextCursor: number | null;
|
||||
season: HistorySeasonDto;
|
||||
}
|
||||
|
||||
export interface InternalMatchCardView {
|
||||
matchId: string;
|
||||
title: string;
|
||||
scheduledAt: string;
|
||||
status: 'finished' | 'in-progress';
|
||||
gameCount: number;
|
||||
winnerTeamIndex?: number;
|
||||
seriesResults: Array<{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string | null;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
winnerTeamIndex: number | null;
|
||||
winnerSide: TeamSide | null;
|
||||
gameDuration: number;
|
||||
}>;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface LeaderboardResponse {
|
||||
rows: LeaderboardRow[];
|
||||
season: HistorySeasonDto;
|
||||
}
|
||||
|
||||
export interface LeaderboardRow {
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
profileIconId: number;
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
winRate: number;
|
||||
totalKills: number;
|
||||
totalDeaths: number;
|
||||
totalAssists: number;
|
||||
kda: number;
|
||||
avgGoldPerMin: number;
|
||||
avgKillParticipation: number;
|
||||
avgCsPerMin: number;
|
||||
avgDamageShare: number;
|
||||
avgVisionScore: number;
|
||||
byLane: Partial<Record<RiotLane, { games: number; wins: number; kda: number }>>;
|
||||
topChampions: Array<{ championId: number; games: number; winRate: number }>;
|
||||
}
|
||||
|
||||
export interface LeaderHighlight {
|
||||
metric: number;
|
||||
userId: string;
|
||||
summonerName: string;
|
||||
championId?: number;
|
||||
matchId?: string;
|
||||
isSingleGame: boolean;
|
||||
}
|
||||
|
||||
export interface TeamInsightsResponse {
|
||||
season: HistorySeasonDto;
|
||||
sideWinRate: {
|
||||
blue: number;
|
||||
red: number;
|
||||
bluePicks: number;
|
||||
redPicks: number;
|
||||
};
|
||||
topKda: LeaderHighlight | null;
|
||||
mostKills: LeaderHighlight | null;
|
||||
topTeamGpm: LeaderHighlight | null;
|
||||
topKillParticipation: LeaderHighlight | null;
|
||||
bestFarm: LeaderHighlight | null;
|
||||
minGamesThreshold: number;
|
||||
}
|
||||
|
||||
export interface InternalMatchDetailResponse {
|
||||
match: InternalMatchCardView;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
riotMatchId: string;
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
win: boolean;
|
||||
objectives: { baron: number; dragon: number; tower: number };
|
||||
participants: Array<{
|
||||
userId: string | null;
|
||||
summonerName: string;
|
||||
teamIndex: number;
|
||||
side: TeamSide;
|
||||
teamPosition: string;
|
||||
championId: number;
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
cs: number;
|
||||
csPerMin: number;
|
||||
gold: number;
|
||||
gpm: number;
|
||||
damageDealtToChampions: number;
|
||||
damageShare: number;
|
||||
killParticipation: number;
|
||||
visionScore: number;
|
||||
items: number[];
|
||||
trinket: number;
|
||||
summonerSpells: [number, number];
|
||||
perks: { primaryStyle?: number; subStyle?: number; keystone?: number };
|
||||
win: boolean;
|
||||
}>;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface UserInternalHistoryResponse {
|
||||
season: HistorySeasonDto;
|
||||
championStats: LeaderboardChampionStats;
|
||||
summary: {
|
||||
windowSize: number;
|
||||
winRate: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
streak: { type: 'win' | 'loss'; count: number } | null;
|
||||
kda: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
bestRating: {
|
||||
rating: number | 'Perfect';
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
matchId: string;
|
||||
} | null;
|
||||
positionRates: Partial<Record<RiotLane, number>>;
|
||||
topChampions: Array<{
|
||||
championId: number;
|
||||
games: number;
|
||||
winRate: number;
|
||||
pickRate: number;
|
||||
avgRating: number;
|
||||
}>;
|
||||
lastFetchedAt: string | null;
|
||||
};
|
||||
matches: RecentMatchView[];
|
||||
nextCursor: number | null;
|
||||
lastFetchedAt: string | null;
|
||||
}
|
||||
|
||||
export interface LeaderboardChampionStats {
|
||||
queueGroup: 'internal';
|
||||
rank: 'all';
|
||||
queueIds: number[];
|
||||
season: HistorySeasonDto;
|
||||
lastFetchedAt: string | null;
|
||||
champions: Array<{
|
||||
championId: number;
|
||||
games: number;
|
||||
wins: number;
|
||||
losses: number;
|
||||
winRate: number;
|
||||
avgKills: number;
|
||||
avgDeaths: number;
|
||||
avgAssists: number;
|
||||
kda: number;
|
||||
totalKills: number;
|
||||
totalDeaths: number;
|
||||
totalAssists: number;
|
||||
doubleKills: number;
|
||||
tripleKills: number;
|
||||
quadraKills: number;
|
||||
pentaKills: number;
|
||||
avgCs: number;
|
||||
avgCsPerMin: number;
|
||||
}>;
|
||||
totals: LeaderboardChampionStats['champions'][number];
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
|
||||
function makeMatch(): MatchDocument {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
return {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
title: '내전',
|
||||
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||
status: 'finished',
|
||||
gameCount: 1,
|
||||
participants: [
|
||||
{
|
||||
userId,
|
||||
puuid: 'puuid-1',
|
||||
gameName: 'Player',
|
||||
profileIconId: 7,
|
||||
},
|
||||
],
|
||||
teams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
name: 'A',
|
||||
members: [{ userId, assignedPosition: 'TOP' }],
|
||||
},
|
||||
{ teamIndex: 2, name: 'B', members: [] },
|
||||
],
|
||||
result: {
|
||||
winnerTeamIndex: 1,
|
||||
riotMatchIds: ['KR_1'],
|
||||
games: [
|
||||
{
|
||||
gameNumber: 1,
|
||||
riotMatchId: 'KR_1',
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex: 1,
|
||||
winnerSide: 'blue',
|
||||
gameCreation: 1_000,
|
||||
gameDuration: 1_800,
|
||||
participants: [
|
||||
{
|
||||
userId,
|
||||
teamIndex: 1,
|
||||
side: 'blue',
|
||||
championId: 266,
|
||||
kills: 5,
|
||||
deaths: 1,
|
||||
assists: 7,
|
||||
win: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: 1,
|
||||
teamBWins: 0,
|
||||
winnerTeamIndex: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as MatchDocument;
|
||||
}
|
||||
|
||||
describe('MatchStatsFragmentBuilder', () => {
|
||||
it('builds a fallback fragment without raw Riot match data', () => {
|
||||
const builder = new MatchStatsFragmentBuilder();
|
||||
const match = makeMatch();
|
||||
|
||||
const fragment = builder.buildFragment({
|
||||
match,
|
||||
rawByRiotMatchId: new Map(),
|
||||
});
|
||||
|
||||
expect(fragment.matchCard.matchId).toBe(match._id.toString());
|
||||
expect(fragment.gameCreationMin).toBe(1_000);
|
||||
expect(fragment.gameCreationMax).toBe(1_000);
|
||||
expect(fragment.userIds.map((id) => id.toString())).toEqual([
|
||||
match.participants[0].userId.toString(),
|
||||
]);
|
||||
expect(fragment.championIds).toEqual([266]);
|
||||
expect(fragment.records).toHaveLength(1);
|
||||
expect(fragment.records[0]).toMatchObject({
|
||||
summonerName: 'Player',
|
||||
championId: 266,
|
||||
kills: 5,
|
||||
deaths: 1,
|
||||
assists: 7,
|
||||
win: true,
|
||||
});
|
||||
expect(fragment.gameDetails[0].teams[0].participants).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,367 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchDocument,
|
||||
MatchGameResultParticipant,
|
||||
TeamSide,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
import type {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
MatchStatsFragment,
|
||||
} from './match-stats.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsFragmentBuilder {
|
||||
public buildFragment(params: {
|
||||
match: MatchDocument;
|
||||
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||
}): MatchStatsFragment {
|
||||
const games = [...(params.match.result?.games ?? [])].sort(
|
||||
(left, right) => left.gameNumber - right.gameNumber,
|
||||
);
|
||||
const matchCard = this.toMatchCard(params.match, games);
|
||||
const gameDetails = games.map((game) => {
|
||||
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
||||
return raw
|
||||
? this.toGameDetail(params.match, game, raw)
|
||||
: this.toFallbackGameDetail(params.match, game);
|
||||
});
|
||||
const records = gameDetails.flatMap((detail) =>
|
||||
detail.teams.flatMap((team) => team.participants),
|
||||
);
|
||||
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
|
||||
|
||||
return {
|
||||
matchCard,
|
||||
records,
|
||||
gameDetails,
|
||||
userIds: [
|
||||
...new Map(
|
||||
records
|
||||
.filter((record) => mongoose.isValidObjectId(record.userId))
|
||||
.map((record) => [
|
||||
record.userId,
|
||||
new mongoose.Types.ObjectId(record.userId),
|
||||
]),
|
||||
).values(),
|
||||
],
|
||||
championIds: [...new Set(records.map((record) => record.championId))],
|
||||
gameCreationMin:
|
||||
gameCreations.length > 0
|
||||
? Math.min(...gameCreations)
|
||||
: params.match.scheduledAt.getTime(),
|
||||
gameCreationMax:
|
||||
gameCreations.length > 0
|
||||
? Math.max(...gameCreations)
|
||||
: params.match.scheduledAt.getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
private toMatchCard(
|
||||
match: MatchDocument,
|
||||
games: NonNullable<MatchDocument['result']>['games'],
|
||||
): InternalMatchCardView {
|
||||
const participantById = new Map(
|
||||
match.participants.map((participant) => [
|
||||
participant.userId.toString(),
|
||||
participant,
|
||||
]),
|
||||
);
|
||||
return {
|
||||
matchId: match._id.toString(),
|
||||
title: match.title,
|
||||
scheduledAt: match.scheduledAt.toISOString(),
|
||||
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
||||
gameCount: match.gameCount,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
seriesResults: match.result?.seriesResults ?? [],
|
||||
games: games.map((game) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId ?? null,
|
||||
blueTeamIndex: game.blueTeamIndex,
|
||||
redTeamIndex: game.redTeamIndex,
|
||||
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
||||
winnerSide: game.winnerSide ?? null,
|
||||
gameDuration: game.gameDuration,
|
||||
})),
|
||||
teams: match.teams.map((team) => ({
|
||||
teamIndex: team.teamIndex,
|
||||
name: team.name,
|
||||
members: team.members.map((member) => {
|
||||
const participant = participantById.get(member.userId.toString());
|
||||
return {
|
||||
userId: member.userId.toString(),
|
||||
summonerName: participant?.gameName ?? 'Unknown',
|
||||
profileIconId: participant?.profileIconId ?? 0,
|
||||
};
|
||||
}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private toGameDetail(
|
||||
match: MatchDocument,
|
||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||
raw: RiotMatchDto,
|
||||
): InternalGameDetail {
|
||||
const puuidByUserId = new Map(
|
||||
match.participants
|
||||
.filter((participant) => participant.puuid)
|
||||
.map((participant) => [
|
||||
participant.userId.toString(),
|
||||
participant.puuid as string,
|
||||
]),
|
||||
);
|
||||
const rawByPuuid = new Map(
|
||||
raw.info.participants.map((participant) => [
|
||||
participant.puuid,
|
||||
participant,
|
||||
]),
|
||||
);
|
||||
const rawTeamIdBySide = new Map<TeamSide, number>();
|
||||
for (const participant of game.participants) {
|
||||
const puuid = puuidByUserId.get(participant.userId.toString());
|
||||
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
|
||||
if (rawParticipant) {
|
||||
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||
const teamIndex =
|
||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||
const rawTeamId = rawTeamIdBySide.get(side);
|
||||
const rawTeam = raw.info.teams.find(
|
||||
(team) => team.teamId === rawTeamId,
|
||||
);
|
||||
const teamRawParticipants = raw.info.participants.filter(
|
||||
(participant) => participant.teamId === rawTeamId,
|
||||
);
|
||||
const teamKills = teamRawParticipants.reduce(
|
||||
(sum, participant) => sum + participant.kills,
|
||||
0,
|
||||
);
|
||||
const teamDamage = teamRawParticipants.reduce(
|
||||
(sum, participant) => sum + participant.totalDamageDealtToChampions,
|
||||
0,
|
||||
);
|
||||
return {
|
||||
teamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: {
|
||||
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
||||
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
||||
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
||||
},
|
||||
participants: game.participants
|
||||
.filter((participant) => participant.side === side)
|
||||
.map((participant) =>
|
||||
this.toRecord({
|
||||
match,
|
||||
game,
|
||||
participant,
|
||||
rawParticipant: rawByPuuid.get(
|
||||
puuidByUserId.get(participant.userId.toString()) ?? '',
|
||||
),
|
||||
teamKills,
|
||||
teamDamage,
|
||||
}),
|
||||
),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private toFallbackGameDetail(
|
||||
match: MatchDocument,
|
||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||
): InternalGameDetail {
|
||||
return {
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
winnerSide: game.winnerSide,
|
||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||
side,
|
||||
win: game.winnerSide === side,
|
||||
objectives: { baron: 0, dragon: 0, tower: 0 },
|
||||
participants: game.participants
|
||||
.filter((participant) => participant.side === side)
|
||||
.map((participant) =>
|
||||
this.toRecord({
|
||||
match,
|
||||
game,
|
||||
participant,
|
||||
teamKills: 0,
|
||||
teamDamage: 0,
|
||||
}),
|
||||
),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private toRecord(params: {
|
||||
match: MatchDocument;
|
||||
game: NonNullable<MatchDocument['result']>['games'][number];
|
||||
participant: MatchGameResultParticipant;
|
||||
rawParticipant?: RiotMatchParticipantDto;
|
||||
teamKills: number;
|
||||
teamDamage: number;
|
||||
}): InternalRecord {
|
||||
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
|
||||
params;
|
||||
const snapshot = match.participants.find((item) =>
|
||||
item.userId.equals(participant.userId),
|
||||
);
|
||||
const minutes = Math.max(
|
||||
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
|
||||
1,
|
||||
);
|
||||
const cs = rawParticipant
|
||||
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
|
||||
: 0;
|
||||
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
|
||||
const killParticipation = percent(
|
||||
participant.kills + participant.assists,
|
||||
teamKills,
|
||||
);
|
||||
const damageShare = percent(damage, teamDamage);
|
||||
const rating = this.resolveRating({
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
killParticipation,
|
||||
csPerMin: average(cs, minutes),
|
||||
damageShare,
|
||||
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
|
||||
});
|
||||
|
||||
return {
|
||||
matchId: match._id.toString(),
|
||||
title: match.title,
|
||||
scheduledAt: match.scheduledAt,
|
||||
gameNumber: game.gameNumber,
|
||||
riotMatchId: game.riotMatchId,
|
||||
gameCreation: game.gameCreation,
|
||||
gameDuration: game.gameDuration,
|
||||
userId: participant.userId.toString(),
|
||||
summonerName:
|
||||
snapshot?.gameName ??
|
||||
rawParticipant?.riotIdGameName ??
|
||||
rawParticipant?.summonerName ??
|
||||
'Unknown',
|
||||
profileIconId: snapshot?.profileIconId ?? 0,
|
||||
teamIndex: participant.teamIndex,
|
||||
side: participant.side,
|
||||
championId: participant.championId,
|
||||
championLevel: rawParticipant?.champLevel ?? 0,
|
||||
teamPosition:
|
||||
rawParticipant?.teamPosition ||
|
||||
rawParticipant?.individualPosition ||
|
||||
'',
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
win: participant.win,
|
||||
cs,
|
||||
csPerMin: average(cs, minutes),
|
||||
gold: rawParticipant?.goldEarned ?? 0,
|
||||
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
|
||||
damageDealtToChampions: damage,
|
||||
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
|
||||
damageShare,
|
||||
killParticipation,
|
||||
visionScore: rawParticipant?.visionScore ?? 0,
|
||||
controlWardsBought: numberField(
|
||||
rawParticipant,
|
||||
'visionWardsBoughtInGame',
|
||||
),
|
||||
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
|
||||
wardsKilled: rawParticipant?.wardsKilled ?? 0,
|
||||
items: [
|
||||
rawParticipant?.item0 ?? 0,
|
||||
rawParticipant?.item1 ?? 0,
|
||||
rawParticipant?.item2 ?? 0,
|
||||
rawParticipant?.item3 ?? 0,
|
||||
rawParticipant?.item4 ?? 0,
|
||||
rawParticipant?.item5 ?? 0,
|
||||
],
|
||||
trinket: rawParticipant?.item6 ?? 0,
|
||||
summonerSpells: [
|
||||
rawParticipant?.summoner1Id ?? 0,
|
||||
rawParticipant?.summoner2Id ?? 0,
|
||||
],
|
||||
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
|
||||
rating,
|
||||
};
|
||||
}
|
||||
|
||||
private resolvePerks(participant: RiotMatchParticipantDto) {
|
||||
const primary = participant.perks.styles.find(
|
||||
(style) => style.description === 'primaryStyle',
|
||||
);
|
||||
const sub = participant.perks.styles.find(
|
||||
(style) => style.description === 'subStyle',
|
||||
);
|
||||
return {
|
||||
primaryStyle: primary?.style,
|
||||
subStyle: sub?.style,
|
||||
keystone: primary?.selections[0]?.perk,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveRating(params: {
|
||||
kills: number;
|
||||
deaths: number;
|
||||
assists: number;
|
||||
killParticipation: number;
|
||||
csPerMin: number;
|
||||
damageShare: number;
|
||||
visionPerMin: number;
|
||||
}): number {
|
||||
const kdaScore = kda(params.kills, params.deaths, params.assists);
|
||||
const score =
|
||||
Math.min(kdaScore / 6, 1) * 4 +
|
||||
Math.min(params.killParticipation / 100, 1) * 2 +
|
||||
Math.min(params.csPerMin / 9, 1) * 2 +
|
||||
Math.min(params.damageShare / 35, 1) +
|
||||
Math.min(params.visionPerMin / 2, 1);
|
||||
return round(score);
|
||||
}
|
||||
}
|
||||
|
||||
function kda(kills: number, deaths: number, assists: number): number {
|
||||
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
|
||||
}
|
||||
|
||||
function percent(value: number, total: number): number {
|
||||
return total > 0 ? Math.round((value / total) * 100) : 0;
|
||||
}
|
||||
|
||||
function average(value: number, total: number): number {
|
||||
return total > 0 ? round(value / total) : 0;
|
||||
}
|
||||
|
||||
function round(value: number): number {
|
||||
return Math.round(value * 10) / 10;
|
||||
}
|
||||
|
||||
function numberField(
|
||||
participant: RiotMatchParticipantDto | undefined,
|
||||
key: string,
|
||||
): number {
|
||||
const value = participant?.[key];
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async upsert(
|
||||
fragment: Omit<MatchStats, 'createdAt' | 'updatedAt'>,
|
||||
): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.updateOne(
|
||||
{ matchId: fragment.matchId },
|
||||
{ $set: fragment },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteOne({ matchId }).exec();
|
||||
}
|
||||
|
||||
public async deleteByMatches(
|
||||
matchIds: mongoose.Types.ObjectId[],
|
||||
): Promise<void> {
|
||||
if (matchIds.length === 0) return;
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
await MatchStatsModel.deleteMany({ matchId: { $in: matchIds } }).exec();
|
||||
}
|
||||
|
||||
public async findByMatch(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<MatchStatsDocument | null> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
return MatchStatsModel.findOne({ matchId }).exec();
|
||||
}
|
||||
|
||||
public async findByCommunity(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
limit?: number;
|
||||
}): Promise<MatchStatsDocument[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
};
|
||||
if (params.fromGameCreation !== undefined) {
|
||||
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||
}
|
||||
if (params.toGameCreation !== undefined) {
|
||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||
}
|
||||
|
||||
return MatchStatsModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(params.limit ?? 300)
|
||||
.exec();
|
||||
}
|
||||
|
||||
public async findByUser(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
fromGameCreation?: number;
|
||||
toGameCreation?: number;
|
||||
}): Promise<MatchStatsDocument[]> {
|
||||
const MatchStatsModel = await this.connectionService.getModel('matchStats');
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
userIds: params.userId,
|
||||
};
|
||||
if (params.fromGameCreation !== undefined) {
|
||||
filter.gameCreationMax = { $gte: params.fromGameCreation };
|
||||
}
|
||||
if (params.toGameCreation !== undefined) {
|
||||
filter.gameCreationMin = { $lte: params.toGameCreation };
|
||||
}
|
||||
|
||||
return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
|
||||
describe('MatchStatsService', () => {
|
||||
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({
|
||||
_id: matchId,
|
||||
status: 'recruiting',
|
||||
result: undefined,
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
if (name === 'riotMatch') return {};
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = {
|
||||
deleteByMatch: jest.fn().mockResolvedValue(undefined),
|
||||
upsert: jest.fn(),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const service = new MatchStatsService(
|
||||
connectionService,
|
||||
repository,
|
||||
{} as MatchStatsFragmentBuilder,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(repository.deleteByMatch).toHaveBeenCalledWith(matchId);
|
||||
expect(repository.upsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('upserts a fragment for eligible matches', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const scheduledAt = new Date('2026-05-03T00:00:00.000Z');
|
||||
const match = {
|
||||
_id: matchId,
|
||||
communityId,
|
||||
scheduledAt,
|
||||
status: 'finished',
|
||||
result: { games: [{ riotMatchId: 'KR_1' }] },
|
||||
};
|
||||
const findById = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue(match),
|
||||
});
|
||||
const riotFind = jest.fn().mockReturnValue({
|
||||
lean: () => ({
|
||||
exec: jest.fn().mockResolvedValue([{ matchId: 'KR_1', raw: {} }]),
|
||||
}),
|
||||
});
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockImplementation(async (name: string) => {
|
||||
if (name === 'match') return { findById };
|
||||
if (name === 'riotMatch') return { find: riotFind };
|
||||
throw new Error(`Unexpected model: ${name}`);
|
||||
}),
|
||||
} as unknown as ConnectionService;
|
||||
const repository = {
|
||||
upsert: jest.fn().mockResolvedValue(undefined),
|
||||
deleteByMatch: jest.fn(),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const builder = {
|
||||
buildFragment: jest.fn().mockReturnValue({
|
||||
matchCard: { matchId: matchId.toString() },
|
||||
records: [],
|
||||
gameDetails: [],
|
||||
userIds: [],
|
||||
championIds: [],
|
||||
gameCreationMin: 1_000,
|
||||
gameCreationMax: 2_000,
|
||||
}),
|
||||
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
|
||||
const service = new MatchStatsService(
|
||||
connectionService,
|
||||
repository,
|
||||
builder,
|
||||
);
|
||||
|
||||
await service.buildAndUpsert(matchId);
|
||||
|
||||
expect(builder.buildFragment).toHaveBeenCalledWith({
|
||||
match,
|
||||
rawByRiotMatchId: expect.any(Map),
|
||||
});
|
||||
expect(repository.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
communityId,
|
||||
scheduledAt,
|
||||
gameCreationMin: 1_000,
|
||||
gameCreationMax: 2_000,
|
||||
builderVersion: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type { MatchDocument } from '../global/database/schema';
|
||||
import type { RiotMatchDto } from '../riot/riot.types';
|
||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||
|
||||
@Injectable()
|
||||
export class MatchStatsService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly repository: MatchStatsRepository,
|
||||
private readonly builder: MatchStatsFragmentBuilder,
|
||||
) {}
|
||||
|
||||
public async buildAndUpsert(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const match = await MatchModel.findById(matchId).exec();
|
||||
if (!match) return;
|
||||
if (!this.isEligible(match)) {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
return;
|
||||
}
|
||||
|
||||
const riotIds = [
|
||||
...new Set(
|
||||
(match.result?.games ?? [])
|
||||
.map((game) => game.riotMatchId)
|
||||
.filter((riotMatchId): riotMatchId is string => Boolean(riotMatchId)),
|
||||
),
|
||||
];
|
||||
const riotDocs =
|
||||
riotIds.length > 0
|
||||
? await RiotMatchModel.find({ matchId: { $in: riotIds } })
|
||||
.lean()
|
||||
.exec()
|
||||
: [];
|
||||
const rawByRiotMatchId = new Map(
|
||||
riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
|
||||
);
|
||||
const fragment = this.builder.buildFragment({ match, rawByRiotMatchId });
|
||||
|
||||
await this.repository.upsert({
|
||||
matchId: match._id,
|
||||
communityId: match.communityId,
|
||||
scheduledAt: match.scheduledAt,
|
||||
gameCreationMin: fragment.gameCreationMin,
|
||||
gameCreationMax: fragment.gameCreationMax,
|
||||
userIds: fragment.userIds,
|
||||
championIds: fragment.championIds,
|
||||
matchCard: fragment.matchCard as unknown as Record<string, unknown>,
|
||||
records: fragment.records,
|
||||
gameDetails: fragment.gameDetails,
|
||||
builtAt: new Date(),
|
||||
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||
});
|
||||
}
|
||||
|
||||
public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise<void> {
|
||||
await this.repository.deleteByMatch(matchId);
|
||||
}
|
||||
|
||||
public async removeByMatches(
|
||||
matchIds: mongoose.Types.ObjectId[],
|
||||
): Promise<void> {
|
||||
await this.repository.deleteByMatches(matchIds);
|
||||
}
|
||||
|
||||
public async backfillCommunity(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<{ processed: number; failed: number }> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const matches = await MatchModel.find({
|
||||
communityId,
|
||||
status: { $in: ['finished', 'in-progress'] },
|
||||
'result.games.0': { $exists: true },
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.select({ _id: 1 })
|
||||
.exec();
|
||||
|
||||
let processed = 0;
|
||||
let failed = 0;
|
||||
for (const match of matches) {
|
||||
try {
|
||||
await this.buildAndUpsert(match._id);
|
||||
processed += 1;
|
||||
} catch {
|
||||
failed += 1;
|
||||
}
|
||||
}
|
||||
return { processed, failed };
|
||||
}
|
||||
|
||||
private isEligible(match: MatchDocument): boolean {
|
||||
return (
|
||||
(match.status === 'finished' || match.status === 'in-progress') &&
|
||||
Boolean(match.result?.games?.length)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {
|
||||
MatchStatsGameDetail,
|
||||
MatchStatsRecord,
|
||||
} from '../global/database/schema';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
|
||||
export const MATCH_STATS_BUILDER_VERSION = 1;
|
||||
|
||||
export type InternalRecord = MatchStatsRecord;
|
||||
export type InternalGameDetail = MatchStatsGameDetail;
|
||||
|
||||
export interface MatchStatsFragment {
|
||||
matchCard: InternalMatchCardView;
|
||||
records: InternalRecord[];
|
||||
gameDetails: InternalGameDetail[];
|
||||
userIds: import('mongoose').Types.ObjectId[];
|
||||
championIds: number[];
|
||||
gameCreationMin: number;
|
||||
gameCreationMax: number;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { Roles } from '../auth/roles.decorator';
|
||||
import { RolesGuard } from '../auth/roles.guard';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import type {
|
||||
BulkDeleteLegacyMatchesRequest,
|
||||
StartLegacyImportRequest,
|
||||
} from './legacy-import.types';
|
||||
import { LegacyImportService } from './legacy-import.service';
|
||||
|
||||
@Controller('communities/:communityId')
|
||||
@Roles('owner', 'admin')
|
||||
@UseGuards(RolesGuard)
|
||||
export class LegacyImportController {
|
||||
constructor(private readonly legacyImportService: LegacyImportService) {}
|
||||
|
||||
@Get('legacy-import/members')
|
||||
public previewMembers(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('windowStart') windowStart?: string,
|
||||
@Query('windowEnd') windowEnd?: string,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.previewMembers({
|
||||
communityId,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('legacy-import')
|
||||
public start(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Body() body: StartLegacyImportRequest,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.start({
|
||||
communityId,
|
||||
triggeredBy: currentUser._id,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
@Get('legacy-import-jobs')
|
||||
public listJobs(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.listJobs({
|
||||
communityId,
|
||||
limit: this.toNumber(limit),
|
||||
});
|
||||
}
|
||||
|
||||
@Get('legacy-import-jobs/:jobId')
|
||||
public getJob(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('jobId') jobId: string,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.getJob({ communityId, jobId });
|
||||
}
|
||||
|
||||
@Post('legacy-import-jobs/:jobId/cancel')
|
||||
public cancel(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('jobId') jobId: string,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.cancel({ communityId, jobId });
|
||||
}
|
||||
|
||||
@Get('legacy-matches')
|
||||
public listLegacyMatches(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('limit') limit?: string,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.listLegacyMatches({
|
||||
communityId,
|
||||
cursor: this.toNumber(cursor),
|
||||
limit: this.toNumber(limit),
|
||||
});
|
||||
}
|
||||
|
||||
@Post('legacy-matches/bulk-delete')
|
||||
public bulkDeleteLegacyMatches(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Body() body: BulkDeleteLegacyMatchesRequest,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.bulkDeleteLegacyMatches({
|
||||
communityId,
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
@Post('legacy-matches/rebuild')
|
||||
public rebuildLegacyMatches(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
return this.legacyImportService.rebuildLegacyMatches({ communityId });
|
||||
}
|
||||
|
||||
private assertSameCommunity(
|
||||
user: UserDocument,
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): void {
|
||||
if (!user.communityId.equals(communityId)) {
|
||||
throw new BadRequestException('Different community.');
|
||||
}
|
||||
}
|
||||
|
||||
private toNumber(value: string | undefined): number | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CommunityStatsModule } from '../community-stats/community-stats.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { LegacyImportController } from './legacy-import.controller';
|
||||
import { LegacyImportService } from './legacy-import.service';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, CommunityStatsModule],
|
||||
controllers: [LegacyImportController],
|
||||
providers: [LegacyImportService],
|
||||
exports: [LegacyImportService],
|
||||
})
|
||||
export class LegacyImportModule {}
|
||||
@@ -0,0 +1,838 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { MatchStatsService } from '../community-stats/match-stats.service';
|
||||
import { CommunityStatsService } from '../community-stats/community-stats.service';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
LegacyImportJobDocument,
|
||||
Match,
|
||||
RiotMatch as StoredRiotMatch,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types';
|
||||
import { RiotMatchService } from '../riot/riot-match.service';
|
||||
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
|
||||
import {
|
||||
buildGameResult,
|
||||
buildParticipantsSnapshot,
|
||||
buildTeams,
|
||||
buildUserByPuuidMap,
|
||||
countKnownParticipants,
|
||||
resolveExternalCount,
|
||||
type UserByPuuidMap,
|
||||
} from './match-builder.util';
|
||||
import {
|
||||
LEGACY_IMPORT_DEFAULT_START_ISO,
|
||||
LEGACY_IMPORT_LOCK_TTL_SECONDS,
|
||||
LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||
type BulkDeleteLegacyMatchesRequest,
|
||||
type LegacyImportMemberJob,
|
||||
type LegacyImportMemberWindowView,
|
||||
type LegacyMatchListResponse,
|
||||
type RebuildLegacyMatchesResponse,
|
||||
type StartLegacyImportRequest,
|
||||
type StartLegacyImportResponse,
|
||||
} from './legacy-import.types';
|
||||
|
||||
const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
|
||||
const MATCH_ID_PAGE_SIZE = 100;
|
||||
|
||||
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
|
||||
|
||||
@Injectable()
|
||||
export class LegacyImportService {
|
||||
private readonly logger = new Logger(LegacyImportService.name);
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly garnetService: GarnetService,
|
||||
private readonly riotMatchService: RiotMatchService,
|
||||
private readonly communityStatsService: CommunityStatsService,
|
||||
private readonly matchStatsService: MatchStatsService,
|
||||
) {}
|
||||
|
||||
public async previewMembers(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
windowStart?: string;
|
||||
windowEnd?: string;
|
||||
}): Promise<{ members: LegacyImportMemberWindowView[] }> {
|
||||
const { windowStart, windowEnd } = this.resolveWindow(params);
|
||||
const users = await this.findImportableUsers(params.communityId);
|
||||
return {
|
||||
members: users.map((user) =>
|
||||
this.toMemberWindowView(user, windowStart, windowEnd),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
public async start(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
triggeredBy: mongoose.Types.ObjectId;
|
||||
body: StartLegacyImportRequest;
|
||||
}): Promise<StartLegacyImportResponse> {
|
||||
const lockKey = this.communityLockKey(params.communityId);
|
||||
const jobId = randomUUID();
|
||||
const acquired = await this.garnetService.setStringIfAbsent(
|
||||
lockKey,
|
||||
jobId,
|
||||
LEGACY_IMPORT_LOCK_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) {
|
||||
throw new ConflictException('Legacy import is already running.');
|
||||
}
|
||||
|
||||
try {
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(params.communityId)
|
||||
.select({ riotRegion: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
|
||||
const { windowStart, windowEnd } = this.resolveWindow({
|
||||
windowStart: params.body.windowStart,
|
||||
windowEnd: params.body.windowEnd,
|
||||
});
|
||||
const users = await this.findImportableUsers(params.communityId);
|
||||
const overrides = new Map(
|
||||
(params.body.memberOverrides ?? []).map((override) => [
|
||||
override.userId,
|
||||
override,
|
||||
]),
|
||||
);
|
||||
const windows = users
|
||||
.map((user) =>
|
||||
this.resolveMemberWindow(user, windowStart, windowEnd, overrides),
|
||||
)
|
||||
.filter(
|
||||
(window) => window.startTime.getTime() <= window.endTime.getTime(),
|
||||
);
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
await LegacyImportJobModel.create({
|
||||
jobId,
|
||||
communityId: params.communityId,
|
||||
triggeredBy: params.triggeredBy,
|
||||
startedAt: new Date(),
|
||||
state: 'running',
|
||||
windowStart,
|
||||
windowEnd,
|
||||
memberOverrides: windows,
|
||||
totalMembers: windows.length,
|
||||
processedMembers: 0,
|
||||
totalDiscoveredMatchIds: 0,
|
||||
totalImportedMatches: 0,
|
||||
totalSkippedDuplicate: 0,
|
||||
totalErrors: 0,
|
||||
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||
});
|
||||
|
||||
for (const window of windows) {
|
||||
const job: LegacyImportMemberJob = {
|
||||
kind: 'legacy-import-member',
|
||||
jobId: randomUUID(),
|
||||
parentJobId: jobId,
|
||||
communityId: params.communityId.toString(),
|
||||
userId: window.userId.toString(),
|
||||
puuid: window.puuid,
|
||||
startTime: Math.floor(window.startTime.getTime() / 1000),
|
||||
endTime: Math.floor(window.endTime.getTime() / 1000),
|
||||
triggeredBy: params.triggeredBy.toString(),
|
||||
region: (community.riotRegion ?? 'asia') as RiotRegionalRoute,
|
||||
};
|
||||
await this.garnetService.appendStream(
|
||||
RIOT_JOB_LOW_STREAM,
|
||||
{ job: JSON.stringify(job) },
|
||||
{ maxLen: 10_000 },
|
||||
);
|
||||
}
|
||||
|
||||
if (windows.length === 0) {
|
||||
await LegacyImportJobModel.updateOne(
|
||||
{ jobId },
|
||||
{ $set: { state: 'completed', completedAt: new Date() } },
|
||||
).exec();
|
||||
await this.garnetService.delete(lockKey);
|
||||
}
|
||||
|
||||
return {
|
||||
jobId,
|
||||
totalMembers: windows.length,
|
||||
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
|
||||
};
|
||||
} catch (error) {
|
||||
await this.garnetService.delete(lockKey);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async listJobs(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
limit?: number;
|
||||
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const jobs = await LegacyImportJobModel.find({
|
||||
communityId: params.communityId,
|
||||
})
|
||||
.sort({ startedAt: -1 })
|
||||
.limit(Math.min(params.limit ?? 10, 50))
|
||||
.exec();
|
||||
return { jobs };
|
||||
}
|
||||
|
||||
public async getJob(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
jobId: string;
|
||||
}): Promise<LegacyImportJobDocument> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const job = await LegacyImportJobModel.findOne({
|
||||
communityId: params.communityId,
|
||||
jobId: params.jobId,
|
||||
}).exec();
|
||||
if (!job) throw new NotFoundException('Legacy import job not found.');
|
||||
return job;
|
||||
}
|
||||
|
||||
public async cancel(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
jobId: string;
|
||||
}): Promise<LegacyImportJobDocument> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const job = await LegacyImportJobModel.findOneAndUpdate(
|
||||
{
|
||||
communityId: params.communityId,
|
||||
jobId: params.jobId,
|
||||
state: { $in: ['pending', 'running'] },
|
||||
},
|
||||
{ $set: { state: 'cancelled', completedAt: new Date() } },
|
||||
{ returnDocument: 'after' },
|
||||
).exec();
|
||||
if (!job)
|
||||
throw new NotFoundException('Running legacy import job not found.');
|
||||
await this.garnetService.delete(this.communityLockKey(params.communityId));
|
||||
return job;
|
||||
}
|
||||
|
||||
public async processMemberJob(job: LegacyImportMemberJob): Promise<void> {
|
||||
const started = Date.now();
|
||||
const legacyJob = await this.getRunnableJob(job);
|
||||
if (!legacyJob) return;
|
||||
|
||||
let discovered = 0;
|
||||
let imported = 0;
|
||||
let duplicates = 0;
|
||||
let errors = 0;
|
||||
|
||||
try {
|
||||
const userByPuuid = await this.buildUserByPuuidMap(
|
||||
new mongoose.Types.ObjectId(job.communityId),
|
||||
);
|
||||
const matchIds = await this.collectMatchIds(job);
|
||||
discovered = matchIds.size;
|
||||
|
||||
for (const matchId of matchIds) {
|
||||
if (await this.isCancelled(job.parentJobId)) break;
|
||||
const outcome = await this.importSingleMatch(matchId, job, userByPuuid);
|
||||
if (outcome === 'imported') imported += 1;
|
||||
if (outcome === 'duplicate') duplicates += 1;
|
||||
if (outcome === 'error') errors += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
errors += 1;
|
||||
await this.recordError(job.parentJobId, {
|
||||
puuid: job.puuid,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
this.logger.warn(
|
||||
`Legacy import member job failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
await this.finishMemberJob(job, {
|
||||
discovered,
|
||||
imported,
|
||||
duplicates,
|
||||
errors,
|
||||
elapsedSeconds: Math.max(1, Math.round((Date.now() - started) / 1000)),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async listLegacyMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
cursor?: number;
|
||||
limit?: number;
|
||||
}): Promise<LegacyMatchListResponse> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const limit = Math.max(1, Math.min(params.limit ?? 30, 100));
|
||||
const filter: Record<string, unknown> = {
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
};
|
||||
if (params.cursor) {
|
||||
filter.scheduledAt = { $lt: new Date(params.cursor) };
|
||||
}
|
||||
const matches = await MatchModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(limit + 1)
|
||||
.exec();
|
||||
const visible = matches.slice(0, limit);
|
||||
const riotMatchIds = visible
|
||||
.map((match) => match.result?.games[0]?.riotMatchId)
|
||||
.filter((matchId): matchId is string => Boolean(matchId));
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const rawDocs = await RiotMatchModel.find({
|
||||
matchId: { $in: riotMatchIds },
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
const rawById = new Map(
|
||||
rawDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
|
||||
);
|
||||
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
|
||||
return {
|
||||
matches: visible.map((match) => {
|
||||
const riotMatchId = match.result?.games[0]?.riotMatchId ?? null;
|
||||
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
||||
const memberCount = match.result?.games[0]?.participants.length ?? 0;
|
||||
return {
|
||||
matchId: match._id.toString(),
|
||||
title: match.title,
|
||||
scheduledAt: match.scheduledAt.toISOString(),
|
||||
riotMatchId,
|
||||
memberCount,
|
||||
externalCount: raw
|
||||
? resolveExternalCount(raw, userByPuuid)
|
||||
: Math.max(0, 10 - memberCount),
|
||||
teamAIndex: match.result?.seriesResults?.[0]?.teamAIndex ?? 1,
|
||||
teamBIndex: match.result?.seriesResults?.[0]?.teamBIndex ?? 2,
|
||||
teamAWins: match.result?.seriesResults?.[0]?.teamAWins ?? 0,
|
||||
teamBWins: match.result?.seriesResults?.[0]?.teamBWins ?? 0,
|
||||
winnerTeamIndex: match.result?.winnerTeamIndex,
|
||||
};
|
||||
}),
|
||||
nextCursor:
|
||||
matches.length > limit
|
||||
? (visible[visible.length - 1]?.scheduledAt.getTime() ?? null)
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
public async bulkDeleteLegacyMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
body: BulkDeleteLegacyMatchesRequest;
|
||||
}): Promise<{ deleted: number }> {
|
||||
const ids = (params.body.matchIds ?? [])
|
||||
.filter((id) => mongoose.isValidObjectId(id))
|
||||
.map((id) => new mongoose.Types.ObjectId(id));
|
||||
if (ids.length === 0) return { deleted: 0 };
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const targets = await MatchModel.find({
|
||||
_id: { $in: ids },
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
})
|
||||
.select({ _id: 1 })
|
||||
.exec();
|
||||
const targetIds = targets.map((match) => match._id);
|
||||
if (targetIds.length === 0) return { deleted: 0 };
|
||||
|
||||
const result = await MatchModel.deleteMany({
|
||||
_id: { $in: targetIds },
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
}).exec();
|
||||
await this.matchStatsService.removeByMatches(targetIds);
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
return { deleted: result.deletedCount ?? 0 };
|
||||
}
|
||||
|
||||
public async rebuildLegacyMatches(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): Promise<RebuildLegacyMatchesResponse> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const matches = await MatchModel.find({
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
}).exec();
|
||||
const riotMatchIds = matches
|
||||
.map(
|
||||
(match) =>
|
||||
match.result?.games[0]?.riotMatchId ??
|
||||
match.result?.riotMatchIds?.[0],
|
||||
)
|
||||
.filter((matchId): matchId is string => Boolean(matchId));
|
||||
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const rawDocs = await RiotMatchModel.find({
|
||||
matchId: { $in: riotMatchIds },
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
const rawById = new Map<string, RiotMatchDto>();
|
||||
for (const doc of rawDocs) {
|
||||
if (isRiotMatchDto(doc.raw)) rawById.set(doc.matchId, doc.raw);
|
||||
}
|
||||
|
||||
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
|
||||
const result: RebuildLegacyMatchesResponse = {
|
||||
scanned: matches.length,
|
||||
rebuilt: 0,
|
||||
normalizedTitles: 0,
|
||||
skippedMissingRaw: 0,
|
||||
skippedNoKnownParticipants: 0,
|
||||
};
|
||||
|
||||
for (const match of matches) {
|
||||
const riotMatchId =
|
||||
match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0];
|
||||
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
|
||||
const title = this.normalizeLegacyTitle(
|
||||
match.title,
|
||||
raw?.info.gameCreation ?? match.scheduledAt.getTime(),
|
||||
);
|
||||
const update: Partial<Match> = {};
|
||||
if (title !== match.title) {
|
||||
update.title = title;
|
||||
result.normalizedTitles += 1;
|
||||
}
|
||||
|
||||
if (!raw || !riotMatchId) {
|
||||
result.skippedMissingRaw += 1;
|
||||
if (Object.keys(update).length > 0) {
|
||||
await MatchModel.updateOne(
|
||||
{ _id: match._id },
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const participants = buildParticipantsSnapshot(raw, userByPuuid);
|
||||
const gameResult = buildGameResult(raw, userByPuuid, 1);
|
||||
if (!gameResult || participants.length === 0) {
|
||||
result.skippedNoKnownParticipants += 1;
|
||||
if (Object.keys(update).length > 0) {
|
||||
await MatchModel.updateOne(
|
||||
{ _id: match._id },
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
update.mapId = raw.info.mapId ?? match.mapId;
|
||||
update.participants = participants;
|
||||
update.teams = buildTeams(raw, userByPuuid);
|
||||
update.result = {
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
await MatchModel.updateOne(
|
||||
{
|
||||
_id: match._id,
|
||||
communityId: params.communityId,
|
||||
legacyImported: true,
|
||||
},
|
||||
{ $set: update },
|
||||
).exec();
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
result.rebuilt += 1;
|
||||
}
|
||||
|
||||
if (result.rebuilt > 0 || result.normalizedTitles > 0) {
|
||||
await this.communityStatsService.invalidateCommunity(params.communityId);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private async collectMatchIds(
|
||||
job: LegacyImportMemberJob,
|
||||
): Promise<Set<string>> {
|
||||
const matchIds = new Set<string>();
|
||||
let start = 0;
|
||||
while (true) {
|
||||
const ids = await this.riotMatchService.getMatchIdsByPuuid(job.puuid, {
|
||||
region: job.region,
|
||||
type: 'tourney',
|
||||
startTime: job.startTime,
|
||||
endTime: job.endTime,
|
||||
start,
|
||||
count: MATCH_ID_PAGE_SIZE,
|
||||
});
|
||||
ids.forEach((matchId) => matchIds.add(matchId));
|
||||
if (ids.length < MATCH_ID_PAGE_SIZE) break;
|
||||
start += MATCH_ID_PAGE_SIZE;
|
||||
}
|
||||
return matchIds;
|
||||
}
|
||||
|
||||
private async importSingleMatch(
|
||||
riotMatchId: string,
|
||||
job: LegacyImportMemberJob,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): Promise<ImportOutcome> {
|
||||
const lockKey = `legacy-import:match:${riotMatchId}`;
|
||||
const acquired = await this.garnetService.setStringIfAbsent(
|
||||
lockKey,
|
||||
job.parentJobId,
|
||||
MATCH_IMPORT_LOCK_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) return 'duplicate';
|
||||
|
||||
try {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const existing = await MatchModel.exists({
|
||||
'result.games.riotMatchId': riotMatchId,
|
||||
});
|
||||
if (existing) return 'duplicate';
|
||||
|
||||
const detail = await this.ensureRiotMatchPersisted(
|
||||
riotMatchId,
|
||||
job.region,
|
||||
);
|
||||
if (!detail.info.tournamentCode) return 'skipped';
|
||||
const counts = countKnownParticipants(detail, userByPuuid);
|
||||
if (counts.total === 0) return 'skipped';
|
||||
|
||||
const gameResult = buildGameResult(detail, userByPuuid, 1);
|
||||
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
|
||||
|
||||
const winnerTeamIndex = gameResult.winnerTeamIndex;
|
||||
const matchPayload: Partial<Match> = {
|
||||
communityId: new mongoose.Types.ObjectId(job.communityId),
|
||||
title: this.formatLegacyDate(detail.info.gameCreation),
|
||||
description: 'Legacy import (자동 생성)',
|
||||
mapId: detail.info.mapId ?? 11,
|
||||
status: 'finished',
|
||||
scheduledAt: new Date(detail.info.gameCreation),
|
||||
maxParticipants: 10,
|
||||
gameCount: 1,
|
||||
gameMode: 'pair',
|
||||
tournamentCodeIds: [],
|
||||
teamBuiltAt: new Date(detail.info.gameCreation),
|
||||
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||
participants: buildParticipantsSnapshot(detail, userByPuuid),
|
||||
teams: buildTeams(detail, userByPuuid),
|
||||
result: {
|
||||
winnerTeamIndex,
|
||||
riotMatchIds: [riotMatchId],
|
||||
games: [gameResult],
|
||||
seriesResults: [
|
||||
{
|
||||
teamAIndex: 1,
|
||||
teamBIndex: 2,
|
||||
teamAWins: winnerTeamIndex === 1 ? 1 : 0,
|
||||
teamBWins: winnerTeamIndex === 2 ? 1 : 0,
|
||||
winnerTeamIndex,
|
||||
},
|
||||
],
|
||||
},
|
||||
legacyImported: true,
|
||||
legacyImportSource: {
|
||||
importedAt: new Date(),
|
||||
importedBy: new mongoose.Types.ObjectId(job.triggeredBy),
|
||||
triggeringPuuid: job.puuid,
|
||||
jobId: job.parentJobId,
|
||||
},
|
||||
prizes: [],
|
||||
notices: [],
|
||||
schedule: [],
|
||||
};
|
||||
const match = await MatchModel.create(matchPayload);
|
||||
await this.matchStatsService.buildAndUpsert(match._id);
|
||||
return 'imported';
|
||||
} catch (error) {
|
||||
await this.recordError(job.parentJobId, {
|
||||
puuid: job.puuid,
|
||||
matchId: riotMatchId,
|
||||
reason: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return 'error';
|
||||
} finally {
|
||||
await this.garnetService.delete(lockKey);
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureRiotMatchPersisted(
|
||||
riotMatchId: string,
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<RiotMatchDto> {
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const stored = await RiotMatchModel.findOne({
|
||||
matchId: riotMatchId,
|
||||
}).exec();
|
||||
if (isRiotMatchDto(stored?.raw)) return stored.raw;
|
||||
|
||||
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
|
||||
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 },
|
||||
{ $set: payload },
|
||||
{ upsert: true },
|
||||
).exec();
|
||||
return dto;
|
||||
}
|
||||
|
||||
private async finishMemberJob(
|
||||
job: LegacyImportMemberJob,
|
||||
stats: {
|
||||
discovered: number;
|
||||
imported: number;
|
||||
duplicates: number;
|
||||
errors: number;
|
||||
elapsedSeconds: number;
|
||||
},
|
||||
): Promise<void> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const current = await LegacyImportJobModel.findOne({
|
||||
jobId: job.parentJobId,
|
||||
}).exec();
|
||||
if (!current || current.state === 'cancelled') return;
|
||||
|
||||
const average =
|
||||
current.averageMemberSeconds === undefined
|
||||
? stats.elapsedSeconds
|
||||
: Math.round(
|
||||
current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3,
|
||||
);
|
||||
|
||||
const nextProcessed = current.processedMembers + 1;
|
||||
const completed = nextProcessed >= current.totalMembers;
|
||||
await LegacyImportJobModel.updateOne(
|
||||
{ jobId: job.parentJobId },
|
||||
{
|
||||
$set: {
|
||||
state: completed ? 'completed' : current.state,
|
||||
completedAt: completed ? new Date() : current.completedAt,
|
||||
averageMemberSeconds: average,
|
||||
},
|
||||
$inc: {
|
||||
processedMembers: 1,
|
||||
totalDiscoveredMatchIds: stats.discovered,
|
||||
totalImportedMatches: stats.imported,
|
||||
totalSkippedDuplicate: stats.duplicates,
|
||||
totalErrors: stats.errors,
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
|
||||
if (completed) {
|
||||
await Promise.all([
|
||||
this.garnetService.delete(
|
||||
this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)),
|
||||
),
|
||||
this.communityStatsService.invalidateCommunity(
|
||||
new mongoose.Types.ObjectId(job.communityId),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
private async getRunnableJob(
|
||||
job: LegacyImportMemberJob,
|
||||
): Promise<LegacyImportJobDocument | null> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const legacyJob = await LegacyImportJobModel.findOne({
|
||||
jobId: job.parentJobId,
|
||||
}).exec();
|
||||
if (!legacyJob || legacyJob.state === 'cancelled') return null;
|
||||
if (legacyJob.state === 'completed' || legacyJob.state === 'failed')
|
||||
return null;
|
||||
return legacyJob;
|
||||
}
|
||||
|
||||
private async isCancelled(parentJobId: string): Promise<boolean> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
const job = await LegacyImportJobModel.findOne({ jobId: parentJobId })
|
||||
.select({ state: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
return job?.state === 'cancelled';
|
||||
}
|
||||
|
||||
private async recordError(
|
||||
jobId: string,
|
||||
error: { puuid?: string; matchId?: string; reason: string },
|
||||
): Promise<void> {
|
||||
const LegacyImportJobModel =
|
||||
await this.connectionService.getModel('legacyImportJob');
|
||||
await LegacyImportJobModel.updateOne(
|
||||
{ jobId },
|
||||
{
|
||||
$push: {
|
||||
errors: {
|
||||
...error,
|
||||
at: new Date(),
|
||||
},
|
||||
},
|
||||
},
|
||||
).exec();
|
||||
}
|
||||
|
||||
private async buildUserByPuuidMap(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<UserByPuuidMap> {
|
||||
const users = await this.findImportableUsers(communityId);
|
||||
return buildUserByPuuidMap(users);
|
||||
}
|
||||
|
||||
private async findImportableUsers(
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
): Promise<UserDocument[]> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.find({
|
||||
communityId,
|
||||
'riotAccounts.0': { $exists: true },
|
||||
}).exec();
|
||||
}
|
||||
|
||||
private toMemberWindowView(
|
||||
user: UserDocument,
|
||||
windowStart: Date,
|
||||
windowEnd: Date,
|
||||
): LegacyImportMemberWindowView {
|
||||
const resolved = this.resolveMemberWindow(
|
||||
user,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
new Map(),
|
||||
);
|
||||
const account =
|
||||
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
return {
|
||||
userId: user._id.toString(),
|
||||
puuid: account.puuid,
|
||||
displayName:
|
||||
user.kakaoTalkNickname ??
|
||||
user.discordNickname ??
|
||||
account.gameName ??
|
||||
user._id.toString(),
|
||||
gameName: account.gameName,
|
||||
tagLine: account.tagLine,
|
||||
profileIconId: account.profileIconId,
|
||||
isActivated: user.isActivated,
|
||||
startTime: resolved.startTime.toISOString(),
|
||||
endTime: resolved.endTime.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
private resolveMemberWindow(
|
||||
user: UserDocument,
|
||||
windowStart: Date,
|
||||
windowEnd: Date,
|
||||
overrides: Map<string, { startTime?: string; endTime?: string }>,
|
||||
) {
|
||||
const account =
|
||||
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
if (!account) throw new BadRequestException('Riot account not found.');
|
||||
const override = overrides.get(user._id.toString());
|
||||
const overrideStart = this.parseOptionalDate(override?.startTime);
|
||||
const overrideEnd = this.parseOptionalDate(override?.endTime);
|
||||
const activeEnd = user.isActivated ? windowEnd : user.updatedAt;
|
||||
const startTime = overrideStart ?? windowStart;
|
||||
const endTime = this.minDate(windowEnd, activeEnd, overrideEnd);
|
||||
return {
|
||||
userId: user._id,
|
||||
puuid: account.puuid,
|
||||
startTime,
|
||||
endTime,
|
||||
};
|
||||
}
|
||||
|
||||
private resolveWindow(params: { windowStart?: string; windowEnd?: string }) {
|
||||
const windowStart =
|
||||
this.parseOptionalDate(params.windowStart) ??
|
||||
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
|
||||
const windowEnd = this.parseOptionalDate(params.windowEnd) ?? new Date();
|
||||
if (windowStart.getTime() > windowEnd.getTime()) {
|
||||
throw new BadRequestException('windowStart must be before windowEnd.');
|
||||
}
|
||||
return { windowStart, windowEnd };
|
||||
}
|
||||
|
||||
private parseOptionalDate(value: string | undefined): Date | undefined {
|
||||
if (!value) return undefined;
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
throw new BadRequestException('Invalid date.');
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
private minDate(...values: Array<Date | undefined>): Date {
|
||||
return new Date(
|
||||
Math.min(...values.filter(Boolean).map((date) => date!.getTime())),
|
||||
);
|
||||
}
|
||||
|
||||
private normalizeLegacyTitle(title: string, gameCreation: number): string {
|
||||
const stripped = title.replace(/^\[(?:legacy|lagacy)\]\s*/i, '').trim();
|
||||
return stripped || this.formatLegacyDate(gameCreation);
|
||||
}
|
||||
|
||||
private formatLegacyDate(gameCreation: number): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
timeZone: 'Asia/Seoul',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(gameCreation));
|
||||
}
|
||||
|
||||
private communityLockKey(communityId: mongoose.Types.ObjectId): string {
|
||||
return `legacy-import:lock:${communityId.toString()}`;
|
||||
}
|
||||
}
|
||||
|
||||
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
|
||||
return Boolean(
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'metadata' in value &&
|
||||
'info' in value,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { RiotRegionalRoute } from '../riot/riot.types';
|
||||
|
||||
export const LEGACY_IMPORT_DEFAULT_START_ISO = '2024-05-01T00:00:00.000Z';
|
||||
export const LEGACY_IMPORT_LOCK_TTL_SECONDS = 6 * 60 * 60;
|
||||
export const LEGACY_IMPORT_MEMBER_AVG_SECONDS = 60;
|
||||
|
||||
export interface LegacyImportMemberJob {
|
||||
kind: 'legacy-import-member';
|
||||
jobId: string;
|
||||
parentJobId: string;
|
||||
communityId: string;
|
||||
userId: string;
|
||||
puuid: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
triggeredBy: string;
|
||||
region: RiotRegionalRoute;
|
||||
}
|
||||
|
||||
export interface LegacyImportMemberOverrideRequest {
|
||||
userId: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
}
|
||||
|
||||
export interface StartLegacyImportRequest {
|
||||
windowStart?: string;
|
||||
windowEnd?: string;
|
||||
memberOverrides?: LegacyImportMemberOverrideRequest[];
|
||||
}
|
||||
|
||||
export interface LegacyImportMemberWindowView {
|
||||
userId: string;
|
||||
puuid: string;
|
||||
displayName: string;
|
||||
gameName: string;
|
||||
tagLine: string;
|
||||
profileIconId: number;
|
||||
isActivated: boolean;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
}
|
||||
|
||||
export interface StartLegacyImportResponse {
|
||||
jobId: string;
|
||||
totalMembers: number;
|
||||
etaSeconds: number;
|
||||
}
|
||||
|
||||
export interface LegacyMatchListResponse {
|
||||
matches: Array<{
|
||||
matchId: string;
|
||||
title: string;
|
||||
scheduledAt: string;
|
||||
riotMatchId: string | null;
|
||||
memberCount: number;
|
||||
externalCount: number;
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
teamAWins: number;
|
||||
teamBWins: number;
|
||||
winnerTeamIndex?: number;
|
||||
}>;
|
||||
nextCursor: number | null;
|
||||
}
|
||||
|
||||
export interface BulkDeleteLegacyMatchesRequest {
|
||||
matchIds?: string[];
|
||||
}
|
||||
|
||||
export interface RebuildLegacyMatchesResponse {
|
||||
scanned: number;
|
||||
rebuilt: number;
|
||||
normalizedTitles: number;
|
||||
skippedMissingRaw: number;
|
||||
skippedNoKnownParticipants: number;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import mongoose from 'mongoose';
|
||||
import type {
|
||||
MatchGameResult,
|
||||
MatchParticipant,
|
||||
MatchTeam,
|
||||
Position,
|
||||
RiotAccount,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
||||
|
||||
const RIOT_BLUE_TEAM_ID = 100;
|
||||
const RIOT_RED_TEAM_ID = 200;
|
||||
|
||||
export interface LegacyUserSnapshot {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
account: RiotAccount;
|
||||
displayName: string;
|
||||
preferredPositions: UserDocument['preferredPositions'];
|
||||
}
|
||||
|
||||
export type UserByPuuidMap = Map<string, LegacyUserSnapshot>;
|
||||
|
||||
export function buildUserByPuuidMap(users: UserDocument[]): UserByPuuidMap {
|
||||
const entries = new Map<string, LegacyUserSnapshot>();
|
||||
for (const user of users) {
|
||||
for (const account of user.riotAccounts) {
|
||||
entries.set(account.puuid, {
|
||||
userId: user._id,
|
||||
account,
|
||||
displayName:
|
||||
user.kakaoTalkNickname ??
|
||||
user.discordNickname ??
|
||||
account.gameName ??
|
||||
user._id.toString(),
|
||||
preferredPositions: user.preferredPositions ?? [],
|
||||
});
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
export function countKnownParticipants(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): { team100: number; team200: number; total: number } {
|
||||
const team100 = detail.info.participants.filter(
|
||||
(participant) =>
|
||||
participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid),
|
||||
).length;
|
||||
const team200 = detail.info.participants.filter(
|
||||
(participant) =>
|
||||
participant.teamId === RIOT_RED_TEAM_ID && userByPuuid.has(participant.puuid),
|
||||
).length;
|
||||
return { team100, team200, total: team100 + team200 };
|
||||
}
|
||||
|
||||
export function resolveTeam100IsBlue(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): boolean {
|
||||
const counts = countKnownParticipants(detail, userByPuuid);
|
||||
return counts.team100 >= counts.team200;
|
||||
}
|
||||
|
||||
export function buildParticipantsSnapshot(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): MatchParticipant[] {
|
||||
return detail.info.participants
|
||||
.map((participant): MatchParticipant | null => {
|
||||
const user = userByPuuid.get(participant.puuid);
|
||||
if (!user) return null;
|
||||
return {
|
||||
userId: user.userId,
|
||||
puuid: user.account.puuid,
|
||||
gameName: user.account.gameName || participant.riotIdGameName,
|
||||
tagLine: user.account.tagLine || participant.riotIdTagLine,
|
||||
profileIconId: user.account.profileIconId,
|
||||
tier:
|
||||
user.account.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
|
||||
user.account.tiers[0],
|
||||
preferredPositions: user.preferredPositions,
|
||||
joinedAt: new Date(detail.info.gameCreation),
|
||||
};
|
||||
})
|
||||
.filter((participant): participant is MatchParticipant => Boolean(participant));
|
||||
}
|
||||
|
||||
export function buildTeams(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): MatchTeam[] {
|
||||
return [
|
||||
{ teamIndex: 1, teamId: RIOT_BLUE_TEAM_ID },
|
||||
{ teamIndex: 2, teamId: RIOT_RED_TEAM_ID },
|
||||
].map(({ teamIndex, teamId }) => {
|
||||
const members = detail.info.participants
|
||||
.filter((participant) => participant.teamId === teamId)
|
||||
.map((participant) => {
|
||||
const user = userByPuuid.get(participant.puuid);
|
||||
if (!user) return null;
|
||||
return {
|
||||
userId: user.userId,
|
||||
assignedPosition: resolveAssignedPosition(participant, user),
|
||||
};
|
||||
})
|
||||
.filter((member): member is NonNullable<typeof member> => Boolean(member));
|
||||
return {
|
||||
teamIndex,
|
||||
name: `${teamIndex}팀`,
|
||||
members,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function buildGameResult(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
gameNumber = 1,
|
||||
): MatchGameResult | null {
|
||||
const winningTeam = detail.info.teams.find((team) => team.win);
|
||||
if (!winningTeam) return null;
|
||||
const winnerSide = resolveSide(winningTeam.teamId);
|
||||
if (!winnerSide) return null;
|
||||
const winnerTeamIndex = winnerSide === 'blue' ? 1 : 2;
|
||||
const participants = detail.info.participants
|
||||
.map((participant) => {
|
||||
const user = userByPuuid.get(participant.puuid);
|
||||
const side = resolveSide(participant.teamId);
|
||||
if (!user || !side) return null;
|
||||
return {
|
||||
userId: user.userId,
|
||||
teamIndex: side === 'blue' ? 1 : 2,
|
||||
side,
|
||||
championId: participant.championId,
|
||||
kills: participant.kills,
|
||||
deaths: participant.deaths,
|
||||
assists: participant.assists,
|
||||
win: participant.win,
|
||||
};
|
||||
})
|
||||
.filter((participant): participant is NonNullable<typeof participant> =>
|
||||
Boolean(participant),
|
||||
);
|
||||
|
||||
return {
|
||||
gameNumber,
|
||||
riotMatchId: detail.metadata.matchId,
|
||||
blueTeamIndex: 1,
|
||||
redTeamIndex: 2,
|
||||
winnerTeamIndex,
|
||||
winnerSide,
|
||||
gameCreation: detail.info.gameCreation,
|
||||
gameDuration: detail.info.gameDuration,
|
||||
participants,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveExternalCount(
|
||||
detail: RiotMatchDto,
|
||||
userByPuuid: UserByPuuidMap,
|
||||
): number {
|
||||
return detail.info.participants.filter(
|
||||
(participant) => !userByPuuid.has(participant.puuid),
|
||||
).length;
|
||||
}
|
||||
|
||||
function resolveSide(teamId: number): 'blue' | 'red' | null {
|
||||
if (teamId === RIOT_BLUE_TEAM_ID) return 'blue';
|
||||
if (teamId === RIOT_RED_TEAM_ID) return 'red';
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveAssignedPosition(
|
||||
participant: RiotMatchParticipantDto,
|
||||
user: LegacyUserSnapshot,
|
||||
): Position {
|
||||
const lane = participant.teamPosition || participant.individualPosition;
|
||||
if (lane === 'TOP') return 'TOP';
|
||||
if (lane === 'JUNGLE') return 'JGL';
|
||||
if (lane === 'MIDDLE') return 'MID';
|
||||
if (lane === 'BOTTOM') return 'ADC';
|
||||
if (lane === 'UTILITY') return 'SUP';
|
||||
return user.preferredPositions[0]?.position ?? 'TOP';
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { BackgroundRefreshScheduler } from './background-refresh.scheduler';
|
||||
import { StaleAccountRepository } from './stale-account.repository';
|
||||
|
||||
@Module({
|
||||
imports: [ConfigModule, RiotModule],
|
||||
providers: [BackgroundRefreshScheduler, StaleAccountRepository],
|
||||
})
|
||||
export class BackgroundRefreshModule {}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import mongoose from 'mongoose';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
import { BackgroundRefreshScheduler } from './background-refresh.scheduler';
|
||||
import {
|
||||
StaleAccountCandidate,
|
||||
StaleAccountRepository,
|
||||
} from './stale-account.repository';
|
||||
|
||||
type SchedulerInternals = BackgroundRefreshScheduler & {
|
||||
tick(): Promise<void>;
|
||||
};
|
||||
|
||||
function successResult() {
|
||||
return {
|
||||
summoner: 'fresh',
|
||||
league: 'fresh',
|
||||
masteries: 'fresh',
|
||||
recentMatches: 'fresh',
|
||||
account: {},
|
||||
};
|
||||
}
|
||||
|
||||
function candidate(puuid: string): StaleAccountCandidate {
|
||||
return {
|
||||
userId: new mongoose.Types.ObjectId(),
|
||||
puuid,
|
||||
};
|
||||
}
|
||||
|
||||
function makeScheduler(enabled = true) {
|
||||
const rawClient = {
|
||||
sendCommand: jest.fn().mockResolvedValue(1),
|
||||
};
|
||||
const garnet = {
|
||||
getString: jest.fn().mockResolvedValue(null),
|
||||
setString: jest.fn().mockResolvedValue(undefined),
|
||||
setStringIfAbsent: jest.fn().mockResolvedValue(true),
|
||||
delete: jest.fn().mockResolvedValue(1),
|
||||
raw: jest.fn().mockReturnValue(rawClient),
|
||||
} as unknown as jest.Mocked<GarnetService> & { raw: jest.Mock };
|
||||
const rateLimiter = {
|
||||
acquireBackground: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
||||
const enrichmentService = {
|
||||
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
|
||||
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
|
||||
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
||||
const staleAccountRepository = {
|
||||
findStaleAccounts: jest.fn().mockResolvedValue([]),
|
||||
} as unknown as jest.Mocked<StaleAccountRepository>;
|
||||
const config = {
|
||||
get: jest.fn().mockReturnValue(enabled ? 'true' : 'false'),
|
||||
} as unknown as ConfigService;
|
||||
|
||||
const scheduler = new BackgroundRefreshScheduler(
|
||||
garnet,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
config,
|
||||
) as SchedulerInternals;
|
||||
|
||||
return {
|
||||
scheduler,
|
||||
garnet,
|
||||
rawClient,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
};
|
||||
}
|
||||
|
||||
describe('BackgroundRefreshScheduler', () => {
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not schedule ticks when disabled', () => {
|
||||
jest.useFakeTimers();
|
||||
const setIntervalSpy = jest.spyOn(global, 'setInterval');
|
||||
const { scheduler } = makeScheduler(false);
|
||||
|
||||
scheduler.onModuleInit();
|
||||
|
||||
expect(setIntervalSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not query stale accounts outside the KST window', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T17:59:59.000Z'));
|
||||
const { scheduler, staleAccountRepository } = makeScheduler();
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not query stale accounts when another leader holds the lock', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, garnet, staleAccountRepository } = makeScheduler();
|
||||
garnet.getString.mockResolvedValue('another-consumer');
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('marks and enriches each stale candidate with background rate tokens', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const {
|
||||
scheduler,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
} = makeScheduler();
|
||||
const candidates = [candidate('puuid-1'), candidate('puuid-2')];
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue(candidates);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(rateLimiter.acquireBackground).toHaveBeenCalledTimes(2);
|
||||
expect(rateLimiter.acquireBackground).toHaveBeenCalledWith(8);
|
||||
expect(enrichmentService.markRefreshRequested).toHaveBeenCalledTimes(2);
|
||||
expect(enrichmentService.markRefreshRequested).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
candidates[0].userId,
|
||||
'puuid-1',
|
||||
);
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
|
||||
userId: candidates[1].userId,
|
||||
puuid: 'puuid-2',
|
||||
options: { force: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('continues after a candidate throws and records a failure counter', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const { scheduler, rawClient, enrichmentService, staleAccountRepository } =
|
||||
makeScheduler();
|
||||
const candidates = [candidate('puuid-1'), candidate('puuid-2')];
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue(candidates);
|
||||
enrichmentService.enrichRiotAccount
|
||||
.mockRejectedValueOnce(new Error('boom'))
|
||||
.mockResolvedValueOnce(successResult() as never);
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(2);
|
||||
expect(rawClient.sendCommand).toHaveBeenCalledWith([
|
||||
'INCR',
|
||||
'riot:bg:fail:puuid-1',
|
||||
]);
|
||||
expect(rawClient.sendCommand).toHaveBeenCalledWith([
|
||||
'EXPIRE',
|
||||
'riot:bg:fail:puuid-1',
|
||||
'86400',
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips candidates already in failure backoff', async () => {
|
||||
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
||||
const {
|
||||
scheduler,
|
||||
garnet,
|
||||
rateLimiter,
|
||||
enrichmentService,
|
||||
staleAccountRepository,
|
||||
} = makeScheduler();
|
||||
staleAccountRepository.findStaleAccounts.mockResolvedValue([
|
||||
candidate('skip-me'),
|
||||
]);
|
||||
garnet.getString.mockImplementation(async (key: string) => {
|
||||
if (key.includes('riot:bg:fail:skip-me')) return '3';
|
||||
return null;
|
||||
});
|
||||
|
||||
await scheduler.tick();
|
||||
|
||||
expect(rateLimiter.acquireBackground).not.toHaveBeenCalled();
|
||||
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
|
||||
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import {
|
||||
type EnrichResult,
|
||||
RiotAccountEnrichmentService,
|
||||
} from '../riot/riot-account-enrichment.service';
|
||||
import { RiotRateLimiterService } from '../riot/riot-rate-limiter.service';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||
import { StaleAccountRepository } from './stale-account.repository';
|
||||
|
||||
const TICK_INTERVAL_MS = 60_000;
|
||||
const LEADER_KEY = 'riot:bg-refresh:leader';
|
||||
const LEADER_TTL_SECONDS = 90;
|
||||
const LEADER_RENEW_INTERVAL_MS = 30_000;
|
||||
const STALE_THRESHOLD_MS = 6 * 60 * 60 * 1000;
|
||||
const PER_TICK_CANDIDATE_LIMIT = 20;
|
||||
const ENRICH_COST_TOKENS = 8;
|
||||
const FAILURE_BACKOFF_KEY_PREFIX = 'riot:bg:fail';
|
||||
const FAILURE_BACKOFF_THRESHOLD = 3;
|
||||
const FAILURE_BACKOFF_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
@Injectable()
|
||||
export class BackgroundRefreshScheduler
|
||||
implements OnModuleInit, OnModuleDestroy
|
||||
{
|
||||
private readonly logger = new Logger(BackgroundRefreshScheduler.name);
|
||||
private tickTimer?: NodeJS.Timeout;
|
||||
private leaderRenewTimer?: NodeJS.Timeout;
|
||||
private tickInProgress = false;
|
||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
private readonly enabled: boolean;
|
||||
|
||||
constructor(
|
||||
private readonly garnet: GarnetService,
|
||||
private readonly rateLimiter: RiotRateLimiterService,
|
||||
private readonly enrichmentService: RiotAccountEnrichmentService,
|
||||
private readonly staleAccountRepository: StaleAccountRepository,
|
||||
config: ConfigService,
|
||||
) {
|
||||
this.enabled = config.get<string>('RIOT_BG_REFRESH_ENABLED') === 'true';
|
||||
}
|
||||
|
||||
public onModuleInit(): void {
|
||||
if (!this.enabled) {
|
||||
this.logger.log(
|
||||
'Background Riot refresh is disabled (RIOT_BG_REFRESH_ENABLED).',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.tickTimer = setInterval(() => void this.safeTick(), TICK_INTERVAL_MS);
|
||||
this.leaderRenewTimer = setInterval(
|
||||
() => void this.renewLeaderIfHeld(),
|
||||
LEADER_RENEW_INTERVAL_MS,
|
||||
);
|
||||
this.tickTimer.unref?.();
|
||||
this.leaderRenewTimer.unref?.();
|
||||
|
||||
void this.safeTick();
|
||||
}
|
||||
|
||||
public onModuleDestroy(): void {
|
||||
if (this.tickTimer) clearInterval(this.tickTimer);
|
||||
if (this.leaderRenewTimer) clearInterval(this.leaderRenewTimer);
|
||||
}
|
||||
|
||||
private async safeTick(): Promise<void> {
|
||||
if (this.tickInProgress) return;
|
||||
this.tickInProgress = true;
|
||||
try {
|
||||
await this.tick();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Background refresh tick failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
this.tickInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async tick(): Promise<void> {
|
||||
if (!isInKstBackgroundWindow()) return;
|
||||
const isLeader = await this.tryBecomeLeader();
|
||||
if (!isLeader) return;
|
||||
|
||||
const olderThan = new Date(Date.now() - STALE_THRESHOLD_MS);
|
||||
const candidates = await this.staleAccountRepository.findStaleAccounts({
|
||||
olderThan,
|
||||
limit: PER_TICK_CANDIDATE_LIMIT,
|
||||
});
|
||||
if (candidates.length === 0) return;
|
||||
|
||||
let processed = 0;
|
||||
let failed = 0;
|
||||
let skipped = 0;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (!isInKstBackgroundWindow()) break;
|
||||
if (await this.isInFailureBackoff(candidate.puuid)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.rateLimiter.acquireBackground(ENRICH_COST_TOKENS);
|
||||
await this.enrichmentService.markRefreshRequested(
|
||||
candidate.userId,
|
||||
candidate.puuid,
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await this.enrichmentService.enrichRiotAccount({
|
||||
userId: candidate.userId,
|
||||
puuid: candidate.puuid,
|
||||
options: { force: false },
|
||||
});
|
||||
|
||||
if (this.isFailedEnrichment(result)) {
|
||||
failed += 1;
|
||||
await this.bumpFailureCounter(candidate.puuid);
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.clearFailureCounter(candidate.puuid);
|
||||
processed += 1;
|
||||
} catch (err) {
|
||||
failed += 1;
|
||||
await this.bumpFailureCounter(candidate.puuid);
|
||||
this.logger.warn(
|
||||
`Background enrichRiotAccount failed for ${candidate.puuid}: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.debug(
|
||||
`Background refresh tick: processed=${processed} failed=${failed} skipped=${skipped} candidates=${candidates.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
private async tryBecomeLeader(): Promise<boolean> {
|
||||
const current = await this.garnet.getString(LEADER_KEY);
|
||||
if (current === this.consumer) {
|
||||
await this.garnet.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (current) return false;
|
||||
|
||||
return this.garnet.setStringIfAbsent(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private async renewLeaderIfHeld(): Promise<void> {
|
||||
try {
|
||||
const current = await this.garnet.getString(LEADER_KEY);
|
||||
if (current !== this.consumer) return;
|
||||
await this.garnet.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Background refresh leader renew failed: ${
|
||||
err instanceof Error ? err.message : err
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async isInFailureBackoff(puuid: string): Promise<boolean> {
|
||||
const count = await this.getFailureCount(puuid);
|
||||
return count >= FAILURE_BACKOFF_THRESHOLD;
|
||||
}
|
||||
|
||||
private async getFailureCount(puuid: string): Promise<number> {
|
||||
const raw = await this.garnet.getString(this.failureBackoffKey(puuid));
|
||||
const count = Number(raw ?? 0);
|
||||
if (!Number.isFinite(count) || count < 0) return 0;
|
||||
return count;
|
||||
}
|
||||
|
||||
private async bumpFailureCounter(puuid: string): Promise<void> {
|
||||
const key = this.failureBackoffKey(puuid);
|
||||
const client = this.garnet.raw();
|
||||
const response = await client.sendCommand(['INCR', key]);
|
||||
await client.sendCommand([
|
||||
'EXPIRE',
|
||||
key,
|
||||
String(FAILURE_BACKOFF_TTL_SECONDS),
|
||||
]);
|
||||
|
||||
const count = Number(response ?? 0);
|
||||
if (Number.isFinite(count) && count >= FAILURE_BACKOFF_THRESHOLD) {
|
||||
this.logger.warn(
|
||||
`Background Riot refresh backoff enabled for ${puuid} after ${count} failures.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async clearFailureCounter(puuid: string): Promise<void> {
|
||||
await this.garnet.delete(this.failureBackoffKey(puuid));
|
||||
}
|
||||
|
||||
private isFailedEnrichment(result: EnrichResult): boolean {
|
||||
if (!result.account) return true;
|
||||
return [
|
||||
result.summoner,
|
||||
result.league,
|
||||
result.masteries,
|
||||
result.recentMatches,
|
||||
].every((status) => status === 'failed');
|
||||
}
|
||||
|
||||
private failureBackoffKey(puuid: string): string {
|
||||
return `${FAILURE_BACKOFF_KEY_PREFIX}:${puuid}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { isInKstBackgroundWindow } from './kst-window.util';
|
||||
|
||||
describe('isInKstBackgroundWindow', () => {
|
||||
it('includes KST 03:00', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-02T18:00:00.000Z'))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('includes KST 09:59', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-03T00:59:59.000Z'))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes KST 10:00', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-03T01:00:00.000Z'))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it('excludes KST 02:59', () => {
|
||||
expect(isInKstBackgroundWindow(new Date('2026-05-02T17:59:59.000Z'))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const BG_WINDOW_START_HOUR = 3;
|
||||
const BG_WINDOW_END_HOUR = 10;
|
||||
const KST_HOUR_FORMAT = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Seoul',
|
||||
hour: '2-digit',
|
||||
hour12: false,
|
||||
});
|
||||
|
||||
export function isInKstBackgroundWindow(now: Date = new Date()): boolean {
|
||||
const hourString = KST_HOUR_FORMAT.format(now);
|
||||
const hour = Number.parseInt(hourString, 10);
|
||||
if (Number.isNaN(hour)) return false;
|
||||
|
||||
const normalizedHour = hour % 24;
|
||||
return (
|
||||
normalizedHour >= BG_WINDOW_START_HOUR &&
|
||||
normalizedHour < BG_WINDOW_END_HOUR
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
buildStaleAccountsPipeline,
|
||||
StaleAccountRepository,
|
||||
} from './stale-account.repository';
|
||||
|
||||
describe('buildStaleAccountsPipeline', () => {
|
||||
const olderThan = new Date('2026-05-03T00:00:00.000Z');
|
||||
|
||||
it('filters to active users before unwinding Riot accounts', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[0]).toEqual({ $match: { isActivated: true } });
|
||||
expect(pipeline[1]).toEqual({ $unwind: '$riotAccounts' });
|
||||
});
|
||||
|
||||
it('matches missing or older lastRefreshRequestedAt values', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[2]).toEqual({
|
||||
$match: {
|
||||
$or: [
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $exists: false } },
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $lt: olderThan } },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('sorts missing refresh timestamps first', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 20 });
|
||||
|
||||
expect(pipeline[3]).toEqual({
|
||||
$addFields: {
|
||||
'riotAccounts.lastRefreshRequestedAtSort': {
|
||||
$ifNull: ['$riotAccounts.lastRefreshRequestedAt', new Date(0)],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(pipeline[4]).toEqual({
|
||||
$sort: { 'riotAccounts.lastRefreshRequestedAtSort': 1 },
|
||||
});
|
||||
});
|
||||
|
||||
it('applies the provided limit', () => {
|
||||
const pipeline = buildStaleAccountsPipeline({ olderThan, limit: 7 });
|
||||
|
||||
expect(pipeline[5]).toEqual({ $limit: 7 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('StaleAccountRepository', () => {
|
||||
it('returns aggregate candidates from the user model', async () => {
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const candidates = [{ userId, puuid: 'puuid-1' }];
|
||||
const exec = jest.fn().mockResolvedValue(candidates);
|
||||
const aggregate = jest.fn().mockReturnValue({ exec });
|
||||
const connectionService = {
|
||||
getModel: jest.fn().mockResolvedValue({ aggregate }),
|
||||
} as unknown as ConnectionService;
|
||||
|
||||
const repository = new StaleAccountRepository(connectionService);
|
||||
await expect(
|
||||
repository.findStaleAccounts({
|
||||
olderThan: new Date('2026-05-03T00:00:00.000Z'),
|
||||
limit: 1,
|
||||
}),
|
||||
).resolves.toBe(candidates);
|
||||
|
||||
expect(connectionService.getModel).toHaveBeenCalledWith('user');
|
||||
expect(aggregate).toHaveBeenCalledWith(
|
||||
buildStaleAccountsPipeline({
|
||||
olderThan: new Date('2026-05-03T00:00:00.000Z'),
|
||||
limit: 1,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import mongoose, { type PipelineStage } from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
|
||||
export interface StaleAccountCandidate {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
lastRefreshRequestedAt?: Date;
|
||||
}
|
||||
|
||||
export function buildStaleAccountsPipeline(opts: {
|
||||
olderThan: Date;
|
||||
limit: number;
|
||||
}): PipelineStage[] {
|
||||
return [
|
||||
{ $match: { isActivated: true } },
|
||||
{ $unwind: '$riotAccounts' },
|
||||
{
|
||||
$match: {
|
||||
$or: [
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $exists: false } },
|
||||
{ 'riotAccounts.lastRefreshRequestedAt': { $lt: opts.olderThan } },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
'riotAccounts.lastRefreshRequestedAtSort': {
|
||||
$ifNull: ['$riotAccounts.lastRefreshRequestedAt', new Date(0)],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $sort: { 'riotAccounts.lastRefreshRequestedAtSort': 1 } },
|
||||
{ $limit: opts.limit },
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
userId: '$_id',
|
||||
puuid: '$riotAccounts.puuid',
|
||||
lastRefreshRequestedAt: '$riotAccounts.lastRefreshRequestedAt',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class StaleAccountRepository {
|
||||
constructor(private readonly connectionService: ConnectionService) {}
|
||||
|
||||
public async findStaleAccounts(opts: {
|
||||
olderThan: Date;
|
||||
limit: number;
|
||||
}): Promise<StaleAccountCandidate[]> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
return UserModel.aggregate<StaleAccountCandidate>(
|
||||
buildStaleAccountsPipeline(opts),
|
||||
).exec();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';
|
||||
import { AllowPublicAccess } from '../auth/allow-public-access.decorator';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
|
||||
@Controller('riot/jobs')
|
||||
export class RiotJobQueueController {
|
||||
constructor(private readonly jobQueueService: RiotJobQueueService) {}
|
||||
|
||||
@Get('parents/:parentJobId')
|
||||
@AllowPublicAccess()
|
||||
public async getParent(@Param('parentJobId') parentJobId: string) {
|
||||
const status = await this.jobQueueService.getParentStatus(parentJobId);
|
||||
if (!status) throw new NotFoundException('Riot parent job not found.');
|
||||
return status;
|
||||
}
|
||||
|
||||
@Get(':jobId')
|
||||
@AllowPublicAccess()
|
||||
public async getJob(@Param('jobId') jobId: string) {
|
||||
const status = await this.jobQueueService.getStatus(jobId);
|
||||
if (!status) throw new NotFoundException('Riot job not found.');
|
||||
return status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { LegacyImportModule } from '../legacy-import/legacy-import.module';
|
||||
import { RiotModule } from '../riot/riot.module';
|
||||
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
|
||||
import { RiotJobQueueController } from './riot-job-queue.controller';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotJobWorkerService } from './riot-job-worker.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
|
||||
@Module({
|
||||
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)],
|
||||
controllers: [RiotJobQueueController],
|
||||
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
|
||||
exports: [RiotJobQueueService],
|
||||
})
|
||||
export class RiotJobQueueModule {}
|
||||
@@ -0,0 +1,482 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import type {
|
||||
CommunityDocument,
|
||||
RiotAccount,
|
||||
UserDocument,
|
||||
} from '../global/database/schema';
|
||||
import { GarnetService } from '../global/garnet/garnet.service';
|
||||
import {
|
||||
isRiotQueueGroup,
|
||||
resolveRiotQueueIds,
|
||||
type RiotQueueGroup,
|
||||
} from '../riot/riot-queue.constants';
|
||||
import {
|
||||
EnqueueRefreshResult,
|
||||
RIOT_JOB_AVG_SECONDS,
|
||||
RIOT_JOB_DEDUP_TTL_SECONDS,
|
||||
RIOT_JOB_HIGH_COOLDOWN_SECONDS,
|
||||
RIOT_JOB_HIGH_STREAM,
|
||||
RIOT_JOB_LOW_COOLDOWN_SECONDS,
|
||||
RIOT_JOB_LOW_STREAM,
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
RIOT_JOB_STATUS_TTL_SECONDS,
|
||||
RiotJobPriority,
|
||||
RiotJobState,
|
||||
RiotJobStatus,
|
||||
RiotParentJobStatus,
|
||||
RiotRefreshEvent,
|
||||
RiotRefreshSubJob,
|
||||
} from './riot-job-queue.types';
|
||||
import type {
|
||||
EnqueueTournamentResultPollResult,
|
||||
PollTournamentResultJob,
|
||||
} from '../tournament-result/tournament-result.types';
|
||||
|
||||
interface RefreshContext {
|
||||
community: CommunityDocument;
|
||||
user: UserDocument;
|
||||
account: RiotAccount;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotJobQueueService {
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly garnetService: GarnetService,
|
||||
) {}
|
||||
|
||||
public async enqueueRefresh(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
queueGroups: string[];
|
||||
priority: RiotJobPriority;
|
||||
requestedBy?: string;
|
||||
}): Promise<EnqueueRefreshResult> {
|
||||
const context = await this.resolveContext(params);
|
||||
const queueGroups = this.normalizeQueueGroups(params.queueGroups);
|
||||
const stream = this.resolveStream(params.priority);
|
||||
const streamLength = await this.garnetService.streamLength(stream);
|
||||
const dedupKeys = queueGroups.map((queueGroup) =>
|
||||
this.dedupKey(context.account.puuid, queueGroup),
|
||||
);
|
||||
const existingJobIds = await Promise.all(
|
||||
dedupKeys.map((key) => this.garnetService.getString(key)),
|
||||
);
|
||||
const needsNewJob = existingJobIds.some((jobId) => !jobId);
|
||||
|
||||
if (params.priority === 'high' && needsNewJob) {
|
||||
this.assertHighQueueAccepting(streamLength);
|
||||
this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'high');
|
||||
}
|
||||
if (params.priority === 'low' && needsNewJob) {
|
||||
this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'low');
|
||||
}
|
||||
|
||||
const parentJobId = randomUUID();
|
||||
const subJobs: EnqueueRefreshResult['subJobs'] = [];
|
||||
|
||||
for (let index = 0; index < queueGroups.length; index += 1) {
|
||||
const queueGroup = queueGroups[index];
|
||||
const existingJobId = existingJobIds[index];
|
||||
const queuePosition = streamLength + subJobs.length + 1;
|
||||
|
||||
if (existingJobId) {
|
||||
const existingStatus = await this.getStatus(existingJobId);
|
||||
subJobs.push({
|
||||
jobId: existingJobId,
|
||||
queueGroup,
|
||||
alreadyQueued: true,
|
||||
etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
||||
queuePosition: existingStatus?.queuePosition ?? queuePosition,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const job: RiotRefreshSubJob = {
|
||||
jobId: randomUUID(),
|
||||
parentJobId,
|
||||
userId: context.user._id.toString(),
|
||||
puuid: context.account.puuid,
|
||||
region: context.community.riotRegion ?? 'asia',
|
||||
platform: context.community.riotPlatform ?? 'kr',
|
||||
queueGroup,
|
||||
queueIds: resolveRiotQueueIds(queueGroup, 'all'),
|
||||
requestedAt: Date.now(),
|
||||
requestedBy: params.requestedBy,
|
||||
priority: params.priority,
|
||||
};
|
||||
const acquired = await this.garnetService.setStringIfAbsent(
|
||||
dedupKeys[index],
|
||||
job.jobId,
|
||||
RIOT_JOB_DEDUP_TTL_SECONDS,
|
||||
);
|
||||
if (!acquired) {
|
||||
const jobId = await this.garnetService.getString(dedupKeys[index]);
|
||||
if (!jobId) continue;
|
||||
const status = await this.getStatus(jobId);
|
||||
subJobs.push({
|
||||
jobId,
|
||||
queueGroup,
|
||||
alreadyQueued: true,
|
||||
etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS,
|
||||
queuePosition: status?.queuePosition ?? queuePosition,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const status: RiotJobStatus = {
|
||||
jobId: job.jobId,
|
||||
parentJobId,
|
||||
state: 'queued',
|
||||
priority: params.priority,
|
||||
queueGroup,
|
||||
queueIds: job.queueIds,
|
||||
puuid: job.puuid,
|
||||
userId: job.userId,
|
||||
enqueuedAt: new Date(job.requestedAt).toISOString(),
|
||||
etaSeconds: queuePosition * RIOT_JOB_AVG_SECONDS,
|
||||
queuePosition,
|
||||
};
|
||||
|
||||
await Promise.all([
|
||||
this.setStatus(status),
|
||||
this.garnetService.appendStream(
|
||||
stream,
|
||||
{ job: JSON.stringify(job) },
|
||||
{ maxLen: 10_000 },
|
||||
),
|
||||
]);
|
||||
subJobs.push({
|
||||
jobId: job.jobId,
|
||||
queueGroup,
|
||||
alreadyQueued: false,
|
||||
etaSeconds: status.etaSeconds,
|
||||
queuePosition,
|
||||
});
|
||||
}
|
||||
|
||||
await this.setParent(parentJobId, subJobs.map((job) => job.jobId));
|
||||
if (params.priority === 'high' && needsNewJob) {
|
||||
await this.markRefreshRequested(context.user._id, context.account.puuid);
|
||||
}
|
||||
|
||||
return {
|
||||
parentJobId,
|
||||
subJobs,
|
||||
totalEtaSeconds: subJobs.reduce((sum, job) => sum + job.etaSeconds, 0),
|
||||
};
|
||||
}
|
||||
|
||||
public async enqueueTournamentResultPoll(params: {
|
||||
matchId: string;
|
||||
attempt: number;
|
||||
expandedToAllPuuids: boolean;
|
||||
priority: RiotJobPriority;
|
||||
deferUntilMs?: number;
|
||||
}): Promise<EnqueueTournamentResultPollResult> {
|
||||
const job: PollTournamentResultJob = {
|
||||
kind: 'poll-tournament-result',
|
||||
jobId: randomUUID(),
|
||||
matchId: params.matchId,
|
||||
attempt: params.attempt,
|
||||
expandedToAllPuuids: params.expandedToAllPuuids,
|
||||
enqueuedAt: Date.now(),
|
||||
priority: params.priority,
|
||||
};
|
||||
|
||||
if (params.deferUntilMs && params.deferUntilMs > Date.now()) {
|
||||
await this.scheduleJob(job, params.deferUntilMs);
|
||||
} else {
|
||||
await this.appendJob(job);
|
||||
}
|
||||
|
||||
return {
|
||||
jobId: job.jobId,
|
||||
matchId: job.matchId,
|
||||
priority: job.priority,
|
||||
attempt: job.attempt,
|
||||
expandedToAllPuuids: job.expandedToAllPuuids,
|
||||
};
|
||||
}
|
||||
|
||||
public async promoteDueScheduledJobs(limit = 100): Promise<number> {
|
||||
const client = this.garnetService.raw();
|
||||
const raw = (await client.sendCommand([
|
||||
'ZRANGEBYSCORE',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
'-inf',
|
||||
String(Date.now()),
|
||||
'LIMIT',
|
||||
'0',
|
||||
String(limit),
|
||||
])) as string[] | null;
|
||||
const entries = raw ?? [];
|
||||
let promoted = 0;
|
||||
|
||||
for (const entry of entries) {
|
||||
const removed = (await client.sendCommand([
|
||||
'ZREM',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
entry,
|
||||
])) as number;
|
||||
if (removed !== 1) continue;
|
||||
const job = this.parseScheduledJob(entry);
|
||||
if (!job) continue;
|
||||
await this.appendJob(job);
|
||||
promoted += 1;
|
||||
}
|
||||
|
||||
return promoted;
|
||||
}
|
||||
|
||||
public async getStatus(jobId: string): Promise<RiotJobStatus | null> {
|
||||
return this.garnetService.getJson<RiotJobStatus>(this.statusKey(jobId));
|
||||
}
|
||||
|
||||
public async getParentStatus(
|
||||
parentJobId: string,
|
||||
): Promise<RiotParentJobStatus | null> {
|
||||
const jobIds = await this.garnetService.getJson<string[]>(
|
||||
this.parentKey(parentJobId),
|
||||
);
|
||||
if (!jobIds) return null;
|
||||
|
||||
const subJobs = (
|
||||
await Promise.all(jobIds.map((jobId) => this.getStatus(jobId)))
|
||||
).filter((status): status is RiotJobStatus => Boolean(status));
|
||||
const done = subJobs.filter((job) =>
|
||||
job.state === 'completed' || job.state === 'failed',
|
||||
).length;
|
||||
const state = this.resolveParentState(subJobs);
|
||||
|
||||
return {
|
||||
parentJobId,
|
||||
state,
|
||||
done,
|
||||
total: subJobs.length,
|
||||
etaSeconds: subJobs
|
||||
.filter((job) => job.state === 'queued' || job.state === 'processing')
|
||||
.reduce((sum, job) => sum + job.etaSeconds, 0),
|
||||
subJobs,
|
||||
};
|
||||
}
|
||||
|
||||
public async markProcessing(job: RiotRefreshSubJob): Promise<RiotJobStatus> {
|
||||
const status = await this.requireStatus(job.jobId);
|
||||
const next: RiotJobStatus = {
|
||||
...status,
|
||||
state: 'processing',
|
||||
startedAt: new Date().toISOString(),
|
||||
etaSeconds: RIOT_JOB_AVG_SECONDS,
|
||||
queuePosition: 0,
|
||||
};
|
||||
await this.setStatus(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
public async markCompleted(
|
||||
job: RiotRefreshSubJob,
|
||||
): Promise<RiotRefreshEvent> {
|
||||
const status = await this.requireStatus(job.jobId);
|
||||
const next: RiotJobStatus = {
|
||||
...status,
|
||||
state: 'completed',
|
||||
finishedAt: new Date().toISOString(),
|
||||
etaSeconds: 0,
|
||||
queuePosition: 0,
|
||||
};
|
||||
await Promise.all([
|
||||
this.setStatus(next),
|
||||
this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)),
|
||||
]);
|
||||
return this.toEvent(next);
|
||||
}
|
||||
|
||||
public async markFailed(
|
||||
job: RiotRefreshSubJob,
|
||||
error: unknown,
|
||||
): Promise<RiotRefreshEvent> {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const status = await this.requireStatus(job.jobId);
|
||||
const next: RiotJobStatus = {
|
||||
...status,
|
||||
state: 'failed',
|
||||
finishedAt: new Date().toISOString(),
|
||||
error: message,
|
||||
etaSeconds: 0,
|
||||
queuePosition: 0,
|
||||
};
|
||||
await Promise.all([
|
||||
this.setStatus(next),
|
||||
this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)),
|
||||
]);
|
||||
return this.toEvent(next);
|
||||
}
|
||||
|
||||
private async resolveContext(params: {
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
userId: mongoose.Types.ObjectId;
|
||||
}): Promise<RefreshContext> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const [user, community] = await Promise.all([
|
||||
UserModel.findById(params.userId).exec(),
|
||||
CommunityModel.findById(params.communityId).exec(),
|
||||
]);
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
if (!user || !user.communityId.equals(params.communityId)) {
|
||||
throw new NotFoundException('User not found.');
|
||||
}
|
||||
|
||||
const account =
|
||||
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
|
||||
user.riotAccounts[0];
|
||||
if (!account) throw new NotFoundException('Riot account not found.');
|
||||
return { community, user, account };
|
||||
}
|
||||
|
||||
private normalizeQueueGroups(queueGroups: string[]): RiotQueueGroup[] {
|
||||
const values = queueGroups.length > 0 ? queueGroups : ['summoners-rift'];
|
||||
const unique = [...new Set(values)];
|
||||
if (!unique.every(isRiotQueueGroup)) {
|
||||
throw new BadRequestException('Invalid queueGroups.');
|
||||
}
|
||||
return unique;
|
||||
}
|
||||
|
||||
private assertHighQueueAccepting(streamLength: number): void {
|
||||
if (streamLength <= 50) return;
|
||||
throw new HttpException(
|
||||
{
|
||||
reason: 'queue-full',
|
||||
retryAfterSeconds: RIOT_JOB_AVG_SECONDS * streamLength,
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
|
||||
private assertRefreshBudget(
|
||||
lastRequestedAt: Date | undefined,
|
||||
priority: RiotJobPriority,
|
||||
): void {
|
||||
if (!lastRequestedAt) return;
|
||||
const cooldownSeconds =
|
||||
priority === 'high'
|
||||
? RIOT_JOB_HIGH_COOLDOWN_SECONDS
|
||||
: RIOT_JOB_LOW_COOLDOWN_SECONDS;
|
||||
const elapsedSeconds = (Date.now() - lastRequestedAt.getTime()) / 1000;
|
||||
if (elapsedSeconds >= cooldownSeconds) return;
|
||||
throw new HttpException(
|
||||
{
|
||||
reason: 'cooldown',
|
||||
retryAfterSeconds: Math.ceil(cooldownSeconds - elapsedSeconds),
|
||||
},
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
);
|
||||
}
|
||||
|
||||
private async markRefreshRequested(
|
||||
userId: mongoose.Types.ObjectId,
|
||||
puuid: string,
|
||||
): Promise<void> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
await UserModel.updateOne(
|
||||
{ _id: userId, 'riotAccounts.puuid': puuid },
|
||||
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': new Date() } },
|
||||
).exec();
|
||||
}
|
||||
|
||||
private resolveStream(priority: RiotJobPriority): string {
|
||||
return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM;
|
||||
}
|
||||
|
||||
private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) {
|
||||
await this.garnetService.appendStream(
|
||||
this.resolveStream(job.priority),
|
||||
{ job: JSON.stringify(job) },
|
||||
{ maxLen: 10_000 },
|
||||
);
|
||||
}
|
||||
|
||||
private async scheduleJob(
|
||||
job: PollTournamentResultJob,
|
||||
deferUntilMs: number,
|
||||
): Promise<void> {
|
||||
await this.garnetService.raw().sendCommand([
|
||||
'ZADD',
|
||||
RIOT_JOB_SCHEDULED_ZSET,
|
||||
String(deferUntilMs),
|
||||
JSON.stringify(job),
|
||||
]);
|
||||
}
|
||||
|
||||
private parseScheduledJob(value: string): PollTournamentResultJob | null {
|
||||
try {
|
||||
const parsed = JSON.parse(value) as PollTournamentResultJob;
|
||||
return parsed.kind === 'poll-tournament-result' ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState {
|
||||
if (subJobs.some((job) => job.state === 'processing')) return 'processing';
|
||||
if (subJobs.some((job) => job.state === 'queued')) return 'queued';
|
||||
if (subJobs.some((job) => job.state === 'failed')) return 'failed';
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
private async requireStatus(jobId: string): Promise<RiotJobStatus> {
|
||||
const status = await this.getStatus(jobId);
|
||||
if (!status) throw new Error(`Missing riot job status: ${jobId}`);
|
||||
return status;
|
||||
}
|
||||
|
||||
private async setStatus(status: RiotJobStatus): Promise<void> {
|
||||
await this.garnetService.setJson(
|
||||
this.statusKey(status.jobId),
|
||||
status,
|
||||
RIOT_JOB_STATUS_TTL_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private async setParent(parentJobId: string, jobIds: string[]): Promise<void> {
|
||||
await this.garnetService.setJson(
|
||||
this.parentKey(parentJobId),
|
||||
jobIds,
|
||||
RIOT_JOB_STATUS_TTL_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private toEvent(status: RiotJobStatus): RiotRefreshEvent {
|
||||
return {
|
||||
parentJobId: status.parentJobId,
|
||||
jobId: status.jobId,
|
||||
queueGroup: status.queueGroup,
|
||||
puuid: status.puuid,
|
||||
state: status.state,
|
||||
error: status.error,
|
||||
};
|
||||
}
|
||||
|
||||
private statusKey(jobId: string): string {
|
||||
return `riot:job:status:${jobId}`;
|
||||
}
|
||||
|
||||
private parentKey(parentJobId: string): string {
|
||||
return `riot:job:parent:${parentJobId}`;
|
||||
}
|
||||
|
||||
private dedupKey(puuid: string, queueGroup: RiotQueueGroup): string {
|
||||
return `riot:job:dedup:${puuid}:${queueGroup}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
} from '../riot/riot.types';
|
||||
import type { RiotQueueGroup } from '../riot/riot-queue.constants';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||
|
||||
export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high';
|
||||
export const RIOT_JOB_LOW_STREAM = 'riot:queue:low';
|
||||
export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled';
|
||||
export const RIOT_JOB_GROUP = 'riot-refresh-worker';
|
||||
export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60;
|
||||
export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60;
|
||||
export const RIOT_JOB_HIGH_COOLDOWN_SECONDS = 5 * 60;
|
||||
export const RIOT_JOB_LOW_COOLDOWN_SECONDS = 60 * 60;
|
||||
export const RIOT_JOB_AVG_SECONDS = 20;
|
||||
|
||||
export type RiotJobPriority = 'high' | 'low';
|
||||
export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
|
||||
|
||||
export interface RiotRefreshSubJob {
|
||||
kind?: 'refresh-account';
|
||||
jobId: string;
|
||||
parentJobId: string;
|
||||
userId: string;
|
||||
puuid: string;
|
||||
region: RiotRegionalRoute;
|
||||
platform: RiotPlatformRoute;
|
||||
queueGroup: RiotQueueGroup;
|
||||
queueIds: number[];
|
||||
requestedAt: number;
|
||||
requestedBy?: string;
|
||||
priority: RiotJobPriority;
|
||||
}
|
||||
|
||||
export type RiotJobPayload =
|
||||
| RiotRefreshSubJob
|
||||
| PollTournamentResultJob
|
||||
| LegacyImportMemberJob;
|
||||
|
||||
export interface RiotJobStatus {
|
||||
jobId: string;
|
||||
parentJobId: string;
|
||||
state: RiotJobState;
|
||||
priority: RiotJobPriority;
|
||||
queueGroup: RiotQueueGroup;
|
||||
queueIds: number[];
|
||||
puuid: string;
|
||||
userId: string;
|
||||
enqueuedAt: string;
|
||||
startedAt?: string;
|
||||
finishedAt?: string;
|
||||
error?: string;
|
||||
etaSeconds: number;
|
||||
queuePosition: number;
|
||||
alreadyQueued?: boolean;
|
||||
}
|
||||
|
||||
export interface RiotParentJobStatus {
|
||||
parentJobId: string;
|
||||
state: RiotJobState;
|
||||
done: number;
|
||||
total: number;
|
||||
etaSeconds: number;
|
||||
subJobs: RiotJobStatus[];
|
||||
}
|
||||
|
||||
export interface RiotRefreshEvent {
|
||||
parentJobId: string;
|
||||
jobId: string;
|
||||
queueGroup: RiotQueueGroup;
|
||||
puuid: string;
|
||||
state: RiotJobState;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface EnqueueRefreshResult {
|
||||
parentJobId: string;
|
||||
subJobs: Array<{
|
||||
jobId: string;
|
||||
queueGroup: RiotQueueGroup;
|
||||
alreadyQueued: boolean;
|
||||
etaSeconds: number;
|
||||
queuePosition: number;
|
||||
}>;
|
||||
totalEtaSeconds: number;
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import {
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { GarnetService, StreamEntry } from '../global/garnet/garnet.service';
|
||||
import { LegacyImportService } from '../legacy-import/legacy-import.service';
|
||||
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
|
||||
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
|
||||
import {
|
||||
RIOT_JOB_GROUP,
|
||||
RIOT_JOB_HIGH_STREAM,
|
||||
RIOT_JOB_LOW_STREAM,
|
||||
RiotJobPayload,
|
||||
RiotRefreshSubJob,
|
||||
} from './riot-job-queue.types';
|
||||
import { RiotJobQueueService } from './riot-job-queue.service';
|
||||
import { RiotRefreshGateway } from './riot-refresh.gateway';
|
||||
import { TournamentResultService } from '../tournament-result/tournament-result.service';
|
||||
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
|
||||
|
||||
const LEADER_KEY = 'riot:worker:leader';
|
||||
const LEADER_TTL_SECONDS = 60;
|
||||
|
||||
@Injectable()
|
||||
export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(RiotJobWorkerService.name);
|
||||
private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`;
|
||||
private stopped = false;
|
||||
|
||||
constructor(
|
||||
private readonly garnetService: GarnetService,
|
||||
private readonly jobQueueService: RiotJobQueueService,
|
||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly refreshGateway: RiotRefreshGateway,
|
||||
private readonly tournamentResultService: TournamentResultService,
|
||||
private readonly legacyImportService: LegacyImportService,
|
||||
) {}
|
||||
|
||||
public async onModuleInit() {
|
||||
await this.ensureConsumerGroups();
|
||||
void this.loop();
|
||||
}
|
||||
|
||||
public onModuleDestroy() {
|
||||
this.stopped = true;
|
||||
}
|
||||
|
||||
private async loop(): Promise<void> {
|
||||
while (!this.stopped) {
|
||||
try {
|
||||
const isLeader = await this.tryBecomeLeader();
|
||||
if (!isLeader) {
|
||||
await this.sleep(1_000);
|
||||
continue;
|
||||
}
|
||||
|
||||
await this.jobQueueService.promoteDueScheduledJobs();
|
||||
const entry =
|
||||
(await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ??
|
||||
(await this.readOne(RIOT_JOB_LOW_STREAM, 1_000));
|
||||
if (!entry) continue;
|
||||
|
||||
await this.processEntry(entry.stream, entry.message);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Riot job worker loop failed: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
await this.sleep(1_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async processEntry(stream: string, entry: StreamEntry): Promise<void> {
|
||||
const job = this.parseJob(entry);
|
||||
if (!job) {
|
||||
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.isTournamentResultJob(job)) {
|
||||
await this.tournamentResultService.processPollJob(job);
|
||||
return;
|
||||
}
|
||||
if (this.isLegacyImportJob(job)) {
|
||||
await this.legacyImportService.processMemberJob(job);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.jobQueueService.markProcessing(job);
|
||||
for (const queueId of job.queueIds) {
|
||||
await this.recentMatchesService.ensureFreshForQueue({
|
||||
puuid: job.puuid,
|
||||
region: job.region,
|
||||
queueId,
|
||||
});
|
||||
}
|
||||
await this.markUserFetchedAt(job);
|
||||
const event = await this.jobQueueService.markCompleted(job);
|
||||
this.refreshGateway.broadcastRefreshEvent(event);
|
||||
} catch (error) {
|
||||
if (this.isTournamentResultJob(job)) {
|
||||
this.logger.warn(
|
||||
`Tournament result poll job failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.isLegacyImportJob(job)) {
|
||||
this.logger.warn(
|
||||
`Legacy import member job failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const event = await this.jobQueueService.markFailed(job, error);
|
||||
this.refreshGateway.broadcastRefreshEvent(event);
|
||||
this.logger.warn(
|
||||
`Riot refresh job failed ${job.jobId}: ${
|
||||
error instanceof Error ? error.message : error
|
||||
}`,
|
||||
);
|
||||
} finally {
|
||||
await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id);
|
||||
}
|
||||
}
|
||||
|
||||
private async markUserFetchedAt(job: RiotRefreshSubJob): Promise<void> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const now = new Date();
|
||||
const $set: Record<string, Date> = {
|
||||
'riotAccounts.$.matchIdsFetchedAt': now,
|
||||
};
|
||||
for (const queueId of job.queueIds) {
|
||||
$set[`riotAccounts.$.matchIdsByQueueFetchedAt.${queueId}`] = now;
|
||||
}
|
||||
await UserModel.updateOne(
|
||||
{
|
||||
_id: new mongoose.Types.ObjectId(job.userId),
|
||||
'riotAccounts.puuid': job.puuid,
|
||||
},
|
||||
{ $set },
|
||||
).exec();
|
||||
}
|
||||
|
||||
private parseJob(entry: StreamEntry): RiotJobPayload | null {
|
||||
const raw = entry.message.job;
|
||||
if (!raw) return null;
|
||||
try {
|
||||
return JSON.parse(raw) as RiotJobPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private isTournamentResultJob(
|
||||
job: RiotJobPayload,
|
||||
): job is PollTournamentResultJob {
|
||||
return job.kind === 'poll-tournament-result';
|
||||
}
|
||||
|
||||
private isLegacyImportJob(
|
||||
job: RiotJobPayload,
|
||||
): job is LegacyImportMemberJob {
|
||||
return job.kind === 'legacy-import-member';
|
||||
}
|
||||
|
||||
private async readOne(
|
||||
stream: string,
|
||||
blockMs: number,
|
||||
): Promise<{ stream: string; message: StreamEntry } | null> {
|
||||
const result = await this.garnetService.readGroup(
|
||||
stream,
|
||||
RIOT_JOB_GROUP,
|
||||
this.consumer,
|
||||
'>',
|
||||
{ count: 1, blockMs },
|
||||
);
|
||||
const message = result?.[0]?.messages[0];
|
||||
return message ? { stream, message } : null;
|
||||
}
|
||||
|
||||
private async ensureConsumerGroups(): Promise<void> {
|
||||
await Promise.all(
|
||||
[RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => {
|
||||
try {
|
||||
await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (!message.includes('BUSYGROUP')) throw error;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async tryBecomeLeader(): Promise<boolean> {
|
||||
const current = await this.garnetService.getString(LEADER_KEY);
|
||||
if (current === this.consumer) {
|
||||
await this.garnetService.setString(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
if (current) return false;
|
||||
return this.garnetService.setStringIfAbsent(
|
||||
LEADER_KEY,
|
||||
this.consumer,
|
||||
LEADER_TTL_SECONDS,
|
||||
);
|
||||
}
|
||||
|
||||
private sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { Logger } from '@nestjs/common';
|
||||
import {
|
||||
ConnectedSocket,
|
||||
MessageBody,
|
||||
SubscribeMessage,
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
} from '@nestjs/websockets';
|
||||
import type { Namespace, Socket } from 'socket.io';
|
||||
import type { RiotRefreshEvent } from './riot-job-queue.types';
|
||||
|
||||
interface SubscribePayload {
|
||||
puuid?: string;
|
||||
parentJobId?: string;
|
||||
}
|
||||
|
||||
const MAX_ROOMS_PER_SOCKET = 5;
|
||||
|
||||
@WebSocketGateway({
|
||||
namespace: '/riot-refresh',
|
||||
cors: {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'],
|
||||
},
|
||||
})
|
||||
export class RiotRefreshGateway {
|
||||
@WebSocketServer()
|
||||
private server!: Namespace;
|
||||
|
||||
private readonly logger = new Logger(RiotRefreshGateway.name);
|
||||
|
||||
@SubscribeMessage('subscribe')
|
||||
public async handleSubscribe(
|
||||
@ConnectedSocket() socket: Socket,
|
||||
@MessageBody() payload: SubscribePayload,
|
||||
) {
|
||||
const rooms = this.resolveRooms(payload);
|
||||
if (rooms.length === 0) {
|
||||
socket.emit('error', { message: 'Invalid riot refresh subscription.' });
|
||||
return;
|
||||
}
|
||||
|
||||
const currentRooms = [...socket.rooms].filter((room) => room !== socket.id);
|
||||
if (currentRooms.length + rooms.length > MAX_ROOMS_PER_SOCKET) {
|
||||
socket.emit('error', { message: 'Too many riot refresh subscriptions.' });
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(rooms.map((room) => socket.join(room)));
|
||||
socket.emit('subscribed', { rooms });
|
||||
}
|
||||
|
||||
public broadcastRefreshEvent(event: RiotRefreshEvent): void {
|
||||
const rooms = [
|
||||
`puuid:${event.puuid}`,
|
||||
`parent:${event.parentJobId}`,
|
||||
`job:${event.jobId}`,
|
||||
];
|
||||
this.logger.debug(
|
||||
`Broadcast riot refresh ${event.state}: ${event.jobId} (${event.queueGroup})`,
|
||||
);
|
||||
for (const room of rooms) {
|
||||
this.server.to(room).emit('riot-refresh', event);
|
||||
}
|
||||
}
|
||||
|
||||
private resolveRooms(payload: SubscribePayload): string[] {
|
||||
const rooms: string[] = [];
|
||||
if (typeof payload?.puuid === 'string' && payload.puuid.trim()) {
|
||||
rooms.push(`puuid:${payload.puuid.trim()}`);
|
||||
}
|
||||
if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) {
|
||||
rooms.push(`parent:${payload.parentJobId.trim()}`);
|
||||
}
|
||||
return rooms;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user