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
8fn is_default<T: Default + Eq>(t: &T) -> bool {
9    t == &T::default()
10}
11
12// TODO How does the user choose? Think about what "UI" you would prefer.
13#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
14pub enum Credentials {
15    FromString(String),
16    #[schema(value_type = String, example = "/path/to/credentials.json")]
17    FromFile(PathBuf),
18}
19
20#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
21pub struct UserAndPassword {
22    pub user: String,
23    pub password: String,
24}
25
26#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
27pub struct Auth {
28    /// Credentials in the NATS `.creds` format (user JWT + NKey seed).
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub credentials: Option<Credentials>,
31    /// User JWT for decentralized (operator-mode) authentication.
32    ///
33    /// Requires `nkey` to be set as well: the connection nonce is signed
34    /// with the NKey seed. Equivalent to `credentials`, for deployments
35    /// that store the JWT and seed separately (e.g. as two secrets)
36    /// rather than as one `.creds` file.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub jwt: Option<String>,
39    /// NKey seed (`SU...`) for NKey challenge-response authentication.
40    ///
41    /// On its own, authenticates as a bare NKey user (a `nkey:` user in
42    /// the server configuration). Combined with `jwt`, signs the
43    /// connection nonce for decentralized authentication.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub nkey: Option<String>,
46    /// Token for token-based authentication.
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub token: Option<String>,
49    /// Username and password for password-based authentication.
50    #[serde(default, skip_serializing_if = "Option::is_none")]
51    pub user_and_password: Option<UserAndPassword>,
52}
53
54/// TLS options for connecting to a NATS server.
55#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
56pub struct Tls {
57    /// Require an encrypted connection; refuse to connect to servers that
58    /// do not offer TLS.
59    #[serde(default, skip_serializing_if = "is_default")]
60    pub require_tls: bool,
61    /// Path to a PEM file with additional root certificates to trust when
62    /// verifying the server certificate, for servers whose certificates
63    /// are not signed by a public CA.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    #[schema(value_type = String, example = "/path/to/ca.crt")]
66    pub root_certificates_file: Option<PathBuf>,
67}
68
69pub const fn default_connection_timeout_secs() -> u64 {
70    10
71}
72
73pub const fn default_request_timeout_secs() -> u64 {
74    10
75}
76
77pub const fn default_inactivity_timeout_secs() -> u64 {
78    60
79}
80
81pub const fn default_retry_interval_secs() -> u64 {
82    5
83}
84
85/// Options for connecting to a NATS server.
86#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
87pub struct ConnectOptions {
88    /// NATS server URL (e.g., "nats://localhost:4222").
89    pub server_url: String,
90
91    /// Authentication configuration.
92    #[serde(default, skip_serializing_if = "is_default")]
93    pub auth: Auth,
94
95    /// TLS configuration.
96    #[serde(default, skip_serializing_if = "is_default")]
97    pub tls: Tls,
98
99    /// Connection timeout
100    ///
101    /// How long to wait when establishing the initial connection to the
102    /// NATS server.
103    #[serde(default = "default_connection_timeout_secs")]
104    pub connection_timeout_secs: u64,
105
106    /// Request timeout in seconds.
107    ///
108    /// How long to wait for responses to requests.
109    #[serde(default = "default_request_timeout_secs")]
110    pub request_timeout_secs: u64,
111}
112
113#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
114pub enum ReplayPolicy {
115    #[default]
116    Instant,
117    Original,
118}
119
120#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
121pub enum DeliverPolicy {
122    All,
123    Last,
124    New,
125    ByStartSequence {
126        start_sequence: u64,
127    },
128    ByStartTime {
129        #[schema(value_type = String, format = "date-time", example = "2023-01-15T09:30:00Z")]
130        start_time: OffsetDateTime,
131    },
132    LastPerSubject,
133}
134
135#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
136pub struct ConsumerConfig {
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub name: Option<String>,
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub description: Option<String>,
141    #[serde(default, skip_serializing_if = "is_default")]
142    pub filter_subjects: Vec<String>,
143    #[serde(default, skip_serializing_if = "is_default")]
144    pub replay_policy: ReplayPolicy,
145    #[serde(default, skip_serializing_if = "is_default")]
146    pub rate_limit: u64,
147    pub deliver_policy: DeliverPolicy,
148    #[serde(default, skip_serializing_if = "is_default")]
149    pub max_waiting: i64,
150    #[serde(default, skip_serializing_if = "is_default")]
151    pub metadata: HashMap<String, String>,
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub max_batch: Option<i64>,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub max_bytes: Option<i64>,
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub max_expires: Option<std::time::Duration>,
158}
159
160#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
161pub struct NatsInputConfig {
162    pub connection_config: ConnectOptions,
163    pub stream_name: String,
164    /// Maximum time in seconds to wait for the next message before running
165    /// a stream/server health check. Must be at least 1.
166    #[serde(default = "default_inactivity_timeout_secs")]
167    pub inactivity_timeout_secs: u64,
168    /// Delay between automatic reconnect attempts while in retry mode.
169    /// Must be at least 1.
170    #[serde(default = "default_retry_interval_secs")]
171    pub retry_interval_secs: u64,
172    pub consumer_config: ConsumerConfig,
173}
174
175pub const fn default_publish_timeout_secs() -> u64 {
176    5
177}
178
179/// Default max message payload when the bound stream's `max_message_size` is
180/// unset (the server reports -1) and no override is configured: the nats-server
181/// default.
182pub const DEFAULT_MAX_MESSAGE_SIZE_BYTES: usize = 1024 * 1024;
183
184/// Configuration for writing data to a NATS subject with `nats_output`.
185///
186/// The connector publishes to JetStream: each message is published with an
187/// acknowledgment request and the publish is retried until the server
188/// acknowledges it or the pipeline shuts down, so data is not lost to a
189/// server that is momentarily unavailable. The subject must be bound to a
190/// JetStream stream; publishing to a subject with no stream raises
191/// "no responders" and the publish fails.
192#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
193pub struct NatsOutputConfig {
194    /// Options for connecting to the NATS server.
195    pub connection_config: ConnectOptions,
196
197    /// NATS subject to publish to (e.g., "orders.created"). The subject
198    /// must be bound to a JetStream stream on the target server.
199    pub subject: String,
200
201    /// Headers to add to every message published by this connector, as
202    /// key/value pairs. Values are UTF-8 strings.
203    #[serde(default, skip_serializing_if = "Vec::is_empty")]
204    pub headers: Vec<NatsHeader>,
205
206    /// How the `Nats-Msg-Id` header of each message is chosen. Within a
207    /// stream's duplicate window (the stream's `duplicate_window`), the
208    /// server discards a publish whose id it has already stored, which makes
209    /// output replayed after a restart idempotent. Default: `content_hash`.
210    #[serde(default, skip_serializing_if = "is_default")]
211    pub message_id: NatsMessageId,
212
213    /// How long to wait for the server's publish acknowledgment before
214    /// retrying the publish. Must be at least 1.
215    #[serde(default = "default_publish_timeout_secs")]
216    pub publish_timeout_secs: u64,
217
218    /// Override for the maximum message size in bytes the connector offers to
219    /// the encoder. When unset, the connector discovers the limit at connect
220    /// time: the bound stream's `max_message_size` when the stream sets one,
221    /// else the server's max payload. The encoder splits output records across
222    /// messages by this limit; a record larger than the limit fails the
223    /// pipeline with an error naming the record rather than reaching the
224    /// server.
225    #[serde(default, skip_serializing_if = "Option::is_none")]
226    pub max_message_size: Option<usize>,
227}
228
229/// A header attached to every message published by `nats_output`.
230#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
231pub struct NatsHeader {
232    pub key: String,
233    pub value: String,
234}
235
236/// How `nats_output` chooses the `Nats-Msg-Id` header of each message.
237#[derive(Debug, Clone, Copy, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
238#[serde(rename_all = "snake_case")]
239pub enum NatsMessageId {
240    /// The id is derived from the message itself: the number of the
241    /// transaction that produced the output, a hash of the encoded payload,
242    /// and the count of earlier messages in the same transaction with the
243    /// same payload. The id is independent of the data format and is
244    /// reproduced when the pipeline replays the same output after a restart,
245    /// so the server stores each message once within the stream's duplicate
246    /// window. Two messages are only deduplicated when their encoded bytes
247    /// are identical, so exact replay deduplication requires the format to
248    /// emit one record per message (`buffer_size_records: 1` for `json`).
249    #[default]
250    ContentHash,
251    /// No `Nats-Msg-Id` header: output replayed after a restart is stored
252    /// again, and every consumer of the stream must tolerate duplicates.
253    None,
254}