feat(api): add Dakao integration

This commit is contained in:
dahyeon committed 2026-04-28 22:37:00 +09:00
1 parent 9ebdc9b61f
commit ba3894cba2
10 files changed
+1257

No files matched your search

@@ -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<string>('DAKAO_REPLY_SUBJECT_PREFIX')
.catch(() => undefined);
const sendOverride = await this.secretService
.get<string>('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT')
.catch(() => undefined);
const sourceOverride = await this.secretService
.get<string>('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<DakaoResultEnvelope>(
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<void> {
const payload: DakaoSendMessagePayload = {
chatroomId: params.chatroomId,
segments: this.normalizeSegments(params.segments),
};
const envelope: DakaoCommandEnvelope<DakaoSendMessagePayload> = {
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 ?? '-'}`,
);
}
}