import { Injectable } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchStats, MatchStatsDocument } from '../global/database/schema'; export type MatchStatsUserRecordFragment = Pick< MatchStats, 'matchId' | 'records' | 'builderVersion' >; export type MatchStatsDetailFragment = Pick< MatchStats, 'matchId' | 'gameDetails' >; export interface MatchStatsDeleteGuard { sourceCompetitionId: mongoose.Types.ObjectId; sourceRevision: number; } @Injectable() export class MatchStatsRepository { constructor(private readonly connectionService: ConnectionService) {} public async hasCurrentCompetitionFragment(params: { matchId: mongoose.Types.ObjectId; sourceCompetitionId: mongoose.Types.ObjectId; sourceRevision: number; projectorVersion: number; builderVersion: number; }): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); return Boolean( await MatchStatsModel.exists({ matchId: params.matchId, sourceCompetitionId: params.sourceCompetitionId, sourceRevision: { $gte: params.sourceRevision }, projectorVersion: { $gte: params.projectorVersion }, builderVersion: { $gte: params.builderVersion }, }).exec(), ); } public async upsert( fragment: Omit, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); if ( !fragment.sourceCompetitionId || fragment.sourceRevision === undefined ) { const updated = await MatchStatsModel.updateOne( { matchId: fragment.matchId, sourceCompetitionId: { $exists: false }, }, { $set: fragment }, { upsert: false }, ).exec(); if (updated.matchedCount > 0) return; // A legacy builder must never overwrite a Competition-backed fragment // that appeared while the legacy source was being read. try { await MatchStatsModel.updateOne( { matchId: fragment.matchId }, { $setOnInsert: fragment }, { upsert: true }, ).exec(); } catch (error) { if (!isDuplicateKeyError(error)) throw error; } return; } const revisionGuard = competitionRevisionGuard(fragment); const updated = await MatchStatsModel.updateOne( revisionGuard, { $set: fragment }, { upsert: false }, ).exec(); if (updated.matchedCount > 0) return; // If no read model exists, insert it. If a newer revision won the race, // this filter matches it and $setOnInsert intentionally changes nothing. try { await MatchStatsModel.updateOne( { matchId: fragment.matchId }, { $setOnInsert: fragment }, { upsert: true }, ).exec(); } catch (error) { if (!isDuplicateKeyError(error)) throw error; } // A lower revision can win the initial insert between the guarded miss and // the upsert. Re-run the monotonic CAS so every concurrent builder converges // to the highest source revision; a newer winner simply does not match. await MatchStatsModel.updateOne( revisionGuard, { $set: fragment }, { upsert: false }, ).exec(); } public async deleteByMatch( matchId: mongoose.Types.ObjectId, guard?: MatchStatsDeleteGuard, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); await MatchStatsModel.deleteOne( guard ? { matchId, $or: [ { sourceCompetitionId: { $exists: false } }, { sourceCompetitionId: guard.sourceCompetitionId, $or: [ { sourceRevision: { $exists: false } }, { sourceRevision: { $lte: guard.sourceRevision } }, ], }, ], } : { 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 deleteLegacyByMatch( matchId: mongoose.Types.ObjectId, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); await MatchStatsModel.deleteOne({ matchId, sourceCompetitionId: { $exists: false }, }).exec(); } public async findByMatch( matchId: mongoose.Types.ObjectId, ): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); return MatchStatsModel.findOne({ matchId }).exec(); } public async findByRiotMatchIds(riotMatchIds: string[]) { const MatchStatsModel = await this.connectionService.getModel('matchStats'); return MatchStatsModel.find({ 'gameDetails.riotMatchId': { $in: riotMatchIds }, }) .select({ matchId: 1, communityId: 1, 'gameDetails.riotMatchId': 1, 'gameDetails.rawAvailable': 1, }) .lean() .exec(); } public async findMatchPage(params: { communityId: mongoose.Types.ObjectId; from?: number; to?: number; query?: string; format?: 'pair' | 'tournament'; playerId?: string; championId?: number; cursor?: number; cursorMatchId?: string; limit: number; }) { const model = await this.connectionService.getModel('matchStats'); const filter: Record = { communityId: params.communityId }; const conditions: Array> = []; const gameCreation = { ...(params.from === undefined ? {} : { $gte: params.from }), ...(params.to === undefined ? {} : { $lte: params.to }), }; if (Object.keys(gameCreation).length > 0) { conditions.push({ $or: [ { gameDetails: { $elemMatch: { gameCreation } } }, { 'gameDetails.0': { $exists: false }, gameCreationMin: gameCreation, }, ], }); } if (params.from !== undefined) filter.gameCreationMax = { $gte: params.from }; if (params.to !== undefined) filter.gameCreationMin = { $lte: params.to }; if (params.championId) { filter.records = { $elemMatch: { championId: params.championId, ...(Object.keys(gameCreation).length > 0 ? { gameCreation } : {}), }, }; } if (params.query) { filter['matchCard.title'] = { $regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'), $options: 'i', }; } if (params.format) { filter['matchCard.teams.1'] = { $exists: true }; filter['matchCard.teams.2'] = { $exists: params.format === 'tournament' }; } if (params.playerId) { filter['matchCard.teams.members.userId'] = params.playerId; } if (params.cursor !== undefined) { const cursor = new Date(params.cursor); if (params.cursorMatchId) { conditions.push({ $or: [ { scheduledAt: { $lt: cursor } }, { scheduledAt: cursor, matchId: { $lt: new mongoose.Types.ObjectId(params.cursorMatchId), }, }, ], }); } else { filter.scheduledAt = { $lt: cursor }; } } if (conditions.length > 0) filter.$and = conditions; return model .find(filter) .select({ matchId: 1, scheduledAt: 1, matchCard: 1, sourceCompetitionId: 1, sourceRevision: 1, 'gameDetails.gameNumber': 1, 'gameDetails.gameCreation': 1, }) .sort({ scheduledAt: -1, matchId: -1 }) .limit(params.limit) .lean() .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 findSeasonStats(params: { communityId: mongoose.Types.ObjectId; from?: number; to?: number; }) { const model = await this.connectionService.getModel('matchStats'); return model .find({ communityId: params.communityId, ...(params.from === undefined ? {} : { gameCreationMax: { $gte: params.from } }), ...(params.to === undefined ? {} : { gameCreationMin: { $lte: params.to } }), }) .select({ _id: 0, 'records.userId': 1, 'records.summonerName': 1, 'records.tagLine': 1, 'records.profileIconId': 1, 'records.gameCreation': 1, 'records.gameNumber': 1, 'records.matchId': 1, 'records.championId': 1, 'records.teamPosition': 1, 'records.win': 1, 'records.kills': 1, 'records.deaths': 1, 'records.assists': 1, 'records.gpm': 1, 'records.csPerMin': 1, 'records.killParticipation': 1, 'records.visionScore': 1, 'records.damageShare': 1, 'gameDetails.gameCreation': 1, 'gameDetails.gameNumber': 1, 'gameDetails.winnerSide': 1, }) .sort({ scheduledAt: -1 }) .lean() .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 = this.buildUserFilter(params); return MatchStatsModel.find(filter).sort({ scheduledAt: -1 }).exec(); } public async findUserRecordFragments(params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; fromGameCreation?: number; toGameCreation?: number; limit?: number; }): Promise { const MatchStatsModel = await this.connectionService.getModel('matchStats'); const filter = this.buildUserFilter(params); // User history only needs records for summaries/page selection; gameDetails // are much larger and are fetched separately for the visible page. return MatchStatsModel.find(filter) .sort({ scheduledAt: -1 }) .limit(params.limit ?? 300) .select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 }) .lean() .exec(); } public async findDetailsByMatches(params: { communityId: mongoose.Types.ObjectId; matchIds: mongoose.Types.ObjectId[]; }): Promise { if (params.matchIds.length === 0) return []; const MatchStatsModel = await this.connectionService.getModel('matchStats'); return MatchStatsModel.find({ communityId: params.communityId, matchId: { $in: params.matchIds }, }) .select({ _id: 0, matchId: 1, gameDetails: 1 }) .lean() .exec(); } private buildUserFilter(params: { communityId: mongoose.Types.ObjectId; userId: mongoose.Types.ObjectId; fromGameCreation?: number; toGameCreation?: number; }): Record { 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 filter; } } function competitionRevisionGuard( fragment: Omit, ) { return { matchId: fragment.matchId, $or: [ { sourceCompetitionId: { $exists: false } }, { sourceCompetitionId: fragment.sourceCompetitionId }, ], $and: [ { $or: [ { sourceRevision: { $exists: false } }, { sourceRevision: { $lte: fragment.sourceRevision } }, ], }, ], }; } function isDuplicateKeyError(error: unknown): boolean { return ( typeof error === 'object' && error !== null && 'code' in error && error.code === 11_000 ); }