Skip to main content

nidus_rabbitmq/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3
4//! First-party RabbitMQ integration for Nidus.
5//!
6//! The provider exposes native Lapin connections and channels. Convenience
7//! publishing enables publisher confirms and persistent messages, but consumer
8//! acknowledgements, exchanges, queues, bindings, dead-letter exchanges, and
9//! recovery topology remain explicit RabbitMQ capabilities.
10
11use std::{
12    fmt,
13    sync::{
14        Arc,
15        atomic::{AtomicBool, Ordering},
16    },
17    time::{Duration, Instant},
18};
19
20use async_trait::async_trait;
21use lapin::{
22    BasicProperties, Channel, Confirmation, Connection, ConnectionProperties,
23    options::{BasicPublishOptions, BasicQosOptions, ConfirmSelectOptions},
24};
25use nidus_core::{Container, LifecycleHook, NidusError};
26use nidus_integrations::{
27    IntegrationEvent, IntegrationStatus, IntegrationTelemetry, MessageEnvelope,
28};
29use serde::Serialize;
30use thiserror::Error;
31use tokio::sync::{Semaphore, SemaphorePermit};
32
33const MAX_IN_FLIGHT_PUBLISHES: usize = 65_536;
34
35/// Result type for RabbitMQ adapter operations.
36pub type Result<T> = std::result::Result<T, RabbitMqError>;
37
38/// RabbitMQ adapter error preserving native Lapin failures.
39#[derive(Debug, Error)]
40pub enum RabbitMqError {
41    /// Lapin returned an AMQP or connection error.
42    #[error(transparent)]
43    Lapin(#[from] lapin::Error),
44    /// RabbitMQ negatively acknowledged a published message.
45    #[error("RabbitMQ negatively acknowledged the publication")]
46    NegativeAcknowledgement,
47    /// RabbitMQ returned an unroutable mandatory publication.
48    #[error("RabbitMQ returned an unroutable mandatory publication")]
49    Unroutable,
50    /// Publisher confirms were unexpectedly not active.
51    #[error("RabbitMQ publisher confirms were not active")]
52    ConfirmationNotRequested,
53    /// Shared envelope serialization failed.
54    #[error(transparent)]
55    Integration(#[from] nidus_integrations::IntegrationError),
56    /// Nidus provider registration failed.
57    #[error(transparent)]
58    Nidus(#[from] NidusError),
59    /// Adapter configuration was unsafe or incomplete.
60    #[error("invalid RabbitMQ configuration: {message}")]
61    Configuration {
62        /// Redaction-safe validation message.
63        message: &'static str,
64    },
65    /// The bounded provider was closed during an operation.
66    #[error("RabbitMQ provider is shutting down")]
67    ShuttingDown,
68    /// Operations or native close handshakes exceeded the shutdown deadline.
69    #[error("RabbitMQ shutdown exceeded its configured timeout")]
70    ShutdownTimeout,
71}
72
73/// Typed RabbitMQ connection and backpressure configuration.
74#[derive(Clone, Eq, PartialEq)]
75pub struct RabbitMqConfig {
76    uri: String,
77    consumer_prefetch: u16,
78    max_in_flight_publishes: usize,
79    shutdown_timeout: Duration,
80    allow_plaintext_local: bool,
81}
82
83impl RabbitMqConfig {
84    /// Creates TLS-first RabbitMQ configuration with publisher and consumer bounds.
85    pub fn new(uri: impl Into<String>) -> Self {
86        Self {
87            uri: uri.into(),
88            consumer_prefetch: 64,
89            max_in_flight_publishes: 256,
90            shutdown_timeout: Duration::from_secs(10),
91            allow_plaintext_local: false,
92        }
93    }
94
95    /// Sets the native channel prefetch applied to the initial channel.
96    pub fn with_consumer_prefetch(mut self, value: u16) -> Self {
97        self.consumer_prefetch = value;
98        self
99    }
100
101    /// Sets the maximum concurrent provider-owned publications.
102    pub fn with_max_in_flight_publishes(mut self, value: usize) -> Self {
103        self.max_in_flight_publishes = value;
104        self
105    }
106
107    /// Sets the total graceful shutdown deadline.
108    pub fn with_shutdown_timeout(mut self, value: Duration) -> Self {
109        self.shutdown_timeout = value;
110        self
111    }
112
113    /// Explicitly permits `amqp://` for local development and tests.
114    pub fn allow_plaintext_for_local_development(mut self) -> Self {
115        self.allow_plaintext_local = true;
116        self
117    }
118
119    /// Returns the AMQP URI.
120    pub fn uri(&self) -> &str {
121        &self.uri
122    }
123
124    /// Validates TLS and backpressure bounds before network I/O.
125    pub fn validate(&self) -> Result<()> {
126        if self.uri.trim().is_empty() {
127            return Err(RabbitMqError::Configuration {
128                message: "RabbitMQ URI cannot be empty",
129            });
130        }
131        if self.consumer_prefetch == 0
132            || self.max_in_flight_publishes == 0
133            || self.max_in_flight_publishes > MAX_IN_FLIGHT_PUBLISHES
134            || self.shutdown_timeout.is_zero()
135        {
136            return Err(RabbitMqError::Configuration {
137                message: "RabbitMQ prefetch, publish concurrency, or shutdown timeout is invalid",
138            });
139        }
140        if self.uri.starts_with("amqp://") && !self.allow_plaintext_local {
141            return Err(RabbitMqError::Configuration {
142                message: "plaintext RabbitMQ requires an explicit local-development opt-in",
143            });
144        }
145        if self.uri.starts_with("amqp://") && !rabbitmq_url_is_loopback(&self.uri) {
146            return Err(RabbitMqError::Configuration {
147                message: "plaintext RabbitMQ is restricted to loopback servers",
148            });
149        }
150        if !self.uri.starts_with("amqps://") && !self.uri.starts_with("amqp://") {
151            return Err(RabbitMqError::Configuration {
152                message: "RabbitMQ URIs must use amqps:// or explicit loopback amqp://",
153            });
154        }
155        Ok(())
156    }
157}
158
159fn rabbitmq_url_is_loopback(uri: &str) -> bool {
160    url::Url::parse(uri).ok().is_some_and(|url| {
161        url.scheme() == "amqp"
162            && match url.host() {
163                Some(url::Host::Domain(host)) => {
164                    host.eq_ignore_ascii_case("localhost")
165                        || host
166                            .parse::<std::net::IpAddr>()
167                            .is_ok_and(|address| address.is_loopback())
168                }
169                Some(url::Host::Ipv4(host)) => host.is_loopback(),
170                Some(url::Host::Ipv6(host)) => host.is_loopback(),
171                None => false,
172            }
173    })
174}
175
176impl fmt::Debug for RabbitMqConfig {
177    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
178        formatter
179            .debug_struct("RabbitMqConfig")
180            .field("uri", &"<redacted>")
181            .field("consumer_prefetch", &self.consumer_prefetch)
182            .field("max_in_flight_publishes", &self.max_in_flight_publishes)
183            .field("shutdown_timeout", &self.shutdown_timeout)
184            .field("allow_plaintext_local", &self.allow_plaintext_local)
185            .finish()
186    }
187}
188
189/// Builder for a RabbitMQ provider.
190#[derive(Clone, Debug)]
191pub struct RabbitMqProviderBuilder {
192    config: RabbitMqConfig,
193    telemetry: IntegrationTelemetry,
194}
195
196impl RabbitMqProviderBuilder {
197    /// Creates a provider builder.
198    pub fn new(config: RabbitMqConfig) -> Self {
199        Self {
200            config,
201            telemetry: IntegrationTelemetry::new(),
202        }
203    }
204
205    /// Adds shared tracing, metrics, dashboard, or custom telemetry.
206    pub fn telemetry(mut self, telemetry: IntegrationTelemetry) -> Self {
207        self.telemetry = telemetry;
208        self
209    }
210
211    /// Connects with automatic topology recovery and publisher confirms.
212    pub async fn connect(self) -> Result<RabbitMqProvider> {
213        self.config.validate()?;
214        let started_at = Instant::now();
215        let connection = Connection::connect(
216            &self.config.uri,
217            ConnectionProperties::default().enable_auto_recover(),
218        )
219        .await;
220        self.telemetry
221            .record(&IntegrationEvent::new(
222                "nidus-rabbitmq",
223                "connect",
224                if connection.is_ok() {
225                    IntegrationStatus::Success
226                } else {
227                    IntegrationStatus::Failure
228                },
229                started_at.elapsed(),
230            ))
231            .await;
232        let connection = Arc::new(connection?);
233        let channel = connection.create_channel().await?;
234        channel
235            .confirm_select(ConfirmSelectOptions::default())
236            .await?;
237        channel
238            .basic_qos(self.config.consumer_prefetch, BasicQosOptions::default())
239            .await?;
240        Ok(RabbitMqProvider {
241            connection,
242            channel,
243            in_flight: Arc::new(Semaphore::new(self.config.max_in_flight_publishes)),
244            max_in_flight: self.config.max_in_flight_publishes as u32,
245            shutting_down: Arc::new(AtomicBool::new(false)),
246            shutdown_complete: Arc::new(AtomicBool::new(false)),
247            config: self.config,
248            telemetry: self.telemetry,
249        })
250    }
251
252    /// Connects and registers the provider as a Nidus singleton.
253    pub async fn register(self, container: &mut Container) -> Result<()> {
254        container.register_singleton(self.connect().await?)?;
255        Ok(())
256    }
257}
258
259/// Nidus provider exposing native Lapin connection and channel capabilities.
260#[derive(Clone)]
261pub struct RabbitMqProvider {
262    config: RabbitMqConfig,
263    connection: Arc<Connection>,
264    channel: Channel,
265    in_flight: Arc<Semaphore>,
266    max_in_flight: u32,
267    shutting_down: Arc<AtomicBool>,
268    shutdown_complete: Arc<AtomicBool>,
269    telemetry: IntegrationTelemetry,
270}
271
272impl RabbitMqProvider {
273    /// Creates a RabbitMQ provider builder.
274    pub fn builder(config: RabbitMqConfig) -> RabbitMqProviderBuilder {
275        RabbitMqProviderBuilder::new(config)
276    }
277
278    /// Returns the native Lapin connection.
279    pub fn connection(&self) -> &Connection {
280        &self.connection
281    }
282
283    /// Returns the native publisher-confirm channel.
284    pub fn channel(&self) -> &Channel {
285        &self.channel
286    }
287
288    /// Creates an additional native channel for broker-specific topology or consumers.
289    pub async fn create_channel(&self) -> Result<Channel> {
290        Ok(self.connection.create_channel().await?)
291    }
292
293    /// Publishes a persistent mandatory message and waits for broker confirmation.
294    pub async fn publish(
295        &self,
296        exchange: &str,
297        routing_key: &str,
298        payload: &[u8],
299        properties: BasicProperties,
300    ) -> Result<()> {
301        if routing_key.trim().is_empty() {
302            return Err(RabbitMqError::Configuration {
303                message: "RabbitMQ routing_key cannot be empty",
304            });
305        }
306        let _permit = self.acquire_permit().await?;
307        let started_at = Instant::now();
308        let outcome = async {
309            let confirmation = self
310                .channel
311                .basic_publish(
312                    exchange.into(),
313                    routing_key.into(),
314                    BasicPublishOptions {
315                        mandatory: true,
316                        ..Default::default()
317                    },
318                    payload,
319                    properties.with_delivery_mode(2),
320                )
321                .await?
322                .await?;
323            match confirmation {
324                Confirmation::Ack(None) => Ok(()),
325                Confirmation::Ack(Some(_)) => Err(RabbitMqError::Unroutable),
326                Confirmation::Nack(_) => Err(RabbitMqError::NegativeAcknowledgement),
327                Confirmation::NotRequested => Err(RabbitMqError::ConfirmationNotRequested),
328            }
329        }
330        .await;
331        self.record("publish", outcome.is_ok(), started_at).await;
332        outcome
333    }
334
335    /// Publishes a persistent JSON envelope and waits for broker confirmation.
336    pub async fn publish_envelope<T>(
337        &self,
338        exchange: &str,
339        routing_key: &str,
340        envelope: &MessageEnvelope<T>,
341    ) -> Result<()>
342    where
343        T: Serialize,
344    {
345        let properties = BasicProperties::default()
346            .with_content_type("application/json".into())
347            .with_message_id(envelope.id().into())
348            .with_type(envelope.name().into());
349        self.publish(exchange, routing_key, &envelope.to_json()?, properties)
350            .await
351    }
352
353    /// Closes the publisher channel and connection gracefully.
354    pub async fn shutdown(&self) -> Result<()> {
355        if self.shutdown_complete.load(Ordering::Acquire) {
356            return Ok(());
357        }
358        self.shutting_down.store(true, Ordering::Release);
359        let started_at = Instant::now();
360        let result = match tokio::time::timeout(self.config.shutdown_timeout, async {
361            let drained = self
362                .in_flight
363                .acquire_many(self.max_in_flight)
364                .await
365                .map_err(|_| RabbitMqError::ShuttingDown)?;
366            if self.channel.status().connected() {
367                self.channel.close(200, "Nidus shutdown".into()).await?;
368            }
369            if self.connection.status().connected() {
370                self.connection.close(200, "Nidus shutdown".into()).await?;
371            }
372            drop(drained);
373            Ok(())
374        })
375        .await
376        {
377            Ok(result) => result,
378            Err(_) => Err(RabbitMqError::ShutdownTimeout),
379        };
380        self.record("shutdown", result.is_ok(), started_at).await;
381        if result.is_ok() {
382            self.shutdown_complete.store(true, Ordering::Release);
383            self.in_flight.close();
384        }
385        result
386    }
387
388    /// Reports native connection and channel readiness.
389    #[cfg(feature = "health")]
390    pub async fn health_status(&self) -> nidus_http::health::HealthStatus {
391        let started_at = Instant::now();
392        let healthy = !self.shutting_down.load(Ordering::Acquire)
393            && self.connection.status().connected()
394            && !self.connection.status().blocked()
395            && self.channel.status().connected();
396        self.record("health", healthy, started_at).await;
397        if healthy {
398            nidus_http::health::HealthStatus::up()
399        } else {
400            nidus_http::health::HealthStatus::down("rabbitmq connection is not ready")
401        }
402    }
403
404    /// Adds this provider as a readiness check on a health registry.
405    #[cfg(feature = "health")]
406    pub fn register_ready_check(
407        self: Arc<Self>,
408        registry: nidus_http::health::HealthRegistry,
409        name: impl Into<String>,
410    ) -> nidus_http::health::HealthRegistry {
411        registry.ready_check(name, move || {
412            let provider = Arc::clone(&self);
413            async move { provider.health_status().await }
414        })
415    }
416
417    async fn acquire_permit(&self) -> Result<SemaphorePermit<'_>> {
418        if self.shutting_down.load(Ordering::Acquire) {
419            return Err(RabbitMqError::ShuttingDown);
420        }
421        let permit = self
422            .in_flight
423            .acquire()
424            .await
425            .map_err(|_| RabbitMqError::ShuttingDown)?;
426        if self.shutting_down.load(Ordering::Acquire) {
427            return Err(RabbitMqError::ShuttingDown);
428        }
429        Ok(permit)
430    }
431
432    async fn record(&self, operation: &'static str, success: bool, started_at: Instant) {
433        self.telemetry
434            .record(&IntegrationEvent::new(
435                "nidus-rabbitmq",
436                operation,
437                if success {
438                    IntegrationStatus::Success
439                } else {
440                    IntegrationStatus::Failure
441                },
442                started_at.elapsed(),
443            ))
444            .await;
445    }
446}
447
448impl fmt::Debug for RabbitMqProvider {
449    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
450        formatter
451            .debug_struct("RabbitMqProvider")
452            .field("config", &self.config)
453            .field("connected", &self.connection.status().connected())
454            .field("channel_connected", &self.channel.status().connected())
455            .field("shutting_down", &self.shutting_down.load(Ordering::Acquire))
456            .field("available_permits", &self.in_flight.available_permits())
457            .field("telemetry", &self.telemetry)
458            .finish()
459    }
460}
461
462#[async_trait]
463impl LifecycleHook for RabbitMqProvider {
464    async fn on_shutdown(&self) -> nidus_core::Result<()> {
465        self.shutdown()
466            .await
467            .map_err(|_| NidusError::ApplicationBuild {
468                message: "RabbitMQ shutdown failed".to_owned(),
469            })
470    }
471}