import { Types } from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { MatchStats } from '../global/database/schema'; import { MatchStatsRepository } from './match-stats.repository'; describe('MatchStatsRepository', () => { it.each([null, { _id: new Types.ObjectId() }])( 'checks persisted source identity and every build version without loading payloads (%j)', async (stored) => { const exists = jest.fn(() => ({ exec: async () => stored })); const connection = { getModel: jest.fn().mockResolvedValue({ exists }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); const source = { matchId: new Types.ObjectId(), sourceCompetitionId: new Types.ObjectId(), sourceRevision: 12, projectorVersion: 3, builderVersion: 10, }; await expect( repository.hasCurrentCompetitionFragment(source), ).resolves.toBe(Boolean(stored)); expect(exists).toHaveBeenCalledWith({ matchId: source.matchId, sourceCompetitionId: source.sourceCompetitionId, sourceRevision: { $gte: 12 }, projectorVersion: { $gte: 3 }, builderVersion: { $gte: 10 }, }); }, ); it('does not let a legacy upsert overwrite a Competition-backed fragment', async () => { const fragment = { ...statsFragment(12), sourceCompetitionId: undefined, sourceRevision: undefined, projectorVersion: undefined, }; const updateOne = jest .fn() .mockReturnValueOnce({ exec: jest.fn().mockResolvedValue({ matchedCount: 0 }), }) .mockReturnValueOnce({ exec: jest .fn() .mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }), }); const connection = { getModel: jest.fn().mockResolvedValue({ updateOne }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); await repository.upsert(fragment); expect(updateOne).toHaveBeenNthCalledWith( 1, { matchId: fragment.matchId, sourceCompetitionId: { $exists: false }, }, { $set: fragment }, { upsert: false }, ); expect(updateOne).toHaveBeenNthCalledWith( 2, { matchId: fragment.matchId }, { $setOnInsert: fragment }, { upsert: true }, ); }); it('only updates a Competition projection when its revision is not stale', async () => { const updateOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ matchedCount: 1, upsertedCount: 0 }), }); const connection = { getModel: jest.fn().mockResolvedValue({ updateOne }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); const fragment = statsFragment(12); await repository.upsert(fragment); expect(updateOne).toHaveBeenCalledWith( { matchId: fragment.matchId, $or: [ { sourceCompetitionId: { $exists: false } }, { sourceCompetitionId: fragment.sourceCompetitionId }, ], $and: [ { $or: [ { sourceRevision: { $exists: false } }, { sourceRevision: { $lte: 12 } }, ], }, ], }, { $set: fragment }, { upsert: false }, ); }); it('converges concurrent initial upserts to the highest Competition revision', async () => { const older = statsFragment(12); const newer = { ...statsFragment(13), matchId: older.matchId, sourceCompetitionId: older.sourceCompetitionId, }; let stored: ReturnType | undefined; let initialGuardCount = 0; let releaseInitialGuards!: () => void; const initialGuardsReady = new Promise((resolve) => { releaseInitialGuards = resolve; }); let releaseOlderInsert!: () => void; const olderInserted = new Promise((resolve) => { releaseOlderInsert = resolve; }); const updateOne = jest.fn( ( _filter: Record, update: { $set?: ReturnType; $setOnInsert?: ReturnType; }, ) => ({ exec: async () => { const fragment = update.$set ?? update.$setOnInsert!; if (update.$set && !stored && initialGuardCount < 2) { initialGuardCount += 1; if (initialGuardCount === 2) releaseInitialGuards(); await initialGuardsReady; return { matchedCount: 0, upsertedCount: 0 }; } if (update.$setOnInsert) { if (fragment.sourceRevision === 13) await olderInserted; const existed = stored !== undefined; if (!stored) stored = fragment; if (fragment.sourceRevision === 12) releaseOlderInsert(); return { matchedCount: existed ? 1 : 0, upsertedCount: existed ? 0 : 1, }; } if ( stored && stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) && stored.sourceRevision <= fragment.sourceRevision ) { stored = fragment; return { matchedCount: 1, upsertedCount: 0 }; } return { matchedCount: 0, upsertedCount: 0 }; }, }), ); const connection = { getModel: jest.fn().mockResolvedValue({ updateOne }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); await Promise.all([repository.upsert(older), repository.upsert(newer)]); expect(stored?.sourceRevision).toBe(13); }); it('guards a zero-game delete so an observed revision cannot remove newer stats', async () => { const matchId = new Types.ObjectId(); const sourceCompetitionId = new Types.ObjectId(); const deleteOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ deletedCount: 0 }), }); const connection = { getModel: jest.fn().mockResolvedValue({ deleteOne }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); await repository.deleteByMatch(matchId, { sourceCompetitionId, sourceRevision: 12, }); expect(deleteOne).toHaveBeenCalledWith({ matchId, $or: [ { sourceCompetitionId: { $exists: false } }, { sourceCompetitionId, $or: [ { sourceRevision: { $exists: false } }, { sourceRevision: { $lte: 12 } }, ], }, ], }); }); it('deletes only non-Competition stats during legacy source cleanup', async () => { const matchId = new Types.ObjectId(); const deleteOne = jest.fn().mockReturnValue({ exec: jest.fn().mockResolvedValue({ deletedCount: 0 }), }); const connection = { getModel: jest.fn().mockResolvedValue({ deleteOne }), } as unknown as ConnectionService; const repository = new MatchStatsRepository(connection); await repository.deleteLegacyByMatch(matchId); expect(deleteOne).toHaveBeenCalledWith({ matchId, sourceCompetitionId: { $exists: false }, }); }); }); function statsFragment(sourceRevision: number) { return { matchId: new Types.ObjectId(), communityId: new Types.ObjectId(), sourceCompetitionId: new Types.ObjectId(), sourceRevision, projectorVersion: 3, scheduledAt: new Date(), gameCreationMin: 1, gameCreationMax: 2, userIds: [], championIds: [], matchCard: {}, records: [], gameDetails: [], builtAt: new Date(), builderVersion: 9, } satisfies Omit; }