Compare commits

...
2 Commits
6 changed files with 508 additions and 3 deletions

No files matched your search

@@ -62,6 +62,7 @@ function makeWorker() {
processMemberJob: jest.fn(),
} as unknown as jest.Mocked<LegacyImportService>;
const enrichmentService = {
refreshRiotIdentity: jest.fn().mockResolvedValue('unchanged'),
refreshLeagueEntries: jest.fn().mockResolvedValue('updated'),
} as unknown as jest.Mocked<RiotAccountEnrichmentService>;
@@ -116,9 +117,14 @@ describe('RiotJobWorkerService', () => {
);
});
it('refreshes league entries while processing user history refresh jobs', async () => {
const { worker, enrichmentService, recentMatchesService, redisService } =
makeWorker();
it('refreshes Riot identity and league entries while processing user history refresh jobs', async () => {
const {
worker,
enrichmentService,
recentMatchesService,
redisService,
jobQueueService,
} = makeWorker();
const userId = new mongoose.Types.ObjectId().toString();
const job: RiotRefreshSubJob = {
jobId: 'job-1',
@@ -146,11 +152,19 @@ describe('RiotJobWorkerService', () => {
});
expect(recentMatchesService.ensureFreshForQueue).toHaveBeenCalledTimes(2);
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledWith({
userId: expect.any(mongoose.Types.ObjectId),
puuid: 'puuid-1',
region: 'asia',
});
expect(enrichmentService.refreshLeagueEntries).toHaveBeenCalledWith({
userId: expect.any(mongoose.Types.ObjectId),
puuid: 'puuid-1',
platform: 'kr',
});
expect(
enrichmentService.refreshRiotIdentity.mock.invocationCallOrder[0],
).toBeLessThan(jobQueueService.markCompleted.mock.invocationCallOrder[0]);
expect(redisService.acknowledgeStream).toHaveBeenCalledWith(
'riot:queue:high',
RIOT_JOB_GROUP,
@@ -167,6 +181,45 @@ describe('RiotJobWorkerService', () => {
);
});
it('completes successful match refresh work when Riot identity lookup throws', async () => {
const { worker, enrichmentService, jobQueueService, refreshGateway } =
makeWorker();
enrichmentService.refreshRiotIdentity.mockRejectedValueOnce(
new Error('Account-V1 unavailable'),
);
const job: RiotRefreshSubJob = {
jobId: 'job-1',
parentJobId: 'parent-1',
userId: new mongoose.Types.ObjectId().toString(),
puuid: 'puuid-1',
region: 'asia',
platform: 'kr',
queueGroup: 'summoners-rift',
queueIds: [420],
requestedAt: Date.now(),
priority: 'high',
};
await (
worker as unknown as {
processEntry: (
stream: string,
entry: { id: string; message: Record<string, string> },
) => Promise<void>;
}
).processEntry('riot:queue:high', {
id: '1-0',
message: { job: JSON.stringify(job) },
});
expect(enrichmentService.refreshRiotIdentity).toHaveBeenCalledTimes(1);
expect(jobQueueService.markCompleted).toHaveBeenCalledWith(job);
expect(jobQueueService.markFailed).not.toHaveBeenCalled();
expect(refreshGateway.broadcastRefreshEvent).toHaveBeenCalledWith(
expect.objectContaining({ state: 'completed' }),
);
});
it('leaves a stream entry pending when another worker owns the job processing lock', async () => {
const { worker, distributedLockService, redisService } = makeWorker();
distributedLockService.runWithRenewedLock.mockResolvedValueOnce(null);
@@ -156,6 +156,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
queueId,
});
}
await this.refreshRiotIdentity(job);
await this.refreshLeagueEntries(job);
await this.markUserFetchedAt(job);
const event = await this.jobQueueService.markCompleted(job);
@@ -211,6 +212,26 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
}
}
private async refreshRiotIdentity(job: RiotRefreshSubJob): Promise<void> {
try {
const result = await this.enrichmentService.refreshRiotIdentity({
userId: new mongoose.Types.ObjectId(job.userId),
puuid: job.puuid,
region: job.region,
});
if (result !== 'failed') return;
this.logger.warn(
`Riot identity refresh failed ${job.jobId}: puuid=${job.puuid}`,
);
} catch (error) {
this.logger.warn(
`Riot identity refresh failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
private async refreshLeagueEntries(job: RiotRefreshSubJob): Promise<void> {
try {
const result = await this.enrichmentService.refreshLeagueEntries({
@@ -15,6 +15,8 @@ import { RiotSummonerService } from './riot-summoner.service';
interface FakeAccount {
puuid: string;
gameName: string;
tagLine: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
@@ -56,6 +58,8 @@ interface FakeAccount {
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
return {
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'KR1',
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
@@ -130,6 +134,7 @@ function makeService(overrides?: {
...overrides?.summoner,
} as unknown as RiotSummonerService;
const accountService = {
getByPuuid: jest.fn(),
getRegionByPuuid: jest.fn(),
...overrides?.account,
} as unknown as RiotAccountService;
@@ -177,6 +182,150 @@ function makeService(overrides?: {
}
describe('RiotAccountEnrichmentService', () => {
it('updates a changed Riot ID resolved from the stored PUUID', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service, accountService } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: 'KR1',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
region: 'asia',
});
expect(result).toBe('updated');
expect(account.gameName).toBe('NewName');
expect(account.tagLine).toBe('KR1');
expect(user.save).toHaveBeenCalledTimes(1);
expect(accountService.getByPuuid).toHaveBeenCalledWith('puuid-1', {
region: 'asia',
});
});
it('updates a changed Riot tag line resolved from the stored PUUID', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'NEW',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('updated');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('NEW');
expect(user.save).toHaveBeenCalledTimes(1);
});
it('does not save when the Riot ID has not changed', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue({
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'KR1',
}),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('unchanged');
expect(user.save).not.toHaveBeenCalled();
});
it.each([
{
name: 'a mismatched PUUID',
response: {
puuid: 'different-puuid',
gameName: 'NewName',
tagLine: 'NEW',
},
},
{
name: 'a missing game name',
response: {
puuid: 'puuid-1',
gameName: null,
tagLine: 'NEW',
},
},
{
name: 'a blank tag line',
response: {
puuid: 'puuid-1',
gameName: 'NewName',
tagLine: ' ',
},
},
])('preserves the stored Riot ID for $name', async ({ response }) => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockResolvedValue(response),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('failed');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('KR1');
expect(user.save).not.toHaveBeenCalled();
});
it('preserves the stored Riot ID when Account-V1 lookup fails', async () => {
const account = makeAccount();
const user = makeUser(account);
const { service } = makeService({
user,
account: {
getByPuuid: jest.fn().mockRejectedValue(new Error('Riot unavailable')),
},
});
const result = await service.refreshRiotIdentity({
userId: user._id,
puuid: 'puuid-1',
});
expect(result).toBe('failed');
expect(account.gameName).toBe('OldName');
expect(account.tagLine).toBe('KR1');
expect(user.save).not.toHaveBeenCalled();
});
it('returns failed for unknown user', async () => {
const { service } = makeService();
const result = await service.enrichRiotAccount({
@@ -59,6 +59,7 @@ export interface EnrichResult {
}
export type RefreshLeagueEntriesResult = 'updated' | 'failed';
export type RefreshRiotIdentityResult = 'updated' | 'unchanged' | 'failed';
@Injectable()
export class RiotAccountEnrichmentService {
@@ -87,6 +88,56 @@ export class RiotAccountEnrichmentService {
).exec();
}
public async refreshRiotIdentity(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
region?: RiotRegionalRoute;
}): Promise<RefreshRiotIdentityResult> {
try {
const UserModel = await this.connectionService.getModel('user');
const user = await UserModel.findById(params.userId).exec();
if (!user) return 'failed';
const account = user.riotAccounts.find(
(candidate) => candidate.puuid === params.puuid,
);
if (!account) return 'failed';
const identity = await this.accountService.getByPuuid(params.puuid, {
region: params.region ?? DEFAULT_REGION,
});
if (
identity.puuid !== params.puuid ||
!identity.gameName?.trim() ||
!identity.tagLine?.trim()
) {
this.logger.warn(
`Riot identity response was incomplete or mismatched for ${params.puuid}.`,
);
return 'failed';
}
if (
account.gameName === identity.gameName &&
account.tagLine === identity.tagLine
) {
return 'unchanged';
}
account.gameName = identity.gameName;
account.tagLine = identity.tagLine;
await user.save();
return 'updated';
} catch (error) {
this.logger.warn(
`Riot identity refresh failed for ${params.puuid}: ${
error instanceof Error ? error.message : String(error)
}`,
);
return 'failed';
}
}
public async enrichRiotAccount(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
+80
View File
@@ -0,0 +1,80 @@
# Implementation Plan: Refresh Riot ID by PUUID
## Overview
Deliver the behavior in two backend slices. First add and prove the safe
Account-V1-to-user persistence operation. Then invoke it from the existing
personal-history refresh worker before completion is broadcast. No database or
frontend contract change is required.
## Task List
### Phase 1: Identity Refresh Boundary
- [x] Add failing tests for changed, unchanged, incomplete, mismatched, and failed
PUUID identity lookups.
- Acceptance: tests describe state outcomes and fail because the focused method
is not implemented.
- 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] Implement `refreshRiotIdentity` using `RiotAccountService.getByPuuid`.
- Acceptance: valid changed values persist together; invalid results preserve
existing values; unchanged values avoid a write.
- Verify: the Phase 1 focused test passes.
- Files:
`apps/api/src/modules/riot/riot-account-enrichment.service.ts`
### Checkpoint: Phase 1
- [x] The enrichment service has a typed three-state result and all focused tests
pass.
- [x] No schema, endpoint, queue payload, or frontend changes exist.
### Phase 2: Refresh Worker Integration
- [x] Add a failing worker test proving that a user-history job requests identity
refresh with its user ID, PUUID, and region.
- Acceptance: the test fails before worker orchestration is updated.
- Verify:
`pnpm --filter api exec jest --runInBand riot-job-worker.service.spec.ts`
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts`
- [x] Invoke best-effort identity refresh before job completion.
- Acceptance: the worker logs identity failure without aborting successful match
refresh work, and broadcasts completion only after identity refresh returns.
- Verify: the Phase 2 focused test passes.
- Files: `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts`
### Checkpoint: Complete
- [x] Focused API suites pass without skipped tests.
- [x] API lint and build pass.
- [x] Web lint and production build pass, confirming the existing profile
invalidation integration remains compatible.
- [x] Final diff contains only the specification, plan, enrichment service, worker,
and their tests.
## Risks and Mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| 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. |
| Multiple queue groups repeat identity lookup | Low | The personal page requests one queue group; avoid a new dedup mechanism until a measured need exists. |
| 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. |
## Dependencies
```text
validated Account-V1 lookup
-> focused identity persistence method
-> refresh worker orchestration
-> existing completion event
-> existing React Query profile invalidation
```
## Open Questions
None. The user approved the specification and requested implementation.
+151
View File
@@ -0,0 +1,151 @@
# Spec: Refresh Riot ID by PUUID
## Objective
When a user clicks `정보 갱신` on the personal match-history page, resolve the
account's current Riot ID through Riot Account-V1 using the stored PUUID. If the
player changed either their game name or tag line, persist the latest values on
the same embedded Riot account so the refreshed profile header displays the new
Riot ID.
The existing refresh job remains the single user-facing operation. It continues
to refresh matches and ranked data, and additionally refreshes identity before
emitting its completion event.
## Approved Product Decisions
- Use the stored PUUID as the stable identity key; never look up the account by
the possibly stale game name and tag line.
- Query Riot Account-V1 on every manually queued user-history refresh job rather
than applying a name TTL.
- Update `gameName` and `tagLine` together only when Riot returns a matching PUUID
and both values are non-empty.
- Preserve the previous Riot ID if the Account-V1 lookup fails or returns an
incomplete or mismatched response.
- Treat identity refresh as best effort, matching the existing ranked-data refresh
policy: log a failure but allow successful match refresh work to complete.
- Reuse the existing refresh completion event and profile-query invalidation; do
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
match snapshots retain the names recorded by Riot for those games.
## Tech Stack
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
- Riot Account-V1 through the existing `RiotAccountService`
- Redis stream jobs through the existing `RiotJobWorkerService`
- React Query profile invalidation already present in `UserHistoryPage`
## Commands
- Focused tests:
`pnpm --filter api exec jest --runInBand riot-account-enrichment.service.spec.ts riot-job-worker.service.spec.ts`
- API lint: `pnpm --filter api lint`
- API build: `pnpm --filter api build`
- Web lint: `pnpm --filter web lint`
- Web production build: `pnpm --filter web build:prod`
## Project Structure
- `apps/api/src/modules/riot/riot-account.service.ts` owns the validated
Account-V1 PUUID lookup.
- `apps/api/src/modules/riot/riot-account-enrichment.service.ts` owns the
persistence boundary for the embedded Riot account.
- `apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts` verifies
update, no-op, and failure behavior.
- `apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts` orchestrates
identity, match, and ranked refresh work before completion.
- `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.
- `apps/web/src/pages/UserHistoryPage.tsx` already invalidates the profile query
when the refresh socket reports completion and is not modified in this scope.
## Internal Contract
Add one focused method to `RiotAccountEnrichmentService`:
```ts
type RefreshRiotIdentityResult = "updated" | "unchanged" | "failed";
refreshRiotIdentity(params: {
userId: mongoose.Types.ObjectId;
puuid: string;
region?: RiotRegionalRoute;
}): Promise<RefreshRiotIdentityResult>;
```
`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
needed. `failed` means no stored account could be resolved or the external lookup
could not safely provide a complete identity; stored values remain unchanged.
## Code Style
Keep the external validation and persistence decision explicit:
```ts
const identity = await this.accountService.getByPuuid(puuid, { region });
if (identity.puuid !== puuid || !identity.gameName || !identity.tagLine) {
return "failed";
}
```
Use existing single quotes, NestJS logging, Mongoose document mutation, and
Prettier formatting. Do not add a generic identity abstraction or new dependency.
## Testing Strategy
- Write the enrichment-service tests first and confirm they fail before adding
the new method.
- Verify a changed game name and tag line are persisted together.
- Verify identical values return `unchanged` without saving.
- Verify missing values, PUUID mismatch, and Riot lookup errors return `failed`
without overwriting or saving the stored identity.
- Write the worker orchestration expectation before calling the new method.
- Run focused API tests after each slice, then API lint/build and web lint/build
to verify the existing client integration remains valid.
## Boundaries
### Always
- Use the stored PUUID for Account-V1 lookup and verify the returned PUUID.
- Validate both Riot ID fields before mutating the database.
- Preserve the current Riot ID on any unsafe or failed response.
- Keep the existing refresh route, enqueue response, and socket event compatible.
- Run focused tests before broader lint and build verification.
### Ask First
- Add a database field or migration.
- Change refresh failure semantics so an identity lookup failure fails the whole
user-history job.
- Update historical match snapshots or active match participant display names.
- Add a new API response field, endpoint, dependency, or Redis job type.
- Commit, push, deploy, or alter CI configuration.
### Never
- Resolve identity from the stale stored Riot ID.
- Partially update only the game name or only the tag line.
- Replace a valid stored identity with empty or mismatched Account-V1 data.
- Expose Riot API errors or credentials to the browser.
- Mix the change with the separate past-history result-column PR.
## Success Criteria
- Clicking `정보 갱신` causes the queued worker to call Account-V1 by the stored
PUUID.
- A changed Riot game name or tag line is persisted on the matching embedded
account before the completion event is broadcast.
- The completion event triggers the existing profile-query invalidation, so the
personal history header displays the latest `gameName#tagLine`.
- Failed, incomplete, or mismatched Riot identity responses do not overwrite the
existing Riot ID and do not prevent otherwise successful match refresh work.
- Focused tests, API lint/build, and web lint/production build pass.
## Open Questions
None. The user approved this specification and requested implementation. The
existing queue and UI invalidation paths support the behavior without a public
contract change.