This commit is contained in:
dahyeon committed 2026-04-25 11:49:21 -07:00
1 parent 5af2c80cd1
commit f7ee34da4f
78 files changed
+9016 -150

No files matched your search

@@ -0,0 +1,186 @@
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, DakaoSegment } from './dakao.types';
import { DakaoPublisher } from './dakao.publisher';
import { DakaoUserError, DakaoUserService } from './dakao-user.service';
import { IdempotencyCache } from './idempotency.cache';
import { MatchJoinHandler } from './handlers/match-join.handler';
import { MatchListHandler } from './handlers/match-list.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 matchListHandler: MatchListHandler,
private readonly matchJoinHandler: MatchJoinHandler,
) {}
async onModuleInit() {
const subjectOverride = await this.secretService
.get<string>('DAKAO_INBOUND_SUBJECT')
.catch(() => undefined);
this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT;
this.botUserId = await this.secretService
.get<string>('DAKAO_BOT_USER_ID')
.catch(() => undefined);
this.natsService.subscribe<DakaoInboundEvent>(
this.inboundSubject,
(event) => this.handleEvent(event),
);
this.logger.log(
`Dakao inbound subscriber ready on subject="${this.inboundSubject}"`,
);
}
private async handleEvent(event: DakaoInboundEvent): Promise<void> {
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[];
try {
const command = parseCommand(event.origin.chatLog.message);
const correlationId = String(event.origin.chatLog.logId ?? '');
switch (command.kind) {
case 'match-list':
segments = await this.matchListHandler.handle({
communityId,
senderUserId: event.userId,
senderNickname: event.nickname,
});
break;
case 'match-join':
segments = await this.matchJoinHandler.handle({
communityId,
matchId: command.matchId,
senderUserId: event.userId,
senderNickname: event.nickname,
gameName: command.gameName,
tagLine: command.tagLine,
positions: command.positions.positions,
});
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, err),
correlationId: String(event.origin.chatLog.logId ?? ''),
});
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<DakaoInboundEvent>;
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 logId = event.origin.chatLog.logId;
if (typeof logId === 'string') return `${event.projectId}:${logId}`;
if (logId && typeof logId === 'object') {
const { high, low, unsigned } = logId;
return `${event.projectId}:${high ?? ''}|${low ?? ''}|${unsigned ?? ''}`;
}
return null;
}
private parseErrorReply(
event: DakaoInboundEvent,
err: CommandParseError,
): DakaoSegment[] {
const head: DakaoSegment[] = [
{
kind: 'mention',
userId: event.userId,
displayText: event.nickname,
},
];
const text = ((): string => {
switch (err.code) {
case 'unknown_command':
return ` 알 수 없는 명령어입니다. 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션1>,<포지션2>`;
case 'usage':
return ` 사용법: !내전 목록 또는 !내전 신청 <ID> <게임명>#<태그> <포지션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 }];
}
}