feat: add messaging transport rollout

This commit is contained in:
2026-06-06 00:02:52 +09:00
parent 4b91343ee8
commit 6c7a1cf6f6
383 changed files with 99045 additions and 487 deletions
+102 -18
View File
@@ -4,7 +4,7 @@
- Baseline Seed: .stage-pilot/bootstrap/baseline.yaml
- Status: draft
- Owner: project maintainers
- Last Updated (KST): 2026-06-04 (BAT-006)
- Last Updated (KST): 2026-06-05 (BAT-007)
- Source Discovery / Batch: bootstrap-baseline (pre-Discovery); HTTP API = dcy-002 / BAT-002
- Primary Runtime: daemon (HTTP API) + library (slot 도메인)
@@ -25,33 +25,86 @@
## Interface Summary
- HTTP `/v1` API :: 슬롯 코어 데몬이 노출, 매수·매도 전략 데몬이 호출(REQ-005/007/008)
- RabbitMQ `trex.snapshot.req` :: 전략 모듈의 스냅샷 RPC (request-reply, BAT-007)
- RabbitMQ `trex.intent.req` :: 전략 모듈의 매수/매도 admission RPC (request-reply, BAT-007)
- RabbitMQ `trex.events` :: 체결/슬롯 상태 이벤트 topic exchange (pub/sub, BAT-007)
- SlotService :: 슬롯 생명주기 도메인 서비스(전이/사전할당/가용성/재진입 카운트)
- SlotRepository (Protocol) :: 도메인 ↔ 저장소 경계 계약
- BrokerPort (Protocol) :: 단일 브로커 세션 경계(submit/poll/cancel) + `OrderRequest`/`OrderAck`/`FillStatus`
- LedgerPort (Protocol) :: 외부 원장(portfolio-hub) 기록 경계 + `LedgerTrade`/`LedgerWriteResult`/예외 (BAT-006)
- LedgerOutbox (Protocol) + LedgerWriter :: 체결 → 원장 기록의 outbox/재시도/멱등 (BAT-006)
- MessagingTransport (Protocol) :: RabbitMQ / InMemory stub transport 경계 + `TransportHealth` enum (BAT-007)
## Interface: `HTTP /v1` (슬롯 코어 데몬)
> BAT-007 에서 HTTP `/v1` API 표면이 0 으로 제거됨(REQ-025). 이전 baseline 의 `HTTP /v1` 인터페이스 섹션은 더 이상 유효하지 않으며 본 인터페이스 인덱스에서 제거되었다. 전략-facing 통신은 위의 3 RabbitMQ 표면이 전부다.
- Type: http-api
- Consumers / Producers: 매수·매도 전략 데몬(클라이언트) → trex-core 슬롯 코어 데몬(서버). FastAPI+uvicorn.
- Purpose: 전략이 intent 를 제출하고 holding 스냅샷/capacity 를 조회. 코어가 단독 admission + 슬롯 전이(단일 writer).
- Stability: experimental (v1, 슬라이스 1)
## Interface: `RabbitMQ messaging` (전략 모듈 ↔ trex-core, BAT-007)
| 엔드포인트 | 입력 | 출력 | 에러/거부 |
- Type: amqp-messaging
- Consumers / Producers: trex-core daemon ↔ 전략 모듈(외부 소비자). RabbitMQ broker(`TREX_RABBITMQ_URL`) 가 transport.
- Purpose: HTTP `/v1` API 를 대체하는 메시지 기반 통신. 코어가 단독 admission + 슬롯 전이(단일 writer 불변식 A) 를 유지.
- Stability: experimental (BAT-007)
### Topology
| 종류 | 이름 | 타입/속성 | 용도 |
|---|---|---|---|
| `GET /v1/healthz` | — | `{status:"ok"}` 200 | — |
| `POST /v1/intents/buy` | intent_id, trading_date, symbol, qty?, allocated_capital?, entry_price?, strategy_id?, sell_strategy_id?, portfolio_id?, forced_close_at? | `{intent_id, status:admitted|rejected, slot_id?, reason?}` | reject: `no_idle_slot`, `idle_slot_contended` |
| `POST /v1/intents/sell` | intent_id, slot_id, reason?, sell_strategy_id? | `{intent_id, status, slot_id?, reason?}` | reject: `slot_not_found`, `slot_not_holding:<state>`, `slot_state_changed` |
| `GET /v1/intents/{intent_id}` | path intent_id | `{intent_id, status, slot_id?, reason?}` | 404 intent not found |
| `GET /v1/slots?status=&trading_date=` | query | `[SlotSnapshot]` | — |
| `GET /v1/capacity?trading_date=&total_slots=` | query | `{idle_count, holding_count, pending_count, total_slots, scarcity_ratio}` | — |
| 큐 | `trex.snapshot.req` | durable | 스냅샷 RPC 요청 큐 (read-only) |
| 큐 | `trex.intent.req` | durable, `x-dead-letter-exchange=trex.events.dlq` | intent admission RPC 요청 큐 |
| 익스체인지 | `trex.events` | topic, durable | 체결/슬롯 상태 이벤트 발행 |
| 익스체인지 | `trex.events.dlq` | fanout, durable | 처리 실패/unroutable 메시지 격리 |
| 큐 | `trex.events.dlq` | durable | DLQ 수집기 큐 (`trex.events.dlq` 익스체인지 바인딩) |
| 큐 (전략별) | `trex.events.strategy.{strategy_id}` | durable, `x-message-ttl=3.6e6`, `x-max-length=10000`, `x-overflow=drop-head` | 전략 모듈별 이벤트 수신 큐 (`*.{strategy_id}.#` 바인딩) |
### Compatibility / Invariants
- 멱등: `intent_id` dedup(intent_log UNIQUE gate). at-least-once 재전송에도 슬롯 1회만 전이; 재조회는 `GET /v1/intents/{id}`.
- 단일 writer: 모든 슬롯 쓰기는 코어의 SlotService(advisory lock)만. 전략은 제안만, 슬롯/브로커 직접 접근 금지.
- 동기 커밋: 수락 시 admission+전이를 동기 커밋 후 admit/reject 응답(완전 비동기 outbox 는 브로커 Discovery Deferred).
### Patterns
| 패턴 | 표면 | 요청 속성 | 응답 |
|---|---|---|---|
| 스냅샷 RPC | `trex.snapshot.req` | `correlation_id`, `reply_to=amq.rabbitmq.reply-to` | reply-to 큐로 `{view, strategy_id, trading_date, slots[], capacity{}}` |
| intent RPC | `trex.intent.req` | `correlation_id` = intent 멱등키, `reply_to=amq.rabbitmq.reply-to`, `delivery_mode=2` | reply-to 큐로 `{intent_id, status:admitted|rejected, slot_id?, reason?}`. 체결/종료는 응답 아닌 이벤트로 |
| 이벤트 pub/sub | `trex.events` (topic) | routing key `{event_type}.{strategy_id}.{symbol}` | 전략 큐가 자기 `strategy_id` 패턴으로 바인딩 |
### Message contracts
#### `trex.snapshot.req` 요청 payload
```
{ "view": "open" | "all", "strategy_id": str | null, "trading_date": "YYYY-MM-DD" }
```
응답 payload는 슬롯 목록과 capacity 를 운반한다. view 모드와 strategy_id 는 payload(요청 매핑 원칙 — REQ-021).
#### `trex.intent.req` 요청 payload (buy)
```
{ "intent_type": "buy",
"intent_id": "<correlation_id 와 동일>",
"trading_date": "YYYY-MM-DD",
"symbol": str, "qty": float?, "allocated_capital": float?,
"entry_price": float?, "strategy_id": str?, "sell_strategy_id": str?,
"portfolio_id": str?, "forced_close_at": "ISO-8601"? }
```
sell payload 는 `{"intent_type":"sell", "intent_id":..., "slot_id":..., "reason":..., "sell_strategy_id":...}`.
#### `trex.events` payload (BAT-007)
```
{ "event_type": "slot_filled_buy"|"slot_filled_sell"|...,
"slot_id": str, "strategy_id": str?, "symbol": str?,
"status": "<SlotState 값>", "qty": float?, "avg_price": float?,
"portfolio_id": str?, "trading_date": "YYYY-MM-DD",
"sequence_at": "ISO-8601" }
```
- `sequence_at` = 슬롯 `updated_at` 의 단조 증가 토큰. 수신자는 last-wins 적용 가능 → 순서 보증 불요.
- 이벤트의 `strategy_id`/`symbol` 은 routing key 에, 본문에도 함께 운반(이벤트 매핑 원칙 — REQ-021).
### Reliability rules (REQ-023)
- intent RPC: durable + persistent + manual ack-after-commit + `intent_log` correlation_id dedup. 단일 consumer + prefetch=1 → FIFO.
- 스냅샷 RPC: read-only, manual ack, 별도 dedup 불요.
- 이벤트: publisher confirms 활성, unroutable → DLQ. 페이로드는 현재 상태 + 단조 시퀀스(last-wins).
- per-strategy 이벤트 queue: TTL/max-length 초과 시 `drop-head` + 스냅샷 RPC reconcile 로 보정.
### Degrade (REQ-024)
- 어댑터 `TransportHealth` ∈ {connected, disconnected, reconnecting}. 어플리케이션 레이어는 disconnected 상태에서 `TransportUnavailableError` 로 빠르게 실패한다(버퍼링 0, 보수적 중단).
- 재연결은 백오프 1s→2s→4s→8s→16s→30s cap, 어댑터가 자체 구현.
- core 자율 안전 매도는 transport 와 무관하게 동작해야 한다(architecture contract; 자동 트리거 구현은 별도 Discovery).
## Interface: `SlotService`
@@ -193,6 +246,36 @@
- `fee :: float` :: BrokerPort `calculate_fee` 결과(기본 0).
- `tax :: float` :: 기본 0(정밀 모델 후속).
## Interface: `MessagingTransport` (Protocol, BAT-007)
- Type: internal-service (transport boundary)
- Consumers / Producers: 데몬 런타임(소비) ↔ 구현체(`RabbitMQTransport` 운영용 / `InMemoryTransport` 결정론 stub)
- Purpose: 메시지 transport 추상화. 도메인은 transport/AMQP 의존 0(NFR-1).
- Stability: experimental (BAT-007)
### Inputs
- declare_topology() :: 익스체인지/큐/바인딩 선언(멱등)
- publish_event(routing_key, payload, mandatory=True) :: `trex.events` 발행. publisher confirms; unroutable → DLQ
- call_rpc(queue, payload, *, correlation_id, timeout) :: 클라이언트 RPC (직접 reply-to 큐 대기)
- consume_rpc_forever(queue, handler, stop) :: 서버측 RPC 소비 루프(stop 까지 블로킹, 백오프 재연결)
- consume_events_forever(queue, binding_pattern, handler, stop) :: 이벤트 구독 루프
### Outputs / Outcomes
- `health() -> TransportHealth` :: `connected | disconnected | reconnecting`
- DLQ 라우팅 :: 처리 실패/unroutable 메시지는 `trex.events.dlq` exchange/queue 로 격리
### Error Contract
- `TransportUnavailableError` :: connected 가 아닌 상태에서 `publish_event`/`call_rpc` 호출 시 즉시 실패(REQ-024 — 로컬 버퍼링 금지)
- `RpcTimeoutError` :: 설정된 timeout 안에 reply 없음
### Compatibility Rules
- pika BlockingConnection 은 thread-safe 가 아니므로 consumer/publisher 마다 자기 connection/channel 을 가져야 한다.
- 토폴로지 선언은 멱등하지만 attribute(durable, args) 가 기존 큐와 다르면 RabbitMQ 가 PRECONDITION_FAILED 로 거부 → batch 마이그레이션 시 큐 재선언 절차 필요.
## Shared Constraints
- 도메인은 외부 의존(브로커, DB 드라이버 등)을 직접 호출하지 않는다(순수 도메인 경계).
@@ -216,3 +299,4 @@
- 2026-06-03 :: BAT-002 — HTTP `/v1` API 계약(데몬, 6 엔드포인트) + 멱등/단일writer 불변식 추가(REQ-007/008/009).
- 2026-06-04 :: BAT-004 — 브로커 집행 레이어 반영(BrokerPort/paper·KIS 어댑터, execution 루프, broker_order_id 실행큐·멱등, reconciliation) (REQ-011~015).
- 2026-06-04 :: BAT-006 — LedgerPort/LedgerTrade/LedgerWriteResult 계약, LedgerOutbox/LedgerWriter, portfolio-hub `/v1/assets/{asset_id}/ledger/trades` 엔드포인트 + 409→`LedgerConflictError`, FillStatus.execution_id/fee/tax 확장 (REQ-017~020).
- 2026-06-05 :: BAT-007 — HTTP `/v1` API 인터페이스 제거(adapters/api + fastapi/uvicorn 의존 정리), RabbitMQ messaging 계약 추가(스냅샷 RPC `trex.snapshot.req`, intent RPC `trex.intent.req`, 이벤트 topic `trex.events`, 전략별 durable queue + TTL/max-length, DLQ, publisher confirms, ack-after-commit), `MessagingTransport` Protocol + `TransportHealth` 노출 (REQ-021~026).