From ba3894cba2be76594ca575a796e1c93bdb94e28e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Tue, 28 Apr 2026 22:37:00 +0900 Subject: [PATCH] feat(api): add Dakao integration --- .../modules/dakao/dakao-user.service.spec.ts | 171 +++++++ .../src/modules/dakao/dakao-user.service.ts | 428 ++++++++++++++++++ apps/api/src/modules/dakao/dakao.module.ts | 37 ++ apps/api/src/modules/dakao/dakao.options.ts | 13 + .../src/modules/dakao/dakao.publisher.spec.ts | 73 +++ apps/api/src/modules/dakao/dakao.publisher.ts | 154 +++++++ .../api/src/modules/dakao/dakao.subscriber.ts | 230 ++++++++++ apps/api/src/modules/dakao/dakao.types.ts | 102 +++++ .../src/modules/dakao/idempotency.cache.ts | 35 ++ apps/api/src/modules/dakao/riot-id.util.ts | 14 + 10 files changed, 1257 insertions(+) create mode 100644 apps/api/src/modules/dakao/dakao-user.service.spec.ts create mode 100644 apps/api/src/modules/dakao/dakao-user.service.ts create mode 100644 apps/api/src/modules/dakao/dakao.module.ts create mode 100644 apps/api/src/modules/dakao/dakao.options.ts create mode 100644 apps/api/src/modules/dakao/dakao.publisher.spec.ts create mode 100644 apps/api/src/modules/dakao/dakao.publisher.ts create mode 100644 apps/api/src/modules/dakao/dakao.subscriber.ts create mode 100644 apps/api/src/modules/dakao/dakao.types.ts create mode 100644 apps/api/src/modules/dakao/idempotency.cache.ts create mode 100644 apps/api/src/modules/dakao/riot-id.util.ts diff --git a/apps/api/src/modules/dakao/dakao-user.service.spec.ts b/apps/api/src/modules/dakao/dakao-user.service.spec.ts new file mode 100644 index 00000000..bcbedb98 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao-user.service.spec.ts @@ -0,0 +1,171 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { RiotAccount, UserDocument } from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { RiotAccountService } from '../riot/riot-account.service'; +import { DakaoUserService } from './dakao-user.service'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +function makeQuery(value: T) { + return { + exec: jest.fn().mockResolvedValue(value), + }; +} + +function makeService(params: { + user: Partial; + community?: Record | null; + riotAccountService?: Partial; + enrichmentService?: Partial; +}) { + const findOneAndUpdate = jest + .fn() + .mockReturnValue(makeQuery(params.user as UserDocument)); + const findById = jest.fn().mockReturnValue({ + select: jest.fn().mockReturnValue({ + lean: jest.fn().mockReturnValue(makeQuery(params.community ?? {})), + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (name: string) => { + if (name === 'user') return { findOneAndUpdate }; + if (name === 'community') return { findById }; + throw new Error(`Unexpected model: ${name}`); + }), + } as unknown as ConnectionService; + const riotAccountService = { + getByRiotId: jest.fn(), + ...params.riotAccountService, + } as unknown as RiotAccountService; + const enrichmentService = { + enrichRiotAccount: jest.fn(), + ...params.enrichmentService, + } as unknown as RiotAccountEnrichmentService; + + return { + service: new DakaoUserService( + connectionService, + riotAccountService, + enrichmentService, + ), + connectionService, + findOneAndUpdate, + findById, + riotAccountService, + enrichmentService, + }; +} + +describe('DakaoUserService', () => { + it('registers an additional Riot account when the user already has one', async () => { + const save = jest.fn().mockResolvedValue(undefined); + const existingAccount = { + puuid: 'puuid-1', + gameName: '기존소환사', + tagLine: 'KR1', + isPrimary: true, + } as RiotAccount; + const { + service, + connectionService, + riotAccountService, + enrichmentService, + } = makeService({ + user: { + _id: objectId('222222222222222222222222'), + riotAccounts: [existingAccount], + save, + } as Partial, + riotAccountService: { + getByRiotId: jest.fn().mockResolvedValue({ + puuid: 'puuid-2', + gameName: '새소환사', + tagLine: 'KR2', + }), + }, + enrichmentService: { + enrichRiotAccount: jest.fn().mockResolvedValue({ account: null }), + }, + }); + + const result = await service.registerRiotAccount({ + communityId: objectId('111111111111111111111111'), + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + gameName: '새소환사', + tagLine: 'KR2', + }); + + expect(result.riotAccount).toMatchObject({ + puuid: 'puuid-2', + gameName: '새소환사', + tagLine: 'KR2', + isPrimary: false, + }); + expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({ + puuid: 'puuid-1', + isPrimary: true, + }); + expect(result.user.riotAccounts).toHaveLength(2); + expect(connectionService.getModel).toHaveBeenCalledWith('user'); + expect(connectionService.getModel).toHaveBeenCalledWith('community'); + expect(riotAccountService.getByRiotId).toHaveBeenCalledWith( + '새소환사', + 'KR2', + { + region: 'asia', + }, + ); + expect(enrichmentService.enrichRiotAccount).toHaveBeenCalledWith( + expect.objectContaining({ + userId: expect.any(mongoose.Types.ObjectId), + puuid: 'puuid-2', + options: { force: true, platform: 'kr', region: 'asia' }, + }), + ); + expect(save).toHaveBeenCalled(); + }); + + it('reuses an already attached Riot account by puuid', async () => { + const save = jest.fn().mockResolvedValue(undefined); + const existingAccount = { + puuid: 'puuid-1', + gameName: '기존소환사', + tagLine: 'KR1', + isPrimary: true, + } as RiotAccount; + const { service, enrichmentService } = makeService({ + user: { + _id: objectId('222222222222222222222222'), + riotAccounts: [existingAccount], + save, + } as Partial, + riotAccountService: { + getByRiotId: jest.fn().mockResolvedValue({ + puuid: 'puuid-1', + gameName: '바뀐소환사', + tagLine: 'KR1', + }), + }, + }); + + const result = await service.registerRiotAccount({ + communityId: objectId('111111111111111111111111'), + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + gameName: '바뀐소환사', + tagLine: 'KR1', + }); + + expect(result.user.riotAccounts).toHaveLength(1); + expect(result.riotAccount).toMatchObject({ + puuid: 'puuid-1', + gameName: '바뀐소환사', + tagLine: 'KR1', + isPrimary: true, + }); + expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled(); + expect(save).toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/modules/dakao/dakao-user.service.ts b/apps/api/src/modules/dakao/dakao-user.service.ts new file mode 100644 index 00000000..2ffb22c4 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao-user.service.ts @@ -0,0 +1,428 @@ +import { Injectable, Logger } from '@nestjs/common'; +import mongoose, { isValidObjectId } from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + Position, + PositionPreference, + RiotAccount, + UserDocument, +} from '../global/database/schema'; +import { RiotApiError } from '../riot/riot.client.service'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { RiotAccountService } from '../riot/riot-account.service'; +import { + RIOT_PLATFORM_ROUTES, + RIOT_REGIONAL_ROUTES, + RiotPlatformRoute, + RiotRegionalRoute, +} from '../riot/riot.types'; +import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util'; + +export class DakaoUserError extends Error { + constructor( + public readonly code: + | 'invalid_project_id' + | 'community_not_found' + | 'riot_account_not_found' + | 'riot_account_already_registered' + | 'riot_account_conflict' + | 'riot_account_lookup_failed', + public readonly detail?: string, + ) { + super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`); + } +} + +interface ResolveContext { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + kakaoTalkNickname: string; + gameName: string; + tagLine: string; +} + +interface ResolveResult { + user: UserDocument; + riotAccount: RiotAccount; +} + +interface RiotRouting { + platform: RiotPlatformRoute; + region: RiotRegionalRoute; +} + +interface ResolvedRiotIdentity { + requestedGameName: string; + requestedTagLine: string; + dto: { puuid: string; gameName: string | null; tagLine: string | null }; +} + +const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr'; +const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia'; + +@Injectable() +export class DakaoUserService { + private readonly logger = new Logger(DakaoUserService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly riotAccountService: RiotAccountService, + private readonly enrichmentService: RiotAccountEnrichmentService, + ) {} + + public async resolveCommunityIdByDakaoProjectId( + dakaoProjectId: string, + ): Promise { + if (!isValidObjectId(dakaoProjectId)) { + throw new DakaoUserError('invalid_project_id', dakaoProjectId); + } + + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findOne({ + dakaoProjectId: dakaoProjectId, + }) + .select({ _id: 1 }) + .lean() + .exec(); + if (!community) { + throw new DakaoUserError('community_not_found', dakaoProjectId); + } + return community._id as mongoose.Types.ObjectId; + } + + public async upsertUser(params: { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + kakaoTalkNickname: string; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findOneAndUpdate( + { communityId: params.communityId, kakaoTalkId: params.kakaoTalkId }, + { + $set: { kakaoTalkNickname: params.kakaoTalkNickname }, + $setOnInsert: { + communityId: params.communityId, + kakaoTalkId: params.kakaoTalkId, + role: 'member', + isActivated: true, + }, + }, + { upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }, + ).exec(); + if (!user) { + // upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드. + throw new DakaoUserError('community_not_found'); + } + return user; + } + + public async findUserByKakaoTalkId(params: { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + return UserModel.findOne({ + communityId: params.communityId, + kakaoTalkId: params.kakaoTalkId, + }).exec(); + } + + public async resolveRiotAccount( + context: ResolveContext, + ): Promise { + const user = await this.upsertUser(context); + const routing = await this.resolveRiotRouting(context.communityId); + const { requestedGameName, requestedTagLine, dto } = + await this.lookupRiotIdentity(context, routing); + const nextGameName = dto.gameName ?? requestedGameName; + const nextTagLine = dto.tagLine ?? requestedTagLine; + + const existing = user.riotAccounts.find( + (a) => + a.gameName.toLowerCase() === requestedGameName.toLowerCase() && + a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(), + ); + if (existing) { + this.logger.log( + `Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`, + ); + } + + if (existing) { + if (existing.puuid !== dto.puuid) { + this.logger.warn( + `Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`, + ); + existing.puuid = dto.puuid; + existing.gameName = nextGameName; + existing.tagLine = nextTagLine; + this.clearRiotCache(existing); + await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine); + return this.enrichAttachedAccount({ + user, + riotAccount: existing, + platform: routing.platform, + region: routing.region, + }); + } + + if ( + existing.gameName !== nextGameName || + existing.tagLine !== nextTagLine + ) { + existing.gameName = nextGameName; + existing.tagLine = nextTagLine; + await user.save(); + } + return { user, riotAccount: existing }; + } + + const existingByPuuid = user.riotAccounts.find( + (account) => account.puuid === dto.puuid, + ); + if (existingByPuuid) { + if ( + existingByPuuid.gameName !== nextGameName || + existingByPuuid.tagLine !== nextTagLine + ) { + existingByPuuid.gameName = nextGameName; + existingByPuuid.tagLine = nextTagLine; + await user.save(); + } + return { user, riotAccount: existingByPuuid }; + } + + return this.attachRiotAccount({ + user, + puuid: dto.puuid, + gameName: nextGameName, + tagLine: nextTagLine, + platform: routing.platform, + region: routing.region, + }); + } + + public async registerRiotAccount( + context: ResolveContext, + ): Promise { + return this.resolveRiotAccount(context); + } + + public async registerPrimaryRiotAccount( + context: ResolveContext, + ): Promise { + return this.registerRiotAccount(context); + } + + public async registerPreferredPositions(params: { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + kakaoTalkNickname: string; + positions: Position[]; + }): Promise { + const user = await this.upsertUser({ + communityId: params.communityId, + kakaoTalkId: params.kakaoTalkId, + kakaoTalkNickname: params.kakaoTalkNickname, + }); + user.preferredPositions = this.toPositionPreferences(params.positions); + await user.save(); + return user; + } + + private toPositionPreferences(positions: Position[]): PositionPreference[] { + return positions.map((position, index) => ({ + position, + priority: index + 1, + })); + } + + private async lookupRiotIdentity( + context: ResolveContext, + routing: RiotRouting, + ): Promise { + const requestedGameName = normalizeRiotIdPart(context.gameName); + const requestedTagLine = normalizeRiotIdPart(context.tagLine); + this.logRiotIdNormalization(context, requestedGameName, requestedTagLine); + + try { + const dto = await this.riotAccountService.getByRiotId( + requestedGameName, + requestedTagLine, + { region: routing.region }, + ); + this.logger.log( + `Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`, + ); + return { requestedGameName, requestedTagLine, dto }; + } catch (err) { + if (err instanceof RiotApiError && err.status === 404) { + throw new DakaoUserError( + 'riot_account_not_found', + `${requestedGameName}#${requestedTagLine}`, + ); + } + this.logger.error( + `Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${ + (err as Error)?.message ?? err + }`, + ); + throw new DakaoUserError( + 'riot_account_lookup_failed', + (err as Error)?.message, + ); + } + } + + private logRiotIdNormalization( + context: ResolveContext, + normalizedGameName: string, + normalizedTagLine: string, + ): void { + if ( + context.gameName === normalizedGameName && + context.tagLine === normalizedTagLine + ) { + return; + } + + this.logger.warn( + `Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` + + `(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`, + ); + } + + private async resolveRiotRouting( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId) + .select({ riotPlatform: 1, riotRegion: 1 }) + .lean() + .exec(); + + return { + platform: this.toRiotPlatform(community?.riotPlatform), + region: this.toRiotRegion(community?.riotRegion), + }; + } + + private async attachRiotAccount(params: { + user: UserDocument; + puuid: string; + gameName: string; + tagLine: string; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): Promise { + const { user } = params; + const isFirst = user.riotAccounts.length === 0; + user.riotAccounts.push({ + puuid: params.puuid, + gameName: params.gameName, + tagLine: params.tagLine, + profileIconId: 0, + revisionDate: 0, + summonerLevel: 0, + isPrimary: isFirst, + tiers: [], + tierHistory: [], + matchIds: [], + championMasteries: [], + championRecords: {}, + } as unknown as RiotAccount); + + await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine); + + const attached = user.riotAccounts.find((a) => a.puuid === params.puuid); + if (!attached) { + throw new DakaoUserError('riot_account_lookup_failed', 'attach failed'); + } + + return this.enrichAttachedAccount({ + user, + riotAccount: attached, + platform: params.platform, + region: params.region, + }); + } + + private async enrichAttachedAccount(params: { + user: UserDocument; + riotAccount: RiotAccount; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): Promise { + // 외부 API 실패는 등록 자체를 막지 않음. + try { + const enrichResult = await this.enrichmentService.enrichRiotAccount({ + userId: params.user._id, + puuid: params.riotAccount.puuid, + options: { + force: true, + platform: params.platform, + region: params.region, + }, + }); + if (enrichResult.account) { + return { user: params.user, riotAccount: enrichResult.account }; + } + } catch (err) { + this.logger.warn( + `Riot enrichment failed (continuing with empty data): ${ + (err as Error)?.message ?? err + }`, + ); + } + return { user: params.user, riotAccount: params.riotAccount }; + } + + private async saveUserHandlingDuplicate( + user: UserDocument, + gameName: string, + tagLine: string, + ): Promise { + try { + await user.save(); + } catch (err) { + // 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스. + if ((err as { code?: number })?.code === 11000) { + throw new DakaoUserError( + 'riot_account_conflict', + `${gameName}#${tagLine}`, + ); + } + throw err; + } + } + + private clearRiotCache(account: RiotAccount): void { + account.profileIconId = 0; + account.revisionDate = 0; + account.summonerLevel = 0; + account.tiers = []; + account.tierHistory = []; + account.matchIds = []; + account.matchIdsFetchedAt = undefined; + account.recentStatsSummary = undefined; + account.recentStatsFetchedAt = undefined; + account.championMasteries = []; + account.championMasteriesFetchedAt = undefined; + account.championRecords = {}; + account.championRecordsFetchedAt = undefined; + } + + private toRiotPlatform(value: unknown): RiotPlatformRoute { + return typeof value === 'string' && + RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute) + ? (value as RiotPlatformRoute) + : DEFAULT_RIOT_PLATFORM; + } + + private toRiotRegion(value: unknown): RiotRegionalRoute { + return typeof value === 'string' && + RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute) + ? (value as RiotRegionalRoute) + : DEFAULT_RIOT_REGION; + } +} diff --git a/apps/api/src/modules/dakao/dakao.module.ts b/apps/api/src/modules/dakao/dakao.module.ts new file mode 100644 index 00000000..4ffe65d7 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.module.ts @@ -0,0 +1,37 @@ +import { Module } from '@nestjs/common'; +import { MatchModule } from '../match/match.module'; +import { RiotModule } from '../riot/riot.module'; +import { + DAKAO_OPTIONS, + createDefaultDakaoOptions, +} from './dakao.options'; +import { DakaoPublisher } from './dakao.publisher'; +import { DakaoSubscriber } from './dakao.subscriber'; +import { DakaoUserService } from './dakao-user.service'; +import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; +import { MatchCancelHandler } from './handlers/match-cancel.handler'; +import { MatchJoinHandler } from './handlers/match-join.handler'; +import { MatchListHandler } from './handlers/match-list.handler'; +import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler'; + +@Module({ + imports: [RiotModule, MatchModule], + providers: [ + { + provide: DAKAO_OPTIONS, + useFactory: createDefaultDakaoOptions, + }, + DakaoPublisher, + DakaoSubscriber, + DakaoUserService, + IdempotencyCache, + AccountRegisterHandler, + MatchListHandler, + MatchJoinHandler, + MatchCancelHandler, + PreferredPositionRegisterHandler, + ], + exports: [DakaoPublisher], +}) +export class DakaoModule {} diff --git a/apps/api/src/modules/dakao/dakao.options.ts b/apps/api/src/modules/dakao/dakao.options.ts new file mode 100644 index 00000000..98d724c4 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.options.ts @@ -0,0 +1,13 @@ +import { randomUUID } from 'crypto'; + +export const DAKAO_OPTIONS = Symbol('DAKAO_OPTIONS'); + +export interface DakaoOptions { + instanceId: string; +} + +export function createDefaultDakaoOptions(): DakaoOptions { + return { + instanceId: process.env.DAKAO_INSTANCE_ID || randomUUID(), + }; +} diff --git a/apps/api/src/modules/dakao/dakao.publisher.spec.ts b/apps/api/src/modules/dakao/dakao.publisher.spec.ts new file mode 100644 index 00000000..abc0e676 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.publisher.spec.ts @@ -0,0 +1,73 @@ +import { SecretService } from '../global/secret/secret.service'; +import { NatsService } from '../global/nats/nats.service'; +import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types'; +import { DakaoPublisher } from './dakao.publisher'; + +function makePublisher() { + const natsService = { + publish: jest.fn().mockResolvedValue(undefined), + subscribe: jest.fn(), + } as unknown as NatsService; + const secretService = {} as SecretService; + const publisher = new DakaoPublisher(natsService, secretService, { + instanceId: 'test', + }); + + return { publisher, natsService }; +} + +function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload { + const publish = natsService.publish as jest.Mock; + const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope< + DakaoSendMessagePayload + >; + return envelope.payload; +} + +describe('DakaoPublisher', () => { + it('keeps valid mention segments intact', async () => { + const { publisher, natsService } = makePublisher(); + + await publisher.sendMessage({ + chatroomId: '18474390111480678', + segments: [ + { + kind: 'mention', + userId: '6215844374579825921', + displayText: '날으는꼴뚜기/95/여/D', + }, + { kind: 'text', text: ' 신청 완료' }, + ], + }); + + expect(getPublishedPayload(natsService).segments).toEqual([ + { + kind: 'mention', + userId: '6215844374579825921', + displayText: '날으는꼴뚜기/95/여/D', + }, + { kind: 'text', text: ' 신청 완료' }, + ]); + }); + + it('downgrades invalid mention segments to text before publishing', async () => { + const { publisher, natsService } = makePublisher(); + + await publisher.sendMessage({ + chatroomId: '18474390111480678', + segments: [ + { + kind: 'mention', + userId: '-123', + displayText: '소쿠리', + }, + { kind: 'text', text: ' 신청 완료' }, + ], + }); + + expect(getPublishedPayload(natsService).segments).toEqual([ + { kind: 'text', text: '@소쿠리' }, + { kind: 'text', text: ' 신청 완료' }, + ]); + }); +}); diff --git a/apps/api/src/modules/dakao/dakao.publisher.ts b/apps/api/src/modules/dakao/dakao.publisher.ts new file mode 100644 index 00000000..21d49c99 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.publisher.ts @@ -0,0 +1,154 @@ +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import { SecretService } from '../global/secret/secret.service'; +import { NatsService } from '../global/nats/nats.service'; +import { + DakaoCommandEnvelope, + DakaoResultEnvelope, + DakaoSegment, + DakaoSendMessagePayload, +} from './dakao.types'; +import type { DakaoOptions } from './dakao.options'; +import { DAKAO_OPTIONS } from './dakao.options'; + +const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1'; +const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support'; + +@Injectable() +export class DakaoPublisher implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(DakaoPublisher.name); + private replySubject = ''; + private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT; + private source = COMMAND_SOURCE_DEFAULT; + + constructor( + private readonly natsService: NatsService, + private readonly secretService: SecretService, + @Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions, + ) {} + + async onModuleInit() { + const replyOverride = await this.secretService + .get('DAKAO_REPLY_SUBJECT_PREFIX') + .catch(() => undefined); + const sendOverride = await this.secretService + .get('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT') + .catch(() => undefined); + const sourceOverride = await this.secretService + .get('DAKAO_COMMAND_SOURCE') + .catch(() => undefined); + + const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`; + this.replySubject = `${replyPrefix}.${this.options.instanceId}`; + this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT; + this.source = sourceOverride || COMMAND_SOURCE_DEFAULT; + + this.natsService.subscribe( + this.replySubject, + (data) => this.handleReply(data), + ); + this.logger.log( + `Dakao reply subscriber ready on subject="${this.replySubject}"`, + ); + } + + async onModuleDestroy() { + // NatsService 가 subscription 정리한다. + } + + public async sendMessage(params: { + chatroomId: string; + segments: DakaoSegment[]; + correlationId?: string; + }): Promise { + const payload: DakaoSendMessagePayload = { + chatroomId: params.chatroomId, + segments: this.normalizeSegments(params.segments), + }; + const envelope: DakaoCommandEnvelope = { + schema: 'dakao.command.v1', + id: randomUUID(), + type: 'chat.send-message', + source: this.source, + correlationId: params.correlationId, + replySubject: this.replySubject, + payload, + }; + await this.natsService.publish(this.sendMessageSubject, envelope); + } + + private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] { + const normalized: DakaoSegment[] = []; + + for (const segment of segments) { + if (segment.kind === 'text') { + if (segment.text.length > 0) normalized.push(segment); + continue; + } + + if (segment.kind === 'mention') { + const userId = segment.userId.trim(); + const displayText = segment.displayText.trim(); + + if (this.isPositiveIntegerString(userId) && displayText.length > 0) { + normalized.push({ kind: 'mention', userId, displayText }); + continue; + } + + const fallbackText = this.renderMentionFallback(displayText, userId); + this.logger.warn( + `Dakao mention downgraded to text because userId/displayText is invalid: userId="${userId || '-'}" displayText="${displayText || '-'}"`, + ); + normalized.push({ kind: 'text', text: fallbackText }); + continue; + } + + const id = segment.id.trim(); + const altText = segment.altText.trim(); + if ( + id.length > 0 && + altText.length > 0 && + !/[()@]/.test(altText) + ) { + normalized.push({ kind: 'emoticon', id, altText }); + continue; + } + + this.logger.warn( + `Dakao emoticon downgraded to text because id/altText is invalid: id="${id || '-'}" altText="${altText || '-'}"`, + ); + normalized.push({ kind: 'text', text: `(${altText || '이모티콘'})` }); + } + + return normalized.length > 0 + ? normalized + : [{ kind: 'text', text: '명령 처리 결과를 보낼 수 없습니다.' }]; + } + + private isPositiveIntegerString(value: string): boolean { + return /^[1-9]\d*$/.test(value); + } + + private renderMentionFallback(displayText: string, userId: string): string { + const label = displayText || userId || '사용자'; + return label.startsWith('@') ? label : `@${label}`; + } + + private handleReply(reply: DakaoResultEnvelope): void { + if (reply.status === 'succeeded') { + this.logger.log( + `Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`, + ); + return; + } + this.logger.warn( + `Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`, + ); + } +} diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts new file mode 100644 index 00000000..258fff2e --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -0,0 +1,230 @@ +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { NatsService } from '../global/nats/nats.service'; +import { SecretService } from '../global/secret/secret.service'; +import { CommandParseError, parseCommand } from './parsers/command.parser'; +import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types'; +import { DakaoPublisher } from './dakao.publisher'; +import { DakaoUserError, DakaoUserService } from './dakao-user.service'; +import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; +import { MatchCancelHandler } from './handlers/match-cancel.handler'; +import { MatchJoinHandler } from './handlers/match-join.handler'; +import { MatchListHandler } from './handlers/match-list.handler'; +import { PreferredPositionRegisterHandler } from './handlers/preferred-position-register.handler'; + +const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command'; + +@Injectable() +export class DakaoSubscriber implements OnModuleInit { + private readonly logger = new Logger(DakaoSubscriber.name); + private inboundSubject = INBOUND_SUBJECT_DEFAULT; + private botUserId: string | undefined; + + constructor( + private readonly natsService: NatsService, + private readonly secretService: SecretService, + private readonly dakaoUserService: DakaoUserService, + private readonly publisher: DakaoPublisher, + private readonly idempotency: IdempotencyCache, + private readonly accountRegisterHandler: AccountRegisterHandler, + private readonly matchListHandler: MatchListHandler, + private readonly matchJoinHandler: MatchJoinHandler, + private readonly matchCancelHandler: MatchCancelHandler, + private readonly preferredPositionRegisterHandler: PreferredPositionRegisterHandler, + ) {} + + async onModuleInit() { + const subjectOverride = await this.secretService + .get('DAKAO_INBOUND_SUBJECT') + .catch(() => undefined); + this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT; + + this.botUserId = await this.secretService + .get('DAKAO_BOT_USER_ID') + .catch(() => undefined); + + this.natsService.subscribe( + this.inboundSubject, + (event) => this.handleEvent(event), + ); + this.logger.log( + `Dakao inbound subscriber ready on subject="${this.inboundSubject}"`, + ); + } + + private async handleEvent(event: DakaoInboundEvent): Promise { + if (!this.validate(event)) return; + + if (this.botUserId && event.userId === this.botUserId) { + return; + } + + const logIdKey = this.deriveLogIdKey(event); + if (logIdKey && this.idempotency.has(logIdKey)) { + return; + } + if (logIdKey) this.idempotency.remember(logIdKey); + + let communityId: mongoose.Types.ObjectId; + try { + communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId( + event.projectId, + ); + } catch (err) { + if (err instanceof DakaoUserError) { + if (err.code === 'invalid_project_id') { + this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`); + return; + } + if (err.code === 'community_not_found') { + // 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만. + this.logger.warn(`Unknown dakao projectId: ${event.projectId}`); + return; + } + } + throw err; + } + + let segments: DakaoSegment[]; + const senderNickname = this.resolveSenderNickname(event); + const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId); + try { + const command = parseCommand(event.origin.chatLog.message); + + switch (command.kind) { + case 'match-list': + segments = await this.matchListHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + }); + break; + case 'account-register': + segments = await this.accountRegisterHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + gameName: command.gameName, + tagLine: command.tagLine, + }); + break; + case 'match-join': + segments = await this.matchJoinHandler.handle({ + communityId, + matchAndRiotId: command.matchAndRiotId, + senderUserId: event.userId, + senderNickname, + positions: command.positions?.positions, + }); + break; + case 'preferred-position-register': + segments = await this.preferredPositionRegisterHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + positions: command.positions.positions, + }); + break; + case 'match-cancel': + segments = await this.matchCancelHandler.handle({ + communityId, + matchId: command.matchId, + senderUserId: event.userId, + senderNickname, + }); + break; + } + + await this.publisher.sendMessage({ + chatroomId: event.chatroomId, + segments, + correlationId, + }); + } catch (err) { + if (err instanceof CommandParseError) { + // not_a_command 는 명령이 아닌 일반 메시지 → 무시. + if (err.code === 'not_a_command') return; + await this.publisher.sendMessage({ + chatroomId: event.chatroomId, + segments: this.parseErrorReply(event, senderNickname, err), + correlationId, + }); + return; + } + this.logger.error( + `Unhandled dakao event error: ${(err as Error)?.stack ?? err}`, + ); + } + } + + private validate(event: unknown): event is DakaoInboundEvent { + if (!event || typeof event !== 'object') return false; + const e = event as Partial; + if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false; + if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0) + return false; + if (typeof e.nickname !== 'string') return false; + if (typeof e.userId !== 'string' || e.userId.length === 0) return false; + if (!e.origin || typeof e.origin !== 'object') return false; + const chatLog = (e.origin as { chatLog?: unknown }).chatLog; + if (!chatLog || typeof chatLog !== 'object') return false; + if (typeof (chatLog as { message?: unknown }).message !== 'string') + return false; + return true; + } + + private deriveLogIdKey(event: DakaoInboundEvent): string | null { + const serialized = this.serializeDakaoLong(event.origin.chatLog.logId); + return serialized ? `${event.projectId}:${serialized}` : null; + } + + private serializeDakaoLong(value: DakaoLong | string | undefined): string { + if (typeof value === 'string') return value; + if (!value || typeof value !== 'object') return ''; + const high = BigInt(value.high ?? 0); + const low = BigInt.asUintN(32, BigInt(value.low ?? 0)); + const combined = (high << 32n) | low; + return value.unsigned + ? BigInt.asUintN(64, combined).toString() + : BigInt.asIntN(64, combined).toString(); + } + + private resolveSenderNickname(event: DakaoInboundEvent): string { + const primary = event.nickname?.trim(); + if (primary) return primary; + const fallback = event.origin.authorNickname?.trim(); + return fallback ?? ''; + } + + private parseErrorReply( + event: DakaoInboundEvent, + senderNickname: string, + err: CommandParseError, + ): DakaoSegment[] { + const head: DakaoSegment[] = [ + { + kind: 'mention', + userId: event.userId, + displayText: senderNickname, + }, + ]; + const text = ((): string => { + switch (err.code) { + case 'unknown_command': + return ` 알 수 없는 명령어입니다. 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`; + case 'usage': + return ` 사용법: !내전 일정, !내전 계정등록 <게임명>#<태그>, !내전 선호포지션등록 미드,정글, !내전 신청 [코드] [게임명#태그] [포지션1,포지션2], !내전 취소 <코드>`; + case 'invalid_match_id': + return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; + case 'invalid_riot_id': + return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`; + case 'invalid_position': + return ` 포지션 입력이 올바르지 않습니다. 쉼표로 구분해서 최소 2개를 중복 없이 입력해주세요. 사용 가능: 탑, 정글, 미드, 원딜, 서폿`; + default: + return ` 명령을 처리할 수 없습니다.`; + } + })(); + return [...head, { kind: 'text', text }]; + } +} diff --git a/apps/api/src/modules/dakao/dakao.types.ts b/apps/api/src/modules/dakao/dakao.types.ts new file mode 100644 index 00000000..554b3bed --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.types.ts @@ -0,0 +1,102 @@ +// dakao NATS contracts +// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트 +// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령 +// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과 + +// ===== Inbound ===== +export interface DakaoLong { + high?: number; + low?: number; + unsigned?: boolean; +} + +export interface DakaoOriginChatLog { + logId: DakaoLong | string; + chatId: DakaoLong | string; + authorId: DakaoLong | string; + type: number; + sendAt: number; + message: string; + prevId?: DakaoLong | string; + msgId?: number; + revision?: number; + scope?: number; +} + +export interface DakaoOrigin { + chatId: DakaoLong | string; + logId: DakaoLong | string; + authorNickname?: string; + chatLog: DakaoOriginChatLog; + noSeen?: boolean; + notiRead?: boolean; + li?: number; + status?: number; +} + +export interface DakaoInboundEvent { + projectId: string; + chatroomId: string; + nickname: string; + userId: string; + origin: DakaoOrigin; +} + +// ===== Outbound: chat.send-message ===== +export interface DakaoTextSegment { + kind: 'text'; + text: string; +} + +export interface DakaoMentionSegment { + kind: 'mention'; + userId: string; + displayText: string; +} + +export interface DakaoEmoticonSegment { + kind: 'emoticon'; + id: string; + altText: string; +} + +export type DakaoSegment = + | DakaoTextSegment + | DakaoMentionSegment + | DakaoEmoticonSegment; + +export interface DakaoSendMessagePayload { + chatroomId: string; + segments: DakaoSegment[]; + attachment?: string | Record; + type?: number; + noSeen?: boolean; + scope?: number; + silence?: boolean; +} + +export interface DakaoCommandEnvelope { + schema: 'dakao.command.v1'; + id: string; + type: string; + source: string; + correlationId?: string; + replySubject?: string; + payload: TPayload; +} + +// ===== Reply ===== +export interface DakaoResultEnvelope { + schema: 'dakao.result.v1'; + id: string; + type: string; + status: 'succeeded' | 'failed'; + handledAt: string; + correlationId?: string; + result?: Record; + error?: { + code: string; + message: string; + retryable: boolean; + }; +} diff --git a/apps/api/src/modules/dakao/idempotency.cache.ts b/apps/api/src/modules/dakao/idempotency.cache.ts new file mode 100644 index 00000000..01dffeca --- /dev/null +++ b/apps/api/src/modules/dakao/idempotency.cache.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@nestjs/common'; + +const TTL_MS = 5 * 60 * 1000; +const MAX_ENTRIES = 5000; + +@Injectable() +export class IdempotencyCache { + private readonly entries = new Map(); + + public has(key: string): boolean { + const expiresAt = this.entries.get(key); + if (expiresAt === undefined) return false; + if (expiresAt < Date.now()) { + this.entries.delete(key); + return false; + } + return true; + } + + public remember(key: string): void { + this.evictExpired(); + if (this.entries.size >= MAX_ENTRIES) { + const oldestKey = this.entries.keys().next().value; + if (oldestKey !== undefined) this.entries.delete(oldestKey); + } + this.entries.set(key, Date.now() + TTL_MS); + } + + private evictExpired(): void { + const now = Date.now(); + for (const [key, expiresAt] of this.entries) { + if (expiresAt < now) this.entries.delete(key); + } + } +} diff --git a/apps/api/src/modules/dakao/riot-id.util.ts b/apps/api/src/modules/dakao/riot-id.util.ts new file mode 100644 index 00000000..2a54240b --- /dev/null +++ b/apps/api/src/modules/dakao/riot-id.util.ts @@ -0,0 +1,14 @@ +const ZERO_WIDTH_CHARACTERS = /[\u200B-\u200D\uFEFF]/g; + +export function normalizeRiotIdPart(value: string): string { + return value.replace(ZERO_WIDTH_CHARACTERS, '').trim().normalize('NFC'); +} + +export function formatCodePoints(value: string): string { + return Array.from(value) + .map((char) => { + const codePoint = char.codePointAt(0); + return `U+${codePoint?.toString(16).toUpperCase().padStart(4, '0')}`; + }) + .join(' '); +}