feldera_types/
config.rs

1//! Controller configuration.
2//!
3//! This module defines the controller configuration structure.  The leaves of
4//! this structure are individual transport-specific and data-format-specific
5//! endpoint configs.  We represent these configs as opaque JSON values, so
6//! that the entire configuration tree can be deserialized from a JSON file.
7
8use crate::transport::adhoc::AdHocInputConfig;
9use crate::transport::clock::ClockConfig;
10use crate::transport::datagen::DatagenInputConfig;
11use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
12use crate::transport::file::{FileInputConfig, FileOutputConfig};
13use crate::transport::http::HttpInputConfig;
14use crate::transport::iceberg::IcebergReaderConfig;
15use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
16use crate::transport::nexmark::NexmarkInputConfig;
17use crate::transport::postgres::{PostgresReaderConfig, PostgresWriterConfig};
18use crate::transport::pubsub::PubSubInputConfig;
19use crate::transport::redis::RedisOutputConfig;
20use crate::transport::s3::S3InputConfig;
21use crate::transport::url::UrlInputConfig;
22use core::fmt;
23use serde::de::{self, MapAccess, Visitor};
24use serde::{Deserialize, Deserializer, Serialize};
25use serde_json::Value as JsonValue;
26use serde_yaml::Value as YamlValue;
27use std::fmt::Display;
28use std::path::Path;
29use std::str::FromStr;
30use std::time::Duration;
31use std::{borrow::Cow, cmp::max, collections::BTreeMap};
32use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
33use utoipa::ToSchema;
34
35const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
36
37/// Default value of `ConnectorConfig::max_queued_records`.
38pub const fn default_max_queued_records() -> u64 {
39    1_000_000
40}
41
42/// Default maximum batch size for connectors, in records.
43///
44/// If you change this then update the comment on
45/// [ConnectorConfig::max_batch_size].
46pub const fn default_max_batch_size() -> u64 {
47    10_000
48}
49
50pub const DEFAULT_CLOCK_RESOLUTION_USECS: u64 = 1_000_000;
51
52/// Pipeline deployment configuration.
53/// It represents configuration entries directly provided by the user
54/// (e.g., runtime configuration) and entries derived from the schema
55/// of the compiled program (e.g., connectors). Storage configuration,
56/// if applicable, is set by the runner.
57#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
58pub struct PipelineConfig {
59    /// Global controller configuration.
60    #[serde(flatten)]
61    #[schema(inline)]
62    pub global: RuntimeConfig,
63
64    /// Pipeline name.
65    pub name: Option<String>,
66
67    /// Configuration for persistent storage
68    ///
69    /// If `global.storage` is `Some(_)`, this field must be set to some
70    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
71    /// this field.
72    #[serde(default)]
73    pub storage_config: Option<StorageConfig>,
74
75    /// Input endpoint configuration.
76    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
77
78    /// Output endpoint configuration.
79    #[serde(default)]
80    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
81}
82
83impl PipelineConfig {
84    pub fn max_parallel_connector_init(&self) -> u64 {
85        max(
86            self.global
87                .max_parallel_connector_init
88                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
89            1,
90        )
91    }
92
93    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
94        let (storage_config, storage_options) = storage.unzip();
95        Self {
96            global: RuntimeConfig {
97                storage: storage_options,
98                ..self.global
99            },
100            storage_config,
101            ..self
102        }
103    }
104
105    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
106        let storage_options = self.global.storage.as_ref();
107        let storage_config = self.storage_config.as_ref();
108        storage_config.zip(storage_options)
109    }
110}
111
112/// Configuration for persistent storage in a [`PipelineConfig`].
113#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
114pub struct StorageConfig {
115    /// A directory to keep pipeline state, as a path on the filesystem of the
116    /// machine or container where the pipeline will run.
117    ///
118    /// When storage is enabled, this directory stores the data for
119    /// [StorageBackendConfig::Default].
120    ///
121    /// When fault tolerance is enabled, this directory stores checkpoints and
122    /// the log.
123    pub path: String,
124
125    /// How to cache access to storage in this pipeline.
126    #[serde(default)]
127    pub cache: StorageCacheConfig,
128}
129
130impl StorageConfig {
131    pub fn path(&self) -> &Path {
132        Path::new(&self.path)
133    }
134}
135
136/// How to cache access to storage within a Feldera pipeline.
137#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
138#[serde(rename_all = "snake_case")]
139pub enum StorageCacheConfig {
140    /// Use the operating system's page cache as the primary storage cache.
141    ///
142    /// This is the default because it currently performs better than
143    /// `FelderaCache`.
144    #[default]
145    PageCache,
146
147    /// Use Feldera's internal cache implementation.
148    ///
149    /// This is under development. It will become the default when its
150    /// performance exceeds that of `PageCache`.
151    FelderaCache,
152}
153
154impl StorageCacheConfig {
155    #[cfg(unix)]
156    pub fn to_custom_open_flags(&self) -> i32 {
157        match self {
158            StorageCacheConfig::PageCache => (),
159            StorageCacheConfig::FelderaCache => {
160                #[cfg(target_os = "linux")]
161                return libc::O_DIRECT;
162            }
163        }
164        0
165    }
166}
167
168/// Storage configuration for a pipeline.
169#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
170#[serde(default)]
171pub struct StorageOptions {
172    /// How to connect to the underlying storage.
173    pub backend: StorageBackendConfig,
174
175    /// For a batch of data maintained as part of a persistent index during a
176    /// pipeline run, the minimum estimated number of bytes to write it to
177    /// storage.
178    ///
179    /// This is provided for debugging and fine-tuning and should ordinarily be
180    /// left unset.
181    ///
182    /// A value of 0 will write even empty batches to storage, and nonzero
183    /// values provide a threshold.  `usize::MAX` would effectively disable
184    /// storage for such batches.  The default is 1,048,576 (1 MiB).
185    pub min_storage_bytes: Option<usize>,
186
187    /// For a batch of data passed through the pipeline during a single step,
188    /// the minimum estimated number of bytes to write it to storage.
189    ///
190    /// This is provided for debugging and fine-tuning and should ordinarily be
191    /// left unset.  A value of 0 will write even empty batches to storage, and
192    /// nonzero values provide a threshold.  `usize::MAX`, the default,
193    /// effectively disables storage for such batches.  If it is set to another
194    /// value, it should ordinarily be greater than or equal to
195    /// `min_storage_bytes`.
196    pub min_step_storage_bytes: Option<usize>,
197
198    /// The form of compression to use in data batches.
199    ///
200    /// Compression has a CPU cost but it can take better advantage of limited
201    /// NVMe and network bandwidth, which means that it can increase overall
202    /// performance.
203    pub compression: StorageCompression,
204
205    /// The maximum size of the in-memory storage cache, in MiB.
206    ///
207    /// If set, the specified cache size is spread across all the foreground and
208    /// background threads. If unset, each foreground or background thread cache
209    /// is limited to 256 MiB.
210    pub cache_mib: Option<usize>,
211}
212
213/// Backend storage configuration.
214#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
215#[serde(tag = "name", content = "config", rename_all = "snake_case")]
216pub enum StorageBackendConfig {
217    /// Use the default storage configuration.
218    ///
219    /// This currently uses the local file system.
220    #[default]
221    Default,
222
223    /// Object storage.
224    Object(ObjectStorageConfig),
225}
226
227impl Display for StorageBackendConfig {
228    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229        match self {
230            StorageBackendConfig::Default => write!(f, "default"),
231            StorageBackendConfig::Object(_) => write!(f, "object"),
232        }
233    }
234}
235
236/// Storage compression algorithm.
237#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
238#[serde(rename_all = "snake_case")]
239pub enum StorageCompression {
240    /// Use Feldera's default compression algorithm.
241    ///
242    /// The default may change as Feldera's performance is tuned and new
243    /// algorithms are introduced.
244    #[default]
245    Default,
246
247    /// Do not compress.
248    None,
249
250    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
251    Snappy,
252}
253
254#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
255pub struct ObjectStorageConfig {
256    /// URL.
257    ///
258    /// The following URL schemes are supported:
259    ///
260    /// * S3:
261    ///   - `s3://<bucket>/<path>`
262    ///   - `s3a://<bucket>/<path>`
263    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
264    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
265    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
266    /// * Google Cloud Storage:
267    ///   - `gs://<bucket>/<path>`
268    /// * Microsoft Azure Blob Storage:
269    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
270    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
271    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
272    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
273    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
274    ///   - `azure://<container>/<path>` (custom)
275    ///   - `https://<account>.dfs.core.windows.net`
276    ///   - `https://<account>.blob.core.windows.net`
277    ///   - `https://<account>.blob.core.windows.net/<container>`
278    ///   - `https://<account>.dfs.fabric.microsoft.com`
279    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
280    ///   - `https://<account>.blob.fabric.microsoft.com`
281    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
282    ///
283    /// Settings derived from the URL will override other settings.
284    pub url: String,
285
286    /// Additional options as key-value pairs.
287    ///
288    /// The following keys are supported:
289    ///
290    /// * S3:
291    ///   - `access_key_id`: AWS Access Key.
292    ///   - `secret_access_key`: AWS Secret Access Key.
293    ///   - `region`: Region.
294    ///   - `default_region`: Default region.
295    ///   - `endpoint`: Custom endpoint for communicating with S3,
296    ///     e.g. `https://localhost:4566` for testing against a localstack
297    ///     instance.
298    ///   - `token`: Token to use for requests (passed to underlying provider).
299    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
300    /// * Google Cloud Storage:
301    ///   - `service_account`: Path to the service account file.
302    ///   - `service_account_key`: The serialized service account key.
303    ///   - `google_application_credentials`: Application credentials path.
304    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
305    /// * Microsoft Azure Blob Storage:
306    ///   - `access_key`: Azure Access Key.
307    ///   - `container_name`: Azure Container Name.
308    ///   - `account`: Azure Account.
309    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
310    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
311    ///   - `client_secret`: Client secret for use in client secret flow.
312    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
313    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
314    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
315    ///
316    /// Options set through the URL take precedence over those set with these
317    /// options.
318    #[serde(flatten)]
319    pub other_options: BTreeMap<String, String>,
320}
321
322/// Global pipeline configuration settings. This is the publicly
323/// exposed type for users to configure pipelines.
324#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
325#[serde(default)]
326pub struct RuntimeConfig {
327    /// Number of DBSP worker threads.
328    ///
329    /// Each DBSP "foreground" worker thread is paired with a "background"
330    /// thread for LSM merging, making the total number of threads twice the
331    /// specified number.
332    ///
333    /// The typical sweet spot for the number of workers is between 4 and 16.
334    /// Each worker increases overall memory consumption for data structures
335    /// used during a step.
336    pub workers: u16,
337
338    /// Storage configuration.
339    ///
340    /// - If this is `None`, the default, the pipeline's state is kept in
341    ///   in-memory data-structures.  This is useful if the pipeline's state
342    ///   will fit in memory and if the pipeline is ephemeral and does not need
343    ///   to be recovered after a restart. The pipeline will most likely run
344    ///   faster since it does not need to access storage.
345    ///
346    /// - If set, the pipeline's state is kept on storage.  This allows the
347    ///   pipeline to work with state that will not fit into memory. It also
348    ///   allows the state to be checkpointed and recovered across restarts.
349    #[serde(deserialize_with = "deserialize_storage_options")]
350    pub storage: Option<StorageOptions>,
351
352    /// Fault tolerance configuration.
353    #[serde(deserialize_with = "deserialize_fault_tolerance")]
354    pub fault_tolerance: FtConfig,
355
356    /// Enable CPU profiler.
357    ///
358    /// The default value is `true`.
359    pub cpu_profiler: bool,
360
361    /// Enable pipeline tracing.
362    pub tracing: bool,
363
364    /// Jaeger tracing endpoint to send tracing information to.
365    pub tracing_endpoint_jaeger: String,
366
367    /// Minimal input batch size.
368    ///
369    /// The controller delays pushing input records to the circuit until at
370    /// least `min_batch_size_records` records have been received (total
371    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
372    /// have passed since at least one input records has been buffered.
373    /// Defaults to 0.
374    pub min_batch_size_records: u64,
375
376    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
377    /// get buffered by the controller, defaults to 0.
378    pub max_buffering_delay_usecs: u64,
379
380    /// Resource reservations and limits. This is enforced
381    /// only in Feldera Cloud.
382    pub resources: ResourceConfig,
383
384    /// Real-time clock resolution in microseconds.
385    ///
386    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
387    /// queries depends on the real-time clock and can change over time without any external
388    /// inputs.  The pipeline will update the clock value and trigger incremental recomputation
389    /// at most each `clock_resolution_usecs` microseconds.
390    ///
391    /// It is set to 1 second (1,000,000 microseconds) by default.
392    ///
393    /// Set to `null` to disable periodic clock updates.
394    pub clock_resolution_usecs: Option<u64>,
395
396    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
397    /// its worker threads.  Specify at least twice as many CPU numbers as
398    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
399    /// might not be able to honor CPU pinning requests.
400    ///
401    /// CPU pinning can make pipelines run faster and perform more consistently,
402    /// as long as different pipelines running on the same machine are pinned to
403    /// different CPUs.
404    pub pin_cpus: Vec<usize>,
405
406    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
407    /// Setting this value will override the default of the runner.
408    pub provisioning_timeout_secs: Option<u64>,
409
410    /// The maximum number of connectors initialized in parallel during pipeline
411    /// startup.
412    ///
413    /// At startup, the pipeline must initialize all of its input and output connectors.
414    /// Depending on the number and types of connectors, this can take a long time.
415    /// To accelerate the process, multiple connectors are initialized concurrently.
416    /// This option controls the maximum number of connectors that can be initialized
417    /// in parallel.
418    ///
419    /// The default is 10.
420    pub max_parallel_connector_init: Option<u64>,
421
422    /// Specification of additional (sidecar) containers.
423    pub init_containers: Option<serde_yaml::Value>,
424
425    /// * If `true`, the suspend operation will first atomically checkpoint the pipeline before
426    ///   deprovisioning the compute resources. When resuming, the pipeline will start from this
427    ///   checkpoint.
428    /// * If `false`, then the pipeline will be suspended without creating an additional checkpoint.
429    ///   When resuming, it will pick up the latest checkpoint made by the periodic checkpointer or
430    ///   by invoking the `/checkpoint` API.
431    pub checkpoint_during_suspend: bool,
432}
433
434/// Accepts "true" and "false" and converts them to the new format.
435fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
436where
437    D: Deserializer<'de>,
438{
439    struct BoolOrStruct;
440
441    impl<'de> Visitor<'de> for BoolOrStruct {
442        type Value = Option<StorageOptions>;
443
444        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
445            formatter.write_str("boolean or StorageOptions")
446        }
447
448        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
449        where
450            E: de::Error,
451        {
452            match v {
453                false => Ok(None),
454                true => Ok(Some(StorageOptions::default())),
455            }
456        }
457
458        fn visit_unit<E>(self) -> Result<Self::Value, E>
459        where
460            E: de::Error,
461        {
462            Ok(None)
463        }
464
465        fn visit_none<E>(self) -> Result<Self::Value, E>
466        where
467            E: de::Error,
468        {
469            Ok(None)
470        }
471
472        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
473        where
474            M: MapAccess<'de>,
475        {
476            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
477        }
478    }
479
480    deserializer.deserialize_any(BoolOrStruct)
481}
482
483/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
484/// tolerance.
485///
486/// Accepts `null` as disabling fault tolerance.
487///
488/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
489/// expect.
490fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
491where
492    D: Deserializer<'de>,
493{
494    struct StringOrStruct;
495
496    impl<'de> Visitor<'de> for StringOrStruct {
497        type Value = FtConfig;
498
499        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
500            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
501        }
502
503        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
504        where
505            E: de::Error,
506        {
507            match v {
508                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
509                    model: Some(FtModel::default()),
510                    ..FtConfig::default()
511                }),
512                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
513            }
514        }
515
516        fn visit_unit<E>(self) -> Result<Self::Value, E>
517        where
518            E: de::Error,
519        {
520            Ok(FtConfig::default())
521        }
522
523        fn visit_none<E>(self) -> Result<Self::Value, E>
524        where
525            E: de::Error,
526        {
527            Ok(FtConfig::default())
528        }
529
530        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
531        where
532            M: MapAccess<'de>,
533        {
534            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
535        }
536    }
537
538    deserializer.deserialize_any(StringOrStruct)
539}
540
541impl Default for RuntimeConfig {
542    fn default() -> Self {
543        Self {
544            workers: 8,
545            storage: Some(StorageOptions::default()),
546            fault_tolerance: FtConfig::default(),
547            cpu_profiler: true,
548            tracing: {
549                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
550                // to keep it on by default.
551                false
552            },
553            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
554            min_batch_size_records: 0,
555            max_buffering_delay_usecs: 0,
556            resources: ResourceConfig::default(),
557            clock_resolution_usecs: { Some(DEFAULT_CLOCK_RESOLUTION_USECS) },
558            pin_cpus: Vec::new(),
559            provisioning_timeout_secs: None,
560            max_parallel_connector_init: None,
561            init_containers: None,
562            checkpoint_during_suspend: true,
563        }
564    }
565}
566
567/// Fault-tolerance configuration.
568///
569/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
570/// which is the configuration that one gets if [RuntimeConfig] omits fault
571/// tolerance configuration.
572///
573/// The default value for [FtConfig::model] enables fault tolerance, as
574/// `Some(FtModel::default())`.  This is the configuration that one gets if
575/// [RuntimeConfig] includes a fault tolerance configuration but does not
576/// specify a particular model.
577#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
578#[serde(rename_all = "snake_case")]
579pub struct FtConfig {
580    /// Fault tolerance model to use.
581    #[serde(with = "none_as_string")]
582    #[serde(default = "default_model")]
583    #[schema(
584        schema_with = none_as_string_schema::<FtModel>,
585    )]
586    pub model: Option<FtModel>,
587
588    /// Interval between automatic checkpoints, in seconds.
589    ///
590    /// The default is 60 seconds.  Values less than 1 or greater than 3600 will
591    /// be forced into that range.
592    #[serde(default = "default_checkpoint_interval_secs")]
593    pub checkpoint_interval_secs: Option<u64>,
594}
595
596fn default_model() -> Option<FtModel> {
597    Some(FtModel::default())
598}
599
600pub fn default_checkpoint_interval_secs() -> Option<u64> {
601    Some(60)
602}
603
604impl Default for FtConfig {
605    fn default() -> Self {
606        Self {
607            model: None,
608            checkpoint_interval_secs: default_checkpoint_interval_secs(),
609        }
610    }
611}
612
613#[cfg(test)]
614mod test {
615    use super::deserialize_fault_tolerance;
616    use crate::config::{FtConfig, FtModel};
617    use serde::{Deserialize, Serialize};
618
619    #[test]
620    fn ft_config() {
621        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
622        #[serde(default)]
623        struct Wrapper {
624            #[serde(deserialize_with = "deserialize_fault_tolerance")]
625            config: FtConfig,
626        }
627
628        // Omitting FtConfig, or specifying null, or specifying model "none", disables fault tolerance.
629        for s in [
630            "{}",
631            r#"{"config": null}"#,
632            r#"{"config": {"model": "none"}}"#,
633        ] {
634            let config: Wrapper = serde_json::from_str(s).unwrap();
635            assert_eq!(
636                config,
637                Wrapper {
638                    config: FtConfig {
639                        model: None,
640                        checkpoint_interval_secs: Some(60)
641                    }
642                }
643            );
644        }
645
646        // Serializing disabled FT produces explicit "none" form.
647        let s = serde_json::to_string(&Wrapper {
648            config: FtConfig::default(),
649        })
650        .unwrap();
651        assert!(s.contains("\"none\""));
652
653        // `{}` for FtConfig, or `{...}` with `model` omitted, enables fault
654        // tolerance.
655        for s in [r#"{"config": {}}"#, r#"{"checkpoint_interval_secs": 60}"#] {
656            assert_eq!(
657                serde_json::from_str::<FtConfig>(s).unwrap(),
658                FtConfig {
659                    model: Some(FtModel::default()),
660                    checkpoint_interval_secs: Some(60)
661                }
662            );
663        }
664
665        // `"checkpoint_interval_secs": null` disables periodic checkpointing.
666        assert_eq!(
667            serde_json::from_str::<FtConfig>(r#"{"checkpoint_interval_secs": null}"#).unwrap(),
668            FtConfig {
669                model: Some(FtModel::default()),
670                checkpoint_interval_secs: None
671            }
672        );
673    }
674}
675
676impl FtConfig {
677    pub fn is_enabled(&self) -> bool {
678        self.model.is_some()
679    }
680
681    /// Returns the checkpoint interval, if fault tolerance is enabled, and
682    /// otherwise `None`.
683    pub fn checkpoint_interval(&self) -> Option<Duration> {
684        if self.is_enabled() {
685            self.checkpoint_interval_secs
686                .map(|interval| Duration::from_secs(interval.clamp(1, 3600)))
687        } else {
688            None
689        }
690    }
691}
692
693/// Serde implementation for de/serializing a string into `Option<T>` where
694/// `"none"` indicates `None` and any other string indicates `Some`.
695///
696/// This could be extended to handle non-strings by adding more forwarding
697/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
698/// them automatically.
699mod none_as_string {
700    use std::marker::PhantomData;
701
702    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
703    use serde::ser::{Serialize, Serializer};
704
705    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
706    where
707        S: Serializer,
708        T: Serialize,
709    {
710        match value.as_ref() {
711            Some(value) => value.serialize(serializer),
712            None => "none".serialize(serializer),
713        }
714    }
715
716    struct NoneAsString<T>(PhantomData<fn() -> T>);
717
718    impl<'de, T> Visitor<'de> for NoneAsString<T>
719    where
720        T: Deserialize<'de>,
721    {
722        type Value = Option<T>;
723
724        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
725            formatter.write_str("string")
726        }
727
728        fn visit_none<E>(self) -> Result<Self::Value, E>
729        where
730            E: serde::de::Error,
731        {
732            Ok(None)
733        }
734
735        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
736        where
737            E: serde::de::Error,
738        {
739            if &value.to_ascii_lowercase() == "none" {
740                Ok(None)
741            } else {
742                Ok(Some(T::deserialize(value.into_deserializer())?))
743            }
744        }
745    }
746
747    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
748    where
749        D: Deserializer<'de>,
750        T: Deserialize<'de>,
751    {
752        deserializer.deserialize_str(NoneAsString(PhantomData))
753    }
754}
755
756/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
757/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
758fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
759    Schema::OneOf(
760        OneOfBuilder::new()
761            .item(RefOr::Ref(Ref::new(format!(
762                "#/components/schemas/{}",
763                T::schema().0
764            ))))
765            .item(
766                ObjectBuilder::new()
767                    .schema_type(SchemaType::String)
768                    .enum_values(Some(vec!["none"])),
769            )
770            .default(Some(
771                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
772            ))
773            .build(),
774    )
775}
776
777/// Fault tolerance model.
778///
779/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
780/// level" of fault tolerance than [Self::AtLeastOnce].
781#[derive(
782    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
783)]
784#[serde(rename_all = "snake_case")]
785pub enum FtModel {
786    /// Each record is output at least once.  Crashes may duplicate output, but
787    /// no input or output is dropped.
788    AtLeastOnce,
789
790    /// Each record is output exactly once.  Crashes do not drop or duplicate
791    /// input or output.
792    #[default]
793    ExactlyOnce,
794}
795
796impl FtModel {
797    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
798        value.map_or("no", |model| model.as_str())
799    }
800
801    pub fn as_str(&self) -> &'static str {
802        match self {
803            FtModel::AtLeastOnce => "at_least_once",
804            FtModel::ExactlyOnce => "exactly_once",
805        }
806    }
807}
808
809pub struct FtModelUnknown;
810
811impl FromStr for FtModel {
812    type Err = FtModelUnknown;
813
814    fn from_str(s: &str) -> Result<Self, Self::Err> {
815        match s.to_ascii_lowercase().as_str() {
816            "exactly_once" => Ok(Self::ExactlyOnce),
817            "at_least_once" => Ok(Self::AtLeastOnce),
818            _ => Err(FtModelUnknown),
819        }
820    }
821}
822
823/// Describes an input connector configuration
824#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
825pub struct InputEndpointConfig {
826    /// The name of the input stream of the circuit that this endpoint is
827    /// connected to.
828    pub stream: Cow<'static, str>,
829
830    /// Connector configuration.
831    #[serde(flatten)]
832    pub connector_config: ConnectorConfig,
833}
834
835/// Deserialize the `start_after` property of a connector configuration.
836/// It requires a non-standard deserialization because we want to accept
837/// either a string or an array of strings.
838fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
839where
840    D: Deserializer<'de>,
841{
842    let value = Option::<JsonValue>::deserialize(deserializer)?;
843    match value {
844        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
845        Some(JsonValue::Array(arr)) => {
846            let vec = arr
847                .into_iter()
848                .map(|item| {
849                    item.as_str()
850                        .map(|s| s.to_string())
851                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
852                })
853                .collect::<Result<Vec<String>, _>>()?;
854            Ok(Some(vec))
855        }
856        Some(JsonValue::Null) | None => Ok(None),
857        _ => Err(serde::de::Error::custom(
858            "invalid 'start_after' property: expected a string, an array of strings, or null",
859        )),
860    }
861}
862
863/// A data connector's configuration
864#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
865pub struct ConnectorConfig {
866    /// Transport endpoint configuration.
867    pub transport: TransportConfig,
868
869    /// Parser configuration.
870    pub format: Option<FormatConfig>,
871
872    /// Name of the index that the connector is attached to.
873    ///
874    /// This property is valid for output connectors only.  It is used with data
875    /// transports and formats that expect output updates in the form of key/value
876    /// pairs, where the key typically represents a unique id associated with the
877    /// table or view.
878    ///
879    /// To support such output formats, an output connector can be attached to an
880    /// index created using the SQL CREATE INDEX statement.  An index of a table
881    /// or view contains the same updates as the table or view itself, indexed by
882    /// one or more key columns.
883    ///
884    /// See individual connector documentation for details on how they work
885    /// with indexes.
886    pub index: Option<String>,
887
888    /// Output buffer configuration.
889    #[serde(flatten)]
890    pub output_buffer_config: OutputBufferConfig,
891
892    /// Maximum batch size, in records.
893    ///
894    /// This is the maximum number of records to process in one batch through
895    /// the circuit.  The time and space cost of processing a batch is
896    /// asymptotically superlinear in the size of the batch, but very small
897    /// batches are less efficient due to constant factors.
898    ///
899    /// This should usually be less than `max_queued_records`, to give the
900    /// connector a round-trip time to restart and refill the buffer while
901    /// batches are being processed.
902    ///
903    /// Some input adapters might not honor this setting.
904    ///
905    /// The default is 10,000.
906    #[serde(default = "default_max_batch_size")]
907    pub max_batch_size: u64,
908
909    /// Backpressure threshold.
910    ///
911    /// Maximal number of records queued by the endpoint before the endpoint
912    /// is paused by the backpressure mechanism.
913    ///
914    /// For input endpoints, this setting bounds the number of records that have
915    /// been received from the input transport but haven't yet been consumed by
916    /// the circuit since the circuit, since the circuit is still busy processing
917    /// previous inputs.
918    ///
919    /// For output endpoints, this setting bounds the number of records that have
920    /// been produced by the circuit but not yet sent via the output transport endpoint
921    /// nor stored in the output buffer (see `enable_output_buffer`).
922    ///
923    /// Note that this is not a hard bound: there can be a small delay between
924    /// the backpressure mechanism is triggered and the endpoint is paused, during
925    /// which more data may be queued.
926    ///
927    /// The default is 1 million.
928    #[serde(default = "default_max_queued_records")]
929    pub max_queued_records: u64,
930
931    /// Create connector in paused state.
932    ///
933    /// The default is `false`.
934    #[serde(default)]
935    pub paused: bool,
936
937    /// Arbitrary user-defined text labels associated with the connector.
938    ///
939    /// These labels can be used in conjunction with the `start_after` property
940    /// to control the start order of connectors.
941    #[serde(default)]
942    pub labels: Vec<String>,
943
944    /// Start the connector after all connectors with specified labels.
945    ///
946    /// This property is used to control the start order of connectors.
947    /// The connector will not start until all connectors with the specified
948    /// labels have finished processing all inputs.
949    #[serde(deserialize_with = "deserialize_start_after")]
950    #[serde(default)]
951    pub start_after: Option<Vec<String>>,
952}
953
954#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
955#[serde(default)]
956pub struct OutputBufferConfig {
957    /// Enable output buffering.
958    ///
959    /// The output buffering mechanism allows decoupling the rate at which the pipeline
960    /// pushes changes to the output transport from the rate of input changes.
961    ///
962    /// By default, output updates produced by the pipeline are pushed directly to
963    /// the output transport. Some destinations may prefer to receive updates in fewer
964    /// bigger batches. For instance, when writing Parquet files, producing
965    /// one bigger file every few minutes is usually better than creating
966    /// small files every few milliseconds.
967    ///
968    /// To achieve such input/output decoupling, users can enable output buffering by
969    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
970    /// updates produced by the pipeline are consolidated in an internal buffer and are
971    /// pushed to the output transport when one of several conditions is satisfied:
972    ///
973    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
974    ///   milliseconds.
975    /// * buffer size exceeds `max_output_buffer_size_records` records.
976    ///
977    /// This flag is `false` by default.
978    // TODO: on-demand output triggered via the API.
979    pub enable_output_buffer: bool,
980
981    /// Maximum time in milliseconds data is kept in the output buffer.
982    ///
983    /// By default, data is kept in the buffer indefinitely until one of
984    /// the other output conditions is satisfied.  When this option is
985    /// set the buffer will be flushed at most every
986    /// `max_output_buffer_time_millis` milliseconds.
987    ///
988    /// NOTE: this configuration option requires the `enable_output_buffer` flag
989    /// to be set.
990    pub max_output_buffer_time_millis: usize,
991
992    /// Maximum number of updates to be kept in the output buffer.
993    ///
994    /// This parameter bounds the maximal size of the buffer.
995    /// Note that the size of the buffer is not always equal to the
996    /// total number of updates output by the pipeline. Updates to the
997    /// same record can overwrite or cancel previous updates.
998    ///
999    /// By default, the buffer can grow indefinitely until one of
1000    /// the other output conditions is satisfied.
1001    ///
1002    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1003    /// to be set.
1004    pub max_output_buffer_size_records: usize,
1005}
1006
1007impl Default for OutputBufferConfig {
1008    fn default() -> Self {
1009        Self {
1010            enable_output_buffer: false,
1011            max_output_buffer_size_records: usize::MAX,
1012            max_output_buffer_time_millis: usize::MAX,
1013        }
1014    }
1015}
1016
1017impl OutputBufferConfig {
1018    pub fn validate(&self) -> Result<(), String> {
1019        if self.enable_output_buffer
1020            && self.max_output_buffer_size_records == Self::default().max_output_buffer_size_records
1021            && self.max_output_buffer_time_millis == Self::default().max_output_buffer_time_millis
1022        {
1023            return Err(
1024                "when the 'enable_output_buffer' flag is set, one of 'max_output_buffer_size_records' and 'max_output_buffer_time_millis' settings must be specified"
1025                    .to_string(),
1026            );
1027        }
1028
1029        Ok(())
1030    }
1031}
1032
1033/// Describes an output connector configuration
1034#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1035pub struct OutputEndpointConfig {
1036    /// The name of the output stream of the circuit that this endpoint is
1037    /// connected to.
1038    pub stream: Cow<'static, str>,
1039
1040    /// Connector configuration.
1041    #[serde(flatten)]
1042    pub connector_config: ConnectorConfig,
1043}
1044
1045/// Transport-specific endpoint configuration passed to
1046/// `crate::OutputTransport::new_endpoint`
1047/// and `crate::InputTransport::new_endpoint`.
1048#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1049#[serde(tag = "name", content = "config", rename_all = "snake_case")]
1050pub enum TransportConfig {
1051    FileInput(FileInputConfig),
1052    FileOutput(FileOutputConfig),
1053    KafkaInput(KafkaInputConfig),
1054    KafkaOutput(KafkaOutputConfig),
1055    PubSubInput(PubSubInputConfig),
1056    UrlInput(UrlInputConfig),
1057    S3Input(S3InputConfig),
1058    DeltaTableInput(DeltaTableReaderConfig),
1059    DeltaTableOutput(DeltaTableWriterConfig),
1060    RedisOutput(RedisOutputConfig),
1061    // Prevent rust from complaining about large size difference between enum variants.
1062    IcebergInput(Box<IcebergReaderConfig>),
1063    PostgresInput(PostgresReaderConfig),
1064    PostgresOutput(PostgresWriterConfig),
1065    Datagen(DatagenInputConfig),
1066    Nexmark(NexmarkInputConfig),
1067    /// Direct HTTP input: cannot be instantiated through API
1068    HttpInput(HttpInputConfig),
1069    /// Direct HTTP output: cannot be instantiated through API
1070    HttpOutput,
1071    /// Ad hoc input: cannot be instantiated through API
1072    AdHocInput(AdHocInputConfig),
1073    ClockInput(ClockConfig),
1074}
1075
1076impl TransportConfig {
1077    pub fn name(&self) -> String {
1078        match self {
1079            TransportConfig::FileInput(_) => "file_input".to_string(),
1080            TransportConfig::FileOutput(_) => "file_output".to_string(),
1081            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
1082            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
1083            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
1084            TransportConfig::UrlInput(_) => "url_input".to_string(),
1085            TransportConfig::S3Input(_) => "s3_input".to_string(),
1086            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
1087            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
1088            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
1089            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
1090            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
1091            TransportConfig::Datagen(_) => "datagen".to_string(),
1092            TransportConfig::Nexmark(_) => "nexmark".to_string(),
1093            TransportConfig::HttpInput(_) => "http_input".to_string(),
1094            TransportConfig::HttpOutput => "http_output".to_string(),
1095            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
1096            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
1097            TransportConfig::ClockInput(_) => "clock".to_string(),
1098        }
1099    }
1100}
1101
1102/// Data format specification used to parse raw data received from the
1103/// endpoint or to encode data sent to the endpoint.
1104#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
1105pub struct FormatConfig {
1106    /// Format name, e.g., "csv", "json", "bincode", etc.
1107    pub name: Cow<'static, str>,
1108
1109    /// Format-specific parser or encoder configuration.
1110    #[serde(default)]
1111    #[schema(value_type = Object)]
1112    pub config: YamlValue,
1113}
1114
1115#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize, ToSchema)]
1116#[serde(default)]
1117pub struct ResourceConfig {
1118    /// The minimum number of CPU cores to reserve
1119    /// for an instance of this pipeline
1120    pub cpu_cores_min: Option<u64>,
1121
1122    /// The maximum number of CPU cores to reserve
1123    /// for an instance of this pipeline
1124    pub cpu_cores_max: Option<u64>,
1125
1126    /// The minimum memory in Megabytes to reserve
1127    /// for an instance of this pipeline
1128    pub memory_mb_min: Option<u64>,
1129
1130    /// The maximum memory in Megabytes to reserve
1131    /// for an instance of this pipeline
1132    pub memory_mb_max: Option<u64>,
1133
1134    /// The total storage in Megabytes to reserve
1135    /// for an instance of this pipeline
1136    pub storage_mb_max: Option<u64>,
1137
1138    /// Storage class to use for an instance of this pipeline.
1139    /// The class determines storage performance such as IOPS and throughput.
1140    pub storage_class: Option<String>,
1141}