feat(api): refresh Riot ID by PUUID

This commit is contained in:
dahyeon committed 2026-07-25 08:37:42 -07:00
1 parent 79534cf43c
commit 9cd5850d43
6 files changed
+508 -3

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;