Skip to main content

nidus_nats/
lib.rs

1#![forbid(unsafe_code)]
2#![deny(missing_docs)]
3
4//! First-party NATS and JetStream integration for Nidus.
5//!
6//! Core NATS and JetStream remain distinct native capabilities. Core publish
7//! followed by `flush` proves the server processed the protocol buffer; a
8//! JetStream publish additionally waits for its persistence acknowledgement.
9
10use std::{
11    fmt,
12    sync::{
13        Arc,
14        atomic::{AtomicBool, Ordering},
15    },
16    time::{Duration, Instant},
17};
18
19use async_trait::async_trait;
20use bytes::Bytes;
21use nidus_core::{Container, LifecycleHook, NidusError};
22use nidus_integrations::{
23    IntegrationEvent, IntegrationStatus, IntegrationTelemetry, MessageEnvelope,
24};
25use serde::Serialize;
26use thiserror::Error;
27use tokio::sync::{Semaphore, SemaphorePermit};
28
29const MAX_IN_FLIGHT: usize = 65_536;
30
31/// Result type for NATS adapter operations.
32pub type Result<T> = std::result::Result<T, NatsError>;
33
34/// NATS adapter error preserving native async-nats errors.
35#[derive(Debug, Error)]
36pub enum NatsError {
37    /// async-nats returned an error.
38    #[error("NATS operation failed: {source}")]
39    Nats {
40        /// Native async-nats source error.
41        #[source]
42        source: async_nats::Error,
43    },
44    /// Shared envelope serialization failed.
45    #[error(transparent)]
46    Integration(#[from] nidus_integrations::IntegrationError),
47    /// Nidus provider registration failed.
48    #[error(transparent)]
49    Nidus(#[from] NidusError),
50    /// Adapter configuration was unsafe or incomplete.
51    #[error("invalid NATS configuration: {message}")]
52    Configuration {
53        /// Redaction-safe validation message.
54        message: &'static str,
55    },
56    /// The bounded provider was closed during an operation.
57    #[error("NATS provider is shutting down")]
58    ShuttingDown,
59    /// Operations or the native drain did not complete before the deadline.
60    #[error("NATS shutdown exceeded its configured timeout")]
61    ShutdownTimeout,
62}
63
64/// Typed NATS connection configuration.
65#[derive(Clone, Eq, PartialEq)]
66pub struct NatsConfig {
67    server: String,
68    client_name: String,
69    connection_timeout: Duration,
70    max_reconnects: usize,
71    max_in_flight: usize,
72    shutdown_timeout: Duration,
73    allow_plaintext_local: bool,
74}
75
76impl NatsConfig {
77    /// Creates TLS-first NATS configuration with bounded reconnects and concurrency.
78    pub fn new(server: impl Into<String>, client_name: impl Into<String>) -> Self {
79        Self {
80            server: server.into(),
81            client_name: client_name.into(),
82            connection_timeout: Duration::from_secs(5),
83            max_reconnects: 60,
84            max_in_flight: 256,
85            shutdown_timeout: Duration::from_secs(10),
86            allow_plaintext_local: false,
87        }
88    }
89
90    /// Explicitly permits `nats://` plaintext for local development and tests.
91    pub fn allow_plaintext_for_local_development(mut self) -> Self {
92        self.allow_plaintext_local = true;
93        self
94    }
95
96    /// Sets the initial connection attempt timeout.
97    pub fn with_connection_timeout(mut self, value: Duration) -> Self {
98        self.connection_timeout = value;
99        self
100    }
101
102    /// Sets the maximum reconnect attempts.
103    pub fn with_max_reconnects(mut self, value: usize) -> Self {
104        self.max_reconnects = value;
105        self
106    }
107
108    /// Sets the maximum concurrent provider-owned publish operations.
109    pub fn with_max_in_flight(mut self, value: usize) -> Self {
110        self.max_in_flight = value;
111        self
112    }
113
114    /// Sets the total graceful shutdown deadline.
115    pub fn with_shutdown_timeout(mut self, value: Duration) -> Self {
116        self.shutdown_timeout = value;
117        self
118    }
119
120    /// Returns the configured server URL.
121    pub fn server(&self) -> &str {
122        &self.server
123    }
124
125    /// Validates TLS and bounds before network I/O.
126    pub fn validate(&self) -> Result<()> {
127        if self.server.trim().is_empty() || self.client_name.trim().is_empty() {
128            return Err(NatsError::Configuration {
129                message: "NATS server and client_name cannot be empty",
130            });
131        }
132        if self.connection_timeout.is_zero()
133            || self.shutdown_timeout.is_zero()
134            || self.max_in_flight == 0
135            || self.max_in_flight > MAX_IN_FLIGHT
136        {
137            return Err(NatsError::Configuration {
138                message: "NATS timeouts and max_in_flight must be within safe bounds",
139            });
140        }
141        if self.server.starts_with("nats://") && !self.allow_plaintext_local {
142            return Err(NatsError::Configuration {
143                message: "plaintext NATS requires an explicit local-development opt-in",
144            });
145        }
146        if self.server.starts_with("nats://") && !nats_url_is_loopback(&self.server) {
147            return Err(NatsError::Configuration {
148                message: "plaintext NATS is restricted to loopback servers",
149            });
150        }
151        if !self.server.starts_with("tls://")
152            && !self.server.starts_with("wss://")
153            && !self.server.starts_with("nats://")
154        {
155            return Err(NatsError::Configuration {
156                message: "NATS URLs must use tls://, wss://, or explicit loopback nats://",
157            });
158        }
159        Ok(())
160    }
161}
162
163fn nats_url_is_loopback(server: &str) -> bool {
164    url::Url::parse(server).ok().is_some_and(|url| {
165        url.scheme() == "nats"
166            && match url.host() {
167                Some(url::Host::Domain(host)) => {
168                    host.eq_ignore_ascii_case("localhost")
169                        || host
170                            .parse::<std::net::IpAddr>()
171                            .is_ok_and(|address| address.is_loopback())
172                }
173                Some(url::Host::Ipv4(host)) => host.is_loopback(),
174                Some(url::Host::Ipv6(host)) => host.is_loopback(),
175                None => false,
176            }
177    })
178}
179
180impl fmt::Debug for NatsConfig {
181    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
182        formatter
183            .debug_struct("NatsConfig")
184            .field("server", &"<redacted>")
185            .field("client_name", &self.client_name)
186            .field("connection_timeout", &self.connection_timeout)
187            .field("max_reconnects", &self.max_reconnects)
188            .field("max_in_flight", &self.max_in_flight)
189            .field("shutdown_timeout", &self.shutdown_timeout)
190            .field("allow_plaintext_local", &self.allow_plaintext_local)
191            .finish()
192    }
193}
194
195/// Builder for a NATS provider.
196#[derive(Clone)]
197pub struct NatsProviderBuilder {
198    config: NatsConfig,
199    options: Option<async_nats::ConnectOptions>,
200    telemetry: IntegrationTelemetry,
201}
202
203impl fmt::Debug for NatsProviderBuilder {
204    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
205        formatter
206            .debug_struct("NatsProviderBuilder")
207            .field("config", &self.config)
208            .field(
209                "connect_options",
210                &self.options.as_ref().map(|_| "<redacted>"),
211            )
212            .field("telemetry", &self.telemetry)
213            .finish()
214    }
215}
216
217impl NatsProviderBuilder {
218    /// Creates a provider builder.
219    pub fn new(config: NatsConfig) -> Self {
220        Self {
221            config,
222            options: None,
223            telemetry: IntegrationTelemetry::new(),
224        }
225    }
226
227    /// Replaces native connect options for credentials, certificates, callbacks, and advanced tuning.
228    pub fn connect_options(mut self, options: async_nats::ConnectOptions) -> Self {
229        self.options = Some(options);
230        self
231    }
232
233    /// Adds shared tracing, metrics, dashboard, or custom telemetry.
234    pub fn telemetry(mut self, telemetry: IntegrationTelemetry) -> Self {
235        self.telemetry = telemetry;
236        self
237    }
238
239    /// Connects and creates native Core NATS and JetStream clients.
240    pub async fn connect(self) -> Result<NatsProvider> {
241        self.config.validate()?;
242        let started_at = Instant::now();
243        let options = self.options.unwrap_or_else(|| {
244            async_nats::ConnectOptions::new()
245                .name(&self.config.client_name)
246                .connection_timeout(self.config.connection_timeout)
247                .max_reconnects(Some(self.config.max_reconnects))
248        });
249        let client = options
250            .connect(self.config.server.clone())
251            .await
252            .map_err(nats_error);
253        self.telemetry
254            .record(&IntegrationEvent::new(
255                "nidus-nats",
256                "connect",
257                if client.is_ok() {
258                    IntegrationStatus::Success
259                } else {
260                    IntegrationStatus::Failure
261                },
262                started_at.elapsed(),
263            ))
264            .await;
265        let client = client?;
266        Ok(NatsProvider {
267            jetstream: async_nats::jetstream::new(client.clone()),
268            client,
269            in_flight: Arc::new(Semaphore::new(self.config.max_in_flight)),
270            max_in_flight: self.config.max_in_flight as u32,
271            shutting_down: Arc::new(AtomicBool::new(false)),
272            shutdown_complete: Arc::new(AtomicBool::new(false)),
273            config: self.config,
274            telemetry: self.telemetry,
275        })
276    }
277
278    /// Connects and registers the provider as a Nidus singleton.
279    pub async fn register(self, container: &mut Container) -> Result<()> {
280        container.register_singleton(self.connect().await?)?;
281        Ok(())
282    }
283}
284
285/// Nidus provider exposing native Core NATS and JetStream clients.
286#[derive(Clone)]
287pub struct NatsProvider {
288    config: NatsConfig,
289    client: async_nats::Client,
290    jetstream: async_nats::jetstream::Context,
291    in_flight: Arc<Semaphore>,
292    max_in_flight: u32,
293    shutting_down: Arc<AtomicBool>,
294    shutdown_complete: Arc<AtomicBool>,
295    telemetry: IntegrationTelemetry,
296}
297
298impl NatsProvider {
299    /// Creates a NATS provider builder.
300    pub fn builder(config: NatsConfig) -> NatsProviderBuilder {
301        NatsProviderBuilder::new(config)
302    }
303
304    /// Returns the native Core NATS client.
305    pub fn client(&self) -> &async_nats::Client {
306        &self.client
307    }
308
309    /// Returns the native JetStream context.
310    pub fn jetstream(&self) -> &async_nats::jetstream::Context {
311        &self.jetstream
312    }
313
314    /// Publishes to Core NATS and flushes the connection buffer.
315    ///
316    /// Core NATS is at-most-once; use [`Self::publish_jetstream`] when durable
317    /// persistence and acknowledgement are required.
318    pub async fn publish(&self, subject: &str, payload: impl Into<Bytes>) -> Result<()> {
319        validate_subject(subject)?;
320        let _permit = self.acquire_permit().await?;
321        let started_at = Instant::now();
322        let result = async {
323            self.client
324                .publish(subject.to_owned(), payload.into())
325                .await
326                .map_err(nats_error)?;
327            self.client.flush().await.map_err(nats_error)
328        }
329        .await;
330        self.record("publish_core", result.is_ok(), started_at)
331            .await;
332        result
333    }
334
335    /// Publishes to JetStream and waits for the server persistence acknowledgement.
336    pub async fn publish_jetstream(
337        &self,
338        subject: &str,
339        payload: impl Into<Bytes>,
340    ) -> Result<async_nats::jetstream::publish::PublishAck> {
341        validate_subject(subject)?;
342        let _permit = self.acquire_permit().await?;
343        let started_at = Instant::now();
344        let result = async {
345            self.jetstream
346                .publish(subject.to_owned(), payload.into())
347                .await
348                .map_err(nats_error)?
349                .await
350                .map_err(nats_error)
351        }
352        .await;
353        self.record("publish_jetstream", result.is_ok(), started_at)
354            .await;
355        result
356    }
357
358    /// Publishes a bounded shared envelope through JetStream.
359    pub async fn publish_envelope<T>(
360        &self,
361        subject: &str,
362        envelope: &MessageEnvelope<T>,
363    ) -> Result<async_nats::jetstream::publish::PublishAck>
364    where
365        T: Serialize,
366    {
367        self.publish_jetstream(subject, envelope.to_json()?).await
368    }
369
370    /// Drains subscriptions and pending publishes before closing the connection.
371    pub async fn shutdown(&self) -> Result<()> {
372        if self.shutdown_complete.load(Ordering::Acquire) {
373            return Ok(());
374        }
375        self.shutting_down.store(true, Ordering::Release);
376        let started_at = Instant::now();
377        let result = match tokio::time::timeout(self.config.shutdown_timeout, async {
378            let drained = self
379                .in_flight
380                .acquire_many(self.max_in_flight)
381                .await
382                .map_err(|_| NatsError::ShuttingDown)?;
383            let result = self.client.drain().await.map_err(nats_error);
384            drop(drained);
385            result
386        })
387        .await
388        {
389            Ok(result) => result,
390            Err(_) => Err(NatsError::ShutdownTimeout),
391        };
392        self.record("shutdown", result.is_ok(), started_at).await;
393        if result.is_ok() {
394            self.shutdown_complete.store(true, Ordering::Release);
395            self.in_flight.close();
396        }
397        result
398    }
399
400    /// Reports readiness from the native reconnecting connection state.
401    #[cfg(feature = "health")]
402    pub async fn health_status(&self) -> nidus_http::health::HealthStatus {
403        let started_at = Instant::now();
404        let healthy = !self.shutting_down.load(Ordering::Acquire)
405            && self.client.connection_state() == async_nats::connection::State::Connected;
406        self.record("health", healthy, started_at).await;
407        if healthy {
408            nidus_http::health::HealthStatus::up()
409        } else {
410            nidus_http::health::HealthStatus::down("nats connection is not ready")
411        }
412    }
413
414    /// Adds this provider as a readiness check on a health registry.
415    #[cfg(feature = "health")]
416    pub fn register_ready_check(
417        self: Arc<Self>,
418        registry: nidus_http::health::HealthRegistry,
419        name: impl Into<String>,
420    ) -> nidus_http::health::HealthRegistry {
421        registry.ready_check(name, move || {
422            let provider = Arc::clone(&self);
423            async move { provider.health_status().await }
424        })
425    }
426
427    async fn acquire_permit(&self) -> Result<SemaphorePermit<'_>> {
428        if self.shutting_down.load(Ordering::Acquire) {
429            return Err(NatsError::ShuttingDown);
430        }
431        let permit = self
432            .in_flight
433            .acquire()
434            .await
435            .map_err(|_| NatsError::ShuttingDown)?;
436        if self.shutting_down.load(Ordering::Acquire) {
437            return Err(NatsError::ShuttingDown);
438        }
439        Ok(permit)
440    }
441
442    async fn record(&self, operation: &'static str, success: bool, started_at: Instant) {
443        self.telemetry
444            .record(&IntegrationEvent::new(
445                "nidus-nats",
446                operation,
447                if success {
448                    IntegrationStatus::Success
449                } else {
450                    IntegrationStatus::Failure
451                },
452                started_at.elapsed(),
453            ))
454            .await;
455    }
456}
457
458impl fmt::Debug for NatsProvider {
459    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
460        formatter
461            .debug_struct("NatsProvider")
462            .field("config", &self.config)
463            .field("connection_state", &self.client.connection_state())
464            .field("shutting_down", &self.shutting_down.load(Ordering::Acquire))
465            .field("available_permits", &self.in_flight.available_permits())
466            .field("telemetry", &self.telemetry)
467            .finish()
468    }
469}
470
471#[async_trait]
472impl LifecycleHook for NatsProvider {
473    async fn on_shutdown(&self) -> nidus_core::Result<()> {
474        self.shutdown()
475            .await
476            .map_err(|_| NidusError::ApplicationBuild {
477                message: "NATS drain failed during shutdown".to_owned(),
478            })
479    }
480}
481
482fn validate_subject(subject: &str) -> Result<()> {
483    if subject.trim().is_empty() {
484        return Err(NatsError::Configuration {
485            message: "NATS subject cannot be empty",
486        });
487    }
488    Ok(())
489}
490
491fn nats_error(error: impl std::error::Error + Send + Sync + 'static) -> NatsError {
492    NatsError::Nats {
493        source: Box::new(error),
494    }
495}