feat: connect tournament views to APIs and recover archived stats

Remove development previews and complete hall of fame, match history, official results, and multi-kill API integration.

Fix active match pagination and team-ready controls, preserve basic scoreboards, and recover statistics when Riot archives arrive.

Use bounded in-process cache invalidation retries and add the Riot match lookup index migration with regression coverage.
This commit is contained in:
dahyeon committed 2026-11-11 02:00:35 +09:00
1 parent 20e1e6ec04
commit 0d7617e2d2
70 files changed
+3739 -1793

No files matched your search

@@ -1,3 +1,9 @@
import type {
CompetitionGameView,
GameAnalysisAvailability,
InternalMatchCompetition,
InternalMatchResultPresentation,
} from '@lolympus/contracts';
import {
BadRequestException,
Injectable,
@@ -5,8 +11,14 @@ import {
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { presentCompetitionDetail } from '../competition/competition.presenter';
import type { Competition } from '../competition/competition.schema';
import { ConnectionService } from '../global/database/connection.service';
import type { CommunityDocument, RiotLane } from '../global/database/schema';
import type {
CommunityDocument,
MatchStatsDocument,
RiotLane,
} from '../global/database/schema';
import type {
HistorySeasonDto,
RecentMatchView,
@@ -43,7 +55,7 @@ const DEFAULT_LIST_LIMIT = 20;
const MAX_LIST_LIMIT = 50;
const MAX_MATCH_SCAN = 300;
const MIN_HIGHLIGHT_GAMES = 5;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 8;
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
interface CommunityStatsContext {
@@ -58,6 +70,15 @@ interface BaseDataset {
matches: InternalMatchCardView[];
records: InternalRecord[];
detailsByMatchId: Map<string, InternalGameDetail[]>;
competition?: InternalMatchCompetition;
}
interface CachedMatchPage extends Omit<InternalMatchListResponse, 'matches'> {
cards: Array<{
card: InternalMatchCardView;
sourceCompetitionId?: string;
sourceRevision?: number;
}>;
}
@Injectable()
@@ -71,6 +92,8 @@ export class CommunityStatsService {
string,
Promise<UserInternalHistoryResponse>
>();
private readonly fragmentRepairs = new Map<string, Promise<number>>();
private readonly rawRecoveryRetryAfter = new Map<string, number>();
constructor(
private readonly connectionService: ConnectionService,
@@ -84,67 +107,141 @@ export class CommunityStatsService {
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 cached = await this.cacheService.get<CachedMatchPage>(key);
const page =
cached ?? (await this.loadMatchPage(params.communityId, params.filters));
if (!cached) await this.cacheService.set(key, page);
const { cards, ...pagination } = page;
if (cards.length === 0) return { ...pagination, matches: [] };
const matchIds = cards.map(
({ card }) => new mongoose.Types.ObjectId(card.matchId),
);
const CompetitionModel =
await this.connectionService.getModel('competition');
const competitions = await CompetitionModel.find({
communityId: params.communityId,
matchId: { $in: matchIds },
})
.select({
matchId: 1,
communityId: 1,
schemaVersion: 1,
revision: 1,
phase: 1,
format: 1,
createdAt: 1,
updatedAt: 1,
'teams.teamId': 1,
'teams.name': 1,
'teams.displayOrder': 1,
'projection.phase': 1,
'projection.formatType': 1,
'projection.outcome': 1,
'projection.series': 1,
})
.lean()
.exec();
const official = new Map(
competitions.map((competition) => [
competition.matchId.toString(),
this.presentOfficialResult(competition),
]),
);
return {
...pagination,
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
const resultPresentation = official.get(card.matchId) ?? {
type: sourceCompetitionId
? ('unavailable' as const)
: ('legacy' as const),
};
const canUseGames =
resultPresentation.type === 'legacy' ||
(resultPresentation.type === 'official' &&
sourceCompetitionId === resultPresentation.competitionId &&
sourceRevision === resultPresentation.sourceRevision);
return {
...(canUseGames ? card : this.adjustCardForRange(card, [])),
resultPresentation,
};
}),
};
}
private async loadMatchPage(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<CachedMatchPage> {
const limit = this.clampLimit(
params.filters.limit,
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 context = await this.resolveContext(communityId, filters);
await this.repairCommunityFragments(communityId);
const page = await this.matchStatsRepository.findMatchPage({
...filters,
communityId,
from: context.from?.getTime(),
to: context.to?.getTime(),
limit: 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,
const last = page.length > limit ? visible.at(-1) : undefined;
return {
cards: visible.map((fragment) => ({
card: this.adjustCardForRange(
fragment.matchCard as unknown as InternalMatchCardView,
(fragment.gameDetails ?? []).filter((game) =>
this.isGameInRange(game.gameCreation, context),
),
),
sourceCompetitionId: fragment.sourceCompetitionId?.toString(),
sourceRevision: fragment.sourceRevision,
})),
nextCursor: last?.scheduledAt.getTime() ?? null,
nextCursorMatchId: last?.matchId.toString(),
season: context.season,
};
await this.cacheService.set(key, response);
return response;
}
public async getSeasons(communityId: mongoose.Types.ObjectId) {
const { community } = await this.resolveContext(communityId, {});
return { seasons: this.resolveSeasons(community) };
}
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;
const { query, ...filters } = params.filters;
const key = this.cacheKey('leaderboard', params.communityId, filters);
let response = await this.cacheService.get<LeaderboardResponse>(key);
if (!response) {
const dataset = await this.buildSeasonDataset(
params.communityId,
filters,
);
const records = this.applyChampionFilter(dataset.records, filters);
response = {
rows: this.buildLeaderboardRows(records),
season: dataset.season,
};
await this.cacheService.set(key, response);
}
const keyword = query?.toLocaleLowerCase('ko-KR');
if (!keyword) return response;
return {
...response,
matchedUserIds: response.rows
.filter(({ summonerName, tagLine }) =>
(tagLine ? summonerName + '#' + tagLine : summonerName)
.toLocaleLowerCase('ko-KR')
.includes(keyword),
)
.map(({ userId }) => userId),
};
}
public async getTeamInsights(params: {
@@ -159,13 +256,13 @@ export class CommunityStatsService {
const cached = await this.cacheService.get<TeamInsightsResponse>(key);
if (cached) return cached;
const dataset = await this.buildBaseDataset(
const dataset = await this.buildSeasonDataset(
params.communityId,
params.filters,
);
const records = this.applyChampionFilter(dataset.records, params.filters);
const rows = this.buildLeaderboardRows(records);
const gameDetails = [...dataset.detailsByMatchId.values()].flat();
const gameDetails = dataset.gameDetails;
const blueGames = gameDetails.length;
const redGames = gameDetails.length;
const blueWins = gameDetails.filter(
@@ -174,6 +271,7 @@ export class CommunityStatsService {
const redWins = gameDetails.filter(
(game) => game.winnerSide === 'red',
).length;
const confirmedGames = blueWins + redWins;
const response: TeamInsightsResponse = {
season: dataset.season,
@@ -182,6 +280,11 @@ export class CommunityStatsService {
red: this.percent(redWins, redGames),
bluePicks: blueGames,
redPicks: redGames,
confirmed: {
sampleSize: confirmedGames,
blue: this.percent(blueWins, confirmedGames),
red: this.percent(redWins, confirmedGames),
},
},
topKda: this.toHighlight(
rows
@@ -222,29 +325,56 @@ export class CommunityStatsService {
communityId: mongoose.Types.ObjectId;
matchId: mongoose.Types.ObjectId;
}): Promise<InternalMatchDetailResponse> {
const revision = await this.getDetailRevision(
params.communityId,
params.matchId,
);
const key = new CommunityStatsCacheKey(
params.communityId.toString(),
'matchDetail',
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}`,
`v${MATCH_STATS_BUILDER_VERSION}:r${MATCH_DETAIL_RESPONSE_CACHE_VERSION}:${params.matchId.toString()}:${revision}`,
);
const cached =
await this.cacheService.get<InternalMatchDetailResponse>(key);
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
if (
cached &&
isCompleteMatchDetailResponse(cached) &&
(!this.canRetryRawRecovery(key) ||
!(await this.hasArchivedMissingRaw(cached.games, cached.competition)))
) {
return cached;
}
const inFlight = this.matchDetailInFlight.get(key.identity);
const identity = key.identity;
const inFlight = this.matchDetailInFlight.get(identity);
if (inFlight) return inFlight;
const promise = this.buildMatchDetailResponse(params, key);
this.matchDetailInFlight.set(key.identity, promise);
this.matchDetailInFlight.set(identity, promise);
try {
return await promise;
} finally {
if (this.matchDetailInFlight.get(key.identity) === promise) {
this.matchDetailInFlight.delete(key.identity);
if (this.matchDetailInFlight.get(identity) === promise) {
this.matchDetailInFlight.delete(identity);
}
}
}
private async getDetailRevision(
communityId: mongoose.Types.ObjectId,
matchId: mongoose.Types.ObjectId,
): Promise<string> {
const CompetitionModel =
await this.connectionService.getModel('competition');
const source = await CompetitionModel.findOne({ communityId, matchId })
.select({ _id: 1, revision: 1, projectorVersion: 1 })
.lean()
.exec();
return source
? `${source._id.toString()}:${source.revision}:${source.projectorVersion}`
: 'legacy';
}
private async buildMatchDetailResponse(
params: {
communityId: mongoose.Types.ObjectId;
@@ -252,27 +382,101 @@ export class CommunityStatsService {
},
key: CommunityStatsCacheKey,
): Promise<InternalMatchDetailResponse> {
const dataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
const match = dataset.matches.find(
let dataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
let match = dataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!match) throw new NotFoundException('Internal match not found.');
let gameDetails = dataset.detailsByMatchId.get(match.matchId) ?? [];
if (gameDetails.some((game) => game.timelineLoaded !== true)) {
let games = linkDetailGames(dataset, match.matchId);
const missingBefore = new Set(
games
.filter(
({ analysisAvailability }) => analysisAvailability === 'missing',
)
.map(({ game }) => game.riotMatchId),
);
const rawRestored =
this.canRetryRawRecovery(key) &&
(await this.hasArchivedMissingRaw(
games.map(({ game, official, analysisAvailability }) => ({
riotMatchId: game.riotMatchId,
gameId: official?.id,
analysisAvailability,
})),
dataset.competition,
));
let canCacheResponse = true;
if (rawRestored || games.some(needsDetailHydration)) {
if (rawRestored) this.deferRawRecovery(key);
await this.matchStatsService.buildAndUpsert(params.matchId, {
includeTimeline: true,
});
const refreshedDataset = await this.buildBaseDataset(params.communityId, {
seasonId: 'all',
});
gameDetails = refreshedDataset.detailsByMatchId.get(match.matchId) ?? [];
const refreshedDataset = await this.buildBaseDataset(
params.communityId,
{
seasonId: 'all',
},
params.matchId,
);
const refreshedMatch = refreshedDataset.matches.find(
(item) => item.matchId === params.matchId.toString(),
);
if (!refreshedMatch)
throw new NotFoundException('Internal match not found.');
dataset = refreshedDataset;
match = refreshedMatch;
games = linkDetailGames(dataset, match.matchId);
const rawImproved = games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'available',
);
if (rawImproved) {
canCacheResponse = await this.cacheService.invalidateCommunityWithRetry(
params.communityId.toString(),
);
if (canCacheResponse) {
try {
// Read the new generation before caching the rebuilt response.
await this.cacheService.get(key);
} catch (error) {
canCacheResponse = false;
this.logger.warn(
`Stats detail cache refresh failed: ${String(error)}`,
);
}
}
}
if (
!games.some(
({ game, analysisAvailability }) =>
missingBefore.has(game.riotMatchId) &&
analysisAvailability === 'missing',
)
) {
this.rawRecoveryRetryAfter.delete(key.field);
}
}
const response: InternalMatchDetailResponse = {
match,
games: gameDetails.map((game) => ({
competition: dataset.competition,
games: games.map(({ game, official, analysisAvailability }) => ({
gameNumber: game.gameNumber,
analysisAvailability,
...(official
? {
gameId: official.id,
gameSlotId: official.gameSlotId,
seriesId: official.seriesId,
ordinal: official.ordinal,
}
: {}),
riotMatchId: game.riotMatchId,
gameCreation: game.gameCreation,
gameDuration: game.gameDuration,
@@ -325,7 +529,12 @@ export class CommunityStatsService {
})),
})),
};
if (gameDetails.every((game) => game.timelineLoaded === true)) {
if (!canCacheResponse) return response;
if (
!games.some(needsDetailHydration) &&
(!dataset.competition ||
response.games.length === dataset.competition.projection.games.length)
) {
await this.cacheService.setDetail(key, response);
} else {
await this.cacheService.set(
@@ -367,65 +576,260 @@ export class CommunityStatsService {
}
}
public async refreshForRiotMatches(riotMatchIds: string[]): Promise<void> {
if (riotMatchIds.length === 0) return;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const archived = await RiotMatchModel.find({
matchId: { $in: [...new Set(riotMatchIds)] },
'raw.info': { $exists: true },
})
.select({ matchId: 1 })
.lean()
.exec();
const ids = new Set(archived.map((match) => match.matchId));
if (ids.size === 0) return;
const fragments = await this.matchStatsRepository.findByRiotMatchIds([
...ids,
]);
const communityIds = new Map<string, mongoose.Types.ObjectId>();
for (const fragment of fragments) {
const missingIds = new Set(
fragment.gameDetails
.filter(
(game) => ids.has(game.riotMatchId) && game.rawAvailable === false,
)
.map((game) => game.riotMatchId),
);
if (missingIds.size === 0) continue;
try {
// Raw enrichment must run even when the Competition revision is current.
await this.matchStatsService.buildAndUpsert(fragment.matchId);
} catch (error) {
this.logger.warn(
`Stats recovery failed for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
try {
// A builder can return without writing, or fail during post-write checks.
// Only actual enrichment should cause a community-wide invalidation.
const updated = await this.matchStatsRepository.findByMatch(
fragment.matchId,
);
if (
updated?.gameDetails.some(
(game) =>
missingIds.has(game.riotMatchId) && game.rawAvailable === true,
)
) {
communityIds.set(
fragment.communityId.toString(),
fragment.communityId,
);
}
} catch (error) {
this.logger.warn(
`Could not verify stats recovery for ${fragment.matchId.toString()}: ${String(error)}`,
);
}
}
for (const communityId of communityIds.values()) {
await this.cacheService.invalidateCommunityWithRetry(
communityId.toString(),
);
}
}
private canRetryRawRecovery(key: CommunityStatsCacheKey): boolean {
return (this.rawRecoveryRetryAfter.get(key.field) ?? 0) <= Date.now();
}
private deferRawRecovery(key: CommunityStatsCacheKey): void {
const now = Date.now();
for (const [field, retryAt] of this.rawRecoveryRetryAfter) {
if (retryAt <= now) this.rawRecoveryRetryAfter.delete(field);
}
if (this.rawRecoveryRetryAfter.size >= 1000) {
this.rawRecoveryRetryAfter.delete(
this.rawRecoveryRetryAfter.keys().next().value!,
);
}
this.rawRecoveryRetryAfter.set(
key.field,
now + INCOMPLETE_MATCH_DETAIL_TTL_SECONDS * 1000,
);
}
private async hasArchivedMissingRaw(
games: Array<
Pick<
InternalMatchDetailResponse['games'][number],
'riotMatchId' | 'gameId' | 'analysisAvailability'
>
>,
competition?: InternalMatchCompetition,
): Promise<boolean> {
const officialById = new Map(
competition?.projection.games.map((game) => [game.id, game]),
);
const ids = games
.filter(
(game) =>
game.analysisAvailability === 'missing' &&
(!competition ||
(game.gameId &&
officialById.get(game.gameId)?.evidence.type === 'riot')),
)
.map((game) => game.riotMatchId);
if (ids.length === 0) return false;
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
return Boolean(
await RiotMatchModel.exists({
matchId: { $in: ids },
'raw.info': { $exists: true },
}).exec(),
);
}
public invalidateCommunity(
communityId: mongoose.Types.ObjectId,
): Promise<number> {
return this.cacheService.invalidateCommunity(communityId.toString());
}
private async buildBaseDataset(
private async buildSeasonDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
): Promise<BaseDataset> {
) {
const context = await this.resolveContext(communityId, filters);
let fragments = await this.matchStatsRepository.findByCommunity({
await this.repairCommunityFragments(communityId);
const fragments = await this.matchStatsRepository.findSeasonStats({
communityId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
from: context.from?.getTime(),
to: context.to?.getTime(),
});
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 gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
const records: InternalRecord[] = [];
const detailsByMatchId = new Map<string, InternalGameDetail[]>();
for (const fragment of fragments) {
const filteredGames = fragment.gameDetails
.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),
const games = fragment.gameDetails.filter((game) =>
this.isGameInRange(game.gameCreation, context),
);
const gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
gameDetails.push(...games);
records.push(
...fragment.records.filter((record) =>
allowedGameNumbers.has(record.gameNumber),
...fragment.records.filter(({ gameNumber }) =>
gameNumbers.has(gameNumber),
),
);
}
return { season: context.season, records, gameDetails };
}
private async buildBaseDataset(
communityId: mongoose.Types.ObjectId,
filters: CommunityStatsFilters,
matchId: mongoose.Types.ObjectId,
): Promise<BaseDataset> {
const context = await this.resolveContext(communityId, filters);
const MatchModel = await this.connectionService.getModel('match');
const match = await MatchModel.findOne({ _id: matchId, communityId })
.lean()
.exec();
if (!match) throw new NotFoundException('Internal match not found.');
const CompetitionModel =
await this.connectionService.getModel('competition');
const [source, stored] = await Promise.all([
CompetitionModel.findOne({ matchId, communityId }).lean().exec(),
this.matchStatsRepository.findByMatch(matchId),
]);
const isCurrent = (fragment: MatchStatsDocument | null) =>
Boolean(
fragment?.communityId.equals(communityId) &&
fragment.builderVersion >= MATCH_STATS_BUILDER_VERSION &&
(source
? fragment.sourceCompetitionId?.equals(source._id) &&
fragment.sourceRevision === source.revision &&
fragment.projectorVersion === source.projectorVersion
: !fragment.sourceCompetitionId && !match.competitionId),
);
let fragment = stored;
if (!isCurrent(fragment) && (source || match.result?.games.length)) {
await this.matchStatsService.buildAndUpsert(matchId);
fragment = await this.matchStatsRepository.findByMatch(matchId);
}
if (!isCurrent(fragment)) fragment = null;
if (!fragment && !source && !match.competitionId) {
throw new NotFoundException('Internal match not found.');
}
const competition =
source &&
presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({
...team,
members: team.members.map((member) => ({ ...member })),
})),
});
const resultPresentation: InternalMatchResultPresentation = source
? this.presentOfficialResult(source)
: { type: match.competitionId ? 'unavailable' : 'legacy' };
const card = (fragment?.matchCard as unknown as
| InternalMatchCardView
| undefined) ?? {
matchId: matchId.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
status: match.status === 'finished' ? 'finished' : 'in-progress',
gameCount: match.gameCount,
seriesResults: [],
games: [],
teams: match.teams.map(({ teamIndex, name }) => ({
teamIndex,
name,
members: [],
})),
};
return {
season: context.season,
matches: cards,
records,
detailsByMatchId,
matches: [{ ...card, resultPresentation }],
records: fragment?.records ?? [],
detailsByMatchId: new Map([
[matchId.toString(), fragment?.gameDetails ?? []],
]),
competition: competition
? {
id: competition.id,
revision: competition.revision,
teams: competition.teams,
projection: competition.projection,
}
: undefined,
};
}
private presentOfficialResult(
source: Competition & { _id: mongoose.Types.ObjectId },
): InternalMatchResultPresentation {
const competition = presentCompetitionDetail({
...source,
teams: source.teams.map((team) => ({ ...team, members: [] })),
});
const { projection } = competition;
return {
type: 'official',
competitionId: competition.id,
sourceRevision: competition.revision,
phase: projection.phase,
formatType: projection.formatType,
teams: competition.teams.map(({ teamId, name }) => ({ teamId, name })),
completedSeriesCount: projection.series.filter(
({ status }) => status === 'completed',
).length,
outcome: projection.outcome,
singleSeries:
projection.formatType === 'paired-series' &&
projection.series.length === 1
? projection.series[0]
: undefined,
};
}
@@ -442,13 +846,25 @@ export class CommunityStatsService {
params.filters,
);
const userId = params.userId.toString();
const fragments = await this.matchStatsRepository.findUserRecordFragments({
const fragmentQuery = {
communityId: params.communityId,
userId: params.userId,
fromGameCreation: context.from?.getTime(),
toGameCreation: context.to?.getTime(),
limit: MAX_MATCH_SCAN,
});
};
let fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
const stale = fragments.filter(
(fragment) => fragment.builderVersion < MATCH_STATS_BUILDER_VERSION,
);
if (stale.length > 0) {
for (const { matchId } of stale) {
await this.matchStatsService.buildAndUpsert(matchId);
}
fragments =
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
}
const allUserRecords = this.extractUserRecords(fragments, userId, context);
const records = this.applyChampionFilter(allUserRecords, params.filters);
const limit = this.clampLimit(params.filters.limit, 30, 50);
@@ -621,9 +1037,22 @@ export class CommunityStatsService {
return rebuilt;
}
private repairCommunityFragments(communityId: mongoose.Types.ObjectId) {
const key = communityId.toString();
const inFlight = this.fragmentRepairs.get(key);
if (inFlight) return inFlight;
const repair = this.rebuildMissingOrStaleFragments(communityId).finally(
() => {
this.fragmentRepairs.delete(key);
},
);
this.fragmentRepairs.set(key, repair);
return repair;
}
private adjustCardForRange(
card: InternalMatchCardView,
filteredGames: InternalGameDetail[],
filteredGames: Pick<InternalGameDetail, 'gameNumber'>[],
): InternalMatchCardView {
const allowedGameNumbers = new Set(
filteredGames.map((game) => game.gameNumber),
@@ -706,13 +1135,20 @@ export class CommunityStatsService {
: season.startedAt
? new Date(season.startedAt)
: null;
const to = filters.to ? new Date(filters.to) : null;
const to = filters.to
? new Date(filters.to)
: season.endedAt
? new Date(season.endedAt)
: 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.');
}
if (from && to && from.getTime() > to.getTime()) {
throw new BadRequestException('Invalid date range.');
}
return { community, season, from, to };
}
@@ -761,7 +1197,9 @@ export class CommunityStatsService {
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]);
const rows = byUser.get(record.userId);
if (rows) rows.push(record);
else byUser.set(record.userId, [record]);
}
return [...byUser.entries()]
.map(([userId, rows]) => this.toLeaderboardRow(userId, rows))
@@ -816,6 +1254,7 @@ export class CommunityStatsService {
return {
userId,
summonerName: first?.summonerName ?? 'Unknown',
tagLine: first?.tagLine || undefined,
profileIconId: first?.profileIconId ?? 0,
games: records.length,
wins,
@@ -907,10 +1346,22 @@ export class CommunityStatsService {
totalKills: kills,
totalDeaths: deaths,
totalAssists: assists,
doubleKills: 0,
tripleKills: 0,
quadraKills: 0,
pentaKills: 0,
doubleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.doubleKills ?? 0),
0,
),
tripleKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.tripleKills ?? 0),
0,
),
quadraKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.quadraKills ?? 0),
0,
),
pentaKills: rows.reduce(
(sum, row) => sum + (row.multiKills?.pentaKills ?? 0),
0,
),
avgCs: this.average(this.sum(rows, 'cs'), rows.length),
avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes),
};
@@ -980,6 +1431,7 @@ export class CommunityStatsService {
championLevel: record.championLevel,
teamPosition: record.teamPosition,
kills: record.kills,
largestMultiKill: record.multiKills?.largestMultiKill,
deaths: record.deaths,
assists: record.assists,
kda: this.kda(record.kills, record.deaths, record.assists),
@@ -1006,6 +1458,14 @@ export class CommunityStatsService {
puuid: participant.userId,
gameName: participant.summonerName,
tagLine: '',
tier: participant.tier
? {
tier: participant.tier.tier,
rank: participant.tier.rank,
leaguePoints: participant.tier.leaguePoints,
fetchedAt: new Date(participant.tier.fetchedAt).toISOString(),
}
: undefined,
championId: participant.championId,
championLevel: participant.championLevel,
teamPosition: participant.teamPosition,
@@ -1161,13 +1621,18 @@ export class CommunityStatsService {
communityId.toString(),
cacheScope,
JSON.stringify([
scope,
MATCH_STATS_BUILDER_VERSION,
scope === 'matches' ? 'matches-page-v1' : scope,
filters.seasonId ?? 'current',
filters.from ?? '',
filters.to ?? '',
filters.championId ?? '',
filters.cursor ?? '',
filters.limit ?? '',
filters.query ?? '',
filters.format ?? '',
filters.playerId ?? '',
filters.cursorMatchId ?? '',
]),
);
}
@@ -1210,6 +1675,46 @@ export class CommunityStatsService {
}
}
interface LinkedDetailGame {
game: InternalGameDetail;
official?: CompetitionGameView;
analysisAvailability: GameAnalysisAvailability;
}
function linkDetailGames(
dataset: BaseDataset,
matchId: string,
): LinkedDetailGame[] {
const officialByEvidence = new Map<string, CompetitionGameView | null>();
for (const game of dataset.competition?.projection.games ?? []) {
const evidence =
game.evidence.type === 'riot'
? game.evidence.riotMatchId
: game.evidence.legacyReference;
const key = JSON.stringify([game.displayNumber, evidence]);
officialByEvidence.set(key, officialByEvidence.has(key) ? null : game);
}
return (dataset.detailsByMatchId.get(matchId) ?? []).flatMap((game) => {
const official = officialByEvidence.get(
JSON.stringify([game.gameNumber, game.riotMatchId]),
);
if (dataset.competition && !official) return [];
// A Riot ID is evidence, not a pending raw fetch. Detail hydration only
// fetches timelines for matches whose raw data is already archived.
const analysisAvailability: GameAnalysisAvailability =
game.rawAvailable === false ? 'missing' : 'available';
return [{ game, official: official ?? undefined, analysisAvailability }];
});
}
function needsDetailHydration({
game,
analysisAvailability,
}: LinkedDetailGame) {
return analysisAvailability === 'available' && game.timelineLoaded !== true;
}
function isCompleteMatchDetailResponse(
response: InternalMatchDetailResponse,
): boolean {