arcly_http/messaging/mod.rs
1//! Event consumer mesh — the inbound half of the event architecture.
2//!
3//! The transactional outbox (`data::outbox`) made *producing* events safe;
4//! this module gives *consuming* them the same framework-grade guarantees,
5//! with NestJS-style ergonomics:
6//!
7//! ```ignore
8//! pub struct OrderEventsConsumer;
9//!
10//! #[EventConsumer]
11//! impl OrderEventsConsumer {
12//! #[EventPattern("order.confirmed")]
13//! async fn on_confirmed(ctx: EventContext) -> Result<(), String> {
14//! let evt: OrderConfirmed = ctx.payload()?;
15//! ctx.inject::<InventoryService>().reserve(evt.order_id).await
16//! }
17//! }
18//! ```
19//!
20//! ## Guarantees
21//!
22//! - **Frozen dispatch** — `#[EventPattern]` handlers register through
23//! `inventory` (the same link-time mechanism as `#[Controller]`); the
24//! topic→handler map is built once at runtime start and never mutated.
25//! - **At-least-once + dedupe** — when an `IdempotencyStore` is in the DI
26//! container, each `idempotency_key` is consumed exactly once per TTL.
27//! - **Bounded retries → DLQ** — a failing message is `nack`ed and retried
28//! up to `max_retries`, then dead-lettered with the failure reason; one
29//! poison message can never wedge a topic.
30//! - **Trace continuity** — the envelope's `traceparent` (stamped by the
31//! outbox producer) becomes this hop's parent span; async hops chain in
32//! the trace UI instead of starting orphan roots.
33//!
34//! The transport (Kafka / AMQP / NATS / in-process bridge) is app-provided
35//! via [`MessageTransport`] — the same boundary rule as every other driver.
36
37pub mod event;
38pub mod runtime;
39
40pub use runtime::ConsumerRuntime;
41
42use futures::future::BoxFuture;
43
44use crate::core::engine::FrozenDiContainer;
45use crate::observability::propagation::TraceContext;
46
47// ─── Envelope ─────────────────────────────────────────────────────────────────
48
49/// One inbound message, transport-agnostic.
50#[derive(Clone, Debug)]
51pub struct InboundMessage {
52 pub topic: String,
53 pub payload: serde_json::Value,
54 /// Consumers dedupe on this under at-least-once delivery.
55 pub idempotency_key: String,
56 pub tenant: Option<String>,
57 /// W3C trace context stamped by the producer (outbox), if any.
58 pub traceparent: Option<String>,
59}
60
61// ─── Transport contract ───────────────────────────────────────────────────────
62
63/// App-provided broker adapter (Kafka / AMQP / NATS / in-process bridge).
64pub trait MessageTransport: Send + Sync + 'static {
65 /// Pull up to `max` messages. An empty Vec means "nothing right now".
66 fn poll(&self, max: usize) -> BoxFuture<'_, Result<Vec<InboundMessage>, String>>;
67 /// Acknowledge successful processing (message will not be redelivered).
68 fn ack<'a>(&'a self, msg: &'a InboundMessage) -> BoxFuture<'a, Result<(), String>>;
69 /// Negative-ack: requeue for a later retry.
70 fn nack<'a>(&'a self, msg: &'a InboundMessage) -> BoxFuture<'a, Result<(), String>>;
71 /// Park a poison message out of band, with the final failure reason.
72 fn dead_letter<'a>(
73 &'a self,
74 msg: &'a InboundMessage,
75 reason: &'a str,
76 ) -> BoxFuture<'a, Result<(), String>>;
77}
78
79// ─── Consumer-side context ────────────────────────────────────────────────────
80
81/// What an `#[EventPattern]` handler receives — DI + payload + trace, no
82/// HTTP types anywhere.
83pub struct EventContext {
84 pub message: InboundMessage,
85 pub container: &'static FrozenDiContainer,
86 /// Continues the producer's trace (or a fresh root when none was carried).
87 pub trace: TraceContext,
88 /// The envelope's tenant, resolved + validated against the same
89 /// `TenantRegistry` as HTTP traffic (suspended tenants never reach
90 /// handlers — their events are dead-lettered upstream).
91 pub tenant: Option<std::sync::Arc<crate::web::tenant::TenantConfig>>,
92}
93
94impl EventContext {
95 /// Resolve a singleton service. O(1), no locks. Panics when absent.
96 #[inline]
97 pub fn inject<T: Send + Sync + 'static>(&self) -> &'static T {
98 self.container.get::<T>()
99 }
100
101 /// Non-panicking variant of [`Self::inject`].
102 #[inline]
103 pub fn try_inject<T: Send + Sync + 'static>(&self) -> Option<&'static T> {
104 self.container.try_get::<T>()
105 }
106
107 /// Deserialize the payload into a typed event.
108 pub fn payload<T: serde::de::DeserializeOwned>(&self) -> Result<T, String> {
109 serde_json::from_value(self.message.payload.clone())
110 .map_err(|e| format!("payload decode failed: {e}"))
111 }
112
113 /// `traceparent` for forwarding to the next hop (HTTP call, next queue).
114 pub fn traceparent(&self) -> String {
115 self.trace.to_traceparent()
116 }
117}
118
119// ─── Typed handler errors ─────────────────────────────────────────────────────
120
121/// What the mesh should do with a failed message. Handlers may keep
122/// returning `Result<(), String>` (strings convert to [`EventError::Retry`])
123/// or return `EventError` directly to decide the message's fate:
124///
125/// ```ignore
126/// #[EventPattern("order.confirmed")]
127/// async fn on_confirmed(ctx: EventContext) -> Result<(), EventError> {
128/// let order: Order = ctx
129/// .payload()
130/// .map_err(EventError::DeadLetter)?; // malformed: retrying won't help
131/// warehouse.reserve(&order).await
132/// .map_err(|e| EventError::Retry(e.to_string())) // transient
133/// }
134/// ```
135#[derive(Debug)]
136pub enum EventError {
137 /// Transient failure (downstream 5xx, lock contention): nack → bounded
138 /// retries → dead-letter at `max_retries`.
139 Retry(String),
140 /// Permanent failure (malformed payload, violated business invariant):
141 /// dead-letter **immediately** — burning the retry budget on a poison
142 /// message only delays the alert.
143 DeadLetter(String),
144}
145
146impl From<String> for EventError {
147 fn from(s: String) -> Self {
148 Self::Retry(s)
149 }
150}
151impl From<&str> for EventError {
152 fn from(s: &str) -> Self {
153 Self::Retry(s.to_owned())
154 }
155}
156impl std::fmt::Display for EventError {
157 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158 match self {
159 Self::Retry(m) => write!(f, "retryable: {m}"),
160 Self::DeadLetter(m) => write!(f, "poison: {m}"),
161 }
162 }
163}
164impl std::error::Error for EventError {}
165
166// ─── Handler registration (filled in by #[EventConsumer]) ────────────────────
167
168/// Static descriptor emitted by the `#[EventPattern]` expansion and collected
169/// at link time — the runtime freezes these into its dispatch map at start.
170pub struct EventHandlerDescriptor {
171 pub topic: &'static str,
172 pub consumer: &'static str,
173 pub handler: fn(EventContext) -> BoxFuture<'static, Result<(), EventError>>,
174}
175
176inventory::collect!(&'static EventHandlerDescriptor);