nats 0.26.0

A Rust NATS client (deprecated — use async-nats instead)
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
// Copyright 2020-2022 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::io;
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::jetstream::{ConsumerInfo, ConsumerOwnership, JetStream};
use crate::Message;

use super::{AckPolicy, BatchOptions};
use crossbeam_channel as channel;

#[derive(Debug)]
pub(crate) struct Inner {
    pid: u64,

    /// messages channel for this subscription.
    pub(crate) messages: channel::Receiver<Message>,

    /// sid of the inbox subscription
    pub(crate) inbox: String,

    /// Ack policy used in methods that automatically ack.
    pub(crate) consumer_ack_policy: AckPolicy,

    /// Name of the stream associated with the subscription.
    pub(crate) info: ConsumerInfo,

    /// Indicates if we own the consumer and are responsible for deleting it or not.
    pub(crate) consumer_ownership: ConsumerOwnership,

    /// Client associated with subscription.
    pub(crate) context: JetStream,
}

impl Drop for Inner {
    fn drop(&mut self) {
        self.context.connection.0.client.unsubscribe(self.pid).ok();

        // Delete the consumer, if we own it.
        if self.consumer_ownership == ConsumerOwnership::Yes {
            self.context
                .delete_consumer(&self.info.stream_name, &self.info.name)
                .ok();
        }
    }
}

/// A `PullSubscription` pulls messages from Server triggered by client actions
/// Pull Subscription does nothing on itself. It has to explicitly request messages
/// using one of available
#[derive(Clone, Debug)]
pub struct PullSubscription(pub(crate) Arc<Inner>);

impl PullSubscription {
    /// Creates a subscription.
    pub(crate) fn new(
        pid: u64,
        consumer_info: ConsumerInfo,
        consumer_ownership: ConsumerOwnership,
        inbox: String,
        messages: channel::Receiver<Message>,
        context: JetStream,
    ) -> PullSubscription {
        PullSubscription(Arc::new(Inner {
            pid,
            inbox,
            messages,
            consumer_ownership,
            consumer_ack_policy: consumer_info.config.ack_policy,
            info: consumer_info,
            context,
        }))
    }

    /// Fetch given amount of messages for `PullSubscription` and return Iterator
    /// to handle them. The returned iterator is blocking, meaning it will wait until
    /// every message from the batch are processed.
    /// It can accept either `usize` defined size of the batch, or `BatchOptions` defining
    /// also `expires` and `no_wait`.
    /// If `no_wait` will be specified, iterator will also return when there are no more messages
    /// in the Consumer.
    ///
    /// # Example
    /// ```no_run
    /// # use nats::jetstream::BatchOptions;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("next")?;
    /// # for _ in 0..20 {
    /// #    context.publish("next", "hello")?;
    /// # }
    /// let consumer = context.pull_subscribe("next")?;
    ///
    /// // pass just number of messages to be fetched
    /// for message in consumer.fetch(10)? {
    ///     println!("received message: {:?}", message);
    /// }
    ///
    /// // pass whole `BatchOptions` to fetch
    /// let messages = consumer.fetch(BatchOptions {
    ///     expires: None,
    ///     no_wait: false,
    ///     batch: 10,
    /// })?;
    /// for message in messages {
    ///     println!("received message {:?}", message);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn fetch<I: Into<BatchOptions>>(&self, batch: I) -> io::Result<BatchIter<'_>> {
        let batch_options = batch.into();
        self.request_batch(batch_options)?;
        Ok(BatchIter {
            batch_size: batch_options.batch,
            processed: 0,
            subscription: self,
        })
    }

    /// Fetch given amount of messages for `PullSubscription` and return Iterator
    /// to handle them. The returned iterator is will retrieve message or wait for new ones for
    /// a given set of time.
    /// It will stop when all messages for given batch are processed.
    /// That can happen if there are no more messages in the stream, or when iterator processed
    /// number of messages specified in batch.
    /// It can accept either `usize` defined size of the batch, or `BatchOptions` defining
    /// also `expires` and `no_wait`.
    /// If `no_wait` will be specified, iterator will also return when there are no more messages
    /// in the Consumer.
    ///
    /// # Example
    /// ```no_run
    /// # use std::time::Duration;
    /// # use nats::jetstream::BatchOptions;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("timeout_fetch")?;
    /// # for _ in 0..20 {
    /// #    context.publish("timeout_fetch", "hello")?;
    /// # }
    /// let consumer = context.pull_subscribe("timeout_fetch")?;
    ///
    /// // pass just number of messages to be fetched
    /// for message in consumer.timeout_fetch(10, Duration::from_millis(100))? {
    ///     println!("received message: {:?}", message);
    /// }
    ///
    /// // pass whole `BatchOptions` to fetch
    /// let messages = consumer.timeout_fetch(
    ///     BatchOptions {
    ///         expires: None,
    ///         no_wait: false,
    ///         batch: 10,
    ///     },
    ///     Duration::from_millis(100),
    /// )?;
    /// for message in messages {
    ///     println!("received message {:?}", message);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn timeout_fetch<I: Into<BatchOptions>>(
        &self,
        batch: I,
        timeout: Duration,
    ) -> io::Result<TimeoutBatchIter<'_>> {
        let batch_options = batch.into();
        self.request_batch(batch_options)?;
        Ok(TimeoutBatchIter {
            timeout,
            batch_size: batch_options.batch,
            processed: 0,
            subscription: self,
        })
    }

    /// High level method that fetches given set of messages, processes them in user-provider
    /// closure and acks them automatically according to `Consumer` `AckPolicy`.
    ///
    /// # Example
    /// ```no_run
    /// # use nats::jetstream::BatchOptions;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("fetch_with_handler")?;
    /// # for _ in 0..20 {
    /// #    context.publish("fetch_with_handler", "hello")?;
    /// # }
    /// let consumer = context.pull_subscribe("fetch_with_handler")?;
    ///
    /// consumer.fetch_with_handler(10, |message| {
    ///     println!("received message: {:?}", message);
    ///     Ok(())
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn fetch_with_handler<F, I>(&self, batch: I, mut handler: F) -> io::Result<()>
    where
        F: FnMut(&Message) -> io::Result<()>,
        I: Into<BatchOptions> + Copy,
    {
        let mut last_message;
        let consumer_ack_policy = self.0.consumer_ack_policy;
        let batch = self.fetch(batch)?;
        for message in batch {
            handler(&message)?;
            if consumer_ack_policy != AckPolicy::None {
                message.ack()?
            }
            last_message = Some(message);
            // if the policy is ack all - optimize and send the ack
            // after the last message was processed.
            if consumer_ack_policy == AckPolicy::All {
                if let Some(last_message) = last_message {
                    last_message.ack()?;
                }
            }
        }
        Ok(())
    }

    /// A low level method that should be used only in specific cases.
    /// Pulls next message available for this `PullSubscription`.
    /// This operation is blocking and will indefinitely wait for new messages.
    /// Keep in mind that this requires user to request for messages first.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("next")?;
    /// # context.publish("next", "hello")?;
    /// let consumer = context.pull_subscribe("next")?;
    /// consumer.request_batch(1)?;
    /// let message = consumer.next();
    /// println!("Received message: {:?}", message);
    /// # Ok(())
    /// # }
    /// ```
    pub fn next(&self) -> Option<Message> {
        self.preprocess(self.0.messages.recv().ok())
    }

    /// A low level method that should be used only in specific cases.
    /// Pulls next message available for this `PullSubscription`.
    /// This operation is non blocking, that will yield `None` if there are no messages each time
    /// it is called.
    /// Keep in mind that this requires user to request for messages first.
    ///
    /// # Example
    /// ```
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("try_next")?;
    /// context.publish("try_next", "hello")?;
    /// let consumer = context.pull_subscribe("try_next")?;
    /// consumer.request_batch(1)?;
    /// let message = consumer.try_next();
    /// println!("Received message: {:?}", message);
    /// assert!(consumer.try_next().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn try_next(&self) -> Option<Message> {
        self.preprocess(self.0.messages.try_recv().ok())
    }

    /// A low level method that should be used only in specific cases.
    /// Pulls next message available for this `PullSubscription`.
    /// This operation is contrast to its siblings `next` and `try_next` returns `Message` wrapped
    /// in `io::Result` as it might return `timeout` error, either on waiting for next message, or
    /// network.
    /// Keep in mind that this requires user to request for messages first.
    ///
    /// # Example
    /// ```no_run
    /// # use std::time::Duration;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("next_timeout")?;
    /// # context.publish("next_timeout", "hello")?;
    /// # context.publish("next_timeout", "hello")?;
    /// let consumer = context.pull_subscribe("next_timeout")?;
    ///
    /// consumer.request_batch(1)?;
    ///
    /// let message = consumer.next_timeout(Duration::from_millis(1000))?;
    /// println!("Received message: {:?}", message);
    ///
    /// // timeout on second, as there are no messages.
    /// let message = consumer.next_timeout(Duration::from_millis(100));
    /// assert!(message.is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn next_timeout(&self, mut timeout: Duration) -> io::Result<Message> {
        loop {
            let start = Instant::now();
            return match self.0.messages.recv_timeout(timeout) {
                Ok(message) => {
                    if message.is_no_messages() {
                        timeout = timeout.saturating_sub(start.elapsed());
                        continue;
                    }
                    if message.is_request_timeout() {
                        return Err(io::Error::new(
                            io::ErrorKind::Other,
                            "next_timeout: Pull Request timed out",
                        ));
                    }
                    Ok(message)
                }
                Err(channel::RecvTimeoutError::Timeout) => Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "next_timeout: timed out",
                )),
                Err(channel::RecvTimeoutError::Disconnected) => Err(io::Error::new(
                    io::ErrorKind::Other,
                    "next_timeout: unsubscribed",
                )),
            };
        }
    }

    /// Sends request for another set of messages to Pull Consumer.
    /// This method does not return any messages. It can be used
    /// to have more granular control of how many request and when are sent.
    ///
    /// # Example
    /// ```no_run
    /// # use nats::jetstream::BatchOptions;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client);
    /// #
    /// # context.add_stream("request_batch")?;
    ///
    /// let consumer = context.pull_subscribe("request_batch")?;
    /// // request specific number of messages.
    /// consumer.request_batch(10)?;
    ///
    /// // request messages specifying whole config.
    /// consumer.request_batch(BatchOptions {
    ///     expires: None,
    ///     no_wait: false,
    ///     batch: 10,
    /// })?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn request_batch<I: Into<BatchOptions>>(&self, batch: I) -> io::Result<()> {
        let batch_opts = batch.into();

        let subject = format!(
            "{}CONSUMER.MSG.NEXT.{}.{}",
            self.0.context.api_prefix(),
            self.0.info.stream_name,
            self.0.info.name,
        );

        let request = serde_json::to_vec(&batch_opts)?;

        self.0.context.connection.publish_with_reply_or_headers(
            &subject,
            Some(self.0.inbox.as_str()),
            None,
            request,
        )?;
        Ok(())
    }

    /// Low level API that should be used with care.
    /// For standard use cases consider using [`PullSubscription::fetch`] or [`PullSubscription::fetch_with_handler`].
    /// Returns iterator for Current Subscription.
    /// As Pull Consumers requires Client to fetch messages, this will yield nothing if explicit [`PullSubscription::request_batch`] was not sent.
    ///
    /// # Example
    /// ```no_run
    /// # use nats::jetstream::BatchOptions;
    /// # fn main() -> std::io::Result<()> {
    /// # let client = nats::connect("demo.nats.io")?;
    /// # let context = nats::jetstream::new(client.clone());
    /// #
    /// # context.add_stream("iter")?;
    /// # for i in 0..20 {
    /// # client.publish("iter", b"data")?;
    /// # }
    ///
    /// let consumer = context.pull_subscribe("iter")?;
    /// // request specific number of messages.
    /// consumer.request_batch(10)?;
    ///
    /// // request messages specifying whole config.
    /// consumer.request_batch(BatchOptions {
    ///     expires: Some(10000),
    ///     no_wait: true,
    ///     batch: 10,
    /// })?;
    /// for (i, message) in consumer.iter().enumerate() {
    ///     println!("received message: {:?}", message);
    ///     message.ack()?;
    /// #   break;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn iter(&self) -> Iter<'_> {
        Iter { subscription: self }
    }

    /// utility to stop iterators if `no messages` or `request timeout` is encountered.
    fn preprocess(&self, message: Option<Message>) -> Option<Message> {
        if let Some(message) = message {
            if message.is_no_messages() {
                return None;
            }
            if message.is_request_timeout() {
                return None;
            }
            return Some(message);
        }
        message
    }
}

/// Iterator that will endlessly wait for messages, unless `no messages` or `request timeout` is encountered.
pub struct Iter<'a> {
    subscription: &'a PullSubscription,
}
impl<'a> Iterator for Iter<'a> {
    type Item = Message;
    fn next(&mut self) -> Option<Self::Item> {
        self.subscription.next()
    }
}

/// Iterator that retrieves messages unless `no messages` or `request timeout` is encountered, or
/// timeout is reached.
pub struct TimeoutIter<'a> {
    subscription: &'a PullSubscription,
    timeout: Duration,
}
impl<'a> Iterator for TimeoutIter<'a> {
    type Item = io::Result<Message>;
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.subscription.next_timeout(self.timeout))
    }
}

/// Iterator for handling batches of messages. Works like `Iter` except stopping after
/// reading number of messages defined in `batch_size`.
pub struct BatchIter<'a> {
    batch_size: usize,
    processed: usize,
    subscription: &'a PullSubscription,
}

impl<'a> Iterator for BatchIter<'a> {
    type Item = Message;
    fn next(&mut self) -> Option<Self::Item> {
        if self.processed >= self.batch_size {
            None
        } else {
            self.processed += 1;
            self.subscription.next()
        }
    }
}

/// Iterator for handling batches of messages. Works like `TryIter` except stopping after
/// reading number of messages defined in `batch_size`.
pub struct TryBatchIter<'a> {
    batch_size: usize,
    processed: usize,
    subscription: &'a PullSubscription,
}

impl<'a> Iterator for TryBatchIter<'a> {
    type Item = Message;
    fn next(&mut self) -> Option<Self::Item> {
        if self.processed == 0 {
            self.processed += 1;
            return self.subscription.next();
        }
        if self.processed >= self.batch_size {
            None
        } else {
            self.processed += 1;
            self.subscription.try_next()
        }
    }
}

/// Iterator for handling batches of messages. Works like `TimeoutIter` except stopping after
/// reading number of messages defined in `batch_size`.
pub struct TimeoutBatchIter<'a> {
    batch_size: usize,
    processed: usize,
    timeout: Duration,
    subscription: &'a PullSubscription,
}

impl<'a> Iterator for TimeoutBatchIter<'a> {
    type Item = io::Result<Message>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.processed >= self.batch_size {
            None
        } else {
            self.processed += 1;
            Some(self.subscription.next_timeout(self.timeout))
        }
    }
}

impl From<usize> for BatchOptions {
    fn from(batch: usize) -> Self {
        BatchOptions {
            batch,
            expires: None,
            no_wait: false,
        }
    }
}