nats.rs 41.9 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
// SPDX-License-Identifier: Apache-2.0
Ryan Olson's avatar
Ryan Olson committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

//! NATS transport
//!
//! The following environment variables are used to configure the NATS client:
//!
//! - `NATS_SERVER`: the NATS server address
//!
//! For authentication, the following environment variables are used and prioritized in the following order:
//!
//! - `NATS_AUTH_USERNAME`: the username for authentication
//! - `NATS_AUTH_PASSWORD`: the password for authentication
//! - `NATS_AUTH_TOKEN`: the token for authentication
//! - `NATS_AUTH_NKEY`: the nkey for authentication
//! - `NATS_AUTH_CREDENTIALS_FILE`: the path to the credentials file
//!
//! Note: `NATS_AUTH_USERNAME` and `NATS_AUTH_PASSWORD` must be used together.
19
use crate::metrics::MetricsHierarchy;
20
use crate::protocols::EndpointId;
21
use crate::traits::events::EventPublisher;
Ryan Olson's avatar
Ryan Olson committed
22

23
use anyhow::Result;
24
use async_nats::connection::State;
25
use async_nats::{Subscriber, client, jetstream};
26
use async_trait::async_trait;
27
use bytes::Bytes;
Ryan Olson's avatar
Ryan Olson committed
28
use derive_builder::Builder;
29
use futures::{StreamExt, TryStreamExt};
30
use prometheus::{Counter, Gauge, Histogram, HistogramOpts, IntCounter, IntGauge, Opts, Registry};
31
32
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
33
use std::path::{Path, PathBuf};
34
use std::sync::atomic::Ordering;
35
use tokio::fs::File as TokioFile;
36
use tokio::io::AsyncRead;
37
use tokio::time;
38
use url::Url;
Ryan Olson's avatar
Ryan Olson committed
39
40
use validator::{Validate, ValidationError};

41
use crate::config::environment_names::nats as env_nats;
42
pub use crate::slug::Slug;
43
use tracing as log;
Ryan Olson's avatar
Ryan Olson committed
44

45
46
use super::utils::build_in_runtime;

47
48
pub const URL_PREFIX: &str = "nats://";

Ryan Olson's avatar
Ryan Olson committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#[derive(Clone)]
pub struct Client {
    client: client::Client,
    js_ctx: jetstream::Context,
}

impl Client {
    /// Create a NATS [`ClientOptionsBuilder`].
    pub fn builder() -> ClientOptionsBuilder {
        ClientOptionsBuilder::default()
    }

    /// Returns a reference to the underlying [`async_nats::client::Client`] instance
    pub fn client(&self) -> &client::Client {
        &self.client
    }

    /// Returns a reference to the underlying [`async_nats::jetstream::Context`] instance
    pub fn jetstream(&self) -> &jetstream::Context {
        &self.js_ctx
    }

71
72
73
74
75
76
    /// host:port of NATS
    pub fn addr(&self) -> String {
        let info = self.client.server_info();
        format!("{}:{}", info.host, info.port)
    }

Ryan Olson's avatar
Ryan Olson committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    /// fetch the list of streams
    pub async fn list_streams(&self) -> Result<Vec<String>> {
        let names = self.js_ctx.stream_names();
        let stream_names: Vec<String> = names.try_collect().await?;
        Ok(stream_names)
    }

    /// fetch the list of consumers for a given stream
    pub async fn list_consumers(&self, stream_name: &str) -> Result<Vec<String>> {
        let stream = self.js_ctx.get_stream(stream_name).await?;
        let consumers: Vec<String> = stream.consumer_names().try_collect().await?;
        Ok(consumers)
    }

    pub async fn stream_info(&self, stream_name: &str) -> Result<jetstream::stream::State> {
        let mut stream = self.js_ctx.get_stream(stream_name).await?;
        let info = stream.info().await?;
        Ok(info.state.clone())
    }

    pub async fn get_stream(&self, name: &str) -> Result<jetstream::stream::Stream> {
        let stream = self.js_ctx.get_stream(name).await?;
        Ok(stream)
    }

Ryan Olson's avatar
Ryan Olson committed
102
103
104
105
106
107
108
109
    /// Issues a broadcast request for all services with the provided `service_name` to report their
    /// current stats. Each service will only respond once. The service may have customized the reply
    /// so the caller should select which endpoint and what concrete data model should be used to
    /// extract the details.
    ///
    /// Note: Because each endpoint will only reply once, the caller must drop the subscription after
    /// some time or it will await forever.
    pub async fn scrape_service(&self, service_name: &str) -> Result<Subscriber> {
Ryan Olson's avatar
Ryan Olson committed
110
111
112
113
114
115
116
117
118
119
120
121
        let subject = format!("$SRV.STATS.{}", service_name);
        let reply_subject = format!("_INBOX.{}", nuid::next());
        let subscription = self.client.subscribe(reply_subject.clone()).await?;

        // Publish the request with the reply-to subject
        self.client
            .publish_with_reply(subject, reply_subject, "".into())
            .await?;

        Ok(subscription)
    }

122
123
124
125
126
127
128
129
130
131
132
133
134
    /// Helper method to get or optionally create an object store bucket
    ///
    /// # Arguments
    /// * `bucket_name` - The name of the bucket to retrieve
    /// * `create_if_not_found` - If true, creates the bucket when it doesn't exist
    ///
    /// # Returns
    /// The object store bucket or an error
    async fn get_or_create_bucket(
        &self,
        bucket_name: &str,
        create_if_not_found: bool,
    ) -> anyhow::Result<jetstream::object_store::ObjectStore> {
135
136
        let context = self.jetstream();

137
138
        match context.get_object_store(bucket_name).await {
            Ok(bucket) => Ok(bucket),
139
140
141
142
143
            Err(err) if err.to_string().contains("stream not found") => {
                // err.source() is GetStreamError, which has a kind() which
                // is GetStreamErrorKind::JetStream which wraps a jetstream::Error
                // which has code 404. Phew. So yeah check the string for now.

144
145
146
147
148
149
150
151
152
153
154
155
156
157
                if create_if_not_found {
                    tracing::debug!("Creating NATS bucket {bucket_name}");
                    context
                        .create_object_store(jetstream::object_store::Config {
                            bucket: bucket_name.to_string(),
                            ..Default::default()
                        })
                        .await
                        .map_err(|e| anyhow::anyhow!("Failed creating bucket / object store: {e}"))
                } else {
                    anyhow::bail!(
                        "NATS get_object_store bucket does not exist: {bucket_name}. {err}."
                    );
                }
158
159
160
161
            }
            Err(err) => {
                anyhow::bail!("NATS get_object_store error: {err}");
            }
162
163
164
165
        }
    }

    /// Upload file to NATS at this URL
166
    pub async fn object_store_upload(&self, filepath: &Path, nats_url: &Url) -> anyhow::Result<()> {
167
168
        let mut disk_file = TokioFile::open(filepath).await?;

169
        let (bucket_name, key) = url_to_bucket_and_key(nats_url)?;
170
        let bucket = self.get_or_create_bucket(&bucket_name, true).await?;
171
172
173
174
175
176
177
178
179
180
181
182

        let key_meta = async_nats::jetstream::object_store::ObjectMetadata {
            name: key.to_string(),
            ..Default::default()
        };
        bucket.put(key_meta, &mut disk_file).await.map_err(|e| {
            anyhow::anyhow!("Failed uploading to bucket / object store {bucket_name}/{key}: {e}")
        })?;

        Ok(())
    }

183
184
185
    /// Download file from NATS at this URL
    pub async fn object_store_download(
        &self,
186
        nats_url: &Url,
187
188
189
190
        filepath: &Path,
    ) -> anyhow::Result<()> {
        let mut disk_file = TokioFile::create(filepath).await?;

191
        let (bucket_name, key) = url_to_bucket_and_key(nats_url)?;
192
        let bucket = self.get_or_create_bucket(&bucket_name, false).await?;
193
194
195
196
197
198
199
200
201
202
203

        let mut obj_reader = bucket.get(&key).await.map_err(|e| {
            anyhow::anyhow!(
                "Failed downloading from bucket / object store {bucket_name}/{key}: {e}"
            )
        })?;
        let _bytes_copied = tokio::io::copy(&mut obj_reader, &mut disk_file).await?;

        Ok(())
    }

204
205
206
207
208
209
210
211
212
213
214
215
    /// Delete a bucket and all it's contents from the NATS object store
    pub async fn object_store_delete_bucket(&self, bucket_name: &str) -> anyhow::Result<()> {
        let context = self.jetstream();
        match context.delete_object_store(&bucket_name).await {
            Ok(_) => Ok(()),
            Err(err) if err.to_string().contains("stream not found") => {
                tracing::trace!(bucket_name, "NATS bucket already gone");
                Ok(())
            }
            Err(err) => Err(anyhow::anyhow!("NATS get_object_store error: {err}")),
        }
    }
216
217

    /// Upload a serializable struct to NATS object store using bincode
218
    pub async fn object_store_upload_data<T>(&self, data: &T, nats_url: &Url) -> anyhow::Result<()>
219
220
221
222
223
224
225
    where
        T: Serialize,
    {
        // Serialize the data using bincode (more efficient binary format)
        let binary_data = bincode::serialize(data)
            .map_err(|e| anyhow::anyhow!("Failed to serialize data with bincode: {e}"))?;

226
        let (bucket_name, key) = url_to_bucket_and_key(nats_url)?;
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
        let bucket = self.get_or_create_bucket(&bucket_name, true).await?;

        let key_meta = async_nats::jetstream::object_store::ObjectMetadata {
            name: key.to_string(),
            ..Default::default()
        };

        // Upload the serialized bytes
        let mut cursor = std::io::Cursor::new(binary_data);
        bucket.put(key_meta, &mut cursor).await.map_err(|e| {
            anyhow::anyhow!("Failed uploading to bucket / object store {bucket_name}/{key}: {e}")
        })?;

        Ok(())
    }

    /// Download and deserialize a struct from NATS object store using bincode
244
    pub async fn object_store_download_data<T>(&self, nats_url: &Url) -> anyhow::Result<T>
245
246
247
    where
        T: DeserializeOwned,
    {
248
        let (bucket_name, key) = url_to_bucket_and_key(nats_url)?;
249
250
251
252
253
254
255
256
257
258
259
260
261
        let bucket = self.get_or_create_bucket(&bucket_name, false).await?;

        let mut obj_reader = bucket.get(&key).await.map_err(|e| {
            anyhow::anyhow!(
                "Failed downloading from bucket / object store {bucket_name}/{key}: {e}"
            )
        })?;

        // Read all bytes into memory
        let mut buffer = Vec::new();
        tokio::io::copy(&mut obj_reader, &mut buffer)
            .await
            .map_err(|e| anyhow::anyhow!("Failed reading object data: {e}"))?;
262
        tracing::debug!("Downloaded {} bytes from {bucket_name}/{key}", buffer.len());
263
264
265
266
267
268
269

        // Deserialize from bincode
        let data = bincode::deserialize(&buffer)
            .map_err(|e| anyhow::anyhow!("Failed to deserialize data with bincode: {e}"))?;

        Ok(data)
    }
Ryan Olson's avatar
Ryan Olson committed
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
}

/// NATS client options
///
/// This object uses the builder pattern with default values that are evaluates
/// from the environment variables if they are not explicitly set by the builder.
#[derive(Debug, Clone, Builder, Validate)]
pub struct ClientOptions {
    #[builder(setter(into), default = "default_server()")]
    #[validate(custom(function = "validate_nats_server"))]
    server: String,

    #[builder(default)]
    auth: NatsAuth,
}

fn default_server() -> String {
287
    if let Ok(server) = std::env::var(env_nats::NATS_SERVER) {
Ryan Olson's avatar
Ryan Olson committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        return server;
    }

    "nats://localhost:4222".to_string()
}

fn validate_nats_server(server: &str) -> Result<(), ValidationError> {
    if server.starts_with("nats://") {
        Ok(())
    } else {
        Err(ValidationError::new("server must start with 'nats://'"))
    }
}

302
303
304
// TODO(jthomson04): We really shouldn't be hardcoding this.
const NATS_WORKER_THREADS: usize = 4;

Ryan Olson's avatar
Ryan Olson committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
impl ClientOptions {
    /// Create a new [`ClientOptionsBuilder`]
    pub fn builder() -> ClientOptionsBuilder {
        ClientOptionsBuilder::default()
    }

    /// Validate the config and attempt to connection to the NATS server
    pub async fn connect(self) -> Result<Client> {
        self.validate()?;

        let client = match self.auth {
            NatsAuth::UserPass(username, password) => {
                async_nats::ConnectOptions::with_user_and_password(username, password)
            }
            NatsAuth::Token(token) => async_nats::ConnectOptions::with_token(token),
            NatsAuth::NKey(nkey) => async_nats::ConnectOptions::with_nkey(nkey),
            NatsAuth::CredentialsFile(path) => {
                async_nats::ConnectOptions::with_credentials_file(path).await?
            }
        };

326
327
328
329
330
        let (client, _) = build_in_runtime(
            async move {
                client
                    .connect(self.server)
                    .await
331
                    .map_err(|e| anyhow::anyhow!("Failed to connect to NATS: {e}. Verify NATS server is running and accessible."))
332
333
334
335
336
            },
            NATS_WORKER_THREADS,
        )
        .await?;

Ryan Olson's avatar
Ryan Olson committed
337
338
        let js_ctx = jetstream::new(client.clone());

339
340
341
342
343
344
        // Validate JetStream is available
        js_ctx
            .query_account()
            .await
            .map_err(|e| anyhow::anyhow!("JetStream not available: {e}"))?;

Ryan Olson's avatar
Ryan Olson committed
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        Ok(Client { client, js_ctx })
    }
}

impl Default for ClientOptions {
    fn default() -> Self {
        ClientOptions {
            server: default_server(),
            auth: NatsAuth::default(),
        }
    }
}

#[derive(Clone, Eq, PartialEq)]
pub enum NatsAuth {
    UserPass(String, String),
    Token(String),
    NKey(String),
    CredentialsFile(PathBuf),
}

impl std::fmt::Debug for NatsAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NatsAuth::UserPass(user, _pass) => {
                write!(f, "UserPass({}, <redacted>)", user)
            }
            NatsAuth::Token(_token) => write!(f, "Token(<redacted>)"),
            NatsAuth::NKey(_nkey) => write!(f, "NKey(<redacted>)"),
            NatsAuth::CredentialsFile(path) => write!(f, "CredentialsFile({:?})", path),
        }
    }
}

impl Default for NatsAuth {
    fn default() -> Self {
        if let (Ok(username), Ok(password)) = (
382
383
            std::env::var(env_nats::auth::NATS_AUTH_USERNAME),
            std::env::var(env_nats::auth::NATS_AUTH_PASSWORD),
Ryan Olson's avatar
Ryan Olson committed
384
385
386
387
        ) {
            return NatsAuth::UserPass(username, password);
        }

388
        if let Ok(token) = std::env::var(env_nats::auth::NATS_AUTH_TOKEN) {
Ryan Olson's avatar
Ryan Olson committed
389
390
391
            return NatsAuth::Token(token);
        }

392
        if let Ok(nkey) = std::env::var(env_nats::auth::NATS_AUTH_NKEY) {
Ryan Olson's avatar
Ryan Olson committed
393
394
395
            return NatsAuth::NKey(nkey);
        }

396
        if let Ok(path) = std::env::var(env_nats::auth::NATS_AUTH_CREDENTIALS_FILE) {
Ryan Olson's avatar
Ryan Olson committed
397
398
399
400
401
402
403
            return NatsAuth::CredentialsFile(PathBuf::from(path));
        }

        NatsAuth::UserPass("user".to_string(), "user".to_string())
    }
}

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/// Extract NATS bucket and key from a nats URL of the form:
/// nats://host[:port]/bucket/key
pub fn url_to_bucket_and_key(url: &Url) -> anyhow::Result<(String, String)> {
    let Some(mut path_segments) = url.path_segments() else {
        anyhow::bail!("No path in NATS URL: {url}");
    };
    let Some(bucket) = path_segments.next() else {
        anyhow::bail!("No bucket in NATS URL: {url}");
    };
    let Some(key) = path_segments.next() else {
        anyhow::bail!("No key in NATS URL: {url}");
    };
    Ok((bucket.to_string(), key.to_string()))
}

419
420
421
422
423
424
425
426
427
428
429
430
431
432
/// A queue implementation using NATS JetStream
pub struct NatsQueue {
    /// The name of the stream to use for the queue
    stream_name: String,
    /// The NATS server URL
    nats_server: String,
    /// Timeout for dequeue operations in seconds
    dequeue_timeout: time::Duration,
    /// The NATS client
    client: Option<Client>,
    /// The subject pattern used for this queue
    subject: String,
    /// The subscriber for pull-based consumption
    subscriber: Option<jetstream::consumer::PullConsumer>,
433
434
    /// Optional consumer name for broadcast pattern (if None, uses "worker-group")
    consumer_name: Option<String>,
435
436
    /// Message stream for efficient message consumption
    message_stream: Option<jetstream::consumer::pull::Stream>,
437
438
439
}

impl NatsQueue {
440
    /// Create a new NatsQueue with the default "worker-group" consumer
441
442
    pub fn new(stream_name: String, nats_server: String, dequeue_timeout: time::Duration) -> Self {
        // Sanitize stream name to remove path separators (like in Python version)
443
444
445
446
447
448
449
450
451
452
453
454
        // rupei: are we sure NATs stream name accepts '_'?
        let sanitized_stream_name = Slug::slugify(&stream_name).to_string();
        let subject = format!("{sanitized_stream_name}.*");

        Self {
            stream_name: sanitized_stream_name,
            nats_server,
            dequeue_timeout,
            client: None,
            subject,
            subscriber: None,
            consumer_name: Some("worker-group".to_string()),
455
            message_stream: None,
456
457
        }
    }
458

459
460
461
462
463
464
465
466
    /// Create a new NatsQueue without a consumer (publisher-only mode)
    pub fn new_without_consumer(
        stream_name: String,
        nats_server: String,
        dequeue_timeout: time::Duration,
    ) -> Self {
        let sanitized_stream_name = Slug::slugify(&stream_name).to_string();
        let subject = format!("{sanitized_stream_name}.*");
467
468
469
470
471
472
473
474

        Self {
            stream_name: sanitized_stream_name,
            nats_server,
            dequeue_timeout,
            client: None,
            subject,
            subscriber: None,
475
            consumer_name: None,
476
            message_stream: None,
477
478
479
480
481
482
483
484
485
486
487
        }
    }

    /// Create a new NatsQueue with a specific consumer name for broadcast pattern
    /// Each consumer with a unique name will receive all messages independently
    pub fn new_with_consumer(
        stream_name: String,
        nats_server: String,
        dequeue_timeout: time::Duration,
        consumer_name: String,
    ) -> Self {
488
489
        let sanitized_stream_name = Slug::slugify(&stream_name).to_string();
        let subject = format!("{sanitized_stream_name}.*");
490
491
492
493
494
495
496
497
498

        Self {
            stream_name: sanitized_stream_name,
            nats_server,
            dequeue_timeout,
            client: None,
            subject,
            subscriber: None,
            consumer_name: Some(consumer_name),
499
            message_stream: None,
500
501
502
503
504
        }
    }

    /// Connect to the NATS server and set up the stream and consumer
    pub async fn connect(&mut self) -> Result<()> {
505
506
507
508
509
        self.connect_with_reset(false).await
    }

    /// Connect to the NATS server and set up the stream and consumer, optionally resetting the stream
    pub async fn connect_with_reset(&mut self, reset_stream: bool) -> Result<()> {
510
511
512
513
514
515
        if self.client.is_none() {
            // Create a new client
            let client_options = Client::builder().server(self.nats_server.clone()).build()?;

            let client = client_options.connect().await?;

516
            // messages older than a hour in the stream will be automatically purged
517
            let max_age = std::env::var(env_nats::stream::DYN_NATS_STREAM_MAX_AGE)
518
519
520
521
                .ok()
                .and_then(|s| s.parse::<u64>().ok())
                .map(time::Duration::from_secs)
                .unwrap_or_else(|| time::Duration::from_secs(60 * 60));
522

523
524
525
            let stream_config = jetstream::stream::Config {
                name: self.stream_name.clone(),
                subjects: vec![self.subject.clone()],
526
                max_age,
527
528
529
                ..Default::default()
            };

530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
            // Get or create the stream
            let stream = client
                .jetstream()
                .get_or_create_stream(stream_config)
                .await?;

            log::debug!("Stream {} is ready", self.stream_name);

            // If reset_stream is true, purge all messages from the stream
            if reset_stream {
                match stream.purge().await {
                    Ok(purge_info) => {
                        log::info!(
                            "Successfully purged {} messages from NATS stream {}",
                            purge_info.purged,
                            self.stream_name
                        );
                    }
                    Err(e) => {
                        log::warn!("Failed to purge NATS stream '{}': {e}", self.stream_name);
550
                    }
551
552
553
554
555
556
557
                }
            }

            // Create persistent subscriber only if consumer_name is set
            if let Some(ref consumer_name) = self.consumer_name {
                let consumer_config = jetstream::consumer::pull::Config {
                    durable_name: Some(consumer_name.clone()),
558
                    inactive_threshold: std::time::Duration::from_secs(3600), // 1 hour
559
560
561
562
                    ..Default::default()
                };

                let subscriber = stream.create_consumer(consumer_config).await?;
563
564
565
566

                // Create the message stream for efficient consumption
                let message_stream = subscriber.messages().await?;

567
                self.subscriber = Some(subscriber);
568
                self.message_stream = Some(message_stream);
569
            }
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586

            self.client = Some(client);
        }

        Ok(())
    }

    /// Ensure we have an active connection
    pub async fn ensure_connection(&mut self) -> Result<()> {
        if self.client.is_none() {
            self.connect().await?;
        }
        Ok(())
    }

    /// Close the connection when done
    pub async fn close(&mut self) -> Result<()> {
587
        self.message_stream = None;
588
589
590
591
592
        self.subscriber = None;
        self.client = None;
        Ok(())
    }

593
594
    /// Shutdown the consumer by deleting it from the stream and closing the connection
    /// This permanently removes the consumer from the server
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    ///
    /// If `consumer_name` is provided, that specific consumer will be deleted instead of the
    /// current consumer. This allows deletion of other consumers on the same stream.
    pub async fn shutdown(&mut self, consumer_name: Option<String>) -> Result<()> {
        // Determine which consumer to delete
        let target_consumer = consumer_name.as_ref().or(self.consumer_name.as_ref());

        // Warn if deleting our own consumer via explicit parameter
        if let Some(ref passed_name) = consumer_name
            && self.consumer_name.as_ref() == Some(passed_name)
        {
            log::warn!(
                "Deleting our own consumer '{}' via explicit consumer_name parameter. \
                Consider calling shutdown without arguments instead.",
                passed_name
            );
        }

        if let (Some(client), Some(consumer_to_delete)) = (&self.client, target_consumer) {
614
615
            // Get the stream and delete the consumer
            let stream = client.jetstream().get_stream(&self.stream_name).await?;
616
617
618
619
620
621
            stream
                .delete_consumer(consumer_to_delete)
                .await
                .map_err(|e| {
                    anyhow::anyhow!("Failed to delete consumer {}: {}", consumer_to_delete, e)
                })?;
622
623
            log::debug!(
                "Deleted consumer {} from stream {}",
624
                consumer_to_delete,
625
626
627
                self.stream_name
            );
        } else {
628
629
            log::debug!(
                "Cannot shutdown consumer: client or target consumer is None (client: {:?}, target_consumer: {:?})",
630
                self.client.is_some(),
631
                target_consumer.is_some()
632
633
634
            );
        }

635
636
637
638
639
640
        // Only close the connection if we deleted our own consumer
        if consumer_name.is_none() {
            self.close().await
        } else {
            Ok(())
        }
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    }

    /// Count the number of consumers for the stream
    pub async fn count_consumers(&mut self) -> Result<usize> {
        self.ensure_connection().await?;

        if let Some(client) = &self.client {
            let mut stream = client.jetstream().get_stream(&self.stream_name).await?;
            let info = stream.info().await?;
            Ok(info.state.consumer_count)
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }

656
657
658
659
660
661
662
663
664
665
666
    /// List all consumer names for the stream
    pub async fn list_consumers(&mut self) -> Result<Vec<String>> {
        self.ensure_connection().await?;

        if let Some(client) = &self.client {
            client.list_consumers(&self.stream_name).await
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }

667
668
669
670
671
672
673
674
675
676
677
678
679
680
    /// Enqueue a task using the provided data
    pub async fn enqueue_task(&mut self, task_data: Bytes) -> Result<()> {
        self.ensure_connection().await?;

        if let Some(client) = &self.client {
            let subject = format!("{}.queue", self.stream_name);
            client.jetstream().publish(subject, task_data).await?;
            Ok(())
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }

    /// Dequeue and return a task as raw bytes
681
    pub async fn dequeue_task(&mut self, timeout: Option<time::Duration>) -> Result<Option<Bytes>> {
682
683
        self.ensure_connection().await?;

684
685
686
687
688
        let Some(ref mut stream) = self.message_stream else {
            return Err(anyhow::anyhow!("Message stream not initialized"));
        };

        let timeout_duration = timeout.unwrap_or(self.dequeue_timeout);
689

690
691
692
693
694
695
        // Try to get next message from the stream with timeout
        let message = tokio::time::timeout(timeout_duration, stream.next()).await;

        match message {
            Ok(Some(Ok(msg))) => {
                msg.ack()
696
697
                    .await
                    .map_err(|e| anyhow::anyhow!("Failed to ack message: {}", e))?;
698
                Ok(Some(msg.payload.clone()))
699
            }
700
701
702
703
704
705
706

            Ok(Some(Err(e))) => Err(anyhow::anyhow!("Failed to get message from stream: {}", e)),

            Ok(None) => Err(anyhow::anyhow!("Message stream ended unexpectedly")),

            // Timeout - no messages available
            Err(_) => Ok(None),
707
708
709
710
711
712
713
714
715
716
        }
    }

    /// Get the number of messages currently in the queue
    pub async fn get_queue_size(&mut self) -> Result<u64> {
        self.ensure_connection().await?;

        if let Some(client) = &self.client {
            // Get consumer info to get pending messages count
            let stream = client.jetstream().get_stream(&self.stream_name).await?;
717
718
719
720
            let consumer_name = self
                .consumer_name
                .clone()
                .unwrap_or_else(|| "worker-group".to_string());
721
            let mut consumer: jetstream::consumer::PullConsumer = stream
722
                .get_consumer(&consumer_name)
723
724
725
726
727
728
729
730
731
                .await
                .map_err(|e| anyhow::anyhow!("Failed to get consumer: {}", e))?;
            let info = consumer.info().await?;

            Ok(info.num_pending)
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }
732

733
734
735
736
737
738
739
740
741
742
743
744
745
    /// Get the total number of messages currently in the stream
    pub async fn get_stream_messages(&mut self) -> Result<u64> {
        self.ensure_connection().await?;

        if let Some(client) = &self.client {
            let mut stream = client.jetstream().get_stream(&self.stream_name).await?;
            let info = stream.info().await?;
            Ok(info.state.messages)
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
    /// Purge messages from the stream up to (but not including) the specified sequence number
    /// This permanently removes messages and affects all consumers of the stream
    pub async fn purge_up_to_sequence(&self, sequence: u64) -> Result<()> {
        if let Some(client) = &self.client {
            let stream = client.jetstream().get_stream(&self.stream_name).await?;

            // NOTE: this purge excludes the sequence itself
            // https://docs.rs/nats/latest/nats/jetstream/struct.PurgeRequest.html
            stream.purge().sequence(sequence).await.map_err(|e| {
                anyhow::anyhow!("Failed to purge stream up to sequence {}: {}", sequence, e)
            })?;

            log::debug!(
                "Purged stream {} up to sequence {}",
                self.stream_name,
                sequence
            );
            Ok(())
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }

    /// Purge messages from the stream up to the minimum acknowledged sequence across all consumers
    /// This finds the lowest acknowledged sequence number across all consumers and purges up to that point
    pub async fn purge_acknowledged(&mut self) -> Result<()> {
        self.ensure_connection().await?;

        let Some(client) = &self.client else {
            return Err(anyhow::anyhow!("Client not connected"));
        };

        let stream = client.jetstream().get_stream(&self.stream_name).await?;

        // Get all consumer names for the stream
        let consumer_names: Vec<String> = stream
            .consumer_names()
            .try_collect()
            .await
            .map_err(|e| anyhow::anyhow!("Failed to list consumers: {}", e))?;

        if consumer_names.is_empty() {
            log::debug!("No consumers found for stream {}", self.stream_name);
            return Ok(());
        }

        // Find the minimum acknowledged sequence across all consumers
        let mut min_ack_sequence = u64::MAX;

        for consumer_name in &consumer_names {
            let mut consumer: jetstream::consumer::PullConsumer = stream
                .get_consumer(consumer_name)
                .await
                .map_err(|e| anyhow::anyhow!("Failed to get consumer {}: {}", consumer_name, e))?;

            let info = consumer.info().await.map_err(|e| {
                anyhow::anyhow!("Failed to get consumer info for {}: {}", consumer_name, e)
            })?;

            // The ack_floor contains the stream sequence of the highest contiguously acknowledged message
            // If stream_sequence is 0, it means no messages have been acknowledged yet
            if info.ack_floor.stream_sequence > 0 {
                min_ack_sequence = min_ack_sequence.min(info.ack_floor.stream_sequence);
                log::debug!(
                    "Consumer {} has ack_floor at sequence {}",
                    consumer_name,
                    info.ack_floor.stream_sequence
                );
            }
        }

        // Only purge if we found a valid minimum acknowledged sequence
        if min_ack_sequence < u64::MAX && min_ack_sequence > 0 {
            // Purge up to (but not including) the minimum acknowledged sequence + 1
            // We add 1 because we want to include the minimum acknowledged message in the purge
            let purge_sequence = min_ack_sequence + 1;

            self.purge_up_to_sequence(purge_sequence).await?;

825
            log::debug!(
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
                "Purged stream {} up to acknowledged sequence {} (purged up to sequence {})",
                self.stream_name,
                min_ack_sequence,
                purge_sequence
            );
        } else {
            log::debug!(
                "No messages to purge for stream {} (min_ack_sequence: {})",
                self.stream_name,
                min_ack_sequence
            );
        }

        Ok(())
    }
841
842
}

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
#[async_trait]
impl EventPublisher for NatsQueue {
    fn subject(&self) -> String {
        self.stream_name.clone()
    }

    async fn publish(
        &self,
        event_name: impl AsRef<str> + Send + Sync,
        event: &(impl Serialize + Send + Sync),
    ) -> Result<()> {
        let bytes = serde_json::to_vec(event)?;
        self.publish_bytes(event_name, bytes).await
    }

    async fn publish_bytes(
        &self,
        event_name: impl AsRef<str> + Send + Sync,
        bytes: Vec<u8>,
    ) -> Result<()> {
        let subject = format!("{}.{}", self.subject(), event_name.as_ref());

        // Note: enqueue_task requires &mut self, but EventPublisher requires &self
        // We need to ensure the client is connected and use it directly
        if let Some(client) = &self.client {
            client.jetstream().publish(subject, bytes.into()).await?;
            Ok(())
        } else {
            Err(anyhow::anyhow!("Client not connected"))
        }
    }
}

876
877
/// The NATS subject / inbox to talk to an instance on.
/// TODO: Do we need to sanitize the names?
878
pub fn instance_subject(endpoint_id: &EndpointId, instance_id: u64) -> String {
879
880
881
882
883
884
    format!(
        "{}_{}.{}-{:x}",
        endpoint_id.namespace, endpoint_id.component, endpoint_id.name, instance_id,
    )
}

Ryan Olson's avatar
Ryan Olson committed
885
886
887
888
889
#[cfg(test)]
mod tests {

    use super::*;
    use figment::Jail;
890
891
892
893
894
895
896
897
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
    struct TestData {
        id: u32,
        name: String,
        values: Vec<f64>,
    }
Ryan Olson's avatar
Ryan Olson committed
898
899
900
901
902
903
904
905
906
907

    #[test]
    fn test_client_options_builder() {
        Jail::expect_with(|_jail| {
            let opts = ClientOptions::builder().build();
            assert!(opts.is_ok());
            Ok(())
        });

        Jail::expect_with(|jail| {
908
909
910
            jail.set_env(env_nats::NATS_SERVER, "nats://localhost:5222");
            jail.set_env(env_nats::auth::NATS_AUTH_USERNAME, "user");
            jail.set_env(env_nats::auth::NATS_AUTH_PASSWORD, "pass");
Ryan Olson's avatar
Ryan Olson committed
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925

            let opts = ClientOptions::builder().build();
            assert!(opts.is_ok());
            let opts = opts.unwrap();

            assert_eq!(opts.server, "nats://localhost:5222");
            assert_eq!(
                opts.auth,
                NatsAuth::UserPass("user".to_string(), "pass".to_string())
            );

            Ok(())
        });

        Jail::expect_with(|jail| {
926
927
928
            jail.set_env(env_nats::NATS_SERVER, "nats://localhost:5222");
            jail.set_env(env_nats::auth::NATS_AUTH_USERNAME, "user");
            jail.set_env(env_nats::auth::NATS_AUTH_PASSWORD, "pass");
Ryan Olson's avatar
Ryan Olson committed
929
930
931
932
933
934
935
936
937
938
939
940
941
942

            let opts = ClientOptions::builder()
                .server("nats://localhost:6222")
                .auth(NatsAuth::Token("token".to_string()))
                .build();
            assert!(opts.is_ok());
            let opts = opts.unwrap();

            assert_eq!(opts.server, "nats://localhost:6222");
            assert_eq!(opts.auth, NatsAuth::Token("token".to_string()));

            Ok(())
        });
    }
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971

    // Integration test for object store data operations using bincode
    #[tokio::test]
    #[ignore] // Requires NATS server to be running
    async fn test_object_store_data_operations() {
        // Create test data
        let test_data = TestData {
            id: 42,
            name: "test_item".to_string(),
            values: vec![1.0, 2.5, 3.7, 4.2],
        };

        // Set up client
        let client_options = ClientOptions::builder()
            .server("nats://localhost:4222")
            .build()
            .expect("Failed to build client options");

        let client = client_options
            .connect()
            .await
            .expect("Failed to connect to NATS");

        // Test URL (using .bin extension to indicate binary format)
        let url =
            Url::parse("nats://localhost/test-bucket/test-data.bin").expect("Failed to parse URL");

        // Upload the data
        client
972
            .object_store_upload_data(&test_data, &url)
973
974
975
976
977
            .await
            .expect("Failed to upload data");

        // Download the data
        let downloaded_data: TestData = client
978
            .object_store_download_data(&url)
979
980
981
982
983
984
985
986
987
988
989
990
            .await
            .expect("Failed to download data");

        // Verify the data matches
        assert_eq!(test_data, downloaded_data);

        // Clean up
        client
            .object_store_delete_bucket("test-bucket")
            .await
            .expect("Failed to delete bucket");
    }
991
992
993
994
995
996
997
998
999
1000
1001
1002

    // Integration test for broadcast pattern with purging
    #[tokio::test]
    #[ignore]
    async fn test_nats_queue_broadcast_with_purge() {
        use uuid::Uuid;

        // Create unique stream name for this test
        let stream_name = format!("test-broadcast-{}", Uuid::new_v4());
        let nats_server = "nats://localhost:4222".to_string();
        let timeout = time::Duration::from_secs(0);

1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
        // Connect to NATS client first to delete stream if it exists
        let client_options = Client::builder()
            .server(nats_server.clone())
            .build()
            .expect("Failed to build client options");

        let client = client_options
            .connect()
            .await
            .expect("Failed to connect to NATS");

        // Delete the stream if it exists (to ensure clean start)
        let _ = client.jetstream().delete_stream(&stream_name).await;

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
        // Create two consumers with different names for the same stream
        let consumer1_name = format!("consumer-{}", Uuid::new_v4());
        let consumer2_name = format!("consumer-{}", Uuid::new_v4());

        let mut queue1 = NatsQueue::new_with_consumer(
            stream_name.clone(),
            nats_server.clone(),
            timeout,
            consumer1_name,
        );

1028
        // Connect queue1 first (it will create the stream)
1029
1030
        queue1.connect().await.expect("Failed to connect queue1");

1031
1032
1033
1034
1035
1036
        // Send 4 messages using the EventPublisher trait
        let message_strings = [
            "message1".to_string(),
            "message2".to_string(),
            "message3".to_string(),
            "message4".to_string(),
1037
1038
        ];

1039
1040
        // Using the EventPublisher trait to publish messages
        for (idx, msg) in message_strings.iter().enumerate() {
1041
            queue1
1042
                .publish("queue", msg)
1043
                .await
1044
                .unwrap_or_else(|_| panic!("Failed to publish message {}", idx + 1));
1045
1046
        }

1047
1048
1049
1050
1051
1052
        // Convert messages to JSON-serialized Bytes for comparison
        let messages: Vec<Bytes> = message_strings
            .iter()
            .map(|s| Bytes::from(serde_json::to_vec(s).unwrap()))
            .collect();

1053
1054
1055
        // Give JetStream a moment to persist the messages
        tokio::time::sleep(time::Duration::from_millis(100)).await;

1056
1057
1058
1059
1060
1061
1062
        // Now create and connect queue2 and queue3 AFTER messages are published (to test persistence)
        let mut queue2 = NatsQueue::new_with_consumer(
            stream_name.clone(),
            nats_server.clone(),
            timeout,
            consumer2_name,
        );
1063

1064
1065
1066
1067
1068
1069
1070
        // Create a third queue without consumer (publisher-only)
        let mut queue3 =
            NatsQueue::new_without_consumer(stream_name.clone(), nats_server.clone(), timeout);

        // Connect queue2 and queue3 after messages are already published
        queue2.connect().await.expect("Failed to connect queue2");
        queue3.connect().await.expect("Failed to connect queue3");
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180

        // Purge the first two messages (sequence 1 and 2)
        // Note: JetStream sequences start at 1, and purge is exclusive of the sequence number
        queue1
            .purge_up_to_sequence(3)
            .await
            .expect("Failed to purge messages");

        // Give JetStream a moment to process the purge
        tokio::time::sleep(time::Duration::from_millis(100)).await;

        // Consumer 1 dequeues one message (message3)
        let msg3_consumer1 = queue1
            .dequeue_task(Some(time::Duration::from_millis(500)))
            .await
            .expect("Failed to dequeue from queue1");
        assert_eq!(
            msg3_consumer1,
            Some(messages[2].clone()),
            "Consumer 1 should get message3"
        );

        // Give JetStream a moment to process acknowledgments
        tokio::time::sleep(time::Duration::from_millis(100)).await;

        // Now run purge_acknowledged
        // At this point:
        // - Consumer 1 has ack'd message 3 (ack_floor = 3)
        // - Consumer 2 hasn't consumed anything yet (ack_floor = 0)
        // - Min ack_floor = 0, so nothing will be purged
        queue1
            .purge_acknowledged()
            .await
            .expect("Failed to purge acknowledged messages");

        // Give JetStream a moment to process the purge
        tokio::time::sleep(time::Duration::from_millis(100)).await;

        // Now collect remaining messages from both consumers
        let mut consumer1_remaining = Vec::new();
        let mut consumer2_remaining = Vec::new();

        // Collect remaining messages from consumer 1
        while let Some(msg) = queue1
            .dequeue_task(None)
            .await
            .expect("Failed to dequeue from queue1")
        {
            consumer1_remaining.push(msg);
        }

        // Collect remaining messages from consumer 2
        while let Some(msg) = queue2
            .dequeue_task(None)
            .await
            .expect("Failed to dequeue from queue2")
        {
            consumer2_remaining.push(msg);
        }

        // Verify consumer 1 gets 1 remaining message (message4)
        assert_eq!(
            consumer1_remaining.len(),
            1,
            "Consumer 1 should have 1 remaining message"
        );
        assert_eq!(
            consumer1_remaining[0], messages[3],
            "Consumer 1 should get message4"
        );

        // Verify consumer 2 gets 2 messages (message3 and message4)
        assert_eq!(
            consumer2_remaining.len(),
            2,
            "Consumer 2 should have 2 messages"
        );
        assert_eq!(
            consumer2_remaining[0], messages[2],
            "Consumer 2 should get message3"
        );
        assert_eq!(
            consumer2_remaining[1], messages[3],
            "Consumer 2 should get message4"
        );

        // Test consumer count and shutdown behavior
        // First verify via consumer 1 that there are two consumers
        let consumer_count = queue1
            .count_consumers()
            .await
            .expect("Failed to count consumers");
        assert_eq!(consumer_count, 2, "Should have 2 consumers initially");

        // Close consumer 1 and verify via consumer 2 that there are still two consumers
        queue1.close().await.expect("Failed to close queue1");

        let consumer_count = queue2
            .count_consumers()
            .await
            .expect("Failed to count consumers");
        assert_eq!(
            consumer_count, 2,
            "Should still have 2 consumers after closing queue1"
        );

        // Reconnect queue1 to be able to shutdown
        queue1.connect().await.expect("Failed to reconnect queue1");

        // Shutdown consumer 1 and verify via consumer 2 that there is only one consumer left
1181
1182
1183
1184
        queue1
            .shutdown(None)
            .await
            .expect("Failed to shutdown queue1");
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201

        let consumer_count = queue2
            .count_consumers()
            .await
            .expect("Failed to count consumers");
        assert_eq!(
            consumer_count, 1,
            "Should have only 1 consumer after shutting down queue1"
        );

        // Clean up by deleting the stream
        client
            .jetstream()
            .delete_stream(&stream_name)
            .await
            .expect("Failed to delete test stream");
    }
Ryan Olson's avatar
Ryan Olson committed
1202
}