async_nats/jetstream/consumer/
mod.rs

1// Copyright 2020-2023 The NATS Authors
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13//
14//! Push and Pull [Consumer] API.
15
16pub mod pull;
17pub mod push;
18#[cfg(feature = "server_2_10")]
19use std::collections::HashMap;
20use std::time::Duration;
21
22use serde::{Deserialize, Serialize};
23use serde_json::json;
24use time::serde::rfc3339;
25
26#[cfg(feature = "server_2_11")]
27use time::OffsetDateTime;
28
29use super::context::{ConsumerInfoError, RequestError};
30use super::response::Response;
31use super::stream::ClusterInfo;
32use super::Context;
33use crate::error::Error;
34use crate::jetstream::consumer;
35
36pub trait IntoConsumerConfig {
37    fn into_consumer_config(self) -> Config;
38}
39
40#[allow(dead_code)]
41#[derive(Clone, Debug)]
42pub struct Consumer<T: IntoConsumerConfig> {
43    pub(crate) context: Context,
44    pub(crate) config: T,
45    pub(crate) info: Info,
46}
47
48impl<T: IntoConsumerConfig> Consumer<T> {
49    pub fn new(config: T, info: consumer::Info, context: Context) -> Self {
50        Self {
51            config,
52            info,
53            context,
54        }
55    }
56}
57impl<T: IntoConsumerConfig> Consumer<T> {
58    /// Retrieves `info` about [Consumer] from the server, updates the cached `info` inside
59    /// [Consumer] and returns it.
60    ///
61    /// # Examples
62    ///
63    /// ```no_run
64    /// # #[tokio::main]
65    /// # async fn main() -> Result<(), async_nats::Error> {
66    /// use async_nats::jetstream::consumer::PullConsumer;
67    /// let client = async_nats::connect("localhost:4222").await?;
68    /// let jetstream = async_nats::jetstream::new(client);
69    ///
70    /// let mut consumer: PullConsumer = jetstream
71    ///     .get_stream("events")
72    ///     .await?
73    ///     .get_consumer("pull")
74    ///     .await?;
75    ///
76    /// let info = consumer.info().await?;
77    /// # Ok(())
78    /// # }
79    /// ```
80    pub async fn info(&mut self) -> Result<&consumer::Info, ConsumerInfoError> {
81        let info = self.fetch_info().await?;
82        self.info = info;
83        Ok(&self.info)
84    }
85
86    async fn fetch_info(&self) -> Result<consumer::Info, ConsumerInfoError> {
87        let subject = format!("CONSUMER.INFO.{}.{}", self.info.stream_name, self.info.name);
88        match self.context.request(subject, &json!({})).await? {
89            Response::Err { error } => Err(error.into()),
90            Response::Ok(info) => Ok(info),
91        }
92    }
93
94    /// Returns cached [Info] for the [Consumer].
95    /// Cache is either from initial creation/retrieval of the [Consumer] or last call to
96    /// [Info].
97    ///
98    /// # Examples
99    ///
100    /// ```no_run
101    /// # #[tokio::main]
102    /// # async fn main() -> Result<(), async_nats::Error> {
103    /// use async_nats::jetstream::consumer::PullConsumer;
104    /// let client = async_nats::connect("localhost:4222").await?;
105    /// let jetstream = async_nats::jetstream::new(client);
106    ///
107    /// let consumer: PullConsumer = jetstream
108    ///     .get_stream("events")
109    ///     .await?
110    ///     .get_consumer("pull")
111    ///     .await?;
112    ///
113    /// let info = consumer.cached_info();
114    /// # Ok(())
115    /// # }
116    /// ```
117    pub fn cached_info(&self) -> &consumer::Info {
118        &self.info
119    }
120}
121
122/// Trait used to convert generic [Stream Config][crate::jetstream::consumer::Config] into either
123/// [Pull][crate::jetstream::consumer::pull::Config] or
124/// [Push][crate::jetstream::consumer::push::Config] config. It validates if given config is
125/// a valid target one.
126pub trait FromConsumer {
127    fn try_from_consumer_config(
128        config: crate::jetstream::consumer::Config,
129    ) -> Result<Self, crate::Error>
130    where
131        Self: Sized;
132}
133
134pub type PullConsumer = Consumer<self::pull::Config>;
135pub type PushConsumer = Consumer<self::push::Config>;
136pub type OrderedPullConsumer = Consumer<self::pull::OrderedConfig>;
137pub type OrderedPushConsumer = Consumer<self::push::OrderedConfig>;
138
139/// Information about a consumer
140#[derive(Debug, Deserialize, Clone, PartialEq, Eq)]
141pub struct Info {
142    /// The stream being consumed
143    pub stream_name: String,
144    /// The consumer's unique name
145    pub name: String,
146    /// The time the consumer was created
147    #[serde(with = "rfc3339")]
148    pub created: time::OffsetDateTime,
149    /// The consumer's configuration
150    pub config: Config,
151    /// Statistics for delivered messages
152    pub delivered: SequenceInfo,
153    /// Statistics for acknowledged messages
154    pub ack_floor: SequenceInfo,
155    /// The number of messages delivered but not yet acknowledged
156    pub num_ack_pending: usize,
157    /// The number of messages re-sent after acknowledgment was not received within the configured
158    /// time threshold
159    pub num_redelivered: usize,
160    /// The number of pull requests waiting for messages
161    pub num_waiting: usize,
162    /// The number of messages pending delivery
163    pub num_pending: u64,
164    /// Information about the consumer's cluster
165    #[serde(skip_serializing_if = "is_default")]
166    pub cluster: Option<ClusterInfo>,
167    /// Indicates if any client is connected and receiving messages from a push consumer
168    #[serde(default, skip_serializing_if = "is_default")]
169    pub push_bound: bool,
170    #[cfg(feature = "server_2_11")]
171    /// Indicates if the consumer is paused
172    #[serde(default)]
173    pub paused: bool,
174    #[cfg(feature = "server_2_11")]
175    /// The remaining time the consumer is paused
176    #[serde(default, with = "serde_nanos")]
177    pub pause_remaining: Option<Duration>,
178}
179
180/// Information about a consumer and the stream it is consuming
181#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
182pub struct SequenceInfo {
183    /// How far along the consumer has progressed
184    #[serde(rename = "consumer_seq")]
185    pub consumer_sequence: u64,
186    /// The aggregate for all stream consumers
187    #[serde(rename = "stream_seq")]
188    pub stream_sequence: u64,
189    // Last activity for the sequence
190    #[serde(
191        default,
192        with = "rfc3339::option",
193        skip_serializing_if = "Option::is_none"
194    )]
195    pub last_active: Option<time::OffsetDateTime>,
196}
197
198/// Configuration for consumers. From a high level, the
199/// `durable_name` and `deliver_subject` fields have a particularly
200/// strong influence on the consumer's overall behavior.
201#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq, Eq)]
202pub struct Config {
203    /// Setting `deliver_subject` to `Some(...)` will cause this consumer
204    /// to be "push-based". This is analogous in some ways to a normal
205    /// NATS subscription (rather than a queue subscriber) in that the
206    /// consumer will receive all messages published to the stream that
207    /// the consumer is interested in. Acknowledgment policies such as
208    /// `AckPolicy::None` and `AckPolicy::All` may be enabled for such
209    /// push-based consumers, which reduce the amount of effort spent
210    /// tracking delivery. Combining `AckPolicy::All` with
211    /// `Consumer::process_batch` enables particularly nice throughput
212    /// optimizations.
213    ///
214    /// Setting `deliver_subject` to `None` will cause this consumer to
215    /// be "pull-based", and will require explicit acknowledgment of
216    /// each message. This is analogous in some ways to a normal NATS
217    /// queue subscriber, where a message will be delivered to a single
218    /// subscriber. Pull-based consumers are intended to be used for
219    /// workloads where it is desirable to have a single process receive
220    /// a message. The only valid `ack_policy` for pull-based consumers
221    /// is the default of `AckPolicy::Explicit`, which acknowledges each
222    /// processed message individually. Pull-based consumers may be a
223    /// good choice for work queue-like workloads where you want messages
224    /// to be handled by a single consumer process. Note that it is
225    /// possible to deliver a message to multiple consumers if the
226    /// consumer crashes or is slow to acknowledge the delivered message.
227    /// This is a fundamental behavior present in all distributed systems
228    /// that attempt redelivery when a consumer fails to acknowledge a message.
229    /// This is known as "at least once" message processing. To achieve
230    /// "exactly once" semantics, it is necessary to implement idempotent
231    /// semantics in any system that is written to as a result of processing
232    /// a message.
233    #[serde(default, skip_serializing_if = "Option::is_none")]
234    pub deliver_subject: Option<String>,
235
236    /// Setting `durable_name` to `Some(...)` will cause this consumer
237    /// to be "durable". This may be a good choice for workloads that
238    /// benefit from the `JetStream` server or cluster remembering the
239    /// progress of consumers for fault tolerance purposes. If a consumer
240    /// crashes, the `JetStream` server or cluster will remember which
241    /// messages the consumer acknowledged. When the consumer recovers,
242    /// this information will allow the consumer to resume processing
243    /// where it left off. If you're unsure, set this to `Some(...)`.
244    ///
245    /// Setting `durable_name` to `None` will cause this consumer to
246    /// be "ephemeral". This may be a good choice for workloads where
247    /// you don't need the `JetStream` server to remember the consumer's
248    /// progress in the case of a crash, such as certain "high churn"
249    /// workloads or workloads where a crashed instance is not required
250    /// to recover.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub durable_name: Option<String>,
253    /// A name of the consumer. Can be specified for both durable and ephemeral
254    /// consumers.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub name: Option<String>,
257    /// A short description of the purpose of this consumer.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub description: Option<String>,
260    /// Deliver group to use.
261    #[serde(default, skip_serializing_if = "Option::is_none")]
262    pub deliver_group: Option<String>,
263    /// Allows for a variety of options that determine how this consumer will receive messages
264    #[serde(flatten)]
265    pub deliver_policy: DeliverPolicy,
266    /// How messages should be acknowledged
267    pub ack_policy: AckPolicy,
268    /// How long to allow messages to remain un-acknowledged before attempting redelivery
269    #[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
270    pub ack_wait: Duration,
271    /// Maximum number of times a specific message will be delivered. Use this to avoid poison pill messages that repeatedly crash your consumer processes forever.
272    #[serde(default, skip_serializing_if = "is_default")]
273    pub max_deliver: i64,
274    /// When consuming from a Stream with many subjects, or wildcards, this selects only specific incoming subjects. Supports wildcards.
275    #[serde(default, skip_serializing_if = "is_default")]
276    pub filter_subject: String,
277    #[cfg(feature = "server_2_10")]
278    /// Fulfills the same role as [Config::filter_subject], but allows filtering by many subjects.
279    #[serde(default, skip_serializing_if = "is_default")]
280    pub filter_subjects: Vec<String>,
281    /// Whether messages are sent as quickly as possible or at the rate of receipt
282    pub replay_policy: ReplayPolicy,
283    /// The rate of message delivery in bits per second
284    #[serde(default, skip_serializing_if = "is_default")]
285    pub rate_limit: u64,
286    /// What percentage of acknowledgments should be samples for observability, 0-100
287    #[serde(
288        rename = "sample_freq",
289        with = "sample_freq_deser",
290        default,
291        skip_serializing_if = "is_default"
292    )]
293    pub sample_frequency: u8,
294    /// The maximum number of waiting consumers.
295    #[serde(default, skip_serializing_if = "is_default")]
296    pub max_waiting: i64,
297    /// The maximum number of unacknowledged messages that may be
298    /// in-flight before pausing sending additional messages to
299    /// this consumer.
300    #[serde(default, skip_serializing_if = "is_default")]
301    pub max_ack_pending: i64,
302    /// Only deliver headers without payloads.
303    #[serde(default, skip_serializing_if = "is_default")]
304    pub headers_only: bool,
305    /// Enable flow control messages
306    #[serde(default, skip_serializing_if = "is_default")]
307    pub flow_control: bool,
308    /// Enable idle heartbeat messages
309    #[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
310    pub idle_heartbeat: Duration,
311    /// Maximum size of a request batch
312    #[serde(default, skip_serializing_if = "is_default")]
313    pub max_batch: i64,
314    /// Maximum size of a request max_bytes
315    #[serde(default, skip_serializing_if = "is_default")]
316    pub max_bytes: i64,
317    /// Maximum value for request expiration
318    #[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
319    pub max_expires: Duration,
320    /// Threshold for ephemeral consumer inactivity
321    #[serde(default, with = "serde_nanos", skip_serializing_if = "is_default")]
322    pub inactive_threshold: Duration,
323    /// Number of consumer replicas
324    #[serde(default, skip_serializing_if = "is_default")]
325    pub num_replicas: usize,
326    /// Force consumer to use memory storage.
327    #[serde(default, skip_serializing_if = "is_default", rename = "mem_storage")]
328    pub memory_storage: bool,
329
330    #[cfg(feature = "server_2_10")]
331    /// Additional consumer metadata.
332    #[serde(default, skip_serializing_if = "is_default")]
333    pub metadata: HashMap<String, String>,
334    /// Custom backoff for missed acknowledgments.
335    #[serde(default, skip_serializing_if = "is_default", with = "serde_nanos")]
336    pub backoff: Vec<Duration>,
337    #[cfg(feature = "server_2_11")]
338    #[serde(default, skip_serializing_if = "is_default")]
339    pub priority_policy: PriorityPolicy,
340    #[cfg(feature = "server_2_11")]
341    #[serde(default, skip_serializing_if = "is_default")]
342    pub priority_groups: Vec<String>,
343    /// For suspending the consumer until the deadline.
344    #[cfg(feature = "server_2_11")]
345    #[serde(
346        default,
347        with = "rfc3339::option",
348        skip_serializing_if = "Option::is_none"
349    )]
350    pub pause_until: Option<OffsetDateTime>,
351}
352
353#[cfg(feature = "server_2_11")]
354#[derive(Default, Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
355pub enum PriorityPolicy {
356    #[serde(rename = "overflow")]
357    Overflow,
358    /// This feature is not yet supported by the client.
359    /// It's part of the enum to ensure that the client can deserialize
360    /// Consumer configurations that used [PriorityPolicy::PinnedClient].
361    #[serde(rename = "pinned_client")]
362    PinnedClient,
363    #[serde(rename = "none")]
364    #[default]
365    None,
366}
367
368impl From<&Config> for Config {
369    fn from(cc: &Config) -> Config {
370        cc.clone()
371    }
372}
373
374impl From<&str> for Config {
375    fn from(s: &str) -> Config {
376        Config {
377            durable_name: Some(s.to_string()),
378            ..Default::default()
379        }
380    }
381}
382
383impl IntoConsumerConfig for Config {
384    fn into_consumer_config(self) -> Config {
385        self
386    }
387}
388impl IntoConsumerConfig for &Config {
389    fn into_consumer_config(self) -> Config {
390        self.clone()
391    }
392}
393
394impl FromConsumer for Config {
395    fn try_from_consumer_config(config: Config) -> Result<Self, crate::Error>
396    where
397        Self: Sized,
398    {
399        Ok(config)
400    }
401}
402
403/// `DeliverPolicy` determines how the consumer should select the first message to deliver.
404#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
405#[repr(u8)]
406#[serde(tag = "deliver_policy")]
407pub enum DeliverPolicy {
408    /// All causes the consumer to receive the oldest messages still present in the system.
409    /// This is the default.
410    #[default]
411    #[serde(rename = "all")]
412    All,
413    /// Last will start the consumer with the last sequence received.
414    #[serde(rename = "last")]
415    Last,
416    /// New will only deliver new messages that are received by the `JetStream` server
417    /// after the consumer is created.
418    #[serde(rename = "new")]
419    New,
420    /// `ByStartSeq` will look for a defined starting sequence to the consumer's configured `opt_start_seq`
421    /// parameter.
422    #[serde(rename = "by_start_sequence")]
423    ByStartSequence {
424        #[serde(rename = "opt_start_seq")]
425        start_sequence: u64,
426    },
427    /// `ByStartTime` will select the first message with a timestamp >= to the consumer's
428    /// configured `opt_start_time` parameter.
429    #[serde(rename = "by_start_time")]
430    ByStartTime {
431        #[serde(rename = "opt_start_time", with = "rfc3339")]
432        start_time: time::OffsetDateTime,
433    },
434    /// `LastPerSubject` will start the consumer with the last message
435    /// for all subjects received.
436    #[serde(rename = "last_per_subject")]
437    LastPerSubject,
438}
439
440/// Determines whether messages will be acknowledged individually,
441/// in batches, or never.
442#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
443#[repr(u8)]
444pub enum AckPolicy {
445    /// All messages will be individually acknowledged. This is the default.
446    #[default]
447    #[serde(rename = "explicit")]
448    Explicit = 2,
449    /// No messages are acknowledged.
450    #[serde(rename = "none")]
451    None = 0,
452    /// Acknowledges all messages with lower sequence numbers when a later
453    /// message is acknowledged. Useful for "batching" acknowledgment.
454    #[serde(rename = "all")]
455    All = 1,
456}
457
458/// `ReplayPolicy` controls whether messages are sent to a consumer
459/// as quickly as possible or at the rate that they were originally received at.
460#[derive(Default, Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq)]
461#[repr(u8)]
462pub enum ReplayPolicy {
463    /// Sends all messages in a stream to the consumer as quickly as possible. This is the default.
464    #[default]
465    #[serde(rename = "instant")]
466    Instant = 0,
467    /// Sends messages to a consumer in a rate-limited fashion based on the rate of receipt. This
468    /// is useful for replaying traffic in a testing or staging environment based on production
469    /// traffic patterns.
470    #[serde(rename = "original")]
471    Original = 1,
472}
473
474fn is_default<T: Default + Eq>(t: &T) -> bool {
475    t == &T::default()
476}
477
478pub(crate) mod sample_freq_deser {
479    pub(crate) fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
480    where
481        T: std::str::FromStr,
482        T::Err: std::fmt::Display,
483        D: serde::Deserializer<'de>,
484    {
485        let s = <String as serde::Deserialize>::deserialize(deserializer)?;
486
487        let mut spliterator = s.split('%');
488        match (spliterator.next(), spliterator.next()) {
489            // No percentage occurred, parse as number
490            (Some(number), None) => T::from_str(number).map_err(serde::de::Error::custom),
491            // A percentage sign occurred right at the end
492            (Some(number), Some("")) => T::from_str(number).map_err(serde::de::Error::custom),
493            _ => Err(serde::de::Error::custom(format!(
494                "Malformed sample frequency: {s}"
495            ))),
496        }
497    }
498
499    pub(crate) fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
500    where
501        T: std::fmt::Display,
502        S: serde::Serializer,
503    {
504        serializer.serialize_str(&value.to_string())
505    }
506}
507
508#[derive(Clone, Copy, Debug, PartialEq)]
509pub enum StreamErrorKind {
510    TimedOut,
511    Other,
512}
513
514impl std::fmt::Display for StreamErrorKind {
515    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
516        match self {
517            Self::TimedOut => write!(f, "timed out"),
518            Self::Other => write!(f, "failed"),
519        }
520    }
521}
522
523pub type StreamError = Error<StreamErrorKind>;
524
525fn backoff(attempt: u32, _: &impl std::error::Error) -> Duration {
526    if attempt < 5 {
527        Duration::from_millis(500 * attempt as u64)
528    } else {
529        Duration::from_secs(10)
530    }
531}