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