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    /// Use the local file system.
224    ///
225    /// This uses ordinary system file operations.
226    File(FileBackendConfig),
227
228    /// Object storage.
229    Object(ObjectStorageConfig),
230}
231
232impl Display for StorageBackendConfig {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        match self {
235            StorageBackendConfig::Default => write!(f, "default"),
236            StorageBackendConfig::File(_) => write!(f, "file"),
237            StorageBackendConfig::Object(_) => write!(f, "object"),
238        }
239    }
240}
241
242/// Storage compression algorithm.
243#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
244#[serde(rename_all = "snake_case")]
245pub enum StorageCompression {
246    /// Use Feldera's default compression algorithm.
247    ///
248    /// The default may change as Feldera's performance is tuned and new
249    /// algorithms are introduced.
250    #[default]
251    Default,
252
253    /// Do not compress.
254    None,
255
256    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
257    Snappy,
258}
259
260#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
261pub struct SyncConfig {
262    /// The endpoint URL for the storage service.
263    ///
264    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
265    /// Example: `http://localhost:9000`
266    ///
267    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
268    pub endpoint: Option<String>,
269
270    /// The name of the storage bucket.
271    ///
272    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
273    pub bucket: String,
274
275    /// The region that this bucket is in.
276    ///
277    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
278    pub region: Option<String>,
279
280    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
281    ///
282    /// Used for provider-specific behavior in rclone.
283    /// If omitted, defaults to `"Other"`.
284    ///
285    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
286    pub provider: Option<String>,
287
288    /// The access key used to authenticate with the storage provider.
289    ///
290    /// If not provided, rclone will fall back to environment-based credentials, such as
291    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
292    /// this can be left empty to allow automatic authentication via the pod's service account.
293    pub access_key: Option<String>,
294
295    /// The secret key used together with the access key for authentication.
296    ///
297    /// If not provided, rclone will fall back to environment-based credentials, such as
298    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
299    /// this can be left empty to allow automatic authentication via the pod's service account.
300    pub secret_key: Option<String>,
301
302    /// If `true`, will try to pull the latest checkpoint from the configured
303    /// object store and resume from that point.
304    pub start_from_checkpoint: bool,
305}
306
307#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
308pub struct ObjectStorageConfig {
309    /// URL.
310    ///
311    /// The following URL schemes are supported:
312    ///
313    /// * S3:
314    ///   - `s3://<bucket>/<path>`
315    ///   - `s3a://<bucket>/<path>`
316    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
317    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
318    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
319    /// * Google Cloud Storage:
320    ///   - `gs://<bucket>/<path>`
321    /// * Microsoft Azure Blob Storage:
322    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
323    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
324    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
325    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
326    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
327    ///   - `azure://<container>/<path>` (custom)
328    ///   - `https://<account>.dfs.core.windows.net`
329    ///   - `https://<account>.blob.core.windows.net`
330    ///   - `https://<account>.blob.core.windows.net/<container>`
331    ///   - `https://<account>.dfs.fabric.microsoft.com`
332    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
333    ///   - `https://<account>.blob.fabric.microsoft.com`
334    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
335    ///
336    /// Settings derived from the URL will override other settings.
337    pub url: String,
338
339    /// Additional options as key-value pairs.
340    ///
341    /// The following keys are supported:
342    ///
343    /// * S3:
344    ///   - `access_key_id`: AWS Access Key.
345    ///   - `secret_access_key`: AWS Secret Access Key.
346    ///   - `region`: Region.
347    ///   - `default_region`: Default region.
348    ///   - `endpoint`: Custom endpoint for communicating with S3,
349    ///     e.g. `https://localhost:4566` for testing against a localstack
350    ///     instance.
351    ///   - `token`: Token to use for requests (passed to underlying provider).
352    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
353    /// * Google Cloud Storage:
354    ///   - `service_account`: Path to the service account file.
355    ///   - `service_account_key`: The serialized service account key.
356    ///   - `google_application_credentials`: Application credentials path.
357    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
358    /// * Microsoft Azure Blob Storage:
359    ///   - `access_key`: Azure Access Key.
360    ///   - `container_name`: Azure Container Name.
361    ///   - `account`: Azure Account.
362    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
363    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
364    ///   - `client_secret`: Client secret for use in client secret flow.
365    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
366    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
367    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
368    ///
369    /// Options set through the URL take precedence over those set with these
370    /// options.
371    #[serde(flatten)]
372    pub other_options: BTreeMap<String, String>,
373}
374
375/// Configuration for local file system access.
376#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
377#[serde(default)]
378pub struct FileBackendConfig {
379    /// Whether to use background threads for file I/O.
380    ///
381    /// Background threads should improve performance, but they can reduce
382    /// performance if too few cores are available. This is provided for
383    /// debugging and fine-tuning and should ordinarily be left unset.
384    pub async_threads: Option<bool>,
385
386    /// Per-I/O operation sleep duration, in milliseconds.
387    ///
388    /// This is for simulating slow storage devices.  Do not use this in
389    /// production.
390    pub ioop_delay: Option<u64>,
391
392    /// Configuration to synchronize checkpoints to object store.
393    pub sync: Option<SyncConfig>,
394}
395
396/// Global pipeline configuration settings. This is the publicly
397/// exposed type for users to configure pipelines.
398#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
399#[serde(default)]
400pub struct RuntimeConfig {
401    /// Number of DBSP worker threads.
402    ///
403    /// Each DBSP "foreground" worker thread is paired with a "background"
404    /// thread for LSM merging, making the total number of threads twice the
405    /// specified number.
406    ///
407    /// The typical sweet spot for the number of workers is between 4 and 16.
408    /// Each worker increases overall memory consumption for data structures
409    /// used during a step.
410    pub workers: u16,
411
412    /// Storage configuration.
413    ///
414    /// - If this is `None`, the default, the pipeline's state is kept in
415    ///   in-memory data-structures.  This is useful if the pipeline's state
416    ///   will fit in memory and if the pipeline is ephemeral and does not need
417    ///   to be recovered after a restart. The pipeline will most likely run
418    ///   faster since it does not need to access storage.
419    ///
420    /// - If set, the pipeline's state is kept on storage.  This allows the
421    ///   pipeline to work with state that will not fit into memory. It also
422    ///   allows the state to be checkpointed and recovered across restarts.
423    #[serde(deserialize_with = "deserialize_storage_options")]
424    pub storage: Option<StorageOptions>,
425
426    /// Fault tolerance configuration.
427    #[serde(deserialize_with = "deserialize_fault_tolerance")]
428    pub fault_tolerance: FtConfig,
429
430    /// Enable CPU profiler.
431    ///
432    /// The default value is `true`.
433    pub cpu_profiler: bool,
434
435    /// Enable pipeline tracing.
436    pub tracing: bool,
437
438    /// Jaeger tracing endpoint to send tracing information to.
439    pub tracing_endpoint_jaeger: String,
440
441    /// Minimal input batch size.
442    ///
443    /// The controller delays pushing input records to the circuit until at
444    /// least `min_batch_size_records` records have been received (total
445    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
446    /// have passed since at least one input records has been buffered.
447    /// Defaults to 0.
448    pub min_batch_size_records: u64,
449
450    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
451    /// get buffered by the controller, defaults to 0.
452    pub max_buffering_delay_usecs: u64,
453
454    /// Resource reservations and limits. This is enforced
455    /// only in Feldera Cloud.
456    pub resources: ResourceConfig,
457
458    /// Real-time clock resolution in microseconds.
459    ///
460    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
461    /// queries depends on the real-time clock and can change over time without any external
462    /// inputs.  The pipeline will update the clock value and trigger incremental recomputation
463    /// at most each `clock_resolution_usecs` microseconds.
464    ///
465    /// It is set to 1 second (1,000,000 microseconds) by default.
466    ///
467    /// Set to `null` to disable periodic clock updates.
468    pub clock_resolution_usecs: Option<u64>,
469
470    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
471    /// its worker threads.  Specify at least twice as many CPU numbers as
472    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
473    /// might not be able to honor CPU pinning requests.
474    ///
475    /// CPU pinning can make pipelines run faster and perform more consistently,
476    /// as long as different pipelines running on the same machine are pinned to
477    /// different CPUs.
478    pub pin_cpus: Vec<usize>,
479
480    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
481    /// Setting this value will override the default of the runner.
482    pub provisioning_timeout_secs: Option<u64>,
483
484    /// The maximum number of connectors initialized in parallel during pipeline
485    /// startup.
486    ///
487    /// At startup, the pipeline must initialize all of its input and output connectors.
488    /// Depending on the number and types of connectors, this can take a long time.
489    /// To accelerate the process, multiple connectors are initialized concurrently.
490    /// This option controls the maximum number of connectors that can be initialized
491    /// in parallel.
492    ///
493    /// The default is 10.
494    pub max_parallel_connector_init: Option<u64>,
495
496    /// Specification of additional (sidecar) containers.
497    pub init_containers: Option<serde_yaml::Value>,
498
499    /// Deprecated: setting this true or false does not have an effect anymore.
500    pub checkpoint_during_suspend: bool,
501
502    /// Sets the number of available runtime threads for the http server.
503    ///
504    /// In most cases, this does not need to be set explicitly and
505    /// the default is sufficient. Can be increased in case the
506    /// pipeline HTTP API operations are a bottleneck.
507    ///
508    /// If not specified, the default is set to `workers`.
509    pub http_workers: Option<u64>,
510
511    /// Sets the number of available runtime threads for async IO tasks.
512    ///
513    /// This affects some networking and file I/O operations
514    /// especially adapters and ad-hoc queries.
515    ///
516    /// In most cases, this does not need to be set explicitly and
517    /// the default is sufficient. Can be increased in case
518    /// ingress, egress or ad-hoc queries are a bottleneck.
519    ///
520    /// If not specified, the default is set to `workers`.
521    pub io_workers: Option<u64>,
522
523    /// Optional settings for tweaking Feldera internals.
524    ///
525    /// The available key-value pairs change from one version of Feldera to
526    /// another, so users should not depend on particular settings being
527    /// available, or on their behavior.
528    pub dev_tweaks: BTreeMap<String, serde_json::Value>,
529
530    /// Log filtering directives.
531    ///
532    /// If set to a valid [tracing-subscriber] filter, this controls the log
533    /// messages emitted by the pipeline process.  Otherwise, or if the filter
534    /// has invalid syntax, messages at "info" severity and higher are written
535    /// to the log and all others are discarded.
536    ///
537    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
538    pub logging: Option<String>,
539}
540
541/// Accepts "true" and "false" and converts them to the new format.
542fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
543where
544    D: Deserializer<'de>,
545{
546    struct BoolOrStruct;
547
548    impl<'de> Visitor<'de> for BoolOrStruct {
549        type Value = Option<StorageOptions>;
550
551        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
552            formatter.write_str("boolean or StorageOptions")
553        }
554
555        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
556        where
557            E: de::Error,
558        {
559            match v {
560                false => Ok(None),
561                true => Ok(Some(StorageOptions::default())),
562            }
563        }
564
565        fn visit_unit<E>(self) -> Result<Self::Value, E>
566        where
567            E: de::Error,
568        {
569            Ok(None)
570        }
571
572        fn visit_none<E>(self) -> Result<Self::Value, E>
573        where
574            E: de::Error,
575        {
576            Ok(None)
577        }
578
579        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
580        where
581            M: MapAccess<'de>,
582        {
583            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
584        }
585    }
586
587    deserializer.deserialize_any(BoolOrStruct)
588}
589
590/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
591/// tolerance.
592///
593/// Accepts `null` as disabling fault tolerance.
594///
595/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
596/// expect.
597fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
598where
599    D: Deserializer<'de>,
600{
601    struct StringOrStruct;
602
603    impl<'de> Visitor<'de> for StringOrStruct {
604        type Value = FtConfig;
605
606        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
607            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
608        }
609
610        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
611        where
612            E: de::Error,
613        {
614            match v {
615                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
616                    model: Some(FtModel::default()),
617                    ..FtConfig::default()
618                }),
619                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
620            }
621        }
622
623        fn visit_unit<E>(self) -> Result<Self::Value, E>
624        where
625            E: de::Error,
626        {
627            Ok(FtConfig::default())
628        }
629
630        fn visit_none<E>(self) -> Result<Self::Value, E>
631        where
632            E: de::Error,
633        {
634            Ok(FtConfig::default())
635        }
636
637        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
638        where
639            M: MapAccess<'de>,
640        {
641            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
642        }
643    }
644
645    deserializer.deserialize_any(StringOrStruct)
646}
647
648impl Default for RuntimeConfig {
649    fn default() -> Self {
650        Self {
651            workers: 8,
652            storage: Some(StorageOptions::default()),
653            fault_tolerance: FtConfig::default(),
654            cpu_profiler: true,
655            tracing: {
656                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
657                // to keep it on by default.
658                false
659            },
660            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
661            min_batch_size_records: 0,
662            max_buffering_delay_usecs: 0,
663            resources: ResourceConfig::default(),
664            clock_resolution_usecs: { Some(DEFAULT_CLOCK_RESOLUTION_USECS) },
665            pin_cpus: Vec::new(),
666            provisioning_timeout_secs: None,
667            max_parallel_connector_init: None,
668            init_containers: None,
669            checkpoint_during_suspend: true,
670            io_workers: None,
671            http_workers: None,
672            dev_tweaks: BTreeMap::default(),
673            logging: None,
674        }
675    }
676}
677
678/// Fault-tolerance configuration.
679///
680/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
681/// which is the configuration that one gets if [RuntimeConfig] omits fault
682/// tolerance configuration.
683///
684/// The default value for [FtConfig::model] enables fault tolerance, as
685/// `Some(FtModel::default())`.  This is the configuration that one gets if
686/// [RuntimeConfig] includes a fault tolerance configuration but does not
687/// specify a particular model.
688#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
689#[serde(rename_all = "snake_case")]
690pub struct FtConfig {
691    /// Fault tolerance model to use.
692    #[serde(with = "none_as_string")]
693    #[serde(default = "default_model")]
694    #[schema(
695        schema_with = none_as_string_schema::<FtModel>,
696    )]
697    pub model: Option<FtModel>,
698
699    /// Interval between automatic checkpoints, in seconds.
700    ///
701    /// The default is 60 seconds.  Values less than 1 or greater than 3600 will
702    /// be forced into that range.
703    #[serde(default = "default_checkpoint_interval_secs")]
704    pub checkpoint_interval_secs: Option<u64>,
705}
706
707fn default_model() -> Option<FtModel> {
708    Some(FtModel::default())
709}
710
711pub fn default_checkpoint_interval_secs() -> Option<u64> {
712    Some(60)
713}
714
715impl Default for FtConfig {
716    fn default() -> Self {
717        Self {
718            model: None,
719            checkpoint_interval_secs: default_checkpoint_interval_secs(),
720        }
721    }
722}
723
724#[cfg(test)]
725mod test {
726    use super::deserialize_fault_tolerance;
727    use crate::config::{FtConfig, FtModel};
728    use serde::{Deserialize, Serialize};
729
730    #[test]
731    fn ft_config() {
732        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
733        #[serde(default)]
734        struct Wrapper {
735            #[serde(deserialize_with = "deserialize_fault_tolerance")]
736            config: FtConfig,
737        }
738
739        // Omitting FtConfig, or specifying null, or specifying model "none", disables fault tolerance.
740        for s in [
741            "{}",
742            r#"{"config": null}"#,
743            r#"{"config": {"model": "none"}}"#,
744        ] {
745            let config: Wrapper = serde_json::from_str(s).unwrap();
746            assert_eq!(
747                config,
748                Wrapper {
749                    config: FtConfig {
750                        model: None,
751                        checkpoint_interval_secs: Some(60)
752                    }
753                }
754            );
755        }
756
757        // Serializing disabled FT produces explicit "none" form.
758        let s = serde_json::to_string(&Wrapper {
759            config: FtConfig::default(),
760        })
761        .unwrap();
762        assert!(s.contains("\"none\""));
763
764        // `{}` for FtConfig, or `{...}` with `model` omitted, enables fault
765        // tolerance.
766        for s in [r#"{"config": {}}"#, r#"{"checkpoint_interval_secs": 60}"#] {
767            assert_eq!(
768                serde_json::from_str::<FtConfig>(s).unwrap(),
769                FtConfig {
770                    model: Some(FtModel::default()),
771                    checkpoint_interval_secs: Some(60)
772                }
773            );
774        }
775
776        // `"checkpoint_interval_secs": null` disables periodic checkpointing.
777        assert_eq!(
778            serde_json::from_str::<FtConfig>(r#"{"checkpoint_interval_secs": null}"#).unwrap(),
779            FtConfig {
780                model: Some(FtModel::default()),
781                checkpoint_interval_secs: None
782            }
783        );
784    }
785}
786
787impl FtConfig {
788    pub fn is_enabled(&self) -> bool {
789        self.model.is_some()
790    }
791
792    /// Returns the checkpoint interval, if fault tolerance is enabled, and
793    /// otherwise `None`.
794    pub fn checkpoint_interval(&self) -> Option<Duration> {
795        if self.is_enabled() {
796            self.checkpoint_interval_secs
797                .map(|interval| Duration::from_secs(interval.clamp(1, 3600)))
798        } else {
799            None
800        }
801    }
802}
803
804/// Serde implementation for de/serializing a string into `Option<T>` where
805/// `"none"` indicates `None` and any other string indicates `Some`.
806///
807/// This could be extended to handle non-strings by adding more forwarding
808/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
809/// them automatically.
810mod none_as_string {
811    use std::marker::PhantomData;
812
813    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
814    use serde::ser::{Serialize, Serializer};
815
816    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
817    where
818        S: Serializer,
819        T: Serialize,
820    {
821        match value.as_ref() {
822            Some(value) => value.serialize(serializer),
823            None => "none".serialize(serializer),
824        }
825    }
826
827    struct NoneAsString<T>(PhantomData<fn() -> T>);
828
829    impl<'de, T> Visitor<'de> for NoneAsString<T>
830    where
831        T: Deserialize<'de>,
832    {
833        type Value = Option<T>;
834
835        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
836            formatter.write_str("string")
837        }
838
839        fn visit_none<E>(self) -> Result<Self::Value, E>
840        where
841            E: serde::de::Error,
842        {
843            Ok(None)
844        }
845
846        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
847        where
848            E: serde::de::Error,
849        {
850            if &value.to_ascii_lowercase() == "none" {
851                Ok(None)
852            } else {
853                Ok(Some(T::deserialize(value.into_deserializer())?))
854            }
855        }
856    }
857
858    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
859    where
860        D: Deserializer<'de>,
861        T: Deserialize<'de>,
862    {
863        deserializer.deserialize_str(NoneAsString(PhantomData))
864    }
865}
866
867/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
868/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
869fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
870    Schema::OneOf(
871        OneOfBuilder::new()
872            .item(RefOr::Ref(Ref::new(format!(
873                "#/components/schemas/{}",
874                T::schema().0
875            ))))
876            .item(
877                ObjectBuilder::new()
878                    .schema_type(SchemaType::String)
879                    .enum_values(Some(vec!["none"])),
880            )
881            .default(Some(
882                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
883            ))
884            .build(),
885    )
886}
887
888/// Fault tolerance model.
889///
890/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
891/// level" of fault tolerance than [Self::AtLeastOnce].
892#[derive(
893    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
894)]
895#[serde(rename_all = "snake_case")]
896pub enum FtModel {
897    /// Each record is output at least once.  Crashes may duplicate output, but
898    /// no input or output is dropped.
899    AtLeastOnce,
900
901    /// Each record is output exactly once.  Crashes do not drop or duplicate
902    /// input or output.
903    #[default]
904    ExactlyOnce,
905}
906
907impl FtModel {
908    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
909        value.map_or("no", |model| model.as_str())
910    }
911
912    pub fn as_str(&self) -> &'static str {
913        match self {
914            FtModel::AtLeastOnce => "at_least_once",
915            FtModel::ExactlyOnce => "exactly_once",
916        }
917    }
918}
919
920pub struct FtModelUnknown;
921
922impl FromStr for FtModel {
923    type Err = FtModelUnknown;
924
925    fn from_str(s: &str) -> Result<Self, Self::Err> {
926        match s.to_ascii_lowercase().as_str() {
927            "exactly_once" => Ok(Self::ExactlyOnce),
928            "at_least_once" => Ok(Self::AtLeastOnce),
929            _ => Err(FtModelUnknown),
930        }
931    }
932}
933
934/// Describes an input connector configuration
935#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
936pub struct InputEndpointConfig {
937    /// The name of the input stream of the circuit that this endpoint is
938    /// connected to.
939    pub stream: Cow<'static, str>,
940
941    /// Connector configuration.
942    #[serde(flatten)]
943    pub connector_config: ConnectorConfig,
944}
945
946/// Deserialize the `start_after` property of a connector configuration.
947/// It requires a non-standard deserialization because we want to accept
948/// either a string or an array of strings.
949fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
950where
951    D: Deserializer<'de>,
952{
953    let value = Option::<JsonValue>::deserialize(deserializer)?;
954    match value {
955        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
956        Some(JsonValue::Array(arr)) => {
957            let vec = arr
958                .into_iter()
959                .map(|item| {
960                    item.as_str()
961                        .map(|s| s.to_string())
962                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
963                })
964                .collect::<Result<Vec<String>, _>>()?;
965            Ok(Some(vec))
966        }
967        Some(JsonValue::Null) | None => Ok(None),
968        _ => Err(serde::de::Error::custom(
969            "invalid 'start_after' property: expected a string, an array of strings, or null",
970        )),
971    }
972}
973
974/// A data connector's configuration
975#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
976pub struct ConnectorConfig {
977    /// Transport endpoint configuration.
978    pub transport: TransportConfig,
979
980    /// Parser configuration.
981    pub format: Option<FormatConfig>,
982
983    /// Name of the index that the connector is attached to.
984    ///
985    /// This property is valid for output connectors only.  It is used with data
986    /// transports and formats that expect output updates in the form of key/value
987    /// pairs, where the key typically represents a unique id associated with the
988    /// table or view.
989    ///
990    /// To support such output formats, an output connector can be attached to an
991    /// index created using the SQL CREATE INDEX statement.  An index of a table
992    /// or view contains the same updates as the table or view itself, indexed by
993    /// one or more key columns.
994    ///
995    /// See individual connector documentation for details on how they work
996    /// with indexes.
997    pub index: Option<String>,
998
999    /// Output buffer configuration.
1000    #[serde(flatten)]
1001    pub output_buffer_config: OutputBufferConfig,
1002
1003    /// Maximum batch size, in records.
1004    ///
1005    /// This is the maximum number of records to process in one batch through
1006    /// the circuit.  The time and space cost of processing a batch is
1007    /// asymptotically superlinear in the size of the batch, but very small
1008    /// batches are less efficient due to constant factors.
1009    ///
1010    /// This should usually be less than `max_queued_records`, to give the
1011    /// connector a round-trip time to restart and refill the buffer while
1012    /// batches are being processed.
1013    ///
1014    /// Some input adapters might not honor this setting.
1015    ///
1016    /// The default is 10,000.
1017    #[serde(default = "default_max_batch_size")]
1018    pub max_batch_size: u64,
1019
1020    /// Backpressure threshold.
1021    ///
1022    /// Maximal number of records queued by the endpoint before the endpoint
1023    /// is paused by the backpressure mechanism.
1024    ///
1025    /// For input endpoints, this setting bounds the number of records that have
1026    /// been received from the input transport but haven't yet been consumed by
1027    /// the circuit since the circuit, since the circuit is still busy processing
1028    /// previous inputs.
1029    ///
1030    /// For output endpoints, this setting bounds the number of records that have
1031    /// been produced by the circuit but not yet sent via the output transport endpoint
1032    /// nor stored in the output buffer (see `enable_output_buffer`).
1033    ///
1034    /// Note that this is not a hard bound: there can be a small delay between
1035    /// the backpressure mechanism is triggered and the endpoint is paused, during
1036    /// which more data may be queued.
1037    ///
1038    /// The default is 1 million.
1039    #[serde(default = "default_max_queued_records")]
1040    pub max_queued_records: u64,
1041
1042    /// Create connector in paused state.
1043    ///
1044    /// The default is `false`.
1045    #[serde(default)]
1046    pub paused: bool,
1047
1048    /// Arbitrary user-defined text labels associated with the connector.
1049    ///
1050    /// These labels can be used in conjunction with the `start_after` property
1051    /// to control the start order of connectors.
1052    #[serde(default)]
1053    pub labels: Vec<String>,
1054
1055    /// Start the connector after all connectors with specified labels.
1056    ///
1057    /// This property is used to control the start order of connectors.
1058    /// The connector will not start until all connectors with the specified
1059    /// labels have finished processing all inputs.
1060    #[serde(deserialize_with = "deserialize_start_after")]
1061    #[serde(default)]
1062    pub start_after: Option<Vec<String>>,
1063}
1064
1065#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1066#[serde(default)]
1067pub struct OutputBufferConfig {
1068    /// Enable output buffering.
1069    ///
1070    /// The output buffering mechanism allows decoupling the rate at which the pipeline
1071    /// pushes changes to the output transport from the rate of input changes.
1072    ///
1073    /// By default, output updates produced by the pipeline are pushed directly to
1074    /// the output transport. Some destinations may prefer to receive updates in fewer
1075    /// bigger batches. For instance, when writing Parquet files, producing
1076    /// one bigger file every few minutes is usually better than creating
1077    /// small files every few milliseconds.
1078    ///
1079    /// To achieve such input/output decoupling, users can enable output buffering by
1080    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
1081    /// updates produced by the pipeline are consolidated in an internal buffer and are
1082    /// pushed to the output transport when one of several conditions is satisfied:
1083    ///
1084    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
1085    ///   milliseconds.
1086    /// * buffer size exceeds `max_output_buffer_size_records` records.
1087    ///
1088    /// This flag is `false` by default.
1089    // TODO: on-demand output triggered via the API.
1090    pub enable_output_buffer: bool,
1091
1092    /// Maximum time in milliseconds data is kept in the output buffer.
1093    ///
1094    /// By default, data is kept in the buffer indefinitely until one of
1095    /// the other output conditions is satisfied.  When this option is
1096    /// set the buffer will be flushed at most every
1097    /// `max_output_buffer_time_millis` milliseconds.
1098    ///
1099    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1100    /// to be set.
1101    pub max_output_buffer_time_millis: usize,
1102
1103    /// Maximum number of updates to be kept in the output buffer.
1104    ///
1105    /// This parameter bounds the maximal size of the buffer.
1106    /// Note that the size of the buffer is not always equal to the
1107    /// total number of updates output by the pipeline. Updates to the
1108    /// same record can overwrite or cancel previous updates.
1109    ///
1110    /// By default, the buffer can grow indefinitely until one of
1111    /// the other output conditions is satisfied.
1112    ///
1113    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1114    /// to be set.
1115    pub max_output_buffer_size_records: usize,
1116}
1117
1118impl Default for OutputBufferConfig {
1119    fn default() -> Self {
1120        Self {
1121            enable_output_buffer: false,
1122            max_output_buffer_size_records: usize::MAX,
1123            max_output_buffer_time_millis: usize::MAX,
1124        }
1125    }
1126}
1127
1128impl OutputBufferConfig {
1129    pub fn validate(&self) -> Result<(), String> {
1130        if self.enable_output_buffer
1131            && self.max_output_buffer_size_records == Self::default().max_output_buffer_size_records
1132            && self.max_output_buffer_time_millis == Self::default().max_output_buffer_time_millis
1133        {
1134            return Err(
1135                "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"
1136                    .to_string(),
1137            );
1138        }
1139
1140        Ok(())
1141    }
1142}
1143
1144/// Describes an output connector configuration
1145#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1146pub struct OutputEndpointConfig {
1147    /// The name of the output stream of the circuit that this endpoint is
1148    /// connected to.
1149    pub stream: Cow<'static, str>,
1150
1151    /// Connector configuration.
1152    #[serde(flatten)]
1153    pub connector_config: ConnectorConfig,
1154}
1155
1156/// Transport-specific endpoint configuration passed to
1157/// `crate::OutputTransport::new_endpoint`
1158/// and `crate::InputTransport::new_endpoint`.
1159#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1160#[serde(tag = "name", content = "config", rename_all = "snake_case")]
1161pub enum TransportConfig {
1162    FileInput(FileInputConfig),
1163    FileOutput(FileOutputConfig),
1164    KafkaInput(KafkaInputConfig),
1165    KafkaOutput(KafkaOutputConfig),
1166    PubSubInput(PubSubInputConfig),
1167    UrlInput(UrlInputConfig),
1168    S3Input(S3InputConfig),
1169    DeltaTableInput(DeltaTableReaderConfig),
1170    DeltaTableOutput(DeltaTableWriterConfig),
1171    RedisOutput(RedisOutputConfig),
1172    // Prevent rust from complaining about large size difference between enum variants.
1173    IcebergInput(Box<IcebergReaderConfig>),
1174    PostgresInput(PostgresReaderConfig),
1175    PostgresOutput(PostgresWriterConfig),
1176    Datagen(DatagenInputConfig),
1177    Nexmark(NexmarkInputConfig),
1178    /// Direct HTTP input: cannot be instantiated through API
1179    HttpInput(HttpInputConfig),
1180    /// Direct HTTP output: cannot be instantiated through API
1181    HttpOutput,
1182    /// Ad hoc input: cannot be instantiated through API
1183    AdHocInput(AdHocInputConfig),
1184    ClockInput(ClockConfig),
1185}
1186
1187impl TransportConfig {
1188    pub fn name(&self) -> String {
1189        match self {
1190            TransportConfig::FileInput(_) => "file_input".to_string(),
1191            TransportConfig::FileOutput(_) => "file_output".to_string(),
1192            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
1193            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
1194            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
1195            TransportConfig::UrlInput(_) => "url_input".to_string(),
1196            TransportConfig::S3Input(_) => "s3_input".to_string(),
1197            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
1198            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
1199            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
1200            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
1201            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
1202            TransportConfig::Datagen(_) => "datagen".to_string(),
1203            TransportConfig::Nexmark(_) => "nexmark".to_string(),
1204            TransportConfig::HttpInput(_) => "http_input".to_string(),
1205            TransportConfig::HttpOutput => "http_output".to_string(),
1206            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
1207            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
1208            TransportConfig::ClockInput(_) => "clock".to_string(),
1209        }
1210    }
1211}
1212
1213/// Data format specification used to parse raw data received from the
1214/// endpoint or to encode data sent to the endpoint.
1215#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
1216pub struct FormatConfig {
1217    /// Format name, e.g., "csv", "json", "bincode", etc.
1218    pub name: Cow<'static, str>,
1219
1220    /// Format-specific parser or encoder configuration.
1221    #[serde(default)]
1222    #[schema(value_type = Object)]
1223    pub config: YamlValue,
1224}
1225
1226#[derive(Debug, Clone, Eq, PartialEq, Default, Serialize, Deserialize, ToSchema)]
1227#[serde(default)]
1228pub struct ResourceConfig {
1229    /// The minimum number of CPU cores to reserve
1230    /// for an instance of this pipeline
1231    pub cpu_cores_min: Option<u64>,
1232
1233    /// The maximum number of CPU cores to reserve
1234    /// for an instance of this pipeline
1235    pub cpu_cores_max: Option<u64>,
1236
1237    /// The minimum memory in Megabytes to reserve
1238    /// for an instance of this pipeline
1239    pub memory_mb_min: Option<u64>,
1240
1241    /// The maximum memory in Megabytes to reserve
1242    /// for an instance of this pipeline
1243    pub memory_mb_max: Option<u64>,
1244
1245    /// The total storage in Megabytes to reserve
1246    /// for an instance of this pipeline
1247    pub storage_mb_max: Option<u64>,
1248
1249    /// Storage class to use for an instance of this pipeline.
1250    /// The class determines storage performance such as IOPS and throughput.
1251    pub storage_class: Option<String>,
1252}