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 between automatic reconnect attempts.
107pub const DEFAULT_RETRY_INTERVAL: ConfigDuration = ConfigDuration::from_secs(5);
108
109// The defaults as the OpenAPI schema shows them, one function per
110// `#[schema(default = ...)]`.
111fn default_connection_timeout() -> String {
112    DEFAULT_CONNECTION_TIMEOUT.to_string()
113}
114fn default_request_timeout() -> String {
115    DEFAULT_REQUEST_TIMEOUT.to_string()
116}
117fn default_inactivity_timeout() -> String {
118    DEFAULT_INACTIVITY_TIMEOUT.to_string()
119}
120fn default_retry_interval() -> String {
121    DEFAULT_RETRY_INTERVAL.to_string()
122}
123
124/// Options for connecting to a NATS server.
125#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
126pub struct ConnectOptions {
127    /// NATS server URL (e.g., "nats://localhost:4222").
128    pub server_url: String,
129
130    /// Authentication configuration.
131    #[serde(default, skip_serializing_if = "is_default")]
132    pub auth: Auth,
133
134    /// TLS configuration.
135    #[serde(default, skip_serializing_if = "is_default")]
136    pub tls: Tls,
137
138    /// Connection timeout, for example `10s`.
139    ///
140    /// How long to wait when establishing the initial connection to the
141    /// NATS server. Unset selects the default, `DEFAULT_CONNECTION_TIMEOUT`.
142    #[serde(
143        default,
144        alias = "connection_timeout_secs",
145        deserialize_with = "duration_connection_timeout",
146        skip_serializing_if = "Option::is_none"
147    )]
148    #[schema(value_type = Option<String>, default = default_connection_timeout)]
149    pub connection_timeout: Option<ConfigDuration>,
150
151    /// Request timeout, for example `10s`.
152    ///
153    /// How long to wait for responses to requests. Unset selects
154    /// the default, `DEFAULT_REQUEST_TIMEOUT`.
155    #[serde(
156        default,
157        alias = "request_timeout_secs",
158        deserialize_with = "duration_request_timeout",
159        skip_serializing_if = "Option::is_none"
160    )]
161    #[schema(value_type = Option<String>, default = default_request_timeout)]
162    pub request_timeout: Option<ConfigDuration>,
163}
164
165impl ConnectOptions {
166    /// The initial-connection timeout in effect, or
167    /// [`DEFAULT_CONNECTION_TIMEOUT`].
168    pub fn connection_timeout(&self) -> ConfigDuration {
169        self.connection_timeout
170            .unwrap_or(DEFAULT_CONNECTION_TIMEOUT)
171    }
172
173    /// The request timeout in effect, or [`DEFAULT_REQUEST_TIMEOUT`].
174    pub fn request_timeout(&self) -> ConfigDuration {
175        self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT)
176    }
177}
178
179#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
180pub enum ReplayPolicy {
181    #[default]
182    Instant,
183    Original,
184}
185
186#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
187pub enum DeliverPolicy {
188    All,
189    Last,
190    New,
191    ByStartSequence {
192        start_sequence: u64,
193    },
194    ByStartTime {
195        #[schema(value_type = String, format = "date-time", example = "2023-01-15T09:30:00Z")]
196        start_time: OffsetDateTime,
197    },
198    LastPerSubject,
199}
200
201#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
202pub struct ConsumerConfig {
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub name: Option<String>,
205    #[serde(default, skip_serializing_if = "Option::is_none")]
206    pub description: Option<String>,
207    #[serde(default, skip_serializing_if = "is_default")]
208    pub filter_subjects: Vec<String>,
209    #[serde(default, skip_serializing_if = "is_default")]
210    pub replay_policy: ReplayPolicy,
211    #[serde(default, skip_serializing_if = "is_default")]
212    pub rate_limit: u64,
213    pub deliver_policy: DeliverPolicy,
214    #[serde(default, skip_serializing_if = "is_default")]
215    pub max_waiting: i64,
216    #[serde(default, skip_serializing_if = "is_default")]
217    pub metadata: HashMap<String, String>,
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub max_batch: Option<i64>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub max_bytes: Option<i64>,
222    /// How long a pull request may stay parked on the server before it
223    /// expires, for example `30s`.
224    ///
225    /// Unset leaves the NATS server's own default in place.
226    #[serde(
227        default,
228        alias = "max_expires",
229        deserialize_with = "duration_max_expiry",
230        skip_serializing_if = "Option::is_none"
231    )]
232    #[schema(value_type = Option<String>)]
233    pub max_expiry: Option<ConfigDuration>,
234}
235
236#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
237pub struct NatsInputConfig {
238    pub connection_config: ConnectOptions,
239    pub stream_name: String,
240    /// Maximum time to wait for the next message before running a
241    /// stream/server health check, for example `60s`. Must be at least one
242    /// second. Unset selects the default, `DEFAULT_INACTIVITY_TIMEOUT`.
243    #[serde(
244        default,
245        alias = "inactivity_timeout_secs",
246        deserialize_with = "duration_inactivity_timeout",
247        skip_serializing_if = "Option::is_none"
248    )]
249    #[schema(value_type = Option<String>, default = default_inactivity_timeout)]
250    pub inactivity_timeout: Option<ConfigDuration>,
251
252    /// Delay between automatic reconnect attempts while in retry mode, for
253    /// example `5s`. Must be at least one second. Unset selects
254    /// the default, `DEFAULT_RETRY_INTERVAL`.
255    #[serde(
256        default,
257        alias = "retry_interval_secs",
258        deserialize_with = "duration_retry_interval",
259        skip_serializing_if = "Option::is_none"
260    )]
261    #[schema(value_type = Option<String>, default = default_retry_interval)]
262    pub retry_interval: Option<ConfigDuration>,
263
264    pub consumer_config: ConsumerConfig,
265}
266
267/// Default time to wait for the server's publish acknowledgment.
268pub const DEFAULT_PUBLISH_TIMEOUT: ConfigDuration = ConfigDuration::from_secs(5);
269
270/// The default as the OpenAPI schema shows it.
271fn default_publish_timeout() -> String {
272    DEFAULT_PUBLISH_TIMEOUT.to_string()
273}
274
275/// Default max message payload when the bound stream's `max_message_size` is
276/// unset (the server reports -1) and no override is configured: the nats-server
277/// default.
278pub const DEFAULT_MAX_MESSAGE_SIZE_BYTES: usize = 1024 * 1024;
279
280/// Configuration for writing data to a NATS subject with `nats_output`.
281///
282/// The connector publishes to JetStream: each message is published with an
283/// acknowledgment request and the publish is retried until the server
284/// acknowledges it or the pipeline shuts down, so data is not lost to a
285/// server that is momentarily unavailable. The subject must be bound to a
286/// JetStream stream; publishing to a subject with no stream raises
287/// "no responders" and the publish fails.
288#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
289pub struct NatsOutputConfig {
290    /// Options for connecting to the NATS server.
291    pub connection_config: ConnectOptions,
292
293    /// NATS subject to publish to (e.g., "orders.created"). The subject
294    /// must be bound to a JetStream stream on the target server.
295    pub subject: String,
296
297    /// Headers to add to every message published by this connector, as
298    /// key/value pairs. Values are UTF-8 strings.
299    #[serde(default, skip_serializing_if = "Vec::is_empty")]
300    pub headers: Vec<NatsHeader>,
301
302    /// How the `Nats-Msg-Id` header of each message is chosen. Within a
303    /// stream's duplicate window (the stream's `duplicate_window`), the
304    /// server discards a publish whose id it has already stored, which makes
305    /// output replayed after a restart idempotent. Default: `content_hash`.
306    #[serde(default, skip_serializing_if = "is_default")]
307    pub message_id: NatsMessageId,
308
309    /// How long to wait for the server's publish acknowledgment before
310    /// retrying the publish, for example `5s`. Must be at least one second.
311    /// Unset selects the default, `DEFAULT_PUBLISH_TIMEOUT`.
312    #[serde(
313        default,
314        alias = "publish_timeout_secs",
315        deserialize_with = "duration_publish_timeout",
316        skip_serializing_if = "Option::is_none"
317    )]
318    #[schema(value_type = Option<String>, default = default_publish_timeout)]
319    pub publish_timeout: Option<ConfigDuration>,
320
321    /// Override for the maximum message size in bytes the connector offers to
322    /// the encoder. When unset, the connector discovers the limit at connect
323    /// time: the bound stream's `max_message_size` when the stream sets one,
324    /// else the server's max payload. The encoder splits output records across
325    /// messages by this limit; a record larger than the limit fails the
326    /// pipeline with an error naming the record rather than reaching the
327    /// server.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub max_message_size: Option<usize>,
330}
331
332impl NatsOutputConfig {
333    /// The publish timeout in effect, or [`DEFAULT_PUBLISH_TIMEOUT`].
334    pub fn publish_timeout(&self) -> ConfigDuration {
335        self.publish_timeout.unwrap_or(DEFAULT_PUBLISH_TIMEOUT)
336    }
337}
338
339/// A header attached to every message published by `nats_output`.
340#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
341pub struct NatsHeader {
342    pub key: String,
343    pub value: String,
344}
345
346/// How `nats_output` chooses the `Nats-Msg-Id` header of each message.
347#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
348#[serde(rename_all = "snake_case")]
349pub enum NatsMessageId {
350    /// The id is derived from the message itself: the number of the
351    /// transaction that produced the output, a hash of the encoded payload,
352    /// and the count of earlier messages in the same transaction with the
353    /// same payload. The id is independent of the data format and is
354    /// reproduced when the pipeline replays the same output after a restart,
355    /// so the server stores each message once within the stream's duplicate
356    /// window. Two messages are only deduplicated when their encoded bytes
357    /// are identical, so exact replay deduplication requires the format to
358    /// emit one record per message (`buffer_size_records: 1` for `json`).
359    #[default]
360    ContentHash,
361    /// No `Nats-Msg-Id` header: output replayed after a restart is stored
362    /// again, and every consumer of the stream must tolerate duplicates.
363    None,
364}
365
366impl NatsInputConfig {
367    /// The inactivity timeout in effect, or [`DEFAULT_INACTIVITY_TIMEOUT`].
368    pub fn inactivity_timeout(&self) -> ConfigDuration {
369        self.inactivity_timeout
370            .unwrap_or(DEFAULT_INACTIVITY_TIMEOUT)
371    }
372
373    /// The reconnect delay in effect, or [`DEFAULT_RETRY_INTERVAL`].
374    pub fn retry_interval(&self) -> ConfigDuration {
375        self.retry_interval.unwrap_or(DEFAULT_RETRY_INTERVAL)
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    /// Wraps the fields under test in the keys `ConnectOptions` requires.
384    fn connect_options_json(fields: &str) -> String {
385        let separator = if fields.is_empty() { "" } else { ", " };
386        format!(r#"{{"server_url": "nats://localhost:4222"{separator}{fields}}}"#)
387    }
388
389    /// The legacy `{secs, nanos}` expiry rejects every other shape with a
390    /// message naming the setting: an unknown key, an empty object, a bare
391    /// number (never a spelling of this setting), a fractional number.
392    #[test]
393    fn the_legacy_expiry_object_rejects_other_shapes() {
394        for (expiry, expected) in [
395            (r#"{"secs": 45, "millis": 0}"#, "unknown field `millis`"),
396            (r#"{}"#, "{secs, nanos} object"),
397            ("30", "invalid type: integer `30`"),
398            ("30.5", "the number 30.5"),
399        ] {
400            let json = format!(r#"{{"deliver_policy": "All", "max_expires": {expiry}}}"#);
401            let error = serde_json::from_str::<ConsumerConfig>(&json)
402                .unwrap_err()
403                .to_string();
404            assert!(error.contains(expected), "{expiry}: {error}");
405        }
406    }
407
408    /// Wraps the fields under test in the keys `ConsumerConfig` requires.
409    fn consumer_config_json(fields: &str) -> String {
410        let separator = if fields.is_empty() { "" } else { ", " };
411        format!(r#"{{"deliver_policy": "All"{separator}{fields}}}"#)
412    }
413
414    /// Wraps the fields under test in the keys `NatsInputConfig` requires.
415    fn input_config_json(fields: &str) -> String {
416        let separator = if fields.is_empty() { "" } else { ", " };
417        format!(
418            r#"{{"connection_config": {{"server_url": "nats://localhost:4222"}}, "stream_name": "stream", "consumer_config": {{"deliver_policy": "All"}}{separator}{fields}}}"#
419        )
420    }
421
422    /// The connection timeout reads back from both spellings. They reach one
423    /// field, so writing both is rejected as a duplicate.
424    #[test]
425    fn connection_timeout_accepts_both_spellings() {
426        for (fields, expected) in [
427            ("", DEFAULT_CONNECTION_TIMEOUT),
428            (
429                r#""connection_timeout": "500ms""#,
430                ConfigDuration::from_millis(500),
431            ),
432            (
433                r#""connection_timeout_secs": 3"#,
434                ConfigDuration::from_secs(3),
435            ),
436        ] {
437            let json = connect_options_json(fields);
438            let config: ConnectOptions = serde_json::from_str(&json).unwrap();
439            assert_eq!(config.connection_timeout(), expected, "parsing {json}");
440        }
441
442        // Both spellings reach one field, so writing both is a duplicate.
443        let json =
444            connect_options_json(r#""connection_timeout": "1s", "connection_timeout_secs": 2"#);
445        let error = serde_json::from_str::<ConnectOptions>(&json)
446            .unwrap_err()
447            .to_string();
448        assert!(
449            error.contains("duplicate field `connection_timeout`"),
450            "{error}"
451        );
452    }
453
454    /// See [`connection_timeout_accepts_both_spellings`].
455    #[test]
456    fn request_timeout_accepts_both_spellings() {
457        for (fields, expected) in [
458            ("", DEFAULT_REQUEST_TIMEOUT),
459            (
460                r#""request_timeout": "250ms""#,
461                ConfigDuration::from_millis(250),
462            ),
463            (r#""request_timeout_secs": 7"#, ConfigDuration::from_secs(7)),
464        ] {
465            let json = connect_options_json(fields);
466            let config: ConnectOptions = serde_json::from_str(&json).unwrap();
467            assert_eq!(config.request_timeout(), expected, "parsing {json}");
468        }
469    }
470
471    /// The pull-request expiry has no default of its own: with neither field
472    /// set the accessor yields `None`, which leaves the NATS server's own
473    /// expiry in place.  The deprecated field is a `std::time::Duration`, so a
474    /// user writes it as a `{"secs": .., "nanos": ..}` object.
475    #[test]
476    fn max_expiry_accepts_both_spellings() {
477        for (fields, expected) in [
478            ("", None),
479            (
480                r#""max_expiry": "30s""#,
481                Some(ConfigDuration::from_secs(30)),
482            ),
483            (
484                r#""max_expires": {"secs": 45, "nanos": 500000000}"#,
485                Some(ConfigDuration::from_millis(45_500)),
486            ),
487            // An explicit `null` means "unset" on every duration setting.
488            // This one used to reject it as an unmatched variant, because its
489            // superseded spelling was an object rather than a number.
490            (r#""max_expiry": null"#, None),
491            (r#""max_expires": null"#, None),
492        ] {
493            let json = consumer_config_json(fields);
494            let config: ConsumerConfig = serde_json::from_str(&json).unwrap();
495            assert_eq!(config.max_expiry, expected, "parsing {json}");
496        }
497    }
498
499    /// The inactivity timeout reads back from both spellings.
500    #[test]
501    fn inactivity_timeout_accepts_both_spellings() {
502        for (fields, expected) in [
503            ("", DEFAULT_INACTIVITY_TIMEOUT),
504            (
505                r#""inactivity_timeout": "90s""#,
506                ConfigDuration::from_secs(90),
507            ),
508            (
509                r#""inactivity_timeout_secs": 15"#,
510                ConfigDuration::from_secs(15),
511            ),
512        ] {
513            let json = input_config_json(fields);
514            let config: NatsInputConfig = serde_json::from_str(&json).unwrap();
515            assert_eq!(config.inactivity_timeout(), expected, "parsing {json}");
516        }
517    }
518
519    /// See [`inactivity_timeout_accepts_both_spellings`].
520    #[test]
521    fn retry_interval_accepts_both_spellings() {
522        for (fields, expected) in [
523            ("", DEFAULT_RETRY_INTERVAL),
524            (r#""retry_interval": "2s""#, ConfigDuration::from_secs(2)),
525            (
526                r#""retry_interval_secs": 30"#,
527                ConfigDuration::from_secs(30),
528            ),
529        ] {
530            let json = input_config_json(fields);
531            let config: NatsInputConfig = serde_json::from_str(&json).unwrap();
532            assert_eq!(config.retry_interval(), expected, "parsing {json}");
533        }
534    }
535
536    /// The publish timeout reads back from both spellings.
537    #[test]
538    fn publish_timeout_accepts_both_spellings() {
539        for (fields, expected) in [
540            ("", DEFAULT_PUBLISH_TIMEOUT),
541            (r#""publish_timeout": "2s""#, ConfigDuration::from_secs(2)),
542            (
543                r#""publish_timeout_secs": 30"#,
544                ConfigDuration::from_secs(30),
545            ),
546        ] {
547            let separator = if fields.is_empty() { "" } else { ", " };
548            let json = format!(
549                r#"{{"connection_config": {{"server_url": "nats://localhost:4222"}}, "subject": "s"{separator}{fields}}}"#
550            );
551            let config: NatsOutputConfig = serde_json::from_str(&json).unwrap();
552            assert_eq!(config.publish_timeout(), expected, "parsing {json}");
553        }
554    }
555}