feat(api): refresh Riot ID during background updates

This commit is contained in:
dahyeon committed 2026-07-25 09:08:29 -07:00
1 parent 9cd5850d43
commit e3f39fd8b8
6 files changed
+222 -24

No files matched your search

@@ -53,6 +53,7 @@ function makeScheduler() {
} as unknown as jest.Mocked<RiotRateLimiterService>;
const enrichmentService = {
markRefreshRequested: jest.fn().mockResolvedValue(undefined),
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
const staleAccountRepository = {
@@ -134,7 +135,7 @@ describe('BackgroundRefreshScheduler', () => {
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled();
});
it('marks and enriches each stale candidate without background precharge', async () => {
it('marks, refreshes identity, 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();
@@ -149,11 +150,21 @@ describe('BackgroundRefreshScheduler', () => {
candidates[0].userId,
'puuid-1',
);
expect(enrichmentService.refreshRiotIdentity).toHaveBeenNthCalledWith(1, {
userId: candidates[0].userId,
puuid: 'puuid-1',
});
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(2);
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
userId: candidates[1].userId,
puuid: 'puuid-2',
options: { force: false },
});
expect(
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
).toBeLessThan(
enrichmentService.enrichRiotAccount.mock.invocationCallOrder[0],
);
});
it('stops the candidate loop when the refresh gate closes mid-tick', async () => {
@@ -202,6 +213,27 @@ describe('BackgroundRefreshScheduler', () => {
]);
});
it('continues statistics enrichment without a failure counter when identity refresh fails', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, rawClient, enrichmentService, staleAccountRepository } =
makeScheduler();
const account = candidate('puuid-1');
staleAccountRepository.findStaleAccounts.mockResolvedValue([account]);
enrichmentService.refreshRiotIdentity.mockResolvedValueOnce('failed');
await scheduler.tick();
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
userId: account.userId,
puuid: 'puuid-1',
});
expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledTimes(1);
expect(rawClient.sendCommand).not.toHaveBeenCalledWith([
'INCR',
'riot:bg:fail:puuid-1',
]);
});
it('skips candidates already in failure backoff', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, redis, enrichmentService, staleAccountRepository } =
@@ -217,6 +249,7 @@ describe('BackgroundRefreshScheduler', () => {
await scheduler.tick();
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
expect(enrichmentService.refreshRiotIdentity).not.toHaveBeenCalled();
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
});
});
@@ -15,7 +15,10 @@ import {
} from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service';
import { isInKstBackgroundWindow } from './kst-window.util';
import { StaleAccountRepository } from './stale-account.repository';
import {
type StaleAccountCandidate,
StaleAccountRepository,
} from './stale-account.repository';
const TICK_INTERVAL_MS = 60_000;
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
@@ -133,6 +136,7 @@ export class BackgroundRefreshScheduler
candidate.userId,
candidate.puuid,
);
await this.refreshRiotIdentity(candidate);
try {
const result = await this.enrichmentService.enrichRiotAccount({
@@ -165,6 +169,28 @@ export class BackgroundRefreshScheduler
);
}
private async refreshRiotIdentity(
candidate: StaleAccountCandidate,
): Promise<void> {
try {
const result = await this.enrichmentService.refreshRiotIdentity({
userId: candidate.userId,
puuid: candidate.puuid,
});
if (result !== 'failed') return;
this.logger.warn(
`Background Riot identity refresh failed for ${candidate.puuid}.`,
);
} catch (err) {
this.logger.warn(
`Background Riot identity refresh failed for ${candidate.puuid}: ${
err instanceof Error ? err.message : String(err)
}`,
);
}
}
private currentRefreshGatePolicy(): RefreshGatePolicy {
const isDawn = isInKstBackgroundWindow();
return {
@@ -12,6 +12,7 @@ import { RiotLeagueService } from './riot-league.service';
import { RiotRecentMatchesService } from './riot-recent-matches.service';
import { RiotRecentStatsService } from './riot-recent-stats.service';
import { RiotSummonerService } from './riot-summoner.service';
import { type RiotPlatformRoute, type RiotRegionalRoute } from './riot.types';
interface FakeAccount {
puuid: string;
@@ -86,6 +87,11 @@ function makeUser(account: FakeAccount) {
function makeService(overrides?: {
user?: any;
community?: {
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
};
account?: Partial<RiotAccountService>;
summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>;
@@ -102,10 +108,12 @@ function makeService(overrides?: {
select: () => ({
lean: () => ({
exec: () =>
Promise.resolve({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
Promise.resolve(
overrides?.community ?? {
riotPlatform: 'kr',
riotRegion: 'asia',
},
),
}),
}),
});
@@ -199,7 +207,7 @@ describe('RiotAccountEnrichmentService', () => {
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
region: 'asia',
region: 'europe',
});
expect(result).toBe('updated');
@@ -207,7 +215,7 @@ describe('RiotAccountEnrichmentService', () => {
expect(account.tagLine).toBe('KR1');
expect(user.save).toHaveBeenCalledTimes(1);
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'asia',
region: 'europe',
});
});
@@ -236,6 +244,61 @@ describe('RiotAccountEnrichmentService', () => {
expect(user.save).toHaveBeenCalledTimes(1);
});
it('resolves the Riot region from the user community when none is provided', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
community: {
riotPlatform: 'na1',
riotRegion: 'americas',
},
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'NA1',
}),
},
});
await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'americas',
});
});
it('falls back to the default Riot region when the community has no region', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
community: {
riotPlatform: 'kr',
},
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'KR1',
}),
},
});
await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'asia',
});
});
it('does not save when the Riot ID has not changed', async () => {
const account = makeAccount();
const user = makeUser(account);
@@ -103,8 +103,19 @@ export class RiotAccountEnrichmentService {
);
if (!account) return 'failed';
let region = params.region;
if (!region) {
const CommunityModel =
await this.connectionService.getModel('community');
const community = await CommunityModel.findById(user.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
region = community?.riotRegion ?? DEFAULT_REGION;
}
const identity = await this.accountService.getByPuuid(params.puuid, {
region: params.region ?? DEFAULT_REGION,
region,
});
if (
identity.puuid !== params.puuid ||