diff --git a/apps/api/src/modules/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts new file mode 100644 index 00000000..6f3c26f2 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -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(key: string): Promise { + return this.garnetService.getJson(key); + } + + public set( + key: string, + value: unknown, + ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, + ): Promise { + return this.garnetService.setJson(key, value, ttlSeconds); + } + + public setDetail(key: string, value: unknown): Promise { + return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); + } + + public async invalidateCommunity(communityId: string): Promise { + 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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts new file mode 100644 index 00000000..e8d4ee69 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts new file mode 100644 index 00000000..4be3ae42 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -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 {} diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts new file mode 100644 index 00000000..df89ea56 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -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; +} + +@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 { + const key = this.cacheKey('matches', params.communityId, params.filters); + const cached = await this.cacheService.get(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 { + const key = this.cacheKey( + 'leaderboard', + params.communityId, + params.filters, + ); + const cached = await this.cacheService.get(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 { + const key = this.cacheKey( + 'teamInsights', + params.communityId, + params.filters, + ); + const cached = await this.cacheService.get(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 { + const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; + const cached = + await this.cacheService.get(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 { + const key = this.cacheKey( + `userInternal:${params.userId.toString()}`, + params.communityId, + params.filters, + ); + const cached = + await this.cacheService.get(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 { + return this.cacheService.invalidateCommunity(communityId.toString()); + } + + private async buildBaseDataset( + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): Promise { + 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(); + + 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 { + 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(); + 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 { + 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(); + 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(); + 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(); + 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((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, + ): 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> { + const counts = new Map(); + 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>; + } + + 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( + 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; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts new file mode 100644 index 00000000..ec381dea --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -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>; + 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>; + 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]; +} diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts new file mode 100644 index 00000000..3f5c9b1f --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.spec.ts @@ -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); + }); +}); diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts new file mode 100644 index 00000000..b4a10c0d --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -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; + }): 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['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['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(); + 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['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['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; +} diff --git a/apps/api/src/modules/community-stats/match-stats.repository.ts b/apps/api/src/modules/community-stats/match-stats.repository.ts new file mode 100644 index 00000000..21b35acf --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.repository.ts @@ -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, + ): Promise { + 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 { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + await MatchStatsModel.deleteOne({ matchId }).exec(); + } + + public async deleteByMatches( + matchIds: mongoose.Types.ObjectId[], + ): Promise { + 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 { + 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 { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + const filter: Record = { + 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 { + const MatchStatsModel = await this.connectionService.getModel('matchStats'); + const filter: Record = { + 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(); + } +} diff --git a/apps/api/src/modules/community-stats/match-stats.service.spec.ts b/apps/api/src/modules/community-stats/match-stats.service.spec.ts new file mode 100644 index 00000000..552cca15 --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.service.spec.ts @@ -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; + 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; + 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; + 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, + }), + ); + }); +}); diff --git a/apps/api/src/modules/community-stats/match-stats.service.ts b/apps/api/src/modules/community-stats/match-stats.service.ts new file mode 100644 index 00000000..00381a9d --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.service.ts @@ -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 { + 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, + records: fragment.records, + gameDetails: fragment.gameDetails, + builtAt: new Date(), + builderVersion: MATCH_STATS_BUILDER_VERSION, + }); + } + + public async removeByMatch(matchId: mongoose.Types.ObjectId): Promise { + await this.repository.deleteByMatch(matchId); + } + + public async removeByMatches( + matchIds: mongoose.Types.ObjectId[], + ): Promise { + 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) + ); + } +} diff --git a/apps/api/src/modules/community-stats/match-stats.types.ts b/apps/api/src/modules/community-stats/match-stats.types.ts new file mode 100644 index 00000000..ed0901e3 --- /dev/null +++ b/apps/api/src/modules/community-stats/match-stats.types.ts @@ -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; +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.controller.ts b/apps/api/src/modules/legacy-import/legacy-import.controller.ts new file mode 100644 index 00000000..6df3f88b --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.controller.ts @@ -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; + } +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.module.ts b/apps/api/src/modules/legacy-import/legacy-import.module.ts new file mode 100644 index 00000000..9bd9ad80 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.module.ts @@ -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 {} diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts new file mode 100644 index 00000000..9f6a9244 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + const MatchModel = await this.connectionService.getModel('match'); + const limit = Math.max(1, Math.min(params.limit ?? 30, 100)); + const filter: Record = { + 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 { + 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(); + 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 = {}; + 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> { + const matchIds = new Set(); + 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 { + 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 = { + 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 { + 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 = { + 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, + 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 { + 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 { + 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 { + 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 { + 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 { + const users = await this.findImportableUsers(communityId); + return buildUserByPuuidMap(users); + } + + private async findImportableUsers( + communityId: mongoose.Types.ObjectId, + ): Promise { + 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, + ) { + 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 { + 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, + ); +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.types.ts b/apps/api/src/modules/legacy-import/legacy-import.types.ts new file mode 100644 index 00000000..bc2d2205 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.types.ts @@ -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; +} diff --git a/apps/api/src/modules/legacy-import/match-builder.util.ts b/apps/api/src/modules/legacy-import/match-builder.util.ts new file mode 100644 index 00000000..6915ecc4 --- /dev/null +++ b/apps/api/src/modules/legacy-import/match-builder.util.ts @@ -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; + +export function buildUserByPuuidMap(users: UserDocument[]): UserByPuuidMap { + const entries = new Map(); + 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 => 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 => + 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'; +} diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.module.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.module.ts new file mode 100644 index 00000000..2b212a95 --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.module.ts @@ -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 {} diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts new file mode 100644 index 00000000..01b88226 --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts @@ -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; +}; + +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 & { raw: jest.Mock }; + const rateLimiter = { + acquireBackground: jest.fn().mockResolvedValue(undefined), + } as unknown as jest.Mocked; + const enrichmentService = { + markRefreshRequested: jest.fn().mockResolvedValue(undefined), + enrichRiotAccount: jest.fn().mockResolvedValue(successResult()), + } as unknown as jest.Mocked; + const staleAccountRepository = { + findStaleAccounts: jest.fn().mockResolvedValue([]), + } as unknown as jest.Mocked; + 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(); + }); +}); diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts new file mode 100644 index 00000000..730f3e1d --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts @@ -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('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 { + 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 { + 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 { + 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 { + 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 { + const count = await this.getFailureCount(puuid); + return count >= FAILURE_BACKOFF_THRESHOLD; + } + + private async getFailureCount(puuid: string): Promise { + 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 { + 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 { + 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}`; + } +} diff --git a/apps/api/src/modules/riot-background-refresh/kst-window.util.spec.ts b/apps/api/src/modules/riot-background-refresh/kst-window.util.spec.ts new file mode 100644 index 00000000..b2c421fa --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/kst-window.util.spec.ts @@ -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, + ); + }); +}); diff --git a/apps/api/src/modules/riot-background-refresh/kst-window.util.ts b/apps/api/src/modules/riot-background-refresh/kst-window.util.ts new file mode 100644 index 00000000..527fc6ad --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/kst-window.util.ts @@ -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 + ); +} diff --git a/apps/api/src/modules/riot-background-refresh/stale-account.repository.spec.ts b/apps/api/src/modules/riot-background-refresh/stale-account.repository.spec.ts new file mode 100644 index 00000000..3629bf20 --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/stale-account.repository.spec.ts @@ -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, + }), + ); + }); +}); diff --git a/apps/api/src/modules/riot-background-refresh/stale-account.repository.ts b/apps/api/src/modules/riot-background-refresh/stale-account.repository.ts new file mode 100644 index 00000000..a16d54b0 --- /dev/null +++ b/apps/api/src/modules/riot-background-refresh/stale-account.repository.ts @@ -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 { + const UserModel = await this.connectionService.getModel('user'); + return UserModel.aggregate( + buildStaleAccountsPipeline(opts), + ).exec(); + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts new file mode 100644 index 00000000..3caa1162 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts @@ -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; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts new file mode 100644 index 00000000..1bfcae9d --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts @@ -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 {} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts new file mode 100644 index 00000000..ecacef15 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -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 { + 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 { + 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 { + 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 { + return this.garnetService.getJson(this.statusKey(jobId)); + } + + public async getParentStatus( + parentJobId: string, + ): Promise { + const jobIds = await this.garnetService.getJson( + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + const status = await this.getStatus(jobId); + if (!status) throw new Error(`Missing riot job status: ${jobId}`); + return status; + } + + private async setStatus(status: RiotJobStatus): Promise { + await this.garnetService.setJson( + this.statusKey(status.jobId), + status, + RIOT_JOB_STATUS_TTL_SECONDS, + ); + } + + private async setParent(parentJobId: string, jobIds: string[]): Promise { + 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}`; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts new file mode 100644 index 00000000..45968dd0 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts @@ -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; +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts new file mode 100644 index 00000000..a543d8cb --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -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 { + 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 { + 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 { + const UserModel = await this.connectionService.getModel('user'); + const now = new Date(); + const $set: Record = { + '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 { + 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 { + 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 { + return new Promise((resolve) => setTimeout(resolve, ms)); + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts new file mode 100644 index 00000000..477fd717 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -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; + } +} diff --git a/apps/web/src/pages/CommunityInternalStatsPage.tsx b/apps/web/src/pages/CommunityInternalStatsPage.tsx new file mode 100644 index 00000000..667fb046 --- /dev/null +++ b/apps/web/src/pages/CommunityInternalStatsPage.tsx @@ -0,0 +1,406 @@ +import { Link, useLocation, useSearchParams } from 'react-router'; +import { + useCommunity, + useCommunityInternalStatsMatches, + useCommunityLeaderboard, + useDdragonManifest, + useTeamInsights, +} from '../api/hooks'; +import type { + ApiInternalMatchCard, + ApiLeaderHighlight, + ApiLeaderboardRow, + TeamSide, +} from '../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../config'; +import { championDisplayName, championIconUrl, profileIconUrl } from '../lib/ddragon'; +import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league'; + +function formatDateTime(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function sideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function sideText(side: TeamSide) { + return side === 'blue' ? 'text-blue-400' : 'text-red-400'; +} + +function ratioClass(value: number) { + if (value >= 55) return 'text-blue-400'; + if (value >= 50) return 'text-amber-400'; + return 'text-base-content/45'; +} + +function ChampionChip({ + championId, + manifest, +}: { + championId: number; + manifest: ReturnType['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( + + + {icon ? : null} + + {name} + + ); +} + +function MatchCard({ + match, + manifest, +}: { + match: ApiInternalMatchCard; + manifest: ReturnType['data']; +}) { + const primarySeries = match.seriesResults[0]; + const teamName = (teamIndex: number) => + teamIndexLabel( + teamIndex, + match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); + + return ( + +
+
+
+
+ {formatDateTime(match.scheduledAt)} +
+

+ {match.title} +

+
+ {match.games.map((game) => ( + + {game.gameNumber}경기 + {game.winnerSide && game.winnerTeamIndex ? ( + + {teamName(game.winnerTeamIndex)} 승 ({sideLabel(game.winnerSide)}) + + ) : ( + '대기' + )} + {formatDuration(game.gameDuration)} + + ))} +
+
+ +
+ {primarySeries && ( +
+
+
{primarySeries.teamAWins}
+
+ {teamName(primarySeries.teamAIndex)} +
+
+
VS
+
+
{primarySeries.teamBWins}
+
+ {teamName(primarySeries.teamBIndex)} +
+
+
+ )} +
+ +
+ {match.teams.map((team) => ( +
+
+ {team.name} +
+
+ {team.members.slice(0, 5).map((member) => ( +
+ + + + + {member.summonerName} + +
+ ))} +
+
+ ))} +
+
+
+ + ); +} + +function HighlightCard({ + title, + highlight, + suffix = '', +}: { + title: string; + highlight: ApiLeaderHighlight | null | undefined; + suffix?: string; +}) { + return ( +
+
+ {title} +
+
+ {highlight ? `${highlight.metric}${suffix}` : '-'} +
+
+ {highlight?.summonerName ?? '기록 없음'} +
+
+ ); +} + +function LeaderboardTable({ + rows, + manifest, +}: { + rows: ApiLeaderboardRow[]; + manifest: ReturnType['data']; +}) { + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + return ( +
+
+ + + + + + + + + + + + + + + + {rows.map((row, index) => ( + + + + + + + + + + + + ))} + {rows.length === 0 && ( + + + + )} + +
#소환사승률게임KDAGPM킬관여분당 CS주 챔피언
+ {index + 1} + + + + + + + {row.summonerName} + + + + {row.winRate}% + + {row.games} + + {row.kda} + + {row.avgGoldPerMin} + + {row.avgKillParticipation}% + + {row.avgCsPerMin} + +
+ {row.topChampions.map((champion) => ( + + ))} +
+
+ 아직 집계할 내전 기록이 없습니다. +
+
+
+ ); +} + +export default function CommunityInternalStatsPage() { + const [searchParams] = useSearchParams(); + const championIdParam = Number(searchParams.get('championId')); + const championId = + Number.isFinite(championIdParam) && championIdParam > 0 + ? championIdParam + : undefined; + const filters = { + seasonId: searchParams.get('seasonId') ?? undefined, + championId, + limit: 12, + }; + const communityQuery = useCommunity(DEFAULT_COMMUNITY_ID); + const matchesQuery = useCommunityInternalStatsMatches(filters); + const leaderboardQuery = useCommunityLeaderboard(filters); + const insightsQuery = useTeamInsights(filters); + const { data: ddragon } = useDdragonManifest(); + const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; + const season = + leaderboardQuery.data?.season ?? matchesQuery.data?.pages[0]?.season ?? null; + + if (!DEFAULT_COMMUNITY_ID) { + return ( +
+ `VITE_DEFAULT_COMMUNITY_ID` 설정이 필요합니다. +
+ ); + } + + return ( +
+ + ← 홈으로 + + +
+
+
+

+ Community Records +

+

+ {communityQuery.data?.name ?? '커뮤니티'} 내전 전적 +

+

+ 토너먼트 코드로 수집된 결과를 기준으로 매치, 선수 순위, 팀 인사이트를 보여줍니다. +

+
+
+
+ 시즌 +
+
{season?.label ?? '현재 시즌'}
+
+
+
+ +
+ + + + + +
+ +
+
+

최근 내전

+
+ 블루 승률 {insightsQuery.data?.sideWinRate.blue ?? 0}% · 레드 승률{' '} + {insightsQuery.data?.sideWinRate.red ?? 0}% +
+
+ {matchesQuery.isLoading ? ( +
+ 내전 기록을 불러오는 중... +
+ ) : ( +
+ {matches.map((match) => ( + + ))} + {matches.length === 0 && ( +
+ 아직 수집된 내전 결과가 없습니다. +
+ )} +
+ )} + {matchesQuery.hasNextPage && ( + + )} +
+ +
+
+

선수 순위

+
+ 포지션은 Riot Match의 라인 정보를 기준으로 합니다. +
+
+ +
+
+ ); +} diff --git a/apps/web/src/pages/InternalMatchDetailPage.tsx b/apps/web/src/pages/InternalMatchDetailPage.tsx new file mode 100644 index 00000000..7797796b --- /dev/null +++ b/apps/web/src/pages/InternalMatchDetailPage.tsx @@ -0,0 +1,281 @@ +import { Link, useLocation, useParams } from 'react-router'; +import { useDdragonManifest, useInternalMatchDetail } from '../api/hooks'; +import type { ApiInternalMatchDetailResponse, TeamSide } from '../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../config'; +import { championDisplayName, championIconUrl, itemIconUrl } from '../lib/ddragon'; +import { sideShortLabel, teamIndexColorClasses, teamIndexLabel } from '../lib/league'; +import { LANE_LABELS } from '../lib/riot-history'; + +function formatDateTime(value: string | number) { + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatDuration(seconds: number) { + const minutes = Math.floor(seconds / 60); + const rest = seconds % 60; + return `${minutes}:${String(rest).padStart(2, '0')}`; +} + +function sideLabel(side: TeamSide) { + return sideShortLabel(side); +} + +function sideClass(side: TeamSide) { + return side === 'blue' ? 'text-blue-400 border-blue-500/20' : 'text-red-400 border-red-500/20'; +} + +function ChampionCell({ + championId, + manifest, +}: { + championId: number; + manifest: ReturnType['data']; +}) { + const icon = championIconUrl(manifest, championId); + const name = championDisplayName(manifest, championId) ?? String(championId); + return ( +
+ + {icon ? : null} + + {name} +
+ ); +} + +function ItemStrip({ + items, + trinket, + manifest, +}: { + items: number[]; + trinket: number; + manifest: ReturnType['data']; +}) { + return ( +
+ {[...items, trinket].map((itemId, index) => { + const icon = itemIconUrl(manifest, itemId); + return ( + + {icon ? : null} + + ); + })} +
+ ); +} + +function GamePanel({ + game, + manifest, +}: { + game: ApiInternalMatchDetailResponse['games'][number]; + manifest: ReturnType['data']; +}) { + const location = useLocation(); + const historyBackTo = `${location.pathname}${location.search}${location.hash}`; + + return ( +
+
+
+

+ {game.gameNumber}경기 +

+

+ {formatDateTime(game.gameCreation)} · {formatDuration(game.gameDuration)} ·{' '} + {game.riotMatchId} +

+
+
+ {game.teams.map((team) => ( + + {teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}){' '} + {team.win ? '승' : '패'} + + ))} +
+
+ + {game.teams.map((team) => ( +
+
+ {teamIndexLabel(team.teamIndex)} ({sideLabel(team.side)}) · 바론 {team.objectives.baron} · 드래곤{' '} + {team.objectives.dragon} · 타워 {team.objectives.tower} +
+
+ + + + + + + + + + + + + + + + {team.participants.map((participant) => ( + + + + + + + + + + + + ))} + +
소환사챔피언포지션K/D/ACSGPM킬관여피해비중아이템
+ {participant.userId ? ( + + {participant.summonerName} + + ) : ( + + {participant.summonerName} + + )} + + + + {LANE_LABELS[participant.teamPosition] ?? participant.teamPosition ?? '-'} + + {participant.kills} + / + {participant.deaths} + / + {participant.assists} + + {participant.cs} ({participant.csPerMin}/m) + + {participant.gpm} + + {participant.killParticipation}% + + {participant.damageShare}% + + +
+
+
+ ))} +
+ ); +} + +export default function InternalMatchDetailPage() { + const { cid, matchId } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const detailQuery = useInternalMatchDetail(matchId, communityId); + const { data: ddragon } = useDdragonManifest(); + const detail = detailQuery.data; + + if (detailQuery.isLoading) { + return ( +
+ 내전 상세 기록을 불러오는 중... +
+ ); + } + + if (detailQuery.error || !detail) { + return ( +
+

내전 기록을 찾을 수 없습니다

+ + 내전 전적으로 돌아가기 + +
+ ); + } + + const primarySeries = detail.match.seriesResults[0]; + const teamName = (teamIndex: number) => + teamIndexLabel( + teamIndex, + detail.match.teams.find((team) => team.teamIndex === teamIndex)?.name, + ); + + return ( +
+ + ← 내전 전적 + + +
+
+
+

+ {detail.match.title} +

+

+ {formatDateTime(detail.match.scheduledAt)} · {detail.match.gameCount}전제 +

+
+ {primarySeries && ( +
+
+
{primarySeries.teamAWins}
+
+ {teamName(primarySeries.teamAIndex)} +
+
+
VS
+
+
{primarySeries.teamBWins}
+
+ {teamName(primarySeries.teamBIndex)} +
+
+
+ )} +
+
+ +
+ {detail.games.map((game) => ( + + ))} +
+
+ ); +} diff --git a/apps/web/src/pages/admin/LegacyImportPage.tsx b/apps/web/src/pages/admin/LegacyImportPage.tsx new file mode 100644 index 00000000..3479e51d --- /dev/null +++ b/apps/web/src/pages/admin/LegacyImportPage.tsx @@ -0,0 +1,407 @@ +import { useEffect, useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useCancelLegacyImport, + useLegacyImportJobs, + useLegacyImportMembers, + useMe, + useStartLegacyImport, +} from '../../api/hooks'; +import type { LegacyImportJob, StartLegacyImportRequest } from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const DEFAULT_START = '2024-05-01T00:00:00.000Z'; + +function toInputValue(value: string) { + const date = new Date(value); + const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000); + return local.toISOString().slice(0, 16); +} + +function fromInputValue(value: string) { + return value ? new Date(value).toISOString() : undefined; +} + +function formatDate(value: string | undefined) { + if (!value) return '-'; + return new Intl.DateTimeFormat('ko-KR', { + month: 'long', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function formatEta(seconds: number) { + if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`; + if (seconds < 3600) return `${Math.ceil(seconds / 60)}분`; + return `${Math.ceil(seconds / 3600)}시간`; +} + +function progress(job: LegacyImportJob) { + if (job.totalMembers === 0) return 100; + return Math.round((job.processedMembers / job.totalMembers) * 100); +} + +function JobCard({ + job, + onCancel, + cancelling, +}: { + job: LegacyImportJob; + onCancel: (jobId: string) => void; + cancelling: boolean; +}) { + const running = job.state === 'pending' || job.state === 'running'; + const remaining = Math.max(0, job.totalMembers - job.processedMembers); + const eta = remaining * (job.averageMemberSeconds ?? 60); + + return ( +
+
+
+
+ {job.jobId} +
+
+ + {job.state} + + + {job.processedMembers}/{job.totalMembers}명 · 발견{' '} + {job.totalDiscoveredMatchIds} · import {job.totalImportedMatches} · + 중복 {job.totalSkippedDuplicate} · 에러 {job.totalErrors} + +
+
+ {running && ( + + )} +
+
+
+
+
+ + {formatDate(job.windowStart)} ~ {formatDate(job.windowEnd)} + + {running ? `예상 남은 시간 ${formatEta(eta)}` : formatDate(job.completedAt)} +
+
+ ); +} + +export default function LegacyImportPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [windowStart, setWindowStart] = useState(toInputValue(DEFAULT_START)); + const [windowEnd, setWindowEnd] = useState(''); + const [message, setMessage] = useState(null); + const [overrides, setOverrides] = useState< + Record + >({}); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const membersQuery = useLegacyImportMembers( + { + windowStart: fromInputValue(windowStart), + windowEnd: fromInputValue(windowEnd), + }, + communityId, + canManage, + ); + const jobsQuery = useLegacyImportJobs(communityId, canManage); + const startMutation = useStartLegacyImport(communityId); + const cancelMutation = useCancelLegacyImport(communityId); + const members = membersQuery.data?.members ?? []; + + useEffect(() => { + setOverrides( + Object.fromEntries( + members.map((member) => [ + member.userId, + { + startTime: toInputValue(member.startTime), + endTime: toInputValue(member.endTime), + }, + ]), + ), + ); + }, [members]); + + const manageableMemberships = + meQuery.data?.memberships.filter((membership) => { + const role = membership.user.role; + return Boolean( + membership.community && (role === 'owner' || role === 'admin'), + ); + }) ?? []; + const runningJob = useMemo( + () => + jobsQuery.data?.jobs.find( + (job) => job.state === 'pending' || job.state === 'running', + ), + [jobsQuery.data?.jobs], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['legacy-import-jobs', communityId] }), + queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-matches', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-leaderboard', communityId], + }), + ]); + } + + function handleStart() { + if (!window.confirm('과거 type=tourney 매치 백필을 시작할까요? 야간/유휴 시간대 실행을 권장합니다.')) { + return; + } + const payload: StartLegacyImportRequest = { + windowStart: fromInputValue(windowStart), + windowEnd: fromInputValue(windowEnd), + memberOverrides: members.map((member) => ({ + userId: member.userId, + startTime: fromInputValue(overrides[member.userId]?.startTime ?? ''), + endTime: fromInputValue(overrides[member.userId]?.endTime ?? ''), + })), + }; + startMutation.mutate(payload, { + onSuccess: async (result) => { + await invalidate(); + setMessage( + `백필 작업을 시작했습니다. ${result.totalMembers}명, 예상 ${formatEta(result.etaSeconds)}.`, + ); + }, + onError: (error) => { + setMessage(error instanceof Error ? error.message : '백필 시작 실패'); + }, + }); + } + + if (!communityId) { + return ( +
+

커뮤니티 설정이 필요합니다

+
+ ); + } + + if (meQuery.isPending) { + return ( +
+

권한 확인 중...

+
+ ); + } + + if (!canManage) { + return ( +
+

권한이 필요합니다

+

+ Legacy 백필은 owner/admin만 실행할 수 있습니다. +

+ {manageableMemberships.length > 0 && ( +
+ {manageableMemberships.map((membership) => ( + + {membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동 + + ))} +
+ )} +
+ ); + } + + return ( +
+ + ← 목록으로 + +
+
+

+ Legacy 내전 백필 +

+

+ 커뮤니티 멤버 PUUID로 과거 `type=tourney` 매치를 찾아 내전 기록으로 import합니다. +

+
+ + Legacy 매치 정리 + +
+ +
+

검색 윈도우

+
+ + + +
+ {message && ( +
+ {message} +
+ )} +
+ +
+
+

멤버별 윈도우

+

+ 기본 시작일은 2024-05-01이며, 필요하면 멤버별 시작/종료 시간을 조정할 수 있습니다. + 비활성 멤버는 종료일이 마지막 업데이트 시각으로 잡힙니다. +

+
+
+ + + + + + + + + + + + {members.map((member) => ( + + + + + + + + ))} + {members.length === 0 && ( + + + + )} + +
멤버Riot ID상태시작종료
+ {member.displayName} + + {member.gameName}#{member.tagLine} + + {member.isActivated ? '활성' : '비활성'} + + + setOverrides((current) => ({ + ...current, + [member.userId]: { + ...current[member.userId], + startTime: event.target.value, + endTime: current[member.userId]?.endTime ?? '', + }, + })) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> + + + setOverrides((current) => ({ + ...current, + [member.userId]: { + ...current[member.userId], + startTime: current[member.userId]?.startTime ?? '', + endTime: event.target.value, + }, + })) + } + className="border border-base-content/10 bg-transparent px-2 py-1 text-xs" + /> +
+ Riot 계정이 있는 멤버가 없습니다. +
+
+
+ +
+

작업 이력

+ {(jobsQuery.data?.jobs ?? []).map((job) => ( + + cancelMutation.mutate(jobId, { + onSuccess: invalidate, + }) + } + /> + ))} + {(jobsQuery.data?.jobs ?? []).length === 0 && ( +
+ 아직 실행한 백필 작업이 없습니다. +
+ )} +
+
+ ); +} diff --git a/apps/web/src/pages/admin/LegacyMatchesPage.tsx b/apps/web/src/pages/admin/LegacyMatchesPage.tsx new file mode 100644 index 00000000..bf85177d --- /dev/null +++ b/apps/web/src/pages/admin/LegacyMatchesPage.tsx @@ -0,0 +1,259 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useBulkDeleteLegacyMatches, + useDeleteMatch, + useLegacyMatches, + useMe, + useRebuildLegacyMatches, +} from '../../api/hooks'; +import type { LegacyMatchListItem } from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; +import { teamIndexLabel } from '../../lib/league'; + +function formatDate(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function resultLabel(match: LegacyMatchListItem) { + if (!match.winnerTeamIndex) return '-'; + const winnerScore = + match.winnerTeamIndex === match.teamAIndex + ? match.teamAWins + : match.teamBWins; + const loserScore = + match.winnerTeamIndex === match.teamAIndex + ? match.teamBWins + : match.teamAWins; + return `${teamIndexLabel(match.winnerTeamIndex)} ${winnerScore}:${loserScore}`; +} + +export default function LegacyMatchesPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const [selected, setSelected] = useState>({}); + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const matchesQuery = useLegacyMatches(communityId, canManage); + const deleteMutation = useDeleteMatch(communityId); + const bulkDeleteMutation = useBulkDeleteLegacyMatches(communityId); + const rebuildMutation = useRebuildLegacyMatches(communityId); + const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? []; + const selectedIds = useMemo( + () => Object.entries(selected).filter(([, value]) => value).map(([id]) => id), + [selected], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }), + queryClient.invalidateQueries({ queryKey: ['matches', communityId] }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-matches', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-leaderboard', communityId], + }), + queryClient.invalidateQueries({ + queryKey: ['community-internal-stats-team-insights', communityId], + }), + ]); + } + + if (!communityId) { + return ( +
+

커뮤니티 설정이 필요합니다

+
+ ); + } + + if (meQuery.isPending) { + return ( +
+

권한 확인 중...

+
+ ); + } + + if (!canManage) { + return ( +
+

권한이 필요합니다

+

+ Legacy 매치 정리는 owner/admin만 사용할 수 있습니다. +

+
+ ); + } + + return ( +
+ + ← Legacy 백필 + +
+
+

+ Legacy 매치 정리 +

+

+ 백필로 들어온 매치를 확인하고 외부 토너먼트 기록을 삭제할 수 있습니다. +

+
+
+ + +
+
+ + {rebuildMutation.data && ( +
+ 재구성 완료: {rebuildMutation.data.scanned}개 확인 ·{' '} + {rebuildMutation.data.rebuilt}개 갱신 · 제목 정리{' '} + {rebuildMutation.data.normalizedTitles}개 +
+ )} + +
+
+ + + + + + + + + + + + + + + {matches.map((match) => ( + + + + + + + + + + + ))} + {matches.length === 0 && ( + + + + )} + +
+ 0 && selectedIds.length === matches.length} + onChange={(event) => { + const checked = event.target.checked; + setSelected( + Object.fromEntries(matches.map((match) => [match.matchId, checked])), + ); + }} + /> + 시간매치Riot matchId우리 멤버외부결과작업
+ + setSelected((current) => ({ + ...current, + [match.matchId]: event.target.checked, + })) + } + /> + + {formatDate(match.scheduledAt)} + + + {match.title} + + + {match.riotMatchId ?? '-'} + {match.memberCount}명{match.externalCount}명{resultLabel(match)} + +
+ Legacy import 매치가 없습니다. +
+
+
+ + {matchesQuery.hasNextPage && ( + + )} +
+ ); +} diff --git a/apps/web/src/pages/admin/MatchAdminPage.tsx b/apps/web/src/pages/admin/MatchAdminPage.tsx new file mode 100644 index 00000000..ac094df7 --- /dev/null +++ b/apps/web/src/pages/admin/MatchAdminPage.tsx @@ -0,0 +1,451 @@ +import { useMemo, useState } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { Link, useParams } from 'react-router'; +import { + useCreateMatch, + useDeleteMatch, + useMatches, + useMe, + useUpdateMatch, +} from '../../api/hooks'; +import type { + ApiMatch, + ApiMatchScheduleItem, + MatchGameMode, + MatchMutationRequest, +} from '../../api/types'; +import { DEFAULT_COMMUNITY_ID } from '../../config'; + +const DEFAULT_FORM: MatchMutationRequest = { + title: '', + description: '', + mapId: 11, + scheduledAt: toInputValue(new Date(Date.now() + 24 * 60 * 60 * 1000)), + maxParticipants: 10, + gameCount: 3, + gameMode: 'pair', + prizes: [], + notices: [], + schedule: [], +}; + +const GAME_MODE_LABEL: Record = { + pair: '페어', + bracket: '브래킷', + 'round-robin': '라운드 로빈', +}; + +function RequiredBadge() { + return ( + + 필수 + + ); +} + +function toInputValue(value: string | Date) { + const date = value instanceof Date ? value : new Date(value); + const offset = date.getTimezoneOffset(); + return new Date(date.getTime() - offset * 60_000).toISOString().slice(0, 16); +} + +function toIsoFromInput(value: string) { + return new Date(value).toISOString(); +} + +function formatDate(value: string) { + return new Intl.DateTimeFormat('ko-KR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(value)); +} + +function parseLines(value: string) { + return value + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter(Boolean); +} + +function parseSchedule(value: string): ApiMatchScheduleItem[] { + return parseLines(value).map((line) => { + const [time, ...labelParts] = line.split('|').map((part) => part.trim()); + return { + time: time || '00:00', + label: labelParts.join('|') || '일정', + }; + }); +} + +function scheduleToText(schedule: ApiMatchScheduleItem[] = []) { + return schedule.map((item) => `${item.time}|${item.label}`).join('\n'); +} + +function makeForm(match?: ApiMatch): MatchMutationRequest & { + prizesText: string; + noticesText: string; + scheduleText: string; +} { + if (!match) { + return { + ...DEFAULT_FORM, + prizesText: '', + noticesText: '', + scheduleText: '', + }; + } + + return { + title: match.title, + description: match.description, + mapId: match.mapId, + scheduledAt: toInputValue(match.scheduledAt), + maxParticipants: match.maxParticipants, + gameCount: match.gameCount, + gameMode: match.gameMode ?? 'pair', + prizes: match.prizes, + notices: match.notices, + schedule: match.schedule, + prizesText: match.prizes.join('\n'), + noticesText: match.notices.join('\n'), + scheduleText: scheduleToText(match.schedule), + }; +} + +export default function MatchAdminPage() { + const { cid } = useParams(); + const communityId = cid ?? DEFAULT_COMMUNITY_ID; + const queryClient = useQueryClient(); + const meQuery = useMe(); + const matchesQuery = useMatches({ limit: 200 }, communityId); + const createMutation = useCreateMatch(communityId); + const updateMutation = useUpdateMatch(communityId); + const deleteMutation = useDeleteMatch(communityId); + const [editing, setEditing] = useState(null); + const [showForm, setShowForm] = useState(false); + const [form, setForm] = useState(makeForm()); + const [message, setMessage] = useState(null); + + const currentUser = + meQuery.data?.memberships.find( + (membership) => membership.community?._id === communityId, + )?.user ?? null; + const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin'; + const matches = useMemo( + () => [...(matchesQuery.data ?? [])].sort((a, b) => new Date(b.scheduledAt).getTime() - new Date(a.scheduledAt).getTime()), + [matchesQuery.data], + ); + + async function invalidate() { + await Promise.all([ + queryClient.invalidateQueries({ queryKey: ['matches', communityId] }), + queryClient.invalidateQueries({ queryKey: ['match', communityId] }), + ]); + } + + function openCreate() { + setEditing(null); + setForm(makeForm()); + setShowForm(true); + setMessage(null); + } + + function openEdit(match: ApiMatch) { + setEditing(match); + setForm(makeForm(match)); + setShowForm(true); + setMessage(null); + } + + function buildPayload(): MatchMutationRequest { + return { + title: form.title.trim(), + description: form.description?.trim() ?? '', + mapId: Number(form.mapId ?? 11), + scheduledAt: toIsoFromInput(form.scheduledAt), + maxParticipants: Number(form.maxParticipants ?? 10), + gameCount: Number(form.gameCount ?? 3), + gameMode: form.gameMode, + prizes: parseLines(form.prizesText), + notices: parseLines(form.noticesText), + schedule: parseSchedule(form.scheduleText), + }; + } + + function submit() { + setMessage(null); + if (!form.title.trim()) { + setMessage('제목을 입력해주세요.'); + return; + } + if (!form.scheduledAt) { + setMessage('시작 시간을 입력해주세요.'); + return; + } + + const payload = buildPayload(); + + const callbacks = { + onSuccess: async () => { + await invalidate(); + setShowForm(false); + setEditing(null); + setMessage(editing ? '내전을 수정했습니다.' : '내전을 만들었습니다.'); + }, + onError: (error: Error) => setMessage(error.message), + }; + + if (editing) { + updateMutation.mutate({ matchId: editing._id, body: payload }, callbacks); + return; + } + createMutation.mutate(payload, callbacks); + } + + if (!canManage && !meQuery.isPending) { + return ( +
+

권한이 필요합니다

+

+ 내전 관리는 owner/admin만 사용할 수 있습니다. +

+
+ ); + } + + return ( +
+ + ← 목록으로 + +
+
+

내전 관리

+

+ 내전 생성, 모집 정원, 게임 모드와 공지 내용을 관리합니다. +

+
+ +
+ + {message && ( +
+ {message} +
+ )} + + {showForm && ( +
+
+

+ {editing ? '내전 수정' : '새 내전'} +

+ +
+ +
+ +