intercom-rs 1.1.1

A fully typed async wrapper for NATS with JetStream support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//! Work queue support for JetStream.
//!
//! This module provides a convenient interface for creating and using work queues
//! with JetStream, including support for interest-based consumers.

use std::{
    marker::PhantomData,
    pin::Pin,
    task::{Context, Poll},
};

use futures::{Sink, Stream};
use pin_project_lite::pin_project;
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    codec::CodecType,
    error::{Error, Result},
    jetstream::{
        consumer::{JetStreamMessage, PullBatch, PullConsumer, PullMessages},
        stream::{RetentionPolicy, Stream as JsStream, StreamBuilder},
    },
};

/// A typed work queue backed by JetStream with configurable codec.
///
/// Work queues provide at-least-once delivery with automatic acknowledgment tracking.
/// Messages are removed from the queue once acknowledged.
///
/// # Type Parameters
///
/// * `T` - The message type for this queue
/// * `C` - The codec type used for serialization
///
/// # Example
///
/// ```no_run
/// use intercom::{Client, MsgPackCodec, jetstream::queue::WorkQueue};
/// use serde::{Deserialize, Serialize};
/// use futures::StreamExt;
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct Job {
///     id: u64,
///     payload: String,
/// }
///
/// # async fn example() -> intercom::Result<()> {
/// let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
/// let jetstream = client.jetstream();
///
/// // Create a work queue
/// let queue = WorkQueue::<Job, MsgPackCodec>::builder(&jetstream, "jobs")
///     .max_messages(10_000)
///     .create()
///     .await?;
///
/// // Push a job
/// queue.push(&Job { id: 1, payload: "do work".into() }).await?;
///
/// // Option 1: Use as a Stream (pulls one job at a time)
/// let mut queue = queue.into_stream().await?;
/// while let Some(result) = queue.next().await {
///     let job = result?;
///     println!("Processing: {:?}", job.payload);
///     job.ack().await?;
/// }
///
/// // Option 2: Pull a batch of jobs
/// // let mut jobs = queue.pull(10).await?;
/// // while let Some(result) = jobs.next().await {
/// //     let job = result?;
/// //     job.ack().await?;
/// // }
/// # Ok(())
/// # }
/// ```
pub struct WorkQueue<T, C: CodecType> {
    stream: JsStream<C>,
    consumer: PullConsumer<T, C>,
    subject: String,
    context: async_nats::jetstream::Context,
    _marker: PhantomData<(T, C)>,
}

impl<T, C: CodecType> WorkQueue<T, C> {
    /// Create a work queue builder.
    pub fn builder(
        context: &crate::jetstream::context::JetStreamContext<C>,
        name: &str,
    ) -> WorkQueueBuilder<T, C> {
        WorkQueueBuilder::new(context.inner().clone(), name.to_string())
    }

    /// Get the stream backing this queue.
    pub fn stream(&self) -> &JsStream<C> {
        &self.stream
    }

    /// Get the consumer for this queue.
    pub fn consumer(&self) -> &PullConsumer<T, C> {
        &self.consumer
    }

    /// Get the subject for this queue.
    pub fn subject(&self) -> &str {
        &self.subject
    }
}

impl<T: Serialize, C: CodecType> WorkQueue<T, C> {
    /// Push a message to the queue.
    pub async fn push(&self, message: &T) -> Result<u64> {
        let data = C::encode(message)?;
        let ack = self
            .context
            .publish(self.subject.clone(), data.into())
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?;
        Ok(ack.sequence)
    }

    /// Create a sink for pushing messages.
    pub fn sink(&self) -> WorkQueueSink<T, C> {
        WorkQueueSink::new(self.context.clone(), self.subject.clone())
    }
}

impl<T: DeserializeOwned, C: CodecType> WorkQueue<T, C> {
    /// Pull a batch of messages from the queue.
    pub async fn pull(&self, batch_size: usize) -> Result<PullBatch<T, C>> {
        self.consumer.fetch(batch_size).await
    }

    /// Get a continuous stream of messages.
    pub async fn messages(&self) -> Result<crate::jetstream::consumer::PullMessages<T, C>> {
        self.consumer.messages().await
    }

    /// Convert this queue into a [`Stream`] that continuously pulls messages one at a time.
    ///
    /// This is the most ergonomic way to process queue messages when you want to handle
    /// them one at a time in a loop.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use intercom::{Client, MsgPackCodec, jetstream::queue::WorkQueue};
    /// use serde::{Deserialize, Serialize};
    /// use futures::StreamExt;
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct Job { id: u64 }
    ///
    /// # async fn example() -> intercom::Result<()> {
    /// let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    /// let jetstream = client.jetstream();
    /// let queue = WorkQueue::<Job, MsgPackCodec>::builder(&jetstream, "jobs").create().await?;
    ///
    /// // Convert to a Stream and iterate
    /// let mut queue = queue.into_stream().await?;
    /// while let Some(job) = queue.next().await {
    ///     let job = job?;
    ///     println!("Processing job: {:?}", job.payload);
    ///     job.ack().await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn into_stream(self) -> Result<StreamingWorkQueue<T, C>> {
        let messages = self.consumer.messages().await?;
        Ok(StreamingWorkQueue {
            messages,
            context: self.context,
            subject: self.subject,
            _marker: PhantomData,
        })
    }
}

pin_project! {
    /// A work queue that implements [`Stream`] for continuous message processing.
    ///
    /// Created from [`WorkQueue::into_stream`]. This type allows using the queue
    /// directly with `StreamExt` methods like `next()`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use intercom::{Client, MsgPackCodec, jetstream::queue::WorkQueue};
    /// use serde::{Deserialize, Serialize};
    /// use futures::StreamExt;
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct Job { id: u64 }
    ///
    /// # async fn example() -> intercom::Result<()> {
    /// let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    /// let jetstream = client.jetstream();
    /// let queue = WorkQueue::<Job, MsgPackCodec>::builder(&jetstream, "jobs").create().await?;
    ///
    /// let mut streaming = queue.into_stream().await?;
    /// while let Some(job) = streaming.next().await {
    ///     let job = job?;
    ///     job.ack().await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub struct StreamingWorkQueue<T, C: CodecType> {
        #[pin]
        messages: PullMessages<T, C>,
        context: async_nats::jetstream::Context,
        subject: String,
        _marker: PhantomData<(T, C)>,
    }
}

impl<T: Serialize, C: CodecType> StreamingWorkQueue<T, C> {
    /// Push a message to the queue.
    ///
    /// Note: This is available even while streaming, allowing you to add work
    /// to the queue while processing existing messages.
    pub async fn push(&self, message: &T) -> Result<u64> {
        let data = C::encode(message)?;
        let ack = self
            .context
            .publish(self.subject.clone(), data.into())
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?;
        Ok(ack.sequence)
    }
}

impl<T: DeserializeOwned, C: CodecType> Stream for StreamingWorkQueue<T, C> {
    type Item = Result<JetStreamMessage<T>>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.project().messages.poll_next(cx)
    }
}

/// Builder for work queues.
pub struct WorkQueueBuilder<T, C: CodecType> {
    context: async_nats::jetstream::Context,
    name: String,
    subject: Option<String>,
    max_messages: i64,
    max_bytes: i64,
    max_age: std::time::Duration,
    replicas: usize,
    _marker: PhantomData<(T, C)>,
}

impl<T, C: CodecType> WorkQueueBuilder<T, C> {
    /// Create a new work queue builder.
    fn new(context: async_nats::jetstream::Context, name: String) -> Self {
        Self {
            context,
            name,
            subject: None,
            max_messages: -1,
            max_bytes: -1,
            max_age: std::time::Duration::ZERO,
            replicas: 1,
            _marker: PhantomData,
        }
    }

    /// Set the subject for the queue.
    ///
    /// If not set, defaults to the queue name.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Set the maximum number of messages.
    pub fn max_messages(mut self, max: i64) -> Self {
        self.max_messages = max;
        self
    }

    /// Set the maximum bytes.
    pub fn max_bytes(mut self, max: i64) -> Self {
        self.max_bytes = max;
        self
    }

    /// Set the maximum age for messages.
    pub fn max_age(mut self, age: std::time::Duration) -> Self {
        self.max_age = age;
        self
    }

    /// Set the number of replicas.
    pub fn replicas(mut self, replicas: usize) -> Self {
        self.replicas = replicas;
        self
    }

    /// Create the work queue.
    pub async fn create(self) -> Result<WorkQueue<T, C>> {
        let subject = self.subject.unwrap_or_else(|| self.name.clone());
        let consumer_name = format!("{}-worker", self.name);

        // Create the stream with work queue retention
        let stream_builder = StreamBuilder::<C>::new(self.context.clone(), self.name.clone())
            .subjects(vec![subject.clone()])
            .retention(RetentionPolicy::WorkQueue)
            .max_messages(self.max_messages)
            .max_bytes(self.max_bytes)
            .max_age(self.max_age)
            .replicas(self.replicas);

        let stream = stream_builder.create_or_update().await?;

        // Create a durable pull consumer
        let consumer = stream
            .pull_consumer_builder::<T>(&consumer_name)
            .durable()
            .create_or_update()
            .await?;

        Ok(WorkQueue {
            stream,
            consumer,
            subject,
            context: self.context,
            _marker: PhantomData,
        })
    }
}

/// A sink for pushing messages to a work queue.
pub struct WorkQueueSink<T, C: CodecType> {
    context: async_nats::jetstream::Context,
    subject: String,
    _marker: PhantomData<(T, C)>,
}

impl<T, C: CodecType> WorkQueueSink<T, C> {
    fn new(context: async_nats::jetstream::Context, subject: String) -> Self {
        Self {
            context,
            subject,
            _marker: PhantomData,
        }
    }
}

impl<T: Serialize, C: CodecType> WorkQueueSink<T, C> {
    /// Publish a message directly with error handling.
    ///
    /// Unlike the [`Sink`] implementation, this method returns any publish errors
    /// and waits for JetStream acknowledgment.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use intercom::{Client, MsgPackCodec, WorkQueue};
    /// use serde::{Deserialize, Serialize};
    ///
    /// #[derive(Serialize, Deserialize)]
    /// struct Job { id: u64 }
    ///
    /// # async fn example() -> intercom::Result<()> {
    /// let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
    /// let jetstream = client.jetstream();
    /// let queue = WorkQueue::<Job, MsgPackCodec>::builder(&jetstream, "jobs").create().await?;
    /// let sink = queue.sink();
    ///
    /// // Direct publish with acknowledgment
    /// let seq = sink.publish(&Job { id: 1 }).await?;
    /// println!("Published at sequence: {}", seq);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn publish(&self, message: &T) -> Result<u64> {
        let data = C::encode(message)?;
        let ack = self
            .context
            .publish(self.subject.clone(), data.into())
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?;
        Ok(ack.sequence)
    }
}

impl<T, C: CodecType> Clone for WorkQueueSink<T, C> {
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
            subject: self.subject.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T: Serialize, C: CodecType> Sink<T> for WorkQueueSink<T, C> {
    type Error = Error;

    fn poll_ready(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn start_send(self: Pin<&mut Self>, item: T) -> Result<()> {
        let data = C::encode(&item)?;
        // Note: Uses fire-and-forget for Sink compatibility.
        // Use WorkQueueSink::publish() for error handling and acknowledgment.
        let context = self.context.clone();
        let subject = self.subject.clone();
        tokio::spawn(async move {
            let _ = context.publish(subject, data.into()).await;
        });
        Ok(())
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.poll_flush(cx)
    }
}

// ============================================================================
// Interest-Based Queue
// ============================================================================

/// A typed queue with interest-based retention and configurable codec.
///
/// Messages are retained until acknowledged by all consumers that were
/// active when the message was published.
///
/// # Type Parameters
///
/// * `T` - The message type for this queue
/// * `C` - The codec type used for serialization
///
/// # Example
///
/// ```no_run
/// use intercom::{Client, MsgPackCodec, jetstream::queue::InterestQueue};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Debug)]
/// struct Event {
///     id: u64,
///     data: String,
/// }
///
/// # async fn example() -> intercom::Result<()> {
/// let client = Client::<MsgPackCodec>::connect("nats://localhost:4222").await?;
/// let jetstream = client.jetstream();
///
/// // Create an interest-based queue
/// let queue = InterestQueue::<Event, MsgPackCodec>::builder(&jetstream, "events")
///     .subject("events.>")
///     .create()
///     .await?;
///
/// // Add consumers
/// let consumer1 = queue.add_consumer("service-a").await?;
/// let consumer2 = queue.add_consumer("service-b").await?;
///
/// // Both consumers must acknowledge for message removal
/// # Ok(())
/// # }
/// ```
pub struct InterestQueue<T, C: CodecType> {
    stream: JsStream<C>,
    subject: String,
    context: async_nats::jetstream::Context,
    _marker: PhantomData<(T, C)>,
}

impl<T, C: CodecType> InterestQueue<T, C> {
    /// Create an interest queue builder.
    pub fn builder(
        context: &crate::jetstream::context::JetStreamContext<C>,
        name: &str,
    ) -> InterestQueueBuilder<T, C> {
        InterestQueueBuilder::new(context.inner().clone(), name.to_string())
    }

    /// Get the stream backing this queue.
    pub fn stream(&self) -> &JsStream<C> {
        &self.stream
    }

    /// Get the subject for this queue.
    pub fn subject(&self) -> &str {
        &self.subject
    }

    /// Add a durable consumer to this queue.
    pub async fn add_consumer(&self, name: &str) -> Result<PullConsumer<T, C>> {
        self.stream
            .pull_consumer_builder::<T>(name)
            .durable()
            .create_or_update()
            .await
    }

    /// Add a consumer with a filter subject.
    pub async fn add_consumer_filtered(
        &self,
        name: &str,
        filter: &str,
    ) -> Result<PullConsumer<T, C>> {
        self.stream
            .pull_consumer_builder::<T>(name)
            .durable()
            .filter_subject(filter)
            .create_or_update()
            .await
    }
}

impl<T: Serialize, C: CodecType> InterestQueue<T, C> {
    /// Publish a message to the queue.
    pub async fn publish(&self, message: &T) -> Result<u64> {
        let data = C::encode(message)?;
        let ack = self
            .context
            .publish(self.subject.clone(), data.into())
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?;
        Ok(ack.sequence)
    }

    /// Publish a message to a specific subject within the queue's subject space.
    pub async fn publish_to(&self, subject: &str, message: &T) -> Result<u64> {
        let data = C::encode(message)?;
        let ack = self
            .context
            .publish(subject.to_string(), data.into())
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?
            .await
            .map_err(|e| Error::JetStream(e.to_string()))?;
        Ok(ack.sequence)
    }
}

/// Builder for interest-based queues.
pub struct InterestQueueBuilder<T, C: CodecType> {
    context: async_nats::jetstream::Context,
    name: String,
    subject: Option<String>,
    max_messages: i64,
    max_bytes: i64,
    max_age: std::time::Duration,
    replicas: usize,
    _marker: PhantomData<(T, C)>,
}

impl<T, C: CodecType> InterestQueueBuilder<T, C> {
    fn new(context: async_nats::jetstream::Context, name: String) -> Self {
        Self {
            context,
            name,
            subject: None,
            max_messages: -1,
            max_bytes: -1,
            max_age: std::time::Duration::ZERO,
            replicas: 1,
            _marker: PhantomData,
        }
    }

    /// Set the subject for the queue.
    pub fn subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Set the maximum number of messages.
    pub fn max_messages(mut self, max: i64) -> Self {
        self.max_messages = max;
        self
    }

    /// Set the maximum bytes.
    pub fn max_bytes(mut self, max: i64) -> Self {
        self.max_bytes = max;
        self
    }

    /// Set the maximum age for messages.
    pub fn max_age(mut self, age: std::time::Duration) -> Self {
        self.max_age = age;
        self
    }

    /// Set the number of replicas.
    pub fn replicas(mut self, replicas: usize) -> Self {
        self.replicas = replicas;
        self
    }

    /// Create the interest queue.
    pub async fn create(self) -> Result<InterestQueue<T, C>> {
        let subject = self.subject.unwrap_or_else(|| self.name.clone());

        // Create the stream with interest-based retention
        let stream_builder = StreamBuilder::<C>::new(self.context.clone(), self.name.clone())
            .subjects(vec![subject.clone()])
            .retention(RetentionPolicy::Interest)
            .max_messages(self.max_messages)
            .max_bytes(self.max_bytes)
            .max_age(self.max_age)
            .replicas(self.replicas);

        let stream = stream_builder.create_or_update().await?;

        Ok(InterestQueue {
            stream,
            subject,
            context: self.context,
            _marker: PhantomData,
        })
    }
}

// ============================================================================
// Queue Messages (alias for convenience)
// ============================================================================

/// A message from a work queue or interest queue.
///
/// This is an alias for [`JetStreamMessage`] for convenience.
pub type QueueMessage<T> = JetStreamMessage<T>;