223 lines
7.5 KiB
TypeScript
223 lines
7.5 KiB
TypeScript
import mongoose from 'mongoose';
|
|
import { DistributedLockService } from '../global/redis/distributed-lock.service';
|
|
import { RedisService } from '../global/redis/redis.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<void>;
|
|
};
|
|
|
|
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 redis = {
|
|
getString: jest.fn().mockResolvedValue(null),
|
|
delete: jest.fn().mockResolvedValue(1),
|
|
raw: jest.fn().mockReturnValue(rawClient),
|
|
} as unknown as jest.Mocked<RedisService> & { raw: jest.Mock };
|
|
const distributedLockService = {
|
|
acquireLock: jest.fn().mockResolvedValue({
|
|
lockKey: 'distributed-lock:riot-background-refresh:leader',
|
|
lockOwnershipToken: 'lock-owner',
|
|
lockExpirationDurationMilliseconds: 90_000,
|
|
}),
|
|
extendLockIfOwned: jest.fn().mockResolvedValue(true),
|
|
releaseLockIfOwned: jest.fn().mockResolvedValue(true),
|
|
} as unknown as jest.Mocked<DistributedLockService>;
|
|
const rateLimiter = {
|
|
isRefreshWindowOpen: jest.fn().mockResolvedValue(true),
|
|
} as unknown as jest.Mocked<RiotRateLimiterService>;
|
|
const enrichmentService = {
|
|
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
|
|
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
|
|
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
|
|
const staleAccountRepository = {
|
|
findStaleAccounts: jest.fn().mockResolvedValue([]),
|
|
} as unknown as jest.Mocked<StaleAccountRepository>;
|
|
const scheduler = new BackgroundRefreshScheduler(
|
|
redis,
|
|
distributedLockService,
|
|
rateLimiter,
|
|
enrichmentService,
|
|
staleAccountRepository,
|
|
) as SchedulerInternals;
|
|
|
|
return {
|
|
scheduler,
|
|
redis,
|
|
distributedLockService,
|
|
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('uses the dawn refresh gate ratio inside the KST background window', async () => {
|
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
|
const { scheduler, rateLimiter } = makeScheduler();
|
|
|
|
await scheduler.tick();
|
|
|
|
expect(rateLimiter.isRefreshWindowOpen).toHaveBeenCalledWith(0.8);
|
|
});
|
|
|
|
it('uses the opportunistic refresh gate ratio outside the KST background window', async () => {
|
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T17:59:59.000Z'));
|
|
const { scheduler, rateLimiter, staleAccountRepository } = makeScheduler();
|
|
|
|
await scheduler.tick();
|
|
|
|
expect(rateLimiter.isRefreshWindowOpen).toHaveBeenCalledWith(0.5);
|
|
expect(staleAccountRepository.findStaleAccounts).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it('does not query stale accounts when the refresh gate is closed', async () => {
|
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
|
const { scheduler, rateLimiter, staleAccountRepository } = makeScheduler();
|
|
rateLimiter.isRefreshWindowOpen.mockResolvedValue(false);
|
|
|
|
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, distributedLockService, staleAccountRepository } =
|
|
makeScheduler();
|
|
distributedLockService.acquireLock.mockResolvedValueOnce(null);
|
|
|
|
await scheduler.tick();
|
|
|
|
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('marks and enriches each stale candidate without background precharge', async () => {
|
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
|
const { scheduler, enrichmentService, staleAccountRepository } =
|
|
makeScheduler();
|
|
const candidates = [candidate('puuid-1'), candidate('puuid-2')];
|
|
staleAccountRepository.findStaleAccounts.mockResolvedValue(candidates);
|
|
|
|
await scheduler.tick();
|
|
|
|
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('stops the candidate loop when the refresh gate closes mid-tick', async () => {
|
|
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
|
|
const {
|
|
scheduler,
|
|
rateLimiter,
|
|
enrichmentService,
|
|
staleAccountRepository,
|
|
} = makeScheduler();
|
|
staleAccountRepository.findStaleAccounts.mockResolvedValue([
|
|
candidate('puuid-1'),
|
|
candidate('puuid-2'),
|
|
]);
|
|
rateLimiter.isRefreshWindowOpen
|
|
.mockResolvedValueOnce(true)
|
|
.mockResolvedValueOnce(true)
|
|
.mockResolvedValueOnce(false);
|
|
|
|
await scheduler.tick();
|
|
|
|
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
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, redis, enrichmentService, staleAccountRepository } =
|
|
makeScheduler();
|
|
staleAccountRepository.findStaleAccounts.mockResolvedValue([
|
|
candidate('skip-me'),
|
|
]);
|
|
redis.getString.mockImplementation(async (key: string) => {
|
|
if (key.includes('riot:bg:fail:skip-me')) return '3';
|
|
return null;
|
|
});
|
|
|
|
await scheduler.tick();
|
|
|
|
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
|
|
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
|
|
});
|
|
});
|