Compare commits

..
20 changed files with 1157 additions and 32 deletions

No files matched your search

@@ -0,0 +1,122 @@
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { RiotAccountService } from '../riot/riot-account.service';
import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service';
import { DakaoUserService } from './dakao-user.service';
const communityId = new mongoose.Types.ObjectId();
const params = {
communityId,
kakaoTalkId: 'new-id',
previousNickname: '예전 닉',
};
function setup() {
const user = {
_id: new mongoose.Types.ObjectId(),
communityId,
kakaoTalkId: 'old-id',
kakaoTalkNickname: '예전 닉',
riotAccounts: [{ puuid: 'puuid', gameName: '소환사', tagLine: 'KR1' }],
role: 'member',
};
const find = jest.fn().mockReturnValue({
limit: jest
.fn()
.mockReturnValue({ exec: jest.fn().mockResolvedValue([user]) }),
});
const findOne = jest
.fn()
.mockReturnValue({ exec: jest.fn().mockResolvedValue(null) });
const update = jest
.fn()
.mockImplementation(async () => ({ ...user, kakaoTalkId: 'new-id' }));
const findOneAndUpdate = jest.fn().mockReturnValue({ exec: update });
const service = new DakaoUserService(
{
getModel: jest
.fn()
.mockResolvedValue({ find, findOne, findOneAndUpdate }),
} as unknown as ConnectionService,
{} as RiotAccountService,
{} as RiotAccountEnrichmentService,
);
return { service, user, find, findOne, findOneAndUpdate, update };
}
describe('DakaoUserService.transferKakaoTalkId', () => {
it('selects registered users by exact nickname in the current community and changes only the ID', async () => {
const { service, user, find, findOneAndUpdate } = setup();
expect(await service.transferKakaoTalkId(params)).toBe('transferred');
expect(find).toHaveBeenCalledWith({
communityId,
kakaoTalkNickname: '예전 닉',
'riotAccounts.0': { $exists: true },
});
expect(findOneAndUpdate).toHaveBeenCalledWith(
{
_id: user._id,
communityId,
kakaoTalkId: 'old-id',
kakaoTalkNickname: '예전 닉',
'riotAccounts.0': { $exists: true },
},
{ $set: { kakaoTalkId: 'new-id' } },
{ returnDocument: 'after' },
);
});
it.each([
['not-found', 0],
['ambiguous', 2],
] as const)('returns %s without mutation', async (status, count) => {
const { service, user, find, findOneAndUpdate } = setup();
find.mockReturnValue({
limit: () => ({
exec: async () => Array.from({ length: count }, () => user),
}),
});
expect(await service.transferKakaoTalkId(params)).toBe(status);
expect(findOneAndUpdate).not.toHaveBeenCalled();
});
it('does not mutate an already linked user', async () => {
const { service, user, findOneAndUpdate } = setup();
user.kakaoTalkId = 'new-id';
expect(await service.transferKakaoTalkId(params)).toBe('already-linked');
expect(findOneAndUpdate).not.toHaveBeenCalled();
});
it('refuses an ID occupied by another user', async () => {
const { service, findOne, findOneAndUpdate } = setup();
findOne.mockReturnValue({
exec: async () => ({ _id: new mongoose.Types.ObjectId() }),
});
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
expect(findOne).toHaveBeenCalledWith({
communityId,
kakaoTalkId: 'new-id',
});
expect(findOneAndUpdate).not.toHaveBeenCalled();
});
it('reports a concurrent change instead of overwriting it', async () => {
const { service, update } = setup();
update.mockResolvedValue(null);
expect(await service.transferKakaoTalkId(params)).toBe('changed');
});
it('handles a concurrent ID collision', async () => {
const { service, update } = setup();
update.mockRejectedValue({ code: 11000 });
expect(await service.transferKakaoTalkId(params)).toBe('id-conflict');
});
it('propagates unexpected database failures for retry', async () => {
const { service, update } = setup();
update.mockRejectedValue(new Error('database unavailable'));
await expect(service.transferKakaoTalkId(params)).rejects.toThrow(
'database unavailable',
);
});
});
@@ -60,6 +60,14 @@ interface ResolvedRiotIdentity {
const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr';
const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia';
export type KakaoDataTransferResult =
| 'transferred'
| 'already-linked'
| 'not-found'
| 'ambiguous'
| 'id-conflict'
| 'changed';
@Injectable()
export class DakaoUserService {
private readonly logger = new Logger(DakaoUserService.name);
@@ -127,6 +135,44 @@ export class DakaoUserService {
}).exec();
}
public async transferKakaoTalkId(params: {
communityId: mongoose.Types.ObjectId;
kakaoTalkId: string;
previousNickname: string;
}): Promise<KakaoDataTransferResult> {
const UserModel = await this.connectionService.getModel('user');
const targetFilter = {
communityId: params.communityId,
kakaoTalkNickname: params.previousNickname,
'riotAccounts.0': { $exists: true },
};
const candidates = await UserModel.find(targetFilter).limit(2).exec();
if (candidates.length === 0) return 'not-found';
if (candidates.length > 1) return 'ambiguous';
const user = candidates[0];
if (user.kakaoTalkId === params.kakaoTalkId) return 'already-linked';
const occupied = await this.findUserByKakaoTalkId(params);
if (occupied) return 'id-conflict';
try {
// Compare the previous ID so concurrent transfers cannot overwrite one another.
const updated = await UserModel.findOneAndUpdate(
{
...targetFilter,
_id: user._id,
kakaoTalkId: user.kakaoTalkId ?? null,
},
{ $set: { kakaoTalkId: params.kakaoTalkId } },
{ returnDocument: 'after' },
).exec();
return updated ? 'transferred' : 'changed';
} catch (error) {
if ((error as { code?: number })?.code === 11000) return 'id-conflict';
throw error;
}
}
public async resolveRiotAccount(
context: ResolveContext,
): Promise<ResolveResult> {
@@ -12,6 +12,7 @@ import { DakaoUserService } from './dakao-user.service';
import { DakaoSendResultSubscriber } from './dakao-send-result.subscriber';
import { DakaoUrlShortenerService } from './dakao-url-shortener.service';
import { AccountRegisterHandler } from './handlers/account-register.handler';
import { DataTransferHandler } from './handlers/data-transfer.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
@@ -35,6 +36,7 @@ import { PrimaryAccountChangeHandler } from './handlers/primary-account-change.h
DakaoUserService,
DakaoUrlShortenerService,
AccountRegisterHandler,
DataTransferHandler,
MatchListHandler,
MatchJoinHandler,
MatchCancelHandler,
@@ -16,6 +16,7 @@ function makeSubscriber(): DakaoSubscriber {
{} as never,
{} as never,
{} as never,
{} as never,
);
}
@@ -39,6 +40,48 @@ const event = {
} satisfies DakaoInboundEvent;
describe('DakaoSubscriber', () => {
it('routes data transfer with the current sender ID and publishes its reply', async () => {
const subscriber = makeSubscriber();
const segments = [{ kind: 'text', text: ' 데이터 이관 완료' }];
const handle = jest.fn().mockResolvedValue(segments);
const sendMessage = jest.fn();
const markProcessed = jest.fn();
Object.assign(subscriber, {
dakaoUserService: {
resolveCommunityIdByDakaoProjectId: async () => event.projectId,
},
dataTransferHandler: { handle },
publisher: { sendMessage },
inbox: { claim: async () => ({ status: 'claimed' }), markProcessed },
});
await (
subscriber as unknown as {
handleEvent: (input: DakaoInboundEvent) => Promise<void>;
}
).handleEvent({
...event,
origin: {
...event.origin,
chatLog: {
...event.origin.chatLog,
message: '!내전 데이터이관 예전 닉',
},
},
});
expect(handle).toHaveBeenCalledWith({
communityId: event.projectId,
senderUserId: '12345',
senderNickname: '프리리',
previousNickname: '예전 닉',
});
expect(sendMessage).toHaveBeenCalledWith({
chatroomId: 'chatroom-1',
segments,
correlationId: 'log-1',
});
expect(markProcessed).toHaveBeenCalled();
});
it('renders usage help with star emoticon command lines', () => {
const subscriber = makeSubscriber() as unknown as {
parseErrorReply: (
@@ -74,8 +117,10 @@ describe('DakaoSubscriber', () => {
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{
kind: 'text',
text: ' !내전 대표계정변경 소환사이름#태그',
text: ' !내전 대표계정변경 소환사이름#태그\u3000\n',
},
{ kind: 'emoticon', id: '1200281_035', altText: '스타' },
{ kind: 'text', text: ' !내전 데이터이관 예전닉네임' },
]);
});
@@ -7,6 +7,7 @@ import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
import { AccountRegisterHandler } from './handlers/account-register.handler';
import { DataTransferHandler } from './handlers/data-transfer.handler';
import { MatchCancelHandler } from './handlers/match-cancel.handler';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.handler';
@@ -27,6 +28,7 @@ export class DakaoSubscriber implements OnModuleInit {
'!내전 계정등록 소환사이름#태그',
'!내전 선호포지션등록 포지션1,포지션2',
'!내전 대표계정변경 소환사이름#태그',
'!내전 데이터이관 예전닉네임',
];
constructor(
@@ -42,6 +44,7 @@ export class DakaoSubscriber implements OnModuleInit {
private readonly matchCancelHandler: MatchCancelHandler,
private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler,
private readonly primaryAccountChangeHandler: PrimaryAccountChangeHandler,
private readonly dataTransferHandler: DataTransferHandler,
) {}
async onModuleInit() {
@@ -119,6 +122,14 @@ export class DakaoSubscriber implements OnModuleInit {
const command = parseCommand(event.origin.chatLog.message);
switch (command.kind) {
case 'data-transfer':
segments = await this.dataTransferHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname,
previousNickname: command.previousNickname,
});
break;
case 'match-list':
segments = await this.matchListHandler.handle({
communityId,
@@ -0,0 +1,49 @@
import mongoose from 'mongoose';
import {
DakaoUserService,
KakaoDataTransferResult,
} from '../dakao-user.service';
import { DataTransferHandler } from './data-transfer.handler';
const params = {
communityId: new mongoose.Types.ObjectId(),
senderUserId: 'new-id',
senderNickname: '현재 닉',
previousNickname: '예전 닉',
};
describe('DataTransferHandler', () => {
it.each<[KakaoDataTransferResult, string]>([
['transferred', '데이터 이관 완료'],
['already-linked', '이미 현재 카카오톡 계정에 연결'],
['not-found', '찾을 수 없습니다'],
['ambiguous', '여러 명'],
['id-conflict', '이미 다른 사용자'],
['changed', '변경되었습니다'],
])('replies to the sender for %s', async (result, message) => {
const transferKakaoTalkId = jest.fn().mockResolvedValue(result);
const handler = new DataTransferHandler({
transferKakaoTalkId,
} as unknown as DakaoUserService);
expect(await handler.handle(params)).toEqual([
{ kind: 'mention', userId: 'new-id', displayText: '현재 닉' },
{ kind: 'text', text: expect.stringContaining(message) },
]);
expect(transferKakaoTalkId).toHaveBeenCalledWith({
communityId: params.communityId,
kakaoTalkId: 'new-id',
previousNickname: '예전 닉',
});
});
it('propagates unexpected failures', async () => {
const handler = new DataTransferHandler({
transferKakaoTalkId: jest
.fn()
.mockRejectedValue(new Error('database unavailable')),
} as unknown as DakaoUserService);
await expect(handler.handle(params)).rejects.toThrow(
'database unavailable',
);
});
});
@@ -0,0 +1,46 @@
import { Injectable } from '@nestjs/common';
import mongoose from 'mongoose';
import {
DakaoUserService,
KakaoDataTransferResult,
} from '../dakao-user.service';
import { DakaoSegment } from '../dakao.types';
const RESULT_MESSAGES: Record<KakaoDataTransferResult, string> = {
transferred:
'데이터 이관 완료. 기존 라이엇 계정과 내전 기록이 현재 카카오톡 계정에 연결되었습니다.',
'already-linked': '이미 현재 카카오톡 계정에 연결된 사용자입니다.',
'not-found':
'해당 예전 닉네임으로 라이엇 계정이 등록된 사용자를 찾을 수 없습니다.',
ambiguous:
'같은 예전 닉네임으로 등록된 사용자가 여러 명입니다. 운영자에게 문의해주세요.',
'id-conflict':
'현재 카카오톡 계정에 이미 다른 사용자가 등록되어 있습니다. 운영자에게 문의해주세요.',
changed: '이관 중 사용자 정보가 변경되었습니다. 다시 시도해주세요.',
};
@Injectable()
export class DataTransferHandler {
constructor(private readonly dakaoUserService: DakaoUserService) {}
public async handle(params: {
communityId: mongoose.Types.ObjectId;
senderUserId: string;
senderNickname: string;
previousNickname: string;
}): Promise<DakaoSegment[]> {
const result = await this.dakaoUserService.transferKakaoTalkId({
communityId: params.communityId,
kakaoTalkId: params.senderUserId,
previousNickname: params.previousNickname,
});
return [
{
kind: 'mention',
userId: params.senderUserId,
displayText: params.senderNickname,
},
{ kind: 'text', text: ` ${RESULT_MESSAGES[result]}` },
];
}
}
@@ -1,6 +1,19 @@
import { CommandParseError, parseCommand } from './command.parser';
describe('parseCommand', () => {
it('parses data transfer with the complete previous nickname', () => {
expect(parseCommand(' !내전 데이터이관 예전 닉.* ')).toEqual({
kind: 'data-transfer',
previousNickname: '예전 닉.*',
});
});
it('requires a previous nickname for data transfer', () => {
expect(() => parseCommand('!내전 데이터이관 ')).toThrow(
new CommandParseError('usage'),
);
});
it('parses match-list command (목록)', () => {
expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' });
});
@@ -7,6 +7,7 @@ import { normalizeRiotIdPart } from '../riot-id.util';
export type DakaoCommand =
| { kind: 'match-list' }
| { kind: 'data-transfer'; previousNickname: string }
| {
kind: 'account-register';
gameName: string;
@@ -75,6 +76,9 @@ export function parseCommand(rawMessage: string): DakaoCommand {
return parseCancelArgs(args);
case '계정등록':
return parseAccountRegisterArgs(args);
case '데이터이관':
if (!args) throw new CommandParseError('usage');
return { kind: 'data-transfer', previousNickname: args };
case '대표계정변경':
return parsePrimaryAccountChangeArgs(args);
case '선호포지션등록':
@@ -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 {
@@ -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({
@@ -12,9 +12,12 @@ 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;
gameName: string;
tagLine: string;
profileIconId: number;
revisionDate: number;
summonerLevel: number;
@@ -56,6 +59,8 @@ interface FakeAccount {
function makeAccount(overrides: Partial<FakeAccount> = {}): FakeAccount {
return {
puuid: 'puuid-1',
gameName: 'OldName',
tagLine: 'KR1',
profileIconId: 0,
revisionDate: 0,
summonerLevel: 0,
@@ -82,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>;
@@ -98,10 +108,12 @@ function makeService(overrides?: {
select: () => ({
lean: () => ({
exec: () =>
Promise.resolve({
riotPlatform: 'kr',
riotRegion: 'asia',
}),
Promise.resolve(
overrides?.community ?? {
riotPlatform: 'kr',
riotRegion: 'asia',
},
),
}),
}),
});
@@ -130,6 +142,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 +190,205 @@ 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: 'europe',
});
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: 'europe',
});
});
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('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);
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,67 @@ 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';
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,
});
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;
-22
View File
@@ -127,21 +127,6 @@ function formatRefreshError(error: unknown) {
return error instanceof Error ? error.message : "갱신 요청에 실패했습니다.";
}
function socketStatusMeta(status: string): { tone: string; label: string } {
switch (status) {
case "connected":
return { tone: "bg-emerald-400", label: "실시간 연결됨" };
case "connecting":
return { tone: "bg-amber-400", label: "연결 중" };
case "error":
return { tone: "bg-red-400", label: "연결 오류" };
case "disconnected":
return { tone: "bg-base-content/30", label: "연결 끊김" };
default:
return { tone: "bg-base-content/20", label: "대기 중" };
}
}
function ratioClass(value: number) {
if (value >= 55) return "text-blue-400";
if (value >= 50) return "text-amber-400";
@@ -1329,7 +1314,6 @@ export default function UserHistoryPage() {
);
}
const socketStatus = socketStatusMeta(refreshSocket.connectionStatus);
const refreshNoticeIsError =
Boolean(refreshSocket.error) ||
Boolean(refreshNotice?.startsWith("갱신 실패"));
@@ -1386,12 +1370,6 @@ export default function UserHistoryPage() {
? "요청 중..."
: "정보 갱신"}
</button>
{!isInternalQueue && (
<div className="flex items-center gap-1.5 text-[11px] text-base-content/30 sm:justify-end">
<span className={`h-1.5 w-1.5 ${socketStatus.tone}`} />
{socketStatus.label}
</div>
)}
</div>
</div>
{(refreshNotice || refreshSocket.error) && (
+13
View File
@@ -0,0 +1,13 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
const userHistoryPageSource = await readFile(
new URL("../src/pages/UserHistoryPage.tsx", import.meta.url),
"utf8",
);
test("hides the temporary real-time connection status indicator", () => {
assert.doesNotMatch(userHistoryPageSource, /실시간 연결됨/);
assert.doesNotMatch(userHistoryPageSource, /refreshSocket\.connectionStatus/);
});
+121
View File
@@ -0,0 +1,121 @@
# Implementation Plan: Refresh Riot ID by PUUID
## Overview
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
personal-history refresh worker before completion is broadcast. Finally reuse it
from stale-account background refresh with community-aware region resolution and
failure isolation. 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.
### 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
| 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. |
| 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. |
| 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
-> manual refresh worker -> existing completion event -> profile invalidation
-> background scheduler -> existing statistics enrichment and backoff policy
```
## Open Questions
None. The user approved the specification and requested implementation.
+93
View File
@@ -0,0 +1,93 @@
# Spec: 카카오톡 방 이동 후 사용자 데이터 이관
## Objective
`!내전 데이터이관 <예전 kakaoTalkNickname>` 명령으로 기존 user의
`kakaoTalkId`를 명령 발신자의 현재 ID로 변경한다. 기존 user의 `_id`,
`riotAccounts`, 참가 기록, 권한과 기타 데이터는 유지한다.
## Proposed Success Criteria
- 현재 명령이 연결된 community 안에서만 조회한다.
- 인자 전체를 예전 닉네임으로 취급하여 공백이 포함된 닉네임을 지원한다.
- 닉네임은 앞뒤 인자 공백을 제거한 후 정확히 일치하는 값으로 조회한다.
- `riotAccounts`가 있는 기존 user를 이관 대상으로 삼는다.
- 대상 없음, 중복 닉네임, 다른 user의 현재 카카오 ID 점유는 변경 없이 안내한다.
- 성공 시 기존 user의 `kakaoTalkId`만 변경하고 발신자에게 완료를 안내한다.
- 동일 ID로 재시도하면 이미 연결된 상태로 안내한다.
- 동시 변경과 DB 중복 키 오류를 처리하며 새 user를 생성하거나 병합하지 않는다.
## Tech Stack / Project Structure
NestJS 11, TypeScript, Mongoose 9, Jest 30, pnpm workspace.
`apps/api/src/modules/dakao/`의 parser, handler, service, module 및 명령 라우팅을 사용한다.
테스트는 구현 옆 `*.spec.ts`, 명세는 `docs/specs/`에 둔다.
## Commands
- 관련 테스트: `pnpm --filter api test --runInBand dakao`
- 전체 API 테스트: `pnpm --filter api test --runInBand`
- 빌드: `pnpm --filter api build`
- 변경 파일 lint: `pnpm --filter api exec eslint <changed-files>`
- 개발 실행: `pnpm --filter api start:debug`
## Code Style
기존 Injectable handler/service와 discriminated command union 패턴을 따른다.
```typescript
return { kind: 'data-transfer', previousNickname: args };
```
## Testing Strategy
구현 전 실패 테스트를 작성한다. 파싱, 커뮤니티 범위, 성공 후 기존 데이터 보존,
대상 없음/중복, ID 충돌, 재시도, 동시 갱신 실패 및 라우팅/응답을 검증한다.
관련 테스트 후 전체 API 테스트와 빌드를 수행한다.
## Boundaries
- Always: 커뮤니티 범위 제한, 입력 검증, 기존 user 식별자 및 연결 데이터 보존.
- Ask first: 스키마 변경, 의존성 추가, 기존 user 병합/삭제.
- Never: 운영 DB 직접 수정, 비밀값 커밋, 실패 테스트 제거.
## Confirmed Policy
사용자 확인: `riotAccounts`가 등록된 user를 뜻한다. Riot 계정 검증 및 소유권
확인은 하지 않으며 운영으로 통제한다. 예전 닉네임으로 조회하여 ID만 변경한다.
## Implementation Plan and Tasks
1. 이관 서비스: `dakao-user.service.ts` 및 전용 테스트 파일.
- 수락 조건: 기존 데이터 보존, 대상/충돌/재시도/동시 변경 처리.
- 검증: 실패 테스트 확인 후 서비스 테스트 통과.
2. 명령 parser 및 handler: 구현과 각각의 테스트 4개 파일.
- 수락 조건: 공백 포함 닉네임 파싱, 빈 입력 사용법, 결과별 한국어 응답.
- 검증: parser/handler 테스트 통과. 작업 1에 의존.
3. subscriber 및 module 연결: 구현 2개와 subscriber 테스트.
- 수락 조건: 현재 커뮤니티/발신자 ID 전달, 도움말 노출.
- 검증: Dakao 테스트, 전체 API 테스트, 빌드, 변경 파일 lint. 작업 2에 의존.
위험: 동시에 이관되는 user는 기존 ID를 조건으로 갱신하여 덮어쓰기를 막고,
새 ID 동시 점유는 기존 unique 인덱스 오류를 충돌 응답으로 변환한다.
각 단계에서 테스트를 확인하고 다음 단계로 진행한다.
## Verification Results
- 서비스, parser/handler, subscriber 테스트는 기능 미구현 상태의 실패를 확인한 후 통과.
- Dakao: 16 suites / 92 tests 통과.
- API 전체: 99 suites / 634 tests 통과, 기존 테스트 2개 실패.
- `api-performance-report.spec.ts`: Windows `path.relative`의 역슬래시와 기대값 불일치.
- `secret.service.spec.ts`: 환경변수에 의존해 누락된 bootstrap secret의 기대 키 불일치.
- 두 테스트는 변경하지 않은 파일이며 별도 실행에서도 같은 실패 재현.
- API 빌드, 변경 TypeScript 파일 ESLint, `git diff --check` 통과.
- 로컬 실행 환경 Node 24.15.0; 저장소 엔진 요구사항은 Node 26.
- 실제 카카오톡 메시지 전송 및 운영 DB 이관은 실행하지 않음.
- 코드 검토: 커뮤니티 제한, 정확한 닉네임 조회, 등록 계정 필터,
ID만 갱신하는 조건부 업데이트, 충돌 응답, DI 및 명령 라우팅 확인.
## Usage
새 방에서 `!내전 데이터이관 예전 닉네임`을 실행한다. 따옴표 없이 공백을 포함한
닉네임 전체를 입력할 수 있다. 새 ID로 이미 user가 생성되어 있으면 자동 병합하지
않고 운영자 문의를 안내한다. 소유권 확인은 운영 정책으로 통제한다.
+175
View File
@@ -0,0 +1,175 @@
# Spec: Refresh Riot ID by PUUID
## Objective
Whenever an account is refreshed manually from the personal match-history page
or automatically by the stale-account background scheduler, resolve its 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 profile 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 and
every selected stale-account background refresh 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.
- 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
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`
- Scheduled stale-account refresh through `BackgroundRefreshScheduler`
- 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 background-refresh.scheduler.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/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
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. 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
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.
- 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
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.
- Keep background identity failures independent from enrichment failure counters.
- 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.
- 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
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.
- 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.
## 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.