Skip to main content

feldera_types/transport/
nats.rs

1use std::path::PathBuf;
2use time::OffsetDateTime;
3
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use utoipa::ToSchema;
7
8use crate::{
9    duration::{ConfigDuration, LegacyUnit},
10    duration_setting, duration_struct_setting,
11};
12
13duration_setting!(
14    duration_connection_timeout,
15    "connection_timeout",
16    LegacyUnit::Secs
17);
18duration_setting!(
19    duration_request_timeout,
20    "request_timeout",
21    LegacyUnit::Secs
22);
23duration_setting!(
24    duration_inactivity_timeout,
25    "inactivity_timeout",
26    LegacyUnit::Secs
27);
28duration_setting!(duration_retry_interval, "retry_interval", LegacyUnit::Secs);
29duration_setting!(
30    duration_publish_timeout,
31    "publish_timeout",
32    LegacyUnit::Secs
33);
34duration_struct_setting!(duration_max_expiry, "max_expiry");
35
36fn is_default<T: Default + Eq>(t: &T) -> bool {
37    t == &T::default()
38}
39
40// TODO How does the user choose? Think about what "UI" you would prefer.
41#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
42pub enum Credentials {
43    FromString(String),
44    #[schema(value_type = String, example = "/path/to/credentials.json")]
45    FromFile(PathBuf),
46}
47
48#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
49pub struct UserAndPassword {
50    pub user: String,
51    pub password: String,
52}
53
54#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
55pub struct Auth {
56    /// Credentials in the NATS `.creds` format (user JWT + NKey seed).
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    pub credentials: Option<Credentials>,
59    /// User JWT for decentralized (operator-mode) authentication.
60    ///
61    /// Requires `nkey` to be set as well: the connection nonce is signed
62    /// with the NKey seed. Equivalent to `credentials`, for deployments
63    /// that store the JWT and seed separately (e.g. as two secrets)
64    /// rather than as one `.creds` file.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub jwt: Option<String>,
67    /// NKey seed (`SU...`) for NKey challenge-response authentication.
68    ///
69    /// On its own, authenticates as a bare NKey user (a `nkey:` user in
70    /// the server configuration). Combined with `jwt`, signs the
71    /// connection nonce for decentralized authentication.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub nkey: Option<String>,
74    /// Token for token-based authentication.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub token: Option<String>,
77    /// Username and password for password-based authentication.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub user_and_password: Option<UserAndPassword>,
80}
81
82/// TLS options for connecting to a NATS server.
83#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
84pub struct Tls {
85    /// Require an encrypted connection; refuse to connect to servers that
86    /// do not offer TLS.
87    #[serde(default, skip_serializing_if = "is_default")]
88    pub require_tls: bool,
89    /// Path to a PEM file with additional root certificates to trust when
90    /// verifying the server certificate, for servers whose certificates
91    /// are not signed by a public CA.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    #[schema(value_type = String, example = "/path/to/ca.crt")]
94    pub root_certificates_file: Option<PathBuf>,
95}
96
97/// Default time to wait for the initial connection to the NATS server.
98pub const DEFAULT_CONNECTION_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(10);
99
100/// Default time to wait for a response to a NATS request.
101pub const DEFAULT_REQUEST_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(10);
102
103/// Default time to wait for the next message before running a health check.
104pub const DEFAULT_INACTIVITY_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(60);
105
106/// Default delay before the first automatic reconnect attempt.
107pub const DEFAULT_RETRY_INTERVAL: ConfigDuration = ConfigDuration::from_secs(5);
108
109/// Default upper bound on the delay between reconnect attempts.
110pub const DEFAULT_RETRY_MAX_INTERVAL: ConfigDuration = ConfigDuration::from_secs(300);
111
112// The defaults as the OpenAPI schema shows them, one function per
113// `#[schema(default = ...)]`.
114fn default_connection_timeout() -> String {
115    DEFAULT_CONNECTION_TIMEOUT.to_string()
116}
117fn default_request_timeout() -> String {
118    DEFAULT_REQUEST_TIMEOUT.to_string()
119}
120fn default_inactivity_timeout() -> String {
121    DEFAULT_INACTIVITY_TIMEOUT.to_string()
122}
123fn default_retry_interval() -> String {
124    DEFAULT_RETRY_INTERVAL.to_string()
125}
126fn default_retry_max_interval() -> String {
127    DEFAULT_RETRY_MAX_INTERVAL.to_string()
128}
129
130/// Options for connecting to a NATS server.
131#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
132pub struct ConnectOptions {
133    /// NATS server URL (e.g., "nats://localhost:4222").
134    pub server_url: String,
135
136    /// Authentication configuration.
137    #[serde(default, skip_serializing_if = "is_default")]
138    pub auth: Auth,
139
140    /// TLS configuration.
141    #[serde(default, skip_serializing_if = "is_default")]
142    pub tls: Tls,
143
144    /// Connection timeout, for example `10s`.
145    ///
146    /// How long to wait when establishing the initial connection to the
147    /// NATS server. Unset selects the default, `DEFAULT_CONNECTION_TIMEOUT`.
148    #[serde(
149        default,
150        alias = "connection_timeout_secs",
151        deserialize_with = "duration_connection_timeout",
152        skip_serializing_if = "Option::is_none"
153    )]
154    #[schema(value_type = Option<String>, default = default_connection_timeout)]
155    pub connection_timeout: Option<ConfigDuration>,
156
157    /// Request timeout, for example `10s`.
158    ///
159    /// How long to wait for responses to requests. Unset selects
160    /// the default, `DEFAULT_REQUEST_TIMEOUT`.
161    #[serde(
162        default,
163        alias = "request_timeout_secs",
164        deserialize_with = "duration_request_timeout",
165        skip_serializing_if = "Option::is_none"
166    )]
167    #[schema(value_type = Option<String>, default = default_request_timeout)]
168    pub request_timeout: Option<ConfigDuration>,
169}
170
171impl ConnectOptions {
172    /// The initial-connection timeout in effect, or
173    /// [`DEFAULT_CONNECTION_TIMEOUT`].
174    pub fn connection_timeout(&self) -> ConfigDuration {
175        self.connection_timeout
176            .unwrap_or(DEFAULT_CONNECTION_TIMEOUT)
177    }
178
179    /// The request timeout in effect, or [`DEFAULT_REQUEST_TIMEOUT`].
180    pub fn request_timeout(&self) -> ConfigDuration {
181        self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT)
182    }
183}
184
185#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
186pub enum ReplayPolicy {
187    #[default]
188    Instant,
189    Original,
190}
191
192#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
193pub enum DeliverPolicy {
194    All,
195    Last,
196    New,
197    ByStartSequence {
198        start_sequence: u64,
199    },
200    ByStartTime {
201        #[schema(value_type = String, format = "date-time", example = "2023-01-15T09:30:00Z")]
202        start_time: OffsetDateTime,
203    },
204    LastPerSubject,
205}
206
207#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
208pub struct ConsumerConfig {
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub name: Option<String>,
211    #[serde(default, skip_serializing_if = "Option::is_none")]
212    pub description: Option<String>,
213    #[serde(default, skip_serializing_if = "is_default")]
214    pub filter_subjects: Vec<String>,
215    #[serde(default, skip_serializing_if = "is_default")]
216    pub replay_policy: ReplayPolicy,
217    #[serde(default, skip_serializing_if = "is_default")]
218    pub rate_limit: u64,
219    pub deliver_policy: DeliverPolicy,
220    #[serde(default, skip_serializing_if = "is_default")]
221    pub max_waiting: i64,
222    #[serde(default, skip_serializing_if = "is_default")]
223    pub metadata: HashMap<String, String>,
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub max_batch: Option<i64>,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub max_bytes: Option<i64>,
228    /// How long a pull request may stay parked on the server before it
229    /// expires, for example `30s`.
230    ///
231    /// Unset leaves the NATS server's own default in place.
232    #[serde(
233        default,
234        alias = "max_expires",
235        deserialize_with = "duration_max_expiry",
236        skip_serializing_if = "Option::is_none"
237    )]
238    #[schema(value_type = Option<String>)]
239    pub max_expiry: Option<ConfigDuration>,
240}
241
242#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
243pub struct NatsInputConfig {
244    pub connection_config: ConnectOptions,
245    pub stream_name: String,
246    /// Maximum time to wait for the next message before running a
247    /// stream/server health check, for example `60s`. Must be at least one
248    /// second. Unset selects the default, `DEFAULT_INACTIVITY_TIMEOUT`.
249    #[serde(
250        default,
251        alias = "inactivity_timeout_secs",
252        deserialize_with = "duration_inactivity_timeout",
253        skip_serializing_if = "Option::is_none"
254    )]
255    #[schema(value_type = Option<String>, default = default_inactivity_timeout)]
256    pub inactivity_timeout: Option<ConfigDuration>,
257
258    /// Delay before the first automatic reconnect attempt after a failure,
259    /// for example `5s`. The delay doubles on every consecutive failure, up
260    /// to `retry_max_interval`, and is jittered to avoid synchronized retries
261    /// across connectors. Must be at least one second. Unset selects the
262    /// default, `DEFAULT_RETRY_INTERVAL`.
263    #[serde(
264        default,
265        alias = "retry_interval_secs",
266        deserialize_with = "duration_retry_interval",
267        skip_serializing_if = "Option::is_none"
268    )]
269    #[schema(value_type = Option<String>, default = default_retry_interval)]
270    pub retry_interval: Option<ConfigDuration>,
271
272    /// Upper bound on the delay between consecutive reconnect attempts, for
273    /// example `5m`. Must be at least `retry_interval`. Unset selects the
274    /// default, `DEFAULT_RETRY_MAX_INTERVAL`.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    #[schema(value_type = Option<String>, default = default_retry_max_interval)]
277    pub retry_max_interval: Option<ConfigDuration>,
278
279    /// Maximum number of consecutive failed reconnect attempts before the
280    /// connector gives up and reports a fatal error. When unset, the connector
281    /// retries indefinitely. Must be at least 1 when set.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub retry_max_attempts: Option<u32>,
284    pub consumer_config: ConsumerConfig,
285}
286
287/// Default time to wait for the server's publish acknowledgment.
288pub const DEFAULT_PUBLISH_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(5);
289
290/// The default as the OpenAPI schema shows it.
291fn default_publish_timeout() -> String {
292    DEFAULT_PUBLISH_TIMEOUT.to_string()
293}
294
295/// Default max message payload when the bound stream's `max_message_size` is
296/// unset (the server reports -1) and no override is configured: the nats-server
297/// default.
298pub const DEFAULT_MAX_MESSAGE_SIZE_BYTES: usize = 1024 * 1024;
299
300/// Configuration for writing data to a NATS subject with `nats_output`.
301///
302/// The connector publishes to JetStream: each message is published with an
303/// acknowledgment request and the publish is retried until the server
304/// acknowledges it or the pipeline shuts down, so data is not lost to a
305/// server that is momentarily unavailable. The subject must be bound to a
306/// JetStream stream; publishing to a subject with no stream raises
307/// "no responders" and the publish fails.
308#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
309pub struct NatsOutputConfig {
310    /// Options for connecting to the NATS server.
311    pub connection_config: ConnectOptions,
312
313    /// NATS subject to publish to (e.g., "orders.created"). The subject
314    /// must be bound to a JetStream stream on the target server.
315    pub subject: String,
316
317    /// Headers to add to every message published by this connector, as
318    /// key/value pairs. Values are UTF-8 strings.
319    #[serde(default, skip_serializing_if = "Vec::is_empty")]
320    pub headers: Vec<NatsHeader>,
321
322    /// How the `Nats-Msg-Id` header of each message is chosen. Within a
323    /// stream's duplicate window (the stream's `duplicate_window`), the
324    /// server discards a publish whose id it has already stored, which makes
325    /// output replayed after a restart idempotent. Default: `content_hash`.
326    #[serde(default, skip_serializing_if = "is_default")]
327    pub message_id: NatsMessageId,
328
329    /// How long to wait for the server's publish acknowledgment before
330    /// retrying the publish, for example `5s`. Must be at least one second.
331    /// Unset selects the default, `DEFAULT_PUBLISH_TIMEOUT`.
332    #[serde(
333        default,
334        alias = "publish_timeout_secs",
335        deserialize_with = "duration_publish_timeout",
336        skip_serializing_if = "Option::is_none"
337    )]
338    #[schema(value_type = Option<String>, default = default_publish_timeout)]
339    pub publish_timeout: Option<ConfigDuration>,
340
341    /// Override for the maximum message size in bytes the connector offers to
342    /// the encoder. When unset, the connector discovers the limit at connect
343    /// time: the bound stream's `max_message_size` when the stream sets one,
344    /// else the server's max payload. The encoder splits output records across
345    /// messages by this limit; a record larger than the limit fails the
346    /// pipeline with an error naming the record rather than reaching the
347    /// server.
348    #[serde(default, skip_serializing_if = "Option::is_none")]
349    pub max_message_size: Option<usize>,
350}
351
352impl NatsOutputConfig {
353    /// The publish timeout in effect, or [`DEFAULT_PUBLISH_TIMEOUT`].
354    pub fn publish_timeout(&self) -> ConfigDuration {
355        self.publish_timeout.unwrap_or(DEFAULT_PUBLISH_TIMEOUT)
356    }
357}
358
359/// A header attached to every message published by `nats_output`.
360#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
361pub struct NatsHeader {
362    pub key: String,
363    pub value: String,
364}
365
366/// How `nats_output` chooses the `Nats-Msg-Id` header of each message.
367#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
368#[serde(rename_all = "snake_case")]
369pub enum NatsMessageId {
370    /// The id is derived from the message itself: the number of the
371    /// transaction that produced the output, a hash of the encoded payload,
372    /// and the count of earlier messages in the same transaction with the
373    /// same payload. The id is independent of the data format and is
374    /// reproduced when the pipeline replays the same output after a restart,
375    /// so the server stores each message once within the stream's duplicate
376    /// window. Two messages are only deduplicated when their encoded bytes
377    /// are identical, so exact replay deduplication requires the format to
378    /// emit one record per message (`buffer_size_records: 1` for `json`).
379    #[default]
380    ContentHash,
381    /// No `Nats-Msg-Id` header: output replayed after a restart is stored
382    /// again, and every consumer of the stream must tolerate duplicates.
383    None,
384}
385
386impl NatsInputConfig {
387    /// The inactivity timeout in effect, or [`DEFAULT_INACTIVITY_TIMEOUT`].
388    pub fn inactivity_timeout(&self) -> ConfigDuration {
389        self.inactivity_timeout
390            .unwrap_or(DEFAULT_INACTIVITY_TIMEOUT)
391    }
392
393    /// The first reconnect delay in effect, or [`DEFAULT_RETRY_INTERVAL`].
394    pub fn retry_interval(&self) -> ConfigDuration {
395        self.retry_interval.unwrap_or(DEFAULT_RETRY_INTERVAL)
396    }
397
398    /// The reconnect delay bound in effect, or [`DEFAULT_RETRY_MAX_INTERVAL`].
399    pub fn retry_max_interval(&self) -> ConfigDuration {
400        self.retry_max_interval
401            .unwrap_or(DEFAULT_RETRY_MAX_INTERVAL)
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408
409    /// Wraps the fields under test in the keys `ConnectOptions` requires.
410    fn connect_options_json(fields: &str) -> String {
411        let separator = if fields.is_empty() { "" } else { ", " };
412        format!(r#"{{"server_url": "nats://localhost:4222"{separator}{fields}}}"#)
413    }
414
415    /// The legacy `{secs, nanos}` expiry rejects every other shape with a
416    /// message naming the setting: an unknown key, an empty object, a bare
417    /// number (never a spelling of this setting), a fractional number.
418    #[test]
419    fn the_legacy_expiry_object_rejects_other_shapes() {
420        for (expiry, expected) in [
421            (r#"{"secs": 45, "millis": 0}"#, "unknown field `millis`"),
422            (r#"{}"#, "{secs, nanos} object"),
423            ("30", "invalid type: integer `30`"),
424            ("30.5", "the number 30.5"),
425        ] {
426            let json = format!(r#"{{"deliver_policy": "All", "max_expires": {expiry}}}"#);
427            let error = serde_json::from_str::<ConsumerConfig>(&json)
428                .unwrap_err()
429                .to_string();
430            assert!(error.contains(expected), "{expiry}: {error}");
431        }
432    }
433
434    /// Wraps the fields under test in the keys `ConsumerConfig` requires.
435    fn consumer_config_json(fields: &str) -> String {
436        let separator = if fields.is_empty() { "" } else { ", " };
437        format!(r#"{{"deliver_policy": "All"{separator}{fields}}}"#)
438    }
439
440    /// Wraps the fields under test in the keys `NatsInputConfig` requires.
441    fn input_config_json(fields: &str) -> String {
442        let separator = if fields.is_empty() { "" } else { ", " };
443        format!(
444            r#"{{"connection_config": {{"server_url": "nats://localhost:4222"}}, "stream_name": "stream", "consumer_config": {{"deliver_policy": "All"}}{separator}{fields}}}"#
445        )
446    }
447
448    /// The connection timeout reads back from both spellings. They reach one
449    /// field, so writing both is rejected as a duplicate.
450    #[test]
451    fn connection_timeout_accepts_both_spellings() {
452        for (fields, expected) in [
453            ("", DEFAULT_CONNECTION_TIMEOUT),
454            (
455                r#""connection_timeout": "500ms""#,
456                ConfigDuration::from_millis(500),
457            ),
458            (
459                r#""connection_timeout_secs": 3"#,
460                ConfigDuration::from_secs(3),
461            ),
462        ] {
463            let json = connect_options_json(fields);
464            let config: ConnectOptions = serde_json::from_str(&json).unwrap();
465            assert_eq!(config.connection_timeout(), expected, "parsing {json}");
466        }
467
468        // Both spellings reach one field, so writing both is a duplicate.
469        let json =
470            connect_options_json(r#""connection_timeout": "1s", "connection_timeout_secs": 2"#);
471        let error = serde_json::from_str::<ConnectOptions>(&json)
472            .unwrap_err()
473            .to_string();
474        assert!(
475            error.contains("duplicate field `connection_timeout`"),
476            "{error}"
477        );
478    }
479
480    /// See [`connection_timeout_accepts_both_spellings`].
481    #[test]
482    fn request_timeout_accepts_both_spellings() {
483        for (fields, expected) in [
484            ("", DEFAULT_REQUEST_TIMEOUT),
485            (
486                r#""request_timeout": "250ms""#,
487                ConfigDuration::from_millis(250),
488            ),
489            (r#""request_timeout_secs": 7"#, ConfigDuration::from_secs(7)),
490        ] {
491            let json = connect_options_json(fields);
492            let config: ConnectOptions = serde_json::from_str(&json).unwrap();
493            assert_eq!(config.request_timeout(), expected, "parsing {json}");
494        }
495    }
496
497    /// The pull-request expiry has no default of its own: with neither field
498    /// set the accessor yields `None`, which leaves the NATS server's own
499    /// expiry in place.  The deprecated field is a `std::time::Duration`, so a
500    /// user writes it as a `{"secs": .., "nanos": ..}` object.
501    #[test]
502    fn max_expiry_accepts_both_spellings() {
503        for (fields, expected) in [
504            ("", None),
505            (
506                r#""max_expiry": "30s""#,
507                Some(ConfigDuration::from_secs(30)),
508            ),
509            (
510                r#""max_expires": {"secs": 45, "nanos": 500000000}"#,
511                Some(ConfigDuration::from_millis(45_500)),
512            ),
513            // An explicit `null` means "unset" on every duration setting.
514            // This one used to reject it as an unmatched variant, because its
515            // superseded spelling was an object rather than a number.
516            (r#""max_expiry": null"#, None),
517            (r#""max_expires": null"#, None),
518        ] {
519            let json = consumer_config_json(fields);
520            let config: ConsumerConfig = serde_json::from_str(&json).unwrap();
521            assert_eq!(config.max_expiry, expected, "parsing {json}");
522        }
523    }
524
525    /// The inactivity timeout reads back from both spellings.
526    #[test]
527    fn inactivity_timeout_accepts_both_spellings() {
528        for (fields, expected) in [
529            ("", DEFAULT_INACTIVITY_TIMEOUT),
530            (
531                r#""inactivity_timeout": "90s""#,
532                ConfigDuration::from_secs(90),
533            ),
534            (
535                r#""inactivity_timeout_secs": 15"#,
536                ConfigDuration::from_secs(15),
537            ),
538        ] {
539            let json = input_config_json(fields);
540            let config: NatsInputConfig = serde_json::from_str(&json).unwrap();
541            assert_eq!(config.inactivity_timeout(), expected, "parsing {json}");
542        }
543    }
544
545    /// See [`inactivity_timeout_accepts_both_spellings`].
546    #[test]
547    fn retry_interval_accepts_both_spellings() {
548        for (fields, expected) in [
549            ("", DEFAULT_RETRY_INTERVAL),
550            (r#""retry_interval": "2s""#, ConfigDuration::from_secs(2)),
551            (
552                r#""retry_interval_secs": 30"#,
553                ConfigDuration::from_secs(30),
554            ),
555        ] {
556            let json = input_config_json(fields);
557            let config: NatsInputConfig = serde_json::from_str(&json).unwrap();
558            assert_eq!(config.retry_interval(), expected, "parsing {json}");
559        }
560    }
561
562    /// The publish timeout reads back from both spellings.
563    #[test]
564    fn publish_timeout_accepts_both_spellings() {
565        for (fields, expected) in [
566            ("", DEFAULT_PUBLISH_TIMEOUT),
567            (r#""publish_timeout": "2s""#, ConfigDuration::from_secs(2)),
568            (
569                r#""publish_timeout_secs": 30"#,
570                ConfigDuration::from_secs(30),
571            ),
572        ] {
573            let separator = if fields.is_empty() { "" } else { ", " };
574            let json = format!(
575                r#"{{"connection_config": {{"server_url": "nats://localhost:4222"}}, "subject": "s"{separator}{fields}}}"#
576            );
577            let config: NatsOutputConfig = serde_json::from_str(&json).unwrap();
578            assert_eq!(config.publish_timeout(), expected, "parsing {json}");
579        }
580    }
581}