feat(api): refresh Riot ID during background updates #10

Merged
dahyeon merged 1 commits from agent/refresh-riot-id-by-puuid into main 2026-07-25 16:13:19 +00:00
6 changed files with 222 additions and 24 deletions

No files matched your search

@@ -53,6 +53,7 @@ function makeScheduler() {
} as unknown as jest.Mocked<RiotRateLimiterService>; } as unknown as jest.Mocked<RiotRateLimiterService>;
const enrichmentService = { const enrichmentService = {
markRefreshRequested: jest.fn().mockResolvedValue(undefined), markRefreshRequested: jest.fn().mockResolvedValue(undefined),
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
enrichRiotAccount: jest.fn().mockResolvedValue(successResult()), enrichRiotAccount: jest.fn().mockResolvedValue(successResult()),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>; } as unknown as jest.Mocked<RiotAccountEnrichmentService>;
const staleAccountRepository = { const staleAccountRepository = {
@@ -134,7 +135,7 @@ describe('BackgroundRefreshScheduler', () => {
expect(staleAccountRepository.findStaleAccounts).not.toHaveBeenCalled(); 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')); jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, enrichmentService, staleAccountRepository } = const { scheduler, enrichmentService, staleAccountRepository } =
makeScheduler(); makeScheduler();
@@ -149,11 +150,21 @@ describe('BackgroundRefreshScheduler', () => {
candidates[0].userId, candidates[0].userId,
'puuid-1', 'puuid-1',
); );
expect(enrichmentService.refreshRiotIdentity).toHaveBeenNthCalledWith(1, {
userId: candidates[0].userId,
puuid: 'puuid-1',
});
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(2);
expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, { expect(enrichmentService.enrichRiotAccount).toHaveBeenNthCalledWith(2, {
userId: candidates[1].userId, userId: candidates[1].userId,
puuid: 'puuid-2', puuid: 'puuid-2',
options: { force: false }, 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 () => { 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 () => { it('skips candidates already in failure backoff', async () => {
jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z')); jest.useFakeTimers().setSystemTime(new Date('2026-05-02T18:00:00.000Z'));
const { scheduler, redis, enrichmentService, staleAccountRepository } = const { scheduler, redis, enrichmentService, staleAccountRepository } =
@@ -217,6 +249,7 @@ describe('BackgroundRefreshScheduler', () => {
await scheduler.tick(); await scheduler.tick();
expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled(); expect(enrichmentService.markRefreshRequested).not.toHaveBeenCalled();
expect(enrichmentService.refreshRiotIdentity).not.toHaveBeenCalled();
expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled(); expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled();
}); });
}); });
@@ -15,7 +15,10 @@ import {
} from '../global/redis/distributed-lock.service'; } from '../global/redis/distributed-lock.service';
import { RedisService } from '../global/redis/redis.service'; import { RedisService } from '../global/redis/redis.service';
import { isInKstBackgroundWindow } from './kst-window.util'; 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 TICK_INTERVAL_MS = 60_000;
const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader'; const LEADER_LOCK_KEY = 'distributed-lock:riot-background-refresh:leader';
@@ -133,6 +136,7 @@ export class BackgroundRefreshScheduler
candidate.userId, candidate.userId,
candidate.puuid, candidate.puuid,
); );
await this.refreshRiotIdentity(candidate);
try { try {
const result = await this.enrichmentService.enrichRiotAccount({ 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 { private currentRefreshGatePolicy(): RefreshGatePolicy {
const isDawn = isInKstBackgroundWindow(); const isDawn = isInKstBackgroundWindow();
return { return {
@@ -12,6 +12,7 @@ import { RiotLeagueService } from './riot-league.service';
import { RiotRecentMatchesService } from './riot-recent-matches.service'; import { RiotRecentMatchesService } from './riot-recent-matches.service';
import { RiotRecentStatsService } from './riot-recent-stats.service'; import { RiotRecentStatsService } from './riot-recent-stats.service';
import { RiotSummonerService } from './riot-summoner.service'; import { RiotSummonerService } from './riot-summoner.service';
import { type RiotPlatformRoute, type RiotRegionalRoute } from './riot.types';
interface FakeAccount { interface FakeAccount {
puuid: string; puuid: string;
@@ -86,6 +87,11 @@ function makeUser(account: FakeAccount) {
function makeService(overrides?: { function makeService(overrides?: {
user?: any; user?: any;
community?: {
riotPlatform?: RiotPlatformRoute;
riotRegion?: RiotRegionalRoute;
seasonStartedAt?: Date;
};
account?: Partial<RiotAccountService>; account?: Partial<RiotAccountService>;
summoner?: Partial<RiotSummonerService>; summoner?: Partial<RiotSummonerService>;
league?: Partial<RiotLeagueService>; league?: Partial<RiotLeagueService>;
@@ -102,10 +108,12 @@ function makeService(overrides?: {
select: () => ({ select: () => ({
lean: () => ({ lean: () => ({
exec: () => exec: () =>
Promise.resolve({ Promise.resolve(
riotPlatform: 'kr', overrides?.community ?? {
riotRegion: 'asia', riotPlatform: 'kr',
}), riotRegion: 'asia',
},
),
}), }),
}), }),
}); });
@@ -199,7 +207,7 @@ describe('RiotAccountEnrichmentService', () => {
const result = await service.refreshRiotIdentity({ const result = await service.refreshRiotIdentity({
userId: user._id, userId: user._id,
puuid: 'puuid-1', puuid: 'puuid-1',
region: 'asia', region: 'europe',
}); });
expect(result).toBe('updated'); expect(result).toBe('updated');
@@ -207,7 +215,7 @@ describe('RiotAccountEnrichmentService', () => {
expect(account.tagLine).toBe('KR1'); expect(account.tagLine).toBe('KR1');
expect(user.save).toHaveBeenCalledTimes(1); expect(user.save).toHaveBeenCalledTimes(1);
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', { expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'asia', region: 'europe',
}); });
}); });
@@ -236,6 +244,61 @@ describe('RiotAccountEnrichmentService', () => {
expect(user.save).toHaveBeenCalledTimes(1); 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 () => { it('does not save when the Riot ID has not changed', async () => {
const account = makeAccount(); const account = makeAccount();
const user = makeUser(account); const user = makeUser(account);
@@ -103,8 +103,19 @@ export class RiotAccountEnrichmentService {
); );
if (!account) return 'failed'; 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, { const identity = await this.accountService.getByPuuid(params.puuid, {
region: params.region ?? DEFAULT_REGION, region,
}); });
if ( if (
identity.puuid !== params.puuid || identity.puuid !== params.puuid ||
+47 -6
View File
@@ -2,10 +2,11 @@
## Overview ## Overview
Deliver the behavior in two backend slices. First add and prove the safe Deliver the behavior in three backend slices. First add and prove the safe
Account-V1-to-user persistence operation. Then invoke it from the existing Account-V1-to-user persistence operation. Then invoke it from the existing
personal-history refresh worker before completion is broadcast. No database or personal-history refresh worker before completion is broadcast. Finally reuse it
frontend contract change is required. from stale-account background refresh with community-aware region resolution and
failure isolation. No database or frontend contract change is required.
## Task List ## Task List
@@ -55,6 +56,45 @@ frontend contract change is required.
- [x] Final diff contains only the specification, plan, enrichment service, worker, - [x] Final diff contains only the specification, plan, enrichment service, worker,
and their tests. and their tests.
### Phase 3: Background Refresh Integration
- [x] Add a failing enrichment-service test proving that an omitted region is
resolved from the user's community.
- Acceptance: a non-Asia community route reaches Account-V1 without changing the
public method signature.
- Verify:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts`
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts`
- [x] Resolve the community Riot region for region-less identity refresh calls.
- Acceptance: explicit caller regions remain unchanged; missing community routes
use the existing `asia` fallback.
- Verify: the focused enrichment-service test passes.
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
- [x] Add failing background scheduler tests for identity refresh ordering and
failure isolation.
- Acceptance: stale accounts request identity refresh before statistics
enrichment, while identity rejection does not increment failure counters.
- Verify:
`pnpm --filter api exec jest --runInBand background-refresh.scheduler.spec.ts`
- Files:
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
- [x] Invoke best-effort identity refresh from the stale-account loop.
- Acceptance: each processed candidate gets one PUUID identity lookup, statistics
enrichment still determines processed/failed/backoff state, and no new Redis or
database contract is added.
- Verify: the focused background scheduler tests pass.
- Files:
`apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
### Checkpoint: Background Refresh Complete
- [x] Focused identity, manual worker, and background scheduler suites pass.
- [x] API lint, full tests, and build pass.
- [x] Final diff remains limited to the existing feature documents, identity
service/tests, and background scheduler/tests.
## Risks and Mitigations ## Risks and Mitigations
| Risk | Impact | Mitigation | | Risk | Impact | Mitigation |
@@ -62,6 +102,8 @@ frontend contract change is required.
| Account-V1 returns an incomplete identity | High | Require matching PUUID and two non-empty Riot ID fields before mutation. | | Account-V1 returns an incomplete identity | High | Require matching PUUID and two non-empty Riot ID fields before mutation. |
| Riot Account-V1 is temporarily unavailable | Medium | Preserve stored identity, log the failure, and retain existing best-effort job semantics. | | Riot Account-V1 is temporarily unavailable | Medium | Preserve stored identity, log the failure, and retain existing best-effort job semantics. |
| Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. | | Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. |
| Background community uses a non-Asia Riot route | High | Resolve omitted regions from the user's community before falling back to `asia`. |
| Identity lookup failure triggers background backoff | Medium | Isolate identity exceptions and let existing statistics enrichment alone control failure counters. |
| UI keeps the stale profile cached | High | Identity update completes before the existing completion event invalidates the profile query. | | UI keeps the stale profile cached | High | Identity update completes before the existing completion event invalidates the profile query. |
| Historical names are unexpectedly rewritten | Medium | Restrict persistence to the embedded Riot account and leave match snapshots untouched. | | Historical names are unexpectedly rewritten | Medium | Restrict persistence to the embedded Riot account and leave match snapshots untouched. |
@@ -70,9 +112,8 @@ frontend contract change is required.
```text ```text
validated Account-V1 lookup validated Account-V1 lookup
-> focused identity persistence method -> focused identity persistence method
-> refresh worker orchestration -> manual refresh worker -> existing completion event -> profile invalidation
-> existing completion event -> background scheduler -> existing statistics enrichment and backoff policy
-> existing React Query profile invalidation
``` ```
## Open Questions ## Open Questions
+33 -9
View File
@@ -2,11 +2,11 @@
## Objective ## Objective
When a user clicks `정보 갱신` on the personal match-history page, resolve the Whenever an account is refreshed manually from the personal match-history page
account's current Riot ID through Riot Account-V1 using the stored PUUID. If the or automatically by the stale-account background scheduler, resolve its current
player changed either their game name or tag line, persist the latest values on Riot ID through Riot Account-V1 using the stored PUUID. If the player changed
the same embedded Riot account so the refreshed profile header displays the new either their game name or tag line, persist the latest values on the same embedded
Riot ID. Riot account so the profile displays the new Riot ID.
The existing refresh job remains the single user-facing operation. It continues The existing refresh job remains the single user-facing operation. It continues
to refresh matches and ranked data, and additionally refreshes identity before to refresh matches and ranked data, and additionally refreshes identity before
@@ -16,14 +16,19 @@ emitting its completion event.
- Use the stored PUUID as the stable identity key; never look up the account by - Use the stored PUUID as the stable identity key; never look up the account by
the possibly stale game name and tag line. the possibly stale game name and tag line.
- Query Riot Account-V1 on every manually queued user-history refresh job rather - Query Riot Account-V1 on every manually queued user-history refresh job and
than applying a name TTL. every selected stale-account background refresh rather than applying a name TTL.
- Update `gameName` and `tagLine` together only when Riot returns a matching PUUID - Update `gameName` and `tagLine` together only when Riot returns a matching PUUID
and both values are non-empty. and both values are non-empty.
- Preserve the previous Riot ID if the Account-V1 lookup fails or returns an - Preserve the previous Riot ID if the Account-V1 lookup fails or returns an
incomplete or mismatched response. incomplete or mismatched response.
- Treat identity refresh as best effort, matching the existing ranked-data refresh - Treat identity refresh as best effort, matching the existing ranked-data refresh
policy: log a failure but allow successful match refresh work to complete. policy: log a failure but allow successful match refresh work to complete.
- When a caller does not already know the Riot regional route, resolve it from the
user's community and fall back to `asia` only when the community has no route.
- Do not increment the background failure counter or enter backoff solely because
the identity lookup failed; background statistics enrichment retains its
existing success and failure semantics.
- Reuse the existing refresh completion event and profile-query invalidation; do - Reuse the existing refresh completion event and profile-query invalidation; do
not add a new endpoint, response field, socket event, or frontend state path. not add a new endpoint, response field, socket event, or frontend state path.
- Update only the embedded Riot account used by the personal profile. Historical - Update only the embedded Riot account used by the personal profile. Historical
@@ -34,12 +39,13 @@ emitting its completion event.
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api` - NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Account-V1 through the existing `RiotAccountService` - Riot Account-V1 through the existing `RiotAccountService`
- Redis stream jobs through the existing `RiotJobWorkerService` - Redis stream jobs through the existing `RiotJobWorkerService`
- Scheduled stale-account refresh through `BackgroundRefreshScheduler`
- React Query profile invalidation already present in `UserHistoryPage` - React Query profile invalidation already present in `UserHistoryPage`
## Commands ## Commands
- Focused tests: - Focused tests:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts` `pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts background-refresh.scheduler.spec.ts`
- API lint: `pnpm --filter api lint` - API lint: `pnpm --filter api lint`
- API build: `pnpm --filter api build` - API build: `pnpm --filter api build`
- Web lint: `pnpm --filter web lint` - Web lint: `pnpm --filter web lint`
@@ -57,6 +63,11 @@ emitting its completion event.
identity, match, and ranked refresh work before completion. identity, match, and ranked refresh work before completion.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts` verifies - `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts` verifies
that a personal-history refresh job requests the PUUID-based identity refresh. that a personal-history refresh job requests the PUUID-based identity refresh.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts`
orchestrates best-effort identity refresh for stale accounts before statistics
enrichment.
- `apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.spec.ts`
verifies background invocation, ordering, and failure isolation.
- `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query - `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query
when the refresh socket reports completion and is not modified in this scope. when the refresh socket reports completion and is not modified in this scope.
@@ -77,7 +88,9 @@ refreshRiotIdentity(params: {
`updated` means both persisted Riot ID fields now match Account-V1. `unchanged` `updated` means both persisted Riot ID fields now match Account-V1. `unchanged`
means the validated response matched the stored values and no database write was means the validated response matched the stored values and no database write was
needed. `failed` means no stored account could be resolved or the external lookup needed. `failed` means no stored account could be resolved or the external lookup
could not safely provide a complete identity; stored values remain unchanged. could not safely provide a complete identity; stored values remain unchanged. If
`region` is omitted, the service resolves the user's community and uses its
configured `riotRegion`, falling back to `asia` only when unavailable.
## Code Style ## Code Style
@@ -102,6 +115,12 @@ Prettier formatting. Do not add a generic identity abstraction or new dependency
- Verify missing values, PUUID mismatch, and Riot lookup errors return `failed` - Verify missing values, PUUID mismatch, and Riot lookup errors return `failed`
without overwriting or saving the stored identity. without overwriting or saving the stored identity.
- Write the worker orchestration expectation before calling the new method. - Write the worker orchestration expectation before calling the new method.
- Verify a region-less identity refresh uses the user's configured community
region.
- Write background scheduler expectations before adding identity refresh to the
stale-account loop.
- Verify identity refresh happens before statistics enrichment and that a rejected
identity lookup does not increment background failure counters.
- Run focused API tests after each slice, then API lint/build and web lint/build - Run focused API tests after each slice, then API lint/build and web lint/build
to verify the existing client integration remains valid. to verify the existing client integration remains valid.
@@ -113,6 +132,7 @@ Prettier formatting. Do not add a generic identity abstraction or new dependency
- Validate both Riot ID fields before mutating the database. - Validate both Riot ID fields before mutating the database.
- Preserve the current Riot ID on any unsafe or failed response. - Preserve the current Riot ID on any unsafe or failed response.
- Keep the existing refresh route, enqueue response, and socket event compatible. - Keep the existing refresh route, enqueue response, and socket event compatible.
- Keep background identity failures independent from enrichment failure counters.
- Run focused tests before broader lint and build verification. - Run focused tests before broader lint and build verification.
### Ask First ### Ask First
@@ -136,12 +156,16 @@ Prettier formatting. Do not add a generic identity abstraction or new dependency
- Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored - Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored
PUUID. PUUID.
- Selecting a stale account for background refresh also calls Account-V1 by the
stored PUUID before statistics enrichment.
- A changed Riot game name or tag line is persisted on the matching embedded - A changed Riot game name or tag line is persisted on the matching embedded
account before the completion event is broadcast. account before the completion event is broadcast.
- The completion event triggers the existing profile-query invalidation, so the - The completion event triggers the existing profile-query invalidation, so the
personal history header displays the latest `gameName#tagLine`. personal history header displays the latest `gameName#tagLine`.
- Failed, incomplete, or mismatched Riot identity responses do not overwrite the - Failed, incomplete, or mismatched Riot identity responses do not overwrite the
existing Riot ID and do not prevent otherwise successful match refresh work. existing Riot ID and do not prevent otherwise successful match refresh work.
- Background identity lookup failures do not increment the account failure counter
or prevent otherwise successful background enrichment.
- Focused tests, API lint/build, and web lint/production build pass. - Focused tests, API lint/build, and web lint/production build pass.
## Open Questions ## Open Questions