feat(api): enrich Riot accounts
This commit is contained in:
1 parent
463c839782
commit
d6f52a8b15
3 files changed
+991
No files matched your search
@@ -0,0 +1,450 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import {
|
||||
ChampionMasteryEntry,
|
||||
RiotAccount,
|
||||
TierInfo,
|
||||
} from '../global/database/schema';
|
||||
import { RiotAccountService } from './riot-account.service';
|
||||
import { RiotChampionMasteryService } from './riot-champion-mastery.service';
|
||||
import { RiotApiError } from './riot.client.service';
|
||||
import { RiotLeagueService } from './riot-league.service';
|
||||
import {
|
||||
RIOT_RECENT_MATCH_LIMIT,
|
||||
RiotRecentMatchesService,
|
||||
} from './riot-recent-matches.service';
|
||||
import { RiotRecentStatsService } from './riot-recent-stats.service';
|
||||
import { RiotSummonerService } from './riot-summoner.service';
|
||||
import {
|
||||
RiotChampionMasteryDto,
|
||||
RiotLeagueEntryDto,
|
||||
RiotMatchDto,
|
||||
RiotPlatformRoute,
|
||||
RiotRegionalRoute,
|
||||
RiotSummonerDto,
|
||||
} from './riot.types';
|
||||
|
||||
const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr';
|
||||
const DEFAULT_REGION: RiotRegionalRoute = 'asia';
|
||||
const MASTERY_LIMIT = 10;
|
||||
|
||||
const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h
|
||||
const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h
|
||||
const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h
|
||||
|
||||
export interface EnrichOptions {
|
||||
platform?: RiotPlatformRoute;
|
||||
region?: RiotRegionalRoute;
|
||||
force?: boolean;
|
||||
summonerTtlMs?: number;
|
||||
leagueTtlMs?: number;
|
||||
masteryTtlMs?: number;
|
||||
recentMatchesTtlMs?: number;
|
||||
}
|
||||
|
||||
export interface EnrichResult {
|
||||
summoner: 'updated' | 'fresh' | 'failed';
|
||||
league: 'updated' | 'fresh' | 'failed';
|
||||
masteries: 'updated' | 'fresh' | 'failed';
|
||||
recentMatches: 'updated' | 'fresh' | 'failed';
|
||||
account: RiotAccount | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class RiotAccountEnrichmentService {
|
||||
private readonly logger = new Logger(RiotAccountEnrichmentService.name);
|
||||
private readonly inFlight = new Map<string, Promise<EnrichResult>>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
private readonly accountService: RiotAccountService,
|
||||
private readonly summonerService: RiotSummonerService,
|
||||
private readonly leagueService: RiotLeagueService,
|
||||
private readonly masteryService: RiotChampionMasteryService,
|
||||
private readonly recentMatchesService: RiotRecentMatchesService,
|
||||
private readonly recentStatsService: RiotRecentStatsService,
|
||||
) {}
|
||||
|
||||
public async markRefreshRequested(
|
||||
userId: mongoose.Types.ObjectId,
|
||||
puuid: string,
|
||||
at: Date = new Date(),
|
||||
): Promise<void> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
await UserModel.updateOne(
|
||||
{ _id: userId, 'riotAccounts.puuid': puuid },
|
||||
{ $set: { 'riotAccounts.$.lastRefreshRequestedAt': at } },
|
||||
).exec();
|
||||
}
|
||||
|
||||
public async enrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const key = `${params.userId.toString()}:${params.puuid}`;
|
||||
const existing = this.inFlight.get(key);
|
||||
if (existing) return existing;
|
||||
|
||||
const promise = this.doEnrichRiotAccount(params).finally(() => {
|
||||
this.inFlight.delete(key);
|
||||
});
|
||||
this.inFlight.set(key, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async doEnrichRiotAccount(params: {
|
||||
userId: mongoose.Types.ObjectId;
|
||||
puuid: string;
|
||||
options?: EnrichOptions;
|
||||
}): Promise<EnrichResult> {
|
||||
const UserModel = await this.connectionService.getModel('user');
|
||||
const user = await UserModel.findById(params.userId).exec();
|
||||
if (!user) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
recentMatches: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
const account = user.riotAccounts.find((a) => a.puuid === params.puuid);
|
||||
if (!account) {
|
||||
return {
|
||||
summoner: 'failed',
|
||||
league: 'failed',
|
||||
masteries: 'failed',
|
||||
recentMatches: 'failed',
|
||||
account: null,
|
||||
};
|
||||
}
|
||||
|
||||
const CommunityModel = await this.connectionService.getModel('community');
|
||||
const community = await CommunityModel.findById(user.communityId)
|
||||
.select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 })
|
||||
.lean()
|
||||
.exec();
|
||||
|
||||
const opts = params.options ?? {};
|
||||
const platform =
|
||||
opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM;
|
||||
const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION;
|
||||
const now = Date.now();
|
||||
|
||||
const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS;
|
||||
const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS;
|
||||
const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS;
|
||||
const recentMatchesTtl =
|
||||
opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS;
|
||||
const force = opts.force === true;
|
||||
const seasonStartedAt = community?.seasonStartedAt
|
||||
? new Date(community.seasonStartedAt)
|
||||
: undefined;
|
||||
const seasonInvalidatesRecentStats =
|
||||
seasonStartedAt !== undefined &&
|
||||
(!account.recentStatsFetchedAt ||
|
||||
account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime());
|
||||
|
||||
const summonerStale =
|
||||
force ||
|
||||
account.revisionDate === 0 ||
|
||||
now - account.revisionDate > summonerTtl;
|
||||
const leagueStale =
|
||||
force ||
|
||||
account.tiers.length === 0 ||
|
||||
this.tiersOldestAt(account.tiers) < now - leagueTtl;
|
||||
const masteryStale =
|
||||
force ||
|
||||
!account.championMasteriesFetchedAt ||
|
||||
now - account.championMasteriesFetchedAt.getTime() > masteryTtl;
|
||||
const recentMatchesStale =
|
||||
force ||
|
||||
seasonInvalidatesRecentStats ||
|
||||
!account.recentStatsFetchedAt ||
|
||||
!account.recentStatsSummary ||
|
||||
now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl;
|
||||
|
||||
const summonerOutcome = summonerStale
|
||||
? await this.fetchSummonerSafe(params.puuid, platform, region)
|
||||
: { status: 'fresh' as const, dto: null, platform };
|
||||
const effectivePlatform = summonerOutcome.platform ?? platform;
|
||||
|
||||
const [leagueOutcome, masteryOutcome, recentMatchesOutcome] =
|
||||
await Promise.all([
|
||||
leagueStale
|
||||
? this.fetchLeagueSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
masteryStale
|
||||
? this.fetchMasteriesSafe(params.puuid, effectivePlatform)
|
||||
: Promise.resolve({ status: 'fresh' as const, dto: null }),
|
||||
recentMatchesStale
|
||||
? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt)
|
||||
: Promise.resolve({
|
||||
status: 'fresh' as const,
|
||||
summary: null,
|
||||
matchIds: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (summonerOutcome.status === 'updated' && summonerOutcome.dto) {
|
||||
this.applySummoner(account, summonerOutcome.dto);
|
||||
}
|
||||
if (leagueOutcome.status === 'updated' && leagueOutcome.dto) {
|
||||
this.applyLeagueEntries(account, leagueOutcome.dto);
|
||||
}
|
||||
if (masteryOutcome.status === 'updated' && masteryOutcome.dto) {
|
||||
this.applyMasteries(account, masteryOutcome.dto);
|
||||
}
|
||||
if (
|
||||
recentMatchesOutcome.status === 'updated' &&
|
||||
recentMatchesOutcome.summary &&
|
||||
recentMatchesOutcome.matchIds
|
||||
) {
|
||||
this.applyRecentMatches(
|
||||
account,
|
||||
recentMatchesOutcome.summary,
|
||||
recentMatchesOutcome.matchIds,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
summonerOutcome.status === 'updated' ||
|
||||
leagueOutcome.status === 'updated' ||
|
||||
masteryOutcome.status === 'updated' ||
|
||||
recentMatchesOutcome.status === 'updated'
|
||||
) {
|
||||
await user.save();
|
||||
}
|
||||
|
||||
return {
|
||||
summoner: summonerOutcome.status,
|
||||
league: leagueOutcome.status,
|
||||
masteries: masteryOutcome.status,
|
||||
recentMatches: recentMatchesOutcome.status,
|
||||
account,
|
||||
};
|
||||
}
|
||||
|
||||
private async fetchSummonerSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
region: RiotRegionalRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute }
|
||||
| { status: 'failed'; dto: null; platform: RiotPlatformRoute }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.summonerService.getByPuuid(puuid, { platform });
|
||||
return { status: 'updated', dto, platform };
|
||||
} catch (err) {
|
||||
if (err instanceof RiotApiError && err.status === 404) {
|
||||
try {
|
||||
const regionDto = await this.accountService.getRegionByPuuid(puuid, {
|
||||
region,
|
||||
});
|
||||
if (regionDto.region !== platform) {
|
||||
this.logger.warn(
|
||||
`Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`,
|
||||
);
|
||||
}
|
||||
const dto = await this.summonerService.getByPuuid(puuid, {
|
||||
platform: regionDto.region,
|
||||
});
|
||||
return { status: 'updated', dto, platform: regionDto.region };
|
||||
} catch (fallbackErr) {
|
||||
this.logger.warn(
|
||||
`Summoner fallback fetch failed for ${puuid}: ${
|
||||
(fallbackErr as Error)?.message ?? fallbackErr
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
this.logger.warn(
|
||||
`Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`,
|
||||
);
|
||||
return { status: 'failed', dto: null, platform };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchLeagueSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotLeagueEntryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.leagueService.getEntriesByPuuid(puuid, {
|
||||
platform,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`League entries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchMasteriesSafe(
|
||||
puuid: string,
|
||||
platform: RiotPlatformRoute,
|
||||
): Promise<
|
||||
| { status: 'updated'; dto: RiotChampionMasteryDto[] }
|
||||
| { status: 'failed'; dto: null }
|
||||
> {
|
||||
try {
|
||||
const dto = await this.masteryService.getTopByPuuid(puuid, {
|
||||
platform,
|
||||
count: MASTERY_LIMIT,
|
||||
});
|
||||
return { status: 'updated', dto };
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Champion masteries fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', dto: null };
|
||||
}
|
||||
}
|
||||
|
||||
private async fetchRecentMatchesSafe(
|
||||
puuid: string,
|
||||
region: RiotRegionalRoute,
|
||||
seasonStartedAt?: Date,
|
||||
): Promise<
|
||||
| {
|
||||
status: 'updated';
|
||||
summary: RiotAccount['recentStatsSummary'];
|
||||
matchIds: string[];
|
||||
}
|
||||
| { status: 'failed'; summary: null; matchIds: null }
|
||||
> {
|
||||
try {
|
||||
await this.recentMatchesService.syncRecentMatches({
|
||||
puuid,
|
||||
region,
|
||||
limit: RIOT_RECENT_MATCH_LIMIT,
|
||||
});
|
||||
const matches = await this.recentMatchesService.loadFromDb({
|
||||
puuid,
|
||||
limit: RIOT_RECENT_MATCH_LIMIT,
|
||||
});
|
||||
const summary = this.recentStatsService.computeSummary(
|
||||
matches.map((match) => match.raw as unknown as RiotMatchDto),
|
||||
puuid,
|
||||
{ seasonStartedAt },
|
||||
);
|
||||
return {
|
||||
status: 'updated',
|
||||
summary,
|
||||
matchIds: matches.map((match) => match.matchId),
|
||||
};
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Recent matches fetch failed for ${puuid}: ${
|
||||
(err as Error)?.message ?? err
|
||||
}`,
|
||||
);
|
||||
return { status: 'failed', summary: null, matchIds: null };
|
||||
}
|
||||
}
|
||||
|
||||
private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void {
|
||||
account.profileIconId = dto.profileIconId;
|
||||
account.revisionDate = dto.revisionDate;
|
||||
account.summonerLevel = dto.summonerLevel;
|
||||
}
|
||||
|
||||
private applyLeagueEntries(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
): void {
|
||||
const fetchedAt = new Date();
|
||||
this.appendTierHistoryIfChanged(account, entries, fetchedAt);
|
||||
const next: TierInfo[] = entries.map((e) => ({
|
||||
leagueId: e.leagueId,
|
||||
queueType: e.queueType,
|
||||
tier: e.tier,
|
||||
rank: e.rank,
|
||||
puuid: e.puuid,
|
||||
leaguePoints: e.leaguePoints,
|
||||
wins: e.wins,
|
||||
losses: e.losses,
|
||||
veteran: e.veteran,
|
||||
inactive: e.inactive,
|
||||
freshBlood: e.freshBlood,
|
||||
hotStreak: e.hotStreak,
|
||||
miniSeries: e.miniSeries,
|
||||
fetchedAt,
|
||||
}));
|
||||
account.tiers = next;
|
||||
}
|
||||
|
||||
private appendTierHistoryIfChanged(
|
||||
account: RiotAccount,
|
||||
entries: RiotLeagueEntryDto[],
|
||||
recordedAt: Date,
|
||||
): void {
|
||||
for (const entry of entries) {
|
||||
const last = [...account.tierHistory]
|
||||
.reverse()
|
||||
.find((history) => history.queueType === entry.queueType);
|
||||
const changed =
|
||||
!last ||
|
||||
last.tier !== entry.tier ||
|
||||
(last.rank ?? '') !== (entry.rank ?? '');
|
||||
if (!changed) continue;
|
||||
|
||||
account.tierHistory.push({
|
||||
queueType: entry.queueType,
|
||||
tier: entry.tier,
|
||||
rank: entry.rank,
|
||||
leaguePoints: entry.leaguePoints,
|
||||
wins: entry.wins,
|
||||
losses: entry.losses,
|
||||
recordedAt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private applyMasteries(
|
||||
account: RiotAccount,
|
||||
masteries: RiotChampionMasteryDto[],
|
||||
): void {
|
||||
const summary: ChampionMasteryEntry[] = masteries
|
||||
.slice(0, MASTERY_LIMIT)
|
||||
.map((m) => ({ ...m }));
|
||||
account.championMasteries = summary;
|
||||
account.championMasteriesFetchedAt = new Date();
|
||||
}
|
||||
|
||||
private applyRecentMatches(
|
||||
account: RiotAccount,
|
||||
summary: NonNullable<RiotAccount['recentStatsSummary']>,
|
||||
matchIds: string[],
|
||||
): void {
|
||||
const fetchedAt = new Date();
|
||||
account.recentStatsSummary = summary;
|
||||
account.recentStatsFetchedAt = fetchedAt;
|
||||
account.matchIds = matchIds;
|
||||
account.matchIdsFetchedAt = fetchedAt;
|
||||
}
|
||||
|
||||
private tiersOldestAt(tiers: TierInfo[]): number {
|
||||
if (tiers.length === 0) return 0;
|
||||
let oldest = Infinity;
|
||||
for (const t of tiers) {
|
||||
const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0;
|
||||
if (at < oldest) oldest = at;
|
||||
}
|
||||
return oldest === Infinity ? 0 : oldest;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user