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() { 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 scheduler = new BackgroundRefreshScheduler( garnet, rateLimiter, enrichmentService, staleAccountRepository, ) as SchedulerInternals; return { scheduler, garnet, rawClient, rateLimiter, enrichmentService, staleAccountRepository, }; } describe('BackgroundRefreshScheduler', () => { afterEach(() => { jest.useRealTimers(); jest.restoreAllMocks(); }); it('schedules ticks without requiring RIOT_BG_REFRESH_ENABLED', () => { jest.useFakeTimers(); const setIntervalSpy = jest.spyOn(global, 'setInterval'); const { scheduler } = makeScheduler(); scheduler.onModuleInit(); expect(setIntervalSpy).toHaveBeenCalledTimes(2); scheduler.onModuleDestroy(); }); 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(); }); });