Files
lolympus-tournament-support/DAKAO_NATS_API_COMMAND.md
T
2026-04-25 11:49:21 -07:00

16 KiB

Dakao NATS Command API

dakao는 NATS를 통해 외부 시스템으로부터 command를 받아 LOCO 세션에 반영할 수 있다. 현재 구현 기준으로 지원하는 command는 아래 2종이다.

  • chat.send-text 기존 API. text와 extra를 그대로 받아 전송한다. 점진적으로 deprecated 예정.
  • chat.send-message 신규 권장 API. segments 기반으로 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송한다. builder를 거치면서 semantic validation까지 수행한다.

개요

기본 subject

용도 기본 subject 비고
레거시 텍스트 전송 dakao.command.chat.send-text.v1 deprecated 예정
신규 메시지 전송 dakao.command.chat.send-message.v1 권장

관련 환경변수

키 의미
DAKAO_NATS_COMMANDS_ENABLED 1이면 command consumer 활성화
DAKAO_NATS_COMMAND_CHAT_SEND_TEXT_SUBJECT 레거시 subject override
DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT 신규 subject override

전송 포맷

  • NATS payload는 JSON object여야 한다.
  • 내부 구현은 JSON.stringify(...)로 publish하고, subscribe 시 JSON.parse(...)로 역직렬화한다.
  • 응답은 NATS의 transport-level reply가 아니라, command object 내부의 replySubject 필드를 사용해 별도 publish된다.

subject와 type의 관계

운영 규약상 아래처럼 맞춰서 보내는 것을 권장한다.

  • dakao.command.chat.send-text.v1 에는 type: "chat.send-text"
  • dakao.command.chat.send-message.v1 에는 type: "chat.send-message"

현재 구현은 두 subject를 모두 구독한 뒤 type으로 실제 처리를 분기한다. 즉 subject와 type이 어긋나도 처리될 수 있지만, 운영 혼선을 막기 위해 반드시 맞춰서 보내는 것을 권장한다.

공통 Envelope

모든 command는 아래 envelope를 사용한다.

{
  "schema": "dakao.command.v1",
  "id": "cmd-001",
  "type": "chat.send-message",
  "source": "my-service",
  "correlationId": "trace-001",
  "replySubject": "dakao.result.my-service",
  "payload": {}
}

공통 필드

필드 타입 필수 설명
schema string Y 현재는 반드시 dakao.command.v1
id string Y command 고유 ID
type string Y command 종류
source string Y producer 식별자
correlationId string N 추적용 상관관계 ID
replySubject string N 결과를 publish할 subject
payload object Y command 본문

공통 검증

  • 문자열 필드인 id, type, source, correlationId, replySubject는 trim 후 빈 문자열이면 거부된다.
  • 최상위 object와 payload는 정의되지 않은 필드를 허용하지 않는다.
  • replySubject가 없으면 처리 결과는 publish되지 않는다.

Command: chat.send-text

상태

  • 레거시 API
  • 기존 producer 호환성을 위해 유지 중
  • text와 extra를 그대로 전달하므로, 멘션/이모티콘 semantic validation은 수행하지 않는다

권장 subject

dakao.command.chat.send-text.v1

Payload

{
  "chatroomId": "123456789012345678",
  "text": "hello",
  "attachment": {
    "example": true
  },
  "extra": "{}"
}
필드 타입 필수 설명
chatroomId string Y 채팅방 ID. 실운영에서는 decimal string 사용 권장
text string Y 보낼 메시지 본문
attachment string or object N 첨부 payload. object면 전송 직전에 JSON string으로 변환
extra string N LOCO WRITE.extra raw 값

동작

  • 내부적으로 client.sendMessage(chatroomId, text, { attachment, extra }) 로 전송한다.
  • extra를 생략하면 최종 LOCO 전송 시 기본값 "{}" 가 사용된다.
  • 이 API는 extra 구조를 검증하지 않는다.

예시

{
  "schema": "dakao.command.v1",
  "id": "cmd-text-001",
  "type": "chat.send-text",
  "source": "admin-panel",
  "replySubject": "dakao.result.admin-panel",
  "payload": {
    "chatroomId": "123456789012345678",
    "text": "plain text message",
    "extra": "{}"
  }
}

Command: chat.send-message

상태

  • 신규 권장 API
  • 텍스트, 멘션, 카카오톡 이모티콘을 조합해서 전송할 수 있다
  • buildLocoMessage(...) 를 통해 최종 text와 extra를 생성한다
  • Joi schema validation 이후 builder semantic validation이 한 번 더 수행된다

권장 subject

dakao.command.chat.send-message.v1

Payload

{
  "chatroomId": "123456789012345678",
  "segments": [
    { "kind": "text", "text": "안녕하세요 " },
    {
      "kind": "mention",
      "userId": "6215844374579825921",
      "displayText": "날으는꼴뚜기/95/여/D"
    },
    { "kind": "text", "text": " " },
    { "kind": "emoticon", "id": "1200281_004", "altText": "플라워" }
  ],
  "attachment": {
    "example": true
  },
  "type": 1,
  "noSeen": false,
  "scope": 1,
  "silence": false
}
필드 타입 필수 설명
chatroomId string Y 채팅방 ID. 실운영에서는 decimal string 사용 권장
segments array Y 메시지 세그먼트 배열. 최소 1개 이상
attachment string or object N 첨부 payload. object면 전송 직전에 JSON string으로 변환
type integer N LOCO WRITE.type. 기본값 1
noSeen boolean N LOCO WRITE.noSeen. 기본값 false
scope integer N LOCO WRITE.scope. 기본값 1
silence boolean N LOCO WRITE.silence. 기본값 false

Segment 종류

text

{ "kind": "text", "text": "안녕하세요 " }
필드 타입 필수 설명
kind string Y 반드시 text
text string Y 일반 텍스트. 빈 문자열은 허용되지 않음

mention

{
  "kind": "mention",
  "userId": "6215844374579825921",
  "displayText": "날으는꼴뚜기/95/여/D"
}
필드 타입 필수 설명
kind string Y 반드시 mention
userId string Y 양의 정수 문자열 권장. int64 손실 방지를 위해 문자열 사용
displayText string Y 화면에 표시될 이름. builder가 앞의 @를 자동 정리

멘션은 최종 메시지에서 아래처럼 렌더링된다.

@{displayText}

예를 들어 displayText: "홍길동" 이면 @홍길동 으로 전송된다. displayText를 @홍길동처럼 보내도 builder가 앞의 @ 하나를 제거한 뒤 다시 렌더링한다.

emoticon

{
  "kind": "emoticon",
  "id": "1200281_004",
  "altText": "플라워"
}
필드 타입 필수 설명
kind string Y 반드시 emoticon
id string Y 카카오톡 이모티콘 item ID
altText string Y 대체 텍스트. builder가 괄호를 자동 정리

이모티콘은 최종 메시지에서 아래처럼 렌더링된다.

({altText})

예를 들어 altText: "플라워" 이면 (플라워) 로 전송된다. altText를 (플라워)처럼 보내도 builder가 바깥 괄호를 제거한 뒤 다시 렌더링한다.

Builder semantic validation

chat.send-message는 schema validation 외에 아래 규칙도 검사한다.

공통

  • 최종적으로 만들어진 메시지 전체 텍스트는 비어 있으면 안 된다
  • segments가 모두 비어 있거나 렌더링 결과가 빈 문자열이면 거부된다

mention 규칙

  • userId는 양의 정수여야 한다
  • producer에서는 숫자 대신 문자열 사용을 권장한다
  • displayText는 비어 있으면 안 된다
  • 같은 userId를 여러 번 멘션하면 extra.mentions[].at 배열로 합쳐진다
  • 같은 userId를 서로 다른 길이의 displayText로 섞어 보내면 거부된다

emoticon 규칙

  • id는 trim 후 비어 있으면 안 된다
  • altText는 trim 후 비어 있으면 안 된다
  • altText 내부에는 @, (, ) 문자가 들어가면 안 된다
  • 같은 (id, 렌더링 길이) 조합의 이모티콘은 extra.emojis.items[].at 배열로 합쳐진다

extra 생성 규칙

producer가 extra를 직접 만들지 않는다. builder가 최종 텍스트를 기준으로 아래 구조를 자동 생성한다.

{
  "mentions": [
    {
      "user_id": 6215844374579825921,
      "at": [1],
      "len": 13
    }
  ],
  "emojis": {
    "total_item": 1,
    "total_len": 5,
    "items": [
      {
        "id": "1200281_004",
        "len": 5,
        "at": [1]
      }
    ]
  }
}

주의:

  • mentions[].at 는 메시지 안의 @ anchor 순번이다
  • emojis.items[].at 는 메시지 안의 ( anchor 순번이다
  • len 은 렌더링된 문자열 길이 기준이다
  • total_item 은 이모티콘 총 출현 횟수다
  • total_len 은 각 이모티콘 렌더링 길이의 합이다

예시: 추천 전송

{
  "schema": "dakao.command.v1",
  "id": "cmd-msg-001",
  "type": "chat.send-message",
  "source": "admin-panel",
  "correlationId": "trace-20260417-001",
  "replySubject": "dakao.result.admin-panel",
  "payload": {
    "chatroomId": "123456789012345678",
    "segments": [
      { "kind": "text", "text": "😄 " },
      {
        "kind": "mention",
        "userId": "6215844374579825921",
        "displayText": "날으는꼴뚜기/95/여/D"
      },
      { "kind": "text", "text": "  " },
      { "kind": "emoticon", "id": "1200281_004", "altText": "플라워" },
      { "kind": "emoticon", "id": "1200281_003", "altText": "네잎클로버" }
    ],
    "type": 1,
    "noSeen": false,
    "scope": 1,
    "silence": false
  }
}

위 payload는 내부적으로 대략 아래 LOCO 메시지로 변환된다.

{
  "text": "😄 @날으는꼴뚜기/95/여/D  (플라워)(네잎클로버)",
  "extra": "{\"mentions\":[{\"user_id\":6215844374579825921,\"at\":[1],\"len\":13}],\"emojis\":{\"total_item\":2,\"total_len\":12,\"items\":[{\"id\":\"1200281_004\",\"len\":5,\"at\":[1]},{\"id\":\"1200281_003\",\"len\":7,\"at\":[2]}]}}"
}

Result API

응답이 필요한 경우 producer는 command에 replySubject를 포함해야 한다. consumer는 처리 후 replySubject로 결과 object를 publish한다.

공통 Result envelope

{
  "schema": "dakao.result.v1",
  "id": "cmd-msg-001",
  "type": "chat.send-message",
  "status": "succeeded",
  "handledAt": "2026-04-17T12:34:56.789Z",
  "correlationId": "trace-20260417-001",
  "result": {}
}

공통 필드

필드 타입 설명
schema string 현재는 반드시 dakao.result.v1
id string 원본 command ID
type string 원본 command type
status string succeeded 또는 failed
handledAt string ISO-8601 timestamp
correlationId string 원본 correlationId가 있으면 그대로 전달
result object 성공 시 포함
error object 실패 시 포함

Success result

chat.send-text와 chat.send-message의 성공 응답 구조는 동일하다.

{
  "schema": "dakao.result.v1",
  "id": "cmd-msg-001",
  "type": "chat.send-message",
  "status": "succeeded",
  "handledAt": "2026-04-17T12:34:56.789Z",
  "correlationId": "trace-20260417-001",
  "result": {
    "chatroomId": "123456789012345678",
    "messageLength": 31,
    "hasAttachment": true
  }
}
필드 타입 설명
chatroomId string 대상 채팅방 ID
messageLength number 실제 전송된 최종 메시지 길이
hasAttachment boolean attachment가 있으면 포함

Failure result

{
  "schema": "dakao.result.v1",
  "id": "cmd-msg-001",
  "type": "chat.send-message",
  "status": "failed",
  "handledAt": "2026-04-17T12:34:56.789Z",
  "correlationId": "trace-20260417-001",
  "error": {
    "code": "invalid_command",
    "message": "emoticon.altText must not contain '@', '(' or ')': \"(bad@text)\"",
    "retryable": false
  }
}
필드 타입 설명
code string 오류 코드
message string 사람이 읽을 수 있는 오류 메시지
retryable boolean 재시도 권장 여부

현재 사용되는 오류 코드

코드 retryable 의미
invalid_command false envelope/payload/schema/builder validation 실패
command_execution_failed true LOCO 전송 등 실행 단계 실패

응답 publish 조건

아래 조건이 모두 충족될 때만 실패 응답을 publish할 수 있다.

  • replySubject 존재
  • id 존재
  • type 존재

따라서 malformed payload를 보내더라도 replySubject가 없으면 실패 응답은 발행되지 않는다. producer가 처리 결과를 반드시 받아야 한다면 replySubject를 항상 넣는 것을 권장한다.

운영 권장사항

새 producer는 chat.send-message만 사용

권장 이유:

  • 멘션과 이모티콘을 구조적으로 표현할 수 있다
  • extra를 producer가 직접 조립하지 않아도 된다
  • semantic validation이 추가로 수행된다
  • 향후 레거시 chat.send-text 제거 시 마이그레이션 부담이 적다

chatroomId와 userId는 문자열 사용

  • userId는 int64 범위일 수 있으므로 JSON number 대신 string 사용을 권장한다
  • chatroomId도 실운영에서는 decimal string으로 통일하는 것이 안전하다

replySubject는 항상 지정

  • 성공/실패를 추적하려면 replySubject를 항상 넣는 것이 좋다
  • correlationId도 함께 넣어두면 producer 로그와 결과 로그를 쉽게 연결할 수 있다

send-text 사용 시 주의

  • extra 구조를 잘못 만들면 consumer 단계에서는 걸러지지 않는다
  • 멘션, 유니코드 이모지, 카카오톡 이모티콘 혼합 메시지는 send-message 사용을 권장한다

요약

  • 레거시: dakao.command.chat.send-text.v1 + type: "chat.send-text"
  • 권장: dakao.command.chat.send-message.v1 + type: "chat.send-message"
  • 결과 스키마는 공통으로 dakao.result.v1
  • 신규 API는 segments를 받아 builder 기반으로 text와 extra를 안전하게 생성한다