Skip to main content

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::program_schema::ProgramSchema;
9use crate::secret_resolver::default_secrets_directory;
10use crate::transport::adhoc::AdHocInputConfig;
11use crate::transport::clock::ClockConfig;
12use crate::transport::datagen::DatagenInputConfig;
13use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
14use crate::transport::file::{FileInputConfig, FileOutputConfig};
15use crate::transport::http::HttpInputConfig;
16use crate::transport::iceberg::IcebergReaderConfig;
17use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
18use crate::transport::nats::NatsInputConfig;
19use crate::transport::nexmark::NexmarkInputConfig;
20use crate::transport::postgres::{PostgresReaderConfig, PostgresWriterConfig};
21use crate::transport::pubsub::PubSubInputConfig;
22use crate::transport::redis::RedisOutputConfig;
23use crate::transport::s3::S3InputConfig;
24use crate::transport::url::UrlInputConfig;
25use core::fmt;
26use feldera_ir::{MirNode, MirNodeId};
27use serde::de::{self, MapAccess, Visitor};
28use serde::{Deserialize, Deserializer, Serialize};
29use serde_json::Value as JsonValue;
30use std::collections::HashMap;
31use std::fmt::Display;
32use std::path::Path;
33use std::str::FromStr;
34use std::time::Duration;
35use std::{borrow::Cow, cmp::max, collections::BTreeMap};
36use utoipa::ToSchema;
37use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
38
39const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
40
41/// Default value of `ConnectorConfig::max_queued_records`.
42pub const fn default_max_queued_records() -> u64 {
43    1_000_000
44}
45
46pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
47
48pub const DEFAULT_CLOCK_RESOLUTION_USECS: u64 = 1_000_000;
49
50/// Program information included in the pipeline configuration.
51#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
52pub struct ProgramIr {
53    /// The MIR of the program.
54    pub mir: HashMap<MirNodeId, MirNode>,
55    /// Program schema.
56    pub program_schema: ProgramSchema,
57}
58
59/// Pipeline deployment configuration.
60/// It represents configuration entries directly provided by the user
61/// (e.g., runtime configuration) and entries derived from the schema
62/// of the compiled program (e.g., connectors). Storage configuration,
63/// if applicable, is set by the runner.
64#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
65pub struct PipelineConfig {
66    /// Global controller configuration.
67    #[serde(flatten)]
68    #[schema(inline)]
69    pub global: RuntimeConfig,
70
71    /// Configuration for multihost pipelines.
72    ///
73    /// The presence of this field indicates that the pipeline is running in
74    /// multihost mode.  In the pod with ordinal 0, this triggers starting the
75    /// coordinator process.  In all pods, this tells the pipeline process to
76    /// await a connection from the coordinator instead of initializing the
77    /// pipeline immediately.
78    pub multihost: Option<MultihostConfig>,
79
80    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
81    /// It is unique across all tenants and cannot be changed.
82    ///
83    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
84    /// and as such this name is useful to find/identify corresponding resources.
85    pub name: Option<String>,
86
87    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
88    /// be changed by the tenant when the pipeline is stopped.
89    ///
90    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
91    pub given_name: Option<String>,
92
93    /// Configuration for persistent storage
94    ///
95    /// If `global.storage` is `Some(_)`, this field must be set to some
96    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
97    /// this field.
98    #[serde(default)]
99    pub storage_config: Option<StorageConfig>,
100
101    /// Directory containing values of secrets.
102    ///
103    /// If this is not set, a default directory is used.
104    pub secrets_dir: Option<String>,
105
106    /// Input endpoint configuration.
107    #[serde(default)]
108    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
109
110    /// Output endpoint configuration.
111    #[serde(default)]
112    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
113
114    /// Program information.
115    #[serde(default)]
116    pub program_ir: Option<ProgramIr>,
117}
118
119impl PipelineConfig {
120    pub fn max_parallel_connector_init(&self) -> u64 {
121        max(
122            self.global
123                .max_parallel_connector_init
124                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
125            1,
126        )
127    }
128
129    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
130        let (storage_config, storage_options) = storage.unzip();
131        Self {
132            global: RuntimeConfig {
133                storage: storage_options,
134                ..self.global
135            },
136            storage_config,
137            ..self
138        }
139    }
140
141    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
142        let storage_options = self.global.storage.as_ref();
143        let storage_config = self.storage_config.as_ref();
144        storage_config.zip(storage_options)
145    }
146
147    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
148    /// set.
149    pub fn secrets_dir(&self) -> &Path {
150        match &self.secrets_dir {
151            Some(dir) => Path::new(dir.as_str()),
152            None => default_secrets_directory(),
153        }
154    }
155
156    /// Abbreviated config that can be printed in the log on pipeline startup.
157    pub fn display_summary(&self) -> String {
158        // TODO: we may want to further abbreviate connector config.
159        let summary = serde_json::json!({
160            "name": self.name,
161            "given_name": self.given_name,
162            "global": self.global,
163            "storage_config": self.storage_config,
164            "secrets_dir": self.secrets_dir,
165            "inputs": self.inputs,
166            "outputs": self.outputs
167        });
168
169        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
170    }
171}
172
173/// A subset of fields in `PipelineConfig` that are generated by the compiler.
174/// These fields are shipped to the pipeline by the compilation server along with
175/// the program binary.
176// Note: An alternative would be to embed these fields in the program binary itself
177// as static strings. This would work well for program IR, but it would require recompiling
178// the program anytime a connector config changes, whereas today connector changes
179// do not require recompilation.
180#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
181pub struct PipelineConfigProgramInfo {
182    /// Input endpoint configuration.
183    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
184
185    /// Output endpoint configuration.
186    #[serde(default)]
187    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
188
189    /// Program information.
190    #[serde(default)]
191    pub program_ir: Option<ProgramIr>,
192}
193
194/// Configuration for a multihost Feldera pipeline.
195///
196/// This configuration is primarily for the coordinator.
197#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
198pub struct MultihostConfig {
199    /// Number of hosts to launch.
200    ///
201    /// For the configuration to be truly multihost, this should be at least 2.
202    /// A value of 1 still runs the multihost coordinator but it only
203    /// coordinates a single host.
204    pub hosts: usize,
205}
206
207impl Default for MultihostConfig {
208    fn default() -> Self {
209        Self { hosts: 1 }
210    }
211}
212
213/// Configuration for persistent storage in a [`PipelineConfig`].
214#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
215pub struct StorageConfig {
216    /// A directory to keep pipeline state, as a path on the filesystem of the
217    /// machine or container where the pipeline will run.
218    ///
219    /// When storage is enabled, this directory stores the data for
220    /// [StorageBackendConfig::Default].
221    ///
222    /// When fault tolerance is enabled, this directory stores checkpoints and
223    /// the log.
224    pub path: String,
225
226    /// How to cache access to storage in this pipeline.
227    #[serde(default)]
228    pub cache: StorageCacheConfig,
229}
230
231impl StorageConfig {
232    pub fn path(&self) -> &Path {
233        Path::new(&self.path)
234    }
235}
236
237/// How to cache access to storage within a Feldera pipeline.
238#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
239#[serde(rename_all = "snake_case")]
240pub enum StorageCacheConfig {
241    /// Use the operating system's page cache as the primary storage cache.
242    ///
243    /// This is the default because it currently performs better than
244    /// `FelderaCache`.
245    #[default]
246    PageCache,
247
248    /// Use Feldera's internal cache implementation.
249    ///
250    /// This is under development. It will become the default when its
251    /// performance exceeds that of `PageCache`.
252    FelderaCache,
253}
254
255impl StorageCacheConfig {
256    #[cfg(unix)]
257    pub fn to_custom_open_flags(&self) -> i32 {
258        match self {
259            StorageCacheConfig::PageCache => (),
260            StorageCacheConfig::FelderaCache => {
261                #[cfg(target_os = "linux")]
262                return libc::O_DIRECT;
263            }
264        }
265        0
266    }
267}
268
269/// Storage configuration for a pipeline.
270#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
271#[serde(default)]
272pub struct StorageOptions {
273    /// How to connect to the underlying storage.
274    pub backend: StorageBackendConfig,
275
276    /// For a batch of data maintained as part of a persistent index during a
277    /// pipeline run, the minimum estimated number of bytes to write it to
278    /// storage.
279    ///
280    /// This is provided for debugging and fine-tuning and should ordinarily be
281    /// left unset.
282    ///
283    /// A value of 0 will write even empty batches to storage, and nonzero
284    /// values provide a threshold.  `usize::MAX` would effectively disable
285    /// storage for such batches.  The default is 10,048,576 (10 MiB).
286    pub min_storage_bytes: Option<usize>,
287
288    /// For a batch of data passed through the pipeline during a single step,
289    /// the minimum estimated number of bytes to write it to storage.
290    ///
291    /// This is provided for debugging and fine-tuning and should ordinarily be
292    /// left unset.  A value of 0 will write even empty batches to storage, and
293    /// nonzero values provide a threshold.  `usize::MAX`, the default,
294    /// effectively disables storage for such batches.  If it is set to another
295    /// value, it should ordinarily be greater than or equal to
296    /// `min_storage_bytes`.
297    pub min_step_storage_bytes: Option<usize>,
298
299    /// The form of compression to use in data batches.
300    ///
301    /// Compression has a CPU cost but it can take better advantage of limited
302    /// NVMe and network bandwidth, which means that it can increase overall
303    /// performance.
304    pub compression: StorageCompression,
305
306    /// The maximum size of the in-memory storage cache, in MiB.
307    ///
308    /// If set, the specified cache size is spread across all the foreground and
309    /// background threads. If unset, each foreground or background thread cache
310    /// is limited to 256 MiB.
311    pub cache_mib: Option<usize>,
312}
313
314/// Backend storage configuration.
315#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
316#[serde(tag = "name", content = "config", rename_all = "snake_case")]
317pub enum StorageBackendConfig {
318    /// Use the default storage configuration.
319    ///
320    /// This currently uses the local file system.
321    #[default]
322    Default,
323
324    /// Use the local file system.
325    ///
326    /// This uses ordinary system file operations.
327    File(Box<FileBackendConfig>),
328
329    /// Object storage.
330    Object(ObjectStorageConfig),
331}
332
333impl Display for StorageBackendConfig {
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        match self {
336            StorageBackendConfig::Default => write!(f, "default"),
337            StorageBackendConfig::File(_) => write!(f, "file"),
338            StorageBackendConfig::Object(_) => write!(f, "object"),
339        }
340    }
341}
342
343/// Storage compression algorithm.
344#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
345#[serde(rename_all = "snake_case")]
346pub enum StorageCompression {
347    /// Use Feldera's default compression algorithm.
348    ///
349    /// The default may change as Feldera's performance is tuned and new
350    /// algorithms are introduced.
351    #[default]
352    Default,
353
354    /// Do not compress.
355    None,
356
357    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
358    Snappy,
359}
360
361#[derive(Debug, Clone, Eq, PartialEq)]
362pub enum StartFromCheckpoint {
363    Latest,
364    Uuid(uuid::Uuid),
365}
366
367impl ToSchema<'_> for StartFromCheckpoint {
368    fn schema() -> (
369        &'static str,
370        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
371    ) {
372        (
373            "StartFromCheckpoint",
374            utoipa::openapi::RefOr::T(Schema::OneOf(
375                OneOfBuilder::new()
376                    .item(
377                        ObjectBuilder::new()
378                            .schema_type(SchemaType::String)
379                            .enum_values(Some(["latest"].into_iter()))
380                            .build(),
381                    )
382                    .item(
383                        ObjectBuilder::new()
384                            .schema_type(SchemaType::String)
385                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
386                                utoipa::openapi::KnownFormat::Uuid,
387                            )))
388                            .build(),
389                    )
390                    .nullable(true)
391                    .build(),
392            )),
393        )
394    }
395}
396
397impl<'de> Deserialize<'de> for StartFromCheckpoint {
398    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
399    where
400        D: Deserializer<'de>,
401    {
402        struct StartFromCheckpointVisitor;
403
404        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
405            type Value = StartFromCheckpoint;
406
407            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
408                formatter.write_str("a UUID string or the string \"latest\"")
409            }
410
411            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
412            where
413                E: de::Error,
414            {
415                if value == "latest" {
416                    Ok(StartFromCheckpoint::Latest)
417                } else {
418                    uuid::Uuid::parse_str(value)
419                        .map(StartFromCheckpoint::Uuid)
420                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
421                }
422            }
423        }
424
425        deserializer.deserialize_str(StartFromCheckpointVisitor)
426    }
427}
428
429impl Serialize for StartFromCheckpoint {
430    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
431    where
432        S: serde::Serializer,
433    {
434        match self {
435            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
436            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
437        }
438    }
439}
440
441#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
442pub struct SyncConfig {
443    /// The endpoint URL for the storage service.
444    ///
445    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
446    /// Example: `http://localhost:9000`
447    ///
448    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
449    pub endpoint: Option<String>,
450
451    /// The name of the storage bucket.
452    ///
453    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
454    pub bucket: String,
455
456    /// The region that this bucket is in.
457    ///
458    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
459    pub region: Option<String>,
460
461    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
462    ///
463    /// Used for provider-specific behavior in rclone.
464    /// If omitted, defaults to `"Other"`.
465    ///
466    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
467    pub provider: Option<String>,
468
469    /// The access key used to authenticate with the storage provider.
470    ///
471    /// If not provided, rclone will fall back to environment-based credentials, such as
472    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
473    /// this can be left empty to allow automatic authentication via the pod's service account.
474    pub access_key: Option<String>,
475
476    /// The secret key used together with the access key for authentication.
477    ///
478    /// If not provided, rclone will fall back to environment-based credentials, such as
479    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
480    /// this can be left empty to allow automatic authentication via the pod's service account.
481    pub secret_key: Option<String>,
482
483    /// When set, the pipeline will try fetch the specified checkpoint from the
484    /// object store.
485    ///
486    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
487    pub start_from_checkpoint: Option<StartFromCheckpoint>,
488
489    /// When true, the pipeline will fail to initialize if fetching the
490    /// specified checkpoint fails (missing, download error).
491    /// When false, the pipeline will start from scratch instead.
492    ///
493    /// False by default.
494    #[schema(default = std::primitive::bool::default)]
495    #[serde(default)]
496    pub fail_if_no_checkpoint: bool,
497
498    /// The number of file transfers to run in parallel.
499    /// Default: 20
500    pub transfers: Option<u8>,
501
502    /// The number of checkers to run in parallel.
503    /// Default: 20
504    pub checkers: Option<u8>,
505
506    /// Set to skip post copy check of checksums, and only check the file sizes.
507    /// This can significantly improve the throughput.
508    /// Defualt: false
509    pub ignore_checksum: Option<bool>,
510
511    /// Number of streams to use for multi-thread downloads.
512    /// Default: 10
513    pub multi_thread_streams: Option<u8>,
514
515    /// Use multi-thread download for files above this size.
516    /// Format: `[size][Suffix]` (Example: 1G, 500M)
517    /// Supported suffixes: k|M|G|T
518    /// Default: 100M
519    pub multi_thread_cutoff: Option<String>,
520
521    /// The number of chunks of the same file that are uploaded for multipart uploads.
522    /// Default: 10
523    pub upload_concurrency: Option<u8>,
524
525    /// When `true`, the pipeline starts in **standby** mode; processing doesn't
526    /// start until activation (`POST /activate`).
527    /// If this pipeline was previously activated and the storage has not been
528    /// cleared, the pipeline will auto activate, no newer checkpoints will be
529    /// fetched.
530    ///
531    /// Standby behavior depends on `start_from_checkpoint`:
532    /// - If `latest`, pipeline continuously fetches the latest available
533    ///   checkpoint until activated.
534    /// - If checkpoint UUID, pipeline fetches this checkpoint once and waits
535    ///   in standby until activated.
536    ///
537    /// Default: `false`
538    #[schema(default = std::primitive::bool::default)]
539    #[serde(default)]
540    pub standby: bool,
541
542    /// The interval (in seconds) between each attempt to fetch the latest
543    /// checkpoint from object store while in standby mode.
544    ///
545    /// Applies only when `start_from_checkpoint` is set to `latest`.
546    ///
547    /// Default: 10 seconds
548    #[schema(default = default_pull_interval)]
549    #[serde(default = "default_pull_interval")]
550    pub pull_interval: u64,
551
552    /// The interval (in seconds) between each push of checkpoints to object store.
553    ///
554    /// Default: disabled (no periodic push).
555    #[serde(default)]
556    pub push_interval: Option<u64>,
557
558    /// Extra flags to pass to `rclone`.
559    ///
560    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
561    /// Use with caution.
562    ///
563    /// Refer to the docs to see the supported flags:
564    /// - [Global flags](https://rclone.org/flags/)
565    /// - [S3 specific flags](https://rclone.org/s3/)
566    pub flags: Option<Vec<String>>,
567
568    /// The minimum number of checkpoints to retain in object store.
569    /// No checkpoints will be deleted if the total count is below this threshold.
570    ///
571    /// Default: 10
572    #[schema(default = default_retention_min_count)]
573    #[serde(default = "default_retention_min_count")]
574    pub retention_min_count: u32,
575
576    /// The minimum age (in days) a checkpoint must reach before it becomes
577    /// eligible for deletion. All younger checkpoints will be preserved.
578    ///
579    /// Default: 30
580    #[schema(default = default_retention_min_age)]
581    #[serde(default = "default_retention_min_age")]
582    pub retention_min_age: u32,
583}
584
585fn default_pull_interval() -> u64 {
586    10
587}
588
589fn default_retention_min_count() -> u32 {
590    10
591}
592
593fn default_retention_min_age() -> u32 {
594    30
595}
596
597impl SyncConfig {
598    pub fn validate(&self) -> Result<(), String> {
599        if self.standby && self.start_from_checkpoint.is_none() {
600            return Err(r#"invalid sync config: `standby` set to `true` but `start_from_checkpoint` not set.
601Standby mode requires `start_from_checkpoint` to be set.
602Consider setting `start_from_checkpoint` to `"latest"`."#.to_owned());
603        }
604
605        Ok(())
606    }
607}
608
609/// Configuration for supplying a custom pipeline StatefulSet template via a Kubernetes ConfigMap.
610///
611/// Operators can provide a custom StatefulSet YAML that the Kubernetes runner will use when
612/// creating pipeline StatefulSets for a pipeline. The custom template must be stored as the
613/// value of a key in a ConfigMap in the same namespace as the pipeline; set `name` to the
614/// ConfigMap name and `key` to the entry that contains the template.
615///
616/// Recommendations and requirements:
617/// - **Start from the default template and modify it as needed.** The default template is present
618///   in ConfigMap named as `<release-name>-pipeline-template`, with key `pipelineTemplate` in the release
619///   namespace and should be used as a reference.
620/// - The template must contain a valid Kubernetes `StatefulSet` manifest in YAML form. The
621///   runner substitutes variables in the template before parsing; therefore the final YAML
622///   must be syntactically valid.
623/// - The runner performs simple string substitution for the following placeholders. Please ensure these
624///   placeholders are placed at appropriate location for their semantics:
625///   - `{id}`: pipeline Kubernetes name (used for object names and labels)
626///   - `{namespace}`: Kubernetes namespace where the pipeline runs
627///   - `{pipeline_executor_image}`: container image used to run the pipeline executor
628///   - `{binary_ref}`: program binary reference passed as an argument
629///   - `{program_info_ref}`: program info reference passed as an argument
630///   - `{pipeline_storage_path}`: mount path for persistent pipeline storage
631///   - `{storage_class_name}`: storage class name to use for PVCs (if applicable)
632///   - `{deployment_id}`: UUID identifying the deployment instance
633///   - `{deployment_initial}`: initial desired runtime status (e.g., `provisioning`)
634///   - `{bootstrap_policy}`: bootstrap policy value when applicable
635#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
636pub struct PipelineTemplateConfig {
637    /// Name of the ConfigMap containing the pipeline template.
638    pub name: String,
639    /// Key in the ConfigMap containing the pipeline template.
640    ///
641    /// If not set, defaults to `pipelineTemplate`.
642    #[schema(default = default_pipeline_template_key)]
643    #[serde(default = "default_pipeline_template_key")]
644    pub key: String,
645}
646
647fn default_pipeline_template_key() -> String {
648    "pipelineTemplate".to_string()
649}
650
651#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
652pub struct ObjectStorageConfig {
653    /// URL.
654    ///
655    /// The following URL schemes are supported:
656    ///
657    /// * S3:
658    ///   - `s3://<bucket>/<path>`
659    ///   - `s3a://<bucket>/<path>`
660    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
661    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
662    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
663    /// * Google Cloud Storage:
664    ///   - `gs://<bucket>/<path>`
665    /// * Microsoft Azure Blob Storage:
666    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
667    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
668    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
669    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
670    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
671    ///   - `azure://<container>/<path>` (custom)
672    ///   - `https://<account>.dfs.core.windows.net`
673    ///   - `https://<account>.blob.core.windows.net`
674    ///   - `https://<account>.blob.core.windows.net/<container>`
675    ///   - `https://<account>.dfs.fabric.microsoft.com`
676    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
677    ///   - `https://<account>.blob.fabric.microsoft.com`
678    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
679    ///
680    /// Settings derived from the URL will override other settings.
681    pub url: String,
682
683    /// Additional options as key-value pairs.
684    ///
685    /// The following keys are supported:
686    ///
687    /// * S3:
688    ///   - `access_key_id`: AWS Access Key.
689    ///   - `secret_access_key`: AWS Secret Access Key.
690    ///   - `region`: Region.
691    ///   - `default_region`: Default region.
692    ///   - `endpoint`: Custom endpoint for communicating with S3,
693    ///     e.g. `https://localhost:4566` for testing against a localstack
694    ///     instance.
695    ///   - `token`: Token to use for requests (passed to underlying provider).
696    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
697    /// * Google Cloud Storage:
698    ///   - `service_account`: Path to the service account file.
699    ///   - `service_account_key`: The serialized service account key.
700    ///   - `google_application_credentials`: Application credentials path.
701    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
702    /// * Microsoft Azure Blob Storage:
703    ///   - `access_key`: Azure Access Key.
704    ///   - `container_name`: Azure Container Name.
705    ///   - `account`: Azure Account.
706    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
707    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
708    ///   - `client_secret`: Client secret for use in client secret flow.
709    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
710    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
711    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
712    ///
713    /// Options set through the URL take precedence over those set with these
714    /// options.
715    #[serde(flatten)]
716    pub other_options: BTreeMap<String, String>,
717}
718
719/// Configuration for local file system access.
720#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
721#[serde(default)]
722pub struct FileBackendConfig {
723    /// Whether to use background threads for file I/O.
724    ///
725    /// Background threads should improve performance, but they can reduce
726    /// performance if too few cores are available. This is provided for
727    /// debugging and fine-tuning and should ordinarily be left unset.
728    pub async_threads: Option<bool>,
729
730    /// Per-I/O operation sleep duration, in milliseconds.
731    ///
732    /// This is for simulating slow storage devices.  Do not use this in
733    /// production.
734    pub ioop_delay: Option<u64>,
735
736    /// Configuration to synchronize checkpoints to object store.
737    pub sync: Option<SyncConfig>,
738}
739
740/// Global pipeline configuration settings. This is the publicly
741/// exposed type for users to configure pipelines.
742#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
743#[serde(default)]
744pub struct RuntimeConfig {
745    /// Number of DBSP worker threads.
746    ///
747    /// Each DBSP "foreground" worker thread is paired with a "background"
748    /// thread for LSM merging, making the total number of threads twice the
749    /// specified number.
750    ///
751    /// The typical sweet spot for the number of workers is between 4 and 16.
752    /// Each worker increases overall memory consumption for data structures
753    /// used during a step.
754    pub workers: u16,
755
756    /// Number of DBSP hosts.
757    ///
758    /// The worker threads are evenly divided among the hosts.  For single-host
759    /// deployments, this should be 1 (the default).
760    ///
761    /// Multihost pipelines are an enterprise-only preview feature.
762    pub hosts: usize,
763
764    /// Storage configuration.
765    ///
766    /// - If this is `None`, the default, the pipeline's state is kept in
767    ///   in-memory data-structures.  This is useful if the pipeline's state
768    ///   will fit in memory and if the pipeline is ephemeral and does not need
769    ///   to be recovered after a restart. The pipeline will most likely run
770    ///   faster since it does not need to access storage.
771    ///
772    /// - If set, the pipeline's state is kept on storage.  This allows the
773    ///   pipeline to work with state that will not fit into memory. It also
774    ///   allows the state to be checkpointed and recovered across restarts.
775    #[serde(deserialize_with = "deserialize_storage_options")]
776    pub storage: Option<StorageOptions>,
777
778    /// Fault tolerance configuration.
779    #[serde(deserialize_with = "deserialize_fault_tolerance")]
780    pub fault_tolerance: FtConfig,
781
782    /// Enable CPU profiler.
783    ///
784    /// The default value is `true`.
785    pub cpu_profiler: bool,
786
787    /// Enable pipeline tracing.
788    pub tracing: bool,
789
790    /// Jaeger tracing endpoint to send tracing information to.
791    pub tracing_endpoint_jaeger: String,
792
793    /// Minimal input batch size.
794    ///
795    /// The controller delays pushing input records to the circuit until at
796    /// least `min_batch_size_records` records have been received (total
797    /// across all endpoints) or `max_buffering_delay_usecs` microseconds
798    /// have passed since at least one input records has been buffered.
799    /// Defaults to 0.
800    pub min_batch_size_records: u64,
801
802    /// Maximal delay in microseconds to wait for `min_batch_size_records` to
803    /// get buffered by the controller, defaults to 0.
804    pub max_buffering_delay_usecs: u64,
805
806    /// Resource reservations and limits. This is enforced
807    /// only in Feldera Cloud.
808    pub resources: ResourceConfig,
809
810    /// Real-time clock resolution in microseconds.
811    ///
812    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
813    /// queries depends on the real-time clock and can change over time without any external
814    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
815    /// recomputation at most each `clock_resolution_usecs` microseconds.  If the query does not use
816    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
817    ///
818    /// It is set to 1 second (1,000,000 microseconds) by default.
819    pub clock_resolution_usecs: Option<u64>,
820
821    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
822    /// its worker threads.  Specify at least twice as many CPU numbers as
823    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
824    /// might not be able to honor CPU pinning requests.
825    ///
826    /// CPU pinning can make pipelines run faster and perform more consistently,
827    /// as long as different pipelines running on the same machine are pinned to
828    /// different CPUs.
829    pub pin_cpus: Vec<usize>,
830
831    /// Timeout in seconds for the `Provisioning` phase of the pipeline.
832    /// Setting this value will override the default of the runner.
833    pub provisioning_timeout_secs: Option<u64>,
834
835    /// The maximum number of connectors initialized in parallel during pipeline
836    /// startup.
837    ///
838    /// At startup, the pipeline must initialize all of its input and output connectors.
839    /// Depending on the number and types of connectors, this can take a long time.
840    /// To accelerate the process, multiple connectors are initialized concurrently.
841    /// This option controls the maximum number of connectors that can be initialized
842    /// in parallel.
843    ///
844    /// The default is 10.
845    pub max_parallel_connector_init: Option<u64>,
846
847    /// Specification of additional (sidecar) containers.
848    pub init_containers: Option<serde_json::Value>,
849
850    /// Deprecated: setting this true or false does not have an effect anymore.
851    pub checkpoint_during_suspend: bool,
852
853    /// Sets the number of available runtime threads for the http server.
854    ///
855    /// In most cases, this does not need to be set explicitly and
856    /// the default is sufficient. Can be increased in case the
857    /// pipeline HTTP API operations are a bottleneck.
858    ///
859    /// If not specified, the default is set to `workers`.
860    pub http_workers: Option<u64>,
861
862    /// Sets the number of available runtime threads for async IO tasks.
863    ///
864    /// This affects some networking and file I/O operations
865    /// especially adapters and ad-hoc queries.
866    ///
867    /// In most cases, this does not need to be set explicitly and
868    /// the default is sufficient. Can be increased in case
869    /// ingress, egress or ad-hoc queries are a bottleneck.
870    ///
871    /// If not specified, the default is set to `workers`.
872    pub io_workers: Option<u64>,
873
874    /// Environment variables for the pipeline process.
875    ///
876    /// These are key-value pairs injected into the pipeline process environment.
877    /// Some variable names are reserved by the platform and cannot be overridden
878    /// (for example `RUST_LOG`, and variables in the `FELDERA_`,
879    /// `KUBERNETES_`, and `TOKIO_` namespaces).
880    #[serde(default)]
881    pub env: BTreeMap<String, String>,
882
883    /// Optional settings for tweaking Feldera internals.
884    ///
885    /// The available key-value pairs change from one version of Feldera to
886    /// another, so users should not depend on particular settings being
887    /// available, or on their behavior.
888    pub dev_tweaks: BTreeMap<String, serde_json::Value>,
889
890    /// Log filtering directives.
891    ///
892    /// If set to a valid [tracing-subscriber] filter, this controls the log
893    /// messages emitted by the pipeline process.  Otherwise, or if the filter
894    /// has invalid syntax, messages at "info" severity and higher are written
895    /// to the log and all others are discarded.
896    ///
897    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
898    pub logging: Option<String>,
899
900    /// ConfigMap containing a custom pipeline template (Enterprise only).
901    ///
902    /// This feature is only available in Feldera Enterprise. If set, the Kubernetes runner
903    /// will read the template from the specified ConfigMap and use it instead of the default
904    /// StatefulSet template for the configured pipeline.
905    ///
906    /// check [`PipelineTemplateConfig`] documentation for details.
907    pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
908}
909
910/// Accepts "true" and "false" and converts them to the new format.
911fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
912where
913    D: Deserializer<'de>,
914{
915    struct BoolOrStruct;
916
917    impl<'de> Visitor<'de> for BoolOrStruct {
918        type Value = Option<StorageOptions>;
919
920        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
921            formatter.write_str("boolean or StorageOptions")
922        }
923
924        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
925        where
926            E: de::Error,
927        {
928            match v {
929                false => Ok(None),
930                true => Ok(Some(StorageOptions::default())),
931            }
932        }
933
934        fn visit_unit<E>(self) -> Result<Self::Value, E>
935        where
936            E: de::Error,
937        {
938            Ok(None)
939        }
940
941        fn visit_none<E>(self) -> Result<Self::Value, E>
942        where
943            E: de::Error,
944        {
945            Ok(None)
946        }
947
948        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
949        where
950            M: MapAccess<'de>,
951        {
952            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
953        }
954    }
955
956    deserializer.deserialize_any(BoolOrStruct)
957}
958
959/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
960/// tolerance.
961///
962/// Accepts `null` as disabling fault tolerance.
963///
964/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
965/// expect.
966fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
967where
968    D: Deserializer<'de>,
969{
970    struct StringOrStruct;
971
972    impl<'de> Visitor<'de> for StringOrStruct {
973        type Value = FtConfig;
974
975        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
976            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
977        }
978
979        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
980        where
981            E: de::Error,
982        {
983            match v {
984                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
985                    model: Some(FtModel::default()),
986                    ..FtConfig::default()
987                }),
988                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
989            }
990        }
991
992        fn visit_unit<E>(self) -> Result<Self::Value, E>
993        where
994            E: de::Error,
995        {
996            Ok(FtConfig::default())
997        }
998
999        fn visit_none<E>(self) -> Result<Self::Value, E>
1000        where
1001            E: de::Error,
1002        {
1003            Ok(FtConfig::default())
1004        }
1005
1006        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1007        where
1008            M: MapAccess<'de>,
1009        {
1010            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1011        }
1012    }
1013
1014    deserializer.deserialize_any(StringOrStruct)
1015}
1016
1017impl Default for RuntimeConfig {
1018    fn default() -> Self {
1019        Self {
1020            workers: 8,
1021            hosts: 1,
1022            storage: Some(StorageOptions::default()),
1023            fault_tolerance: FtConfig::default(),
1024            cpu_profiler: true,
1025            tracing: {
1026                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
1027                // to keep it on by default.
1028                false
1029            },
1030            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1031            min_batch_size_records: 0,
1032            max_buffering_delay_usecs: 0,
1033            resources: ResourceConfig::default(),
1034            clock_resolution_usecs: { Some(DEFAULT_CLOCK_RESOLUTION_USECS) },
1035            pin_cpus: Vec::new(),
1036            provisioning_timeout_secs: None,
1037            max_parallel_connector_init: None,
1038            init_containers: None,
1039            checkpoint_during_suspend: true,
1040            io_workers: None,
1041            http_workers: None,
1042            env: BTreeMap::default(),
1043            dev_tweaks: BTreeMap::default(),
1044            logging: None,
1045            pipeline_template_configmap: None,
1046        }
1047    }
1048}
1049
1050/// Fault-tolerance configuration.
1051///
1052/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
1053/// which is the configuration that one gets if [RuntimeConfig] omits fault
1054/// tolerance configuration.
1055///
1056/// The default value for [FtConfig::model] enables fault tolerance, as
1057/// `Some(FtModel::default())`.  This is the configuration that one gets if
1058/// [RuntimeConfig] includes a fault tolerance configuration but does not
1059/// specify a particular model.
1060#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1061#[serde(rename_all = "snake_case")]
1062pub struct FtConfig {
1063    /// Fault tolerance model to use.
1064    #[serde(with = "none_as_string")]
1065    #[serde(default = "default_model")]
1066    #[schema(
1067        schema_with = none_as_string_schema::<FtModel>,
1068    )]
1069    pub model: Option<FtModel>,
1070
1071    /// Interval between automatic checkpoints, in seconds.
1072    ///
1073    /// The default is 60 seconds.  Values less than 1 or greater than 3600 will
1074    /// be forced into that range.
1075    #[serde(default = "default_checkpoint_interval_secs")]
1076    pub checkpoint_interval_secs: Option<u64>,
1077}
1078
1079fn default_model() -> Option<FtModel> {
1080    Some(FtModel::default())
1081}
1082
1083pub fn default_checkpoint_interval_secs() -> Option<u64> {
1084    Some(60)
1085}
1086
1087impl Default for FtConfig {
1088    fn default() -> Self {
1089        Self {
1090            model: None,
1091            checkpoint_interval_secs: default_checkpoint_interval_secs(),
1092        }
1093    }
1094}
1095
1096#[cfg(test)]
1097mod test {
1098    use super::deserialize_fault_tolerance;
1099    use crate::config::{FtConfig, FtModel};
1100    use serde::{Deserialize, Serialize};
1101
1102    #[test]
1103    fn ft_config() {
1104        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
1105        #[serde(default)]
1106        struct Wrapper {
1107            #[serde(deserialize_with = "deserialize_fault_tolerance")]
1108            config: FtConfig,
1109        }
1110
1111        // Omitting FtConfig, or specifying null, or specifying model "none", disables fault tolerance.
1112        for s in [
1113            "{}",
1114            r#"{"config": null}"#,
1115            r#"{"config": {"model": "none"}}"#,
1116        ] {
1117            let config: Wrapper = serde_json::from_str(s).unwrap();
1118            assert_eq!(
1119                config,
1120                Wrapper {
1121                    config: FtConfig {
1122                        model: None,
1123                        checkpoint_interval_secs: Some(60)
1124                    }
1125                }
1126            );
1127        }
1128
1129        // Serializing disabled FT produces explicit "none" form.
1130        let s = serde_json::to_string(&Wrapper {
1131            config: FtConfig::default(),
1132        })
1133        .unwrap();
1134        assert!(s.contains("\"none\""));
1135
1136        // `{}` for FtConfig, or `{...}` with `model` omitted, enables fault
1137        // tolerance.
1138        for s in [r#"{"config": {}}"#, r#"{"checkpoint_interval_secs": 60}"#] {
1139            assert_eq!(
1140                serde_json::from_str::<FtConfig>(s).unwrap(),
1141                FtConfig {
1142                    model: Some(FtModel::default()),
1143                    checkpoint_interval_secs: Some(60)
1144                }
1145            );
1146        }
1147
1148        // `"checkpoint_interval_secs": null` disables periodic checkpointing.
1149        assert_eq!(
1150            serde_json::from_str::<FtConfig>(r#"{"checkpoint_interval_secs": null}"#).unwrap(),
1151            FtConfig {
1152                model: Some(FtModel::default()),
1153                checkpoint_interval_secs: None
1154            }
1155        );
1156    }
1157}
1158
1159impl FtConfig {
1160    pub fn is_enabled(&self) -> bool {
1161        self.model.is_some()
1162    }
1163
1164    /// Returns the checkpoint interval, if fault tolerance is enabled, and
1165    /// otherwise `None`.
1166    pub fn checkpoint_interval(&self) -> Option<Duration> {
1167        if self.is_enabled() {
1168            self.checkpoint_interval_secs
1169                .map(|interval| Duration::from_secs(interval.clamp(1, 3600)))
1170        } else {
1171            None
1172        }
1173    }
1174}
1175
1176/// Serde implementation for de/serializing a string into `Option<T>` where
1177/// `"none"` indicates `None` and any other string indicates `Some`.
1178///
1179/// This could be extended to handle non-strings by adding more forwarding
1180/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
1181/// them automatically.
1182mod none_as_string {
1183    use std::marker::PhantomData;
1184
1185    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
1186    use serde::ser::{Serialize, Serializer};
1187
1188    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
1189    where
1190        S: Serializer,
1191        T: Serialize,
1192    {
1193        match value.as_ref() {
1194            Some(value) => value.serialize(serializer),
1195            None => "none".serialize(serializer),
1196        }
1197    }
1198
1199    struct NoneAsString<T>(PhantomData<fn() -> T>);
1200
1201    impl<'de, T> Visitor<'de> for NoneAsString<T>
1202    where
1203        T: Deserialize<'de>,
1204    {
1205        type Value = Option<T>;
1206
1207        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
1208            formatter.write_str("string")
1209        }
1210
1211        fn visit_none<E>(self) -> Result<Self::Value, E>
1212        where
1213            E: serde::de::Error,
1214        {
1215            Ok(None)
1216        }
1217
1218        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
1219        where
1220            E: serde::de::Error,
1221        {
1222            if &value.to_ascii_lowercase() == "none" {
1223                Ok(None)
1224            } else {
1225                Ok(Some(T::deserialize(value.into_deserializer())?))
1226            }
1227        }
1228    }
1229
1230    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
1231    where
1232        D: Deserializer<'de>,
1233        T: Deserialize<'de>,
1234    {
1235        deserializer.deserialize_str(NoneAsString(PhantomData))
1236    }
1237}
1238
1239/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
1240/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
1241fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
1242    Schema::OneOf(
1243        OneOfBuilder::new()
1244            .item(RefOr::Ref(Ref::new(format!(
1245                "#/components/schemas/{}",
1246                T::schema().0
1247            ))))
1248            .item(
1249                ObjectBuilder::new()
1250                    .schema_type(SchemaType::String)
1251                    .enum_values(Some(vec!["none"])),
1252            )
1253            .default(Some(
1254                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
1255            ))
1256            .build(),
1257    )
1258}
1259
1260/// Fault tolerance model.
1261///
1262/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
1263/// level" of fault tolerance than [Self::AtLeastOnce].
1264#[derive(
1265    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
1266)]
1267#[serde(rename_all = "snake_case")]
1268pub enum FtModel {
1269    /// Each record is output at least once.  Crashes may duplicate output, but
1270    /// no input or output is dropped.
1271    AtLeastOnce,
1272
1273    /// Each record is output exactly once.  Crashes do not drop or duplicate
1274    /// input or output.
1275    #[default]
1276    ExactlyOnce,
1277}
1278
1279impl FtModel {
1280    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
1281        value.map_or("no", |model| model.as_str())
1282    }
1283
1284    pub fn as_str(&self) -> &'static str {
1285        match self {
1286            FtModel::AtLeastOnce => "at_least_once",
1287            FtModel::ExactlyOnce => "exactly_once",
1288        }
1289    }
1290}
1291
1292pub struct FtModelUnknown;
1293
1294impl FromStr for FtModel {
1295    type Err = FtModelUnknown;
1296
1297    fn from_str(s: &str) -> Result<Self, Self::Err> {
1298        match s.to_ascii_lowercase().as_str() {
1299            "exactly_once" => Ok(Self::ExactlyOnce),
1300            "at_least_once" => Ok(Self::AtLeastOnce),
1301            _ => Err(FtModelUnknown),
1302        }
1303    }
1304}
1305
1306/// Describes an input connector configuration
1307#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1308pub struct InputEndpointConfig {
1309    /// The name of the input stream of the circuit that this endpoint is
1310    /// connected to.
1311    pub stream: Cow<'static, str>,
1312
1313    /// Connector configuration.
1314    #[serde(flatten)]
1315    pub connector_config: ConnectorConfig,
1316}
1317
1318/// Deserialize the `start_after` property of a connector configuration.
1319/// It requires a non-standard deserialization because we want to accept
1320/// either a string or an array of strings.
1321fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
1322where
1323    D: Deserializer<'de>,
1324{
1325    let value = Option::<JsonValue>::deserialize(deserializer)?;
1326    match value {
1327        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
1328        Some(JsonValue::Array(arr)) => {
1329            let vec = arr
1330                .into_iter()
1331                .map(|item| {
1332                    item.as_str()
1333                        .map(|s| s.to_string())
1334                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
1335                })
1336                .collect::<Result<Vec<String>, _>>()?;
1337            Ok(Some(vec))
1338        }
1339        Some(JsonValue::Null) | None => Ok(None),
1340        _ => Err(serde::de::Error::custom(
1341            "invalid 'start_after' property: expected a string, an array of strings, or null",
1342        )),
1343    }
1344}
1345
1346/// A data connector's configuration
1347#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1348pub struct ConnectorConfig {
1349    /// Transport endpoint configuration.
1350    pub transport: TransportConfig,
1351
1352    /// Parser configuration.
1353    pub format: Option<FormatConfig>,
1354
1355    /// Name of the index that the connector is attached to.
1356    ///
1357    /// This property is valid for output connectors only.  It is used with data
1358    /// transports and formats that expect output updates in the form of key/value
1359    /// pairs, where the key typically represents a unique id associated with the
1360    /// table or view.
1361    ///
1362    /// To support such output formats, an output connector can be attached to an
1363    /// index created using the SQL CREATE INDEX statement.  An index of a table
1364    /// or view contains the same updates as the table or view itself, indexed by
1365    /// one or more key columns.
1366    ///
1367    /// See individual connector documentation for details on how they work
1368    /// with indexes.
1369    pub index: Option<String>,
1370
1371    /// Output buffer configuration.
1372    #[serde(flatten)]
1373    pub output_buffer_config: OutputBufferConfig,
1374
1375    /// Maximum number of records from this connector to process in a single batch.
1376    ///
1377    /// When set, this caps how many records are taken from the connector’s input
1378    /// buffer and pushed through the circuit at once.
1379    ///
1380    /// This is typically configured lower than `max_queued_records` to allow the
1381    /// connector time to restart and refill its buffer while a batch is being
1382    /// processed.
1383    ///
1384    /// Not all input adapters honor this limit.
1385    ///
1386    /// If this is not set, the batch size is derived from `max_worker_batch_size`.
1387    #[serde(skip_serializing_if = "Option::is_none")]
1388    pub max_batch_size: Option<u64>,
1389
1390    /// Maximum number of records processed per batch, per worker thread.
1391    ///
1392    /// When `max_batch_size` is not set, this setting is used to cap
1393    /// the number of records that can be taken from the connector’s input
1394    /// buffer and pushed through the circuit at once.  The effective batch size is computed as:
1395    /// `max_worker_batch_size × workers`.
1396    ///
1397    /// This provides an alternative to `max_batch_size` that automatically adjusts batch
1398    /// size as the number of worker threads changes to maintain constant amount of
1399    /// work per worker per batch.
1400    ///
1401    /// Defaults to 10,000 records per worker.
1402    #[serde(skip_serializing_if = "Option::is_none")]
1403    pub max_worker_batch_size: Option<u64>,
1404
1405    /// Backpressure threshold.
1406    ///
1407    /// Maximal number of records queued by the endpoint before the endpoint
1408    /// is paused by the backpressure mechanism.
1409    ///
1410    /// For input endpoints, this setting bounds the number of records that have
1411    /// been received from the input transport but haven't yet been consumed by
1412    /// the circuit since the circuit, since the circuit is still busy processing
1413    /// previous inputs.
1414    ///
1415    /// For output endpoints, this setting bounds the number of records that have
1416    /// been produced by the circuit but not yet sent via the output transport endpoint
1417    /// nor stored in the output buffer (see `enable_output_buffer`).
1418    ///
1419    /// Note that this is not a hard bound: there can be a small delay between
1420    /// the backpressure mechanism is triggered and the endpoint is paused, during
1421    /// which more data may be queued.
1422    ///
1423    /// The default is 1 million.
1424    #[serde(default = "default_max_queued_records")]
1425    pub max_queued_records: u64,
1426
1427    /// Create connector in paused state.
1428    ///
1429    /// The default is `false`.
1430    #[serde(default)]
1431    pub paused: bool,
1432
1433    /// Arbitrary user-defined text labels associated with the connector.
1434    ///
1435    /// These labels can be used in conjunction with the `start_after` property
1436    /// to control the start order of connectors.
1437    #[serde(default)]
1438    pub labels: Vec<String>,
1439
1440    /// Start the connector after all connectors with specified labels.
1441    ///
1442    /// This property is used to control the start order of connectors.
1443    /// The connector will not start until all connectors with the specified
1444    /// labels have finished processing all inputs.
1445    #[serde(deserialize_with = "deserialize_start_after")]
1446    #[serde(default)]
1447    pub start_after: Option<Vec<String>>,
1448}
1449
1450impl ConnectorConfig {
1451    /// Compare two configs modulo the `paused` field.
1452    ///
1453    /// Used to compare checkpointed and current connector configs.
1454    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
1455        let mut a = self.clone();
1456        let mut b = other.clone();
1457        a.paused = false;
1458        b.paused = false;
1459        a == b
1460    }
1461}
1462
1463#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1464#[serde(default)]
1465pub struct OutputBufferConfig {
1466    /// Enable output buffering.
1467    ///
1468    /// The output buffering mechanism allows decoupling the rate at which the pipeline
1469    /// pushes changes to the output transport from the rate of input changes.
1470    ///
1471    /// By default, output updates produced by the pipeline are pushed directly to
1472    /// the output transport. Some destinations may prefer to receive updates in fewer
1473    /// bigger batches. For instance, when writing Parquet files, producing
1474    /// one bigger file every few minutes is usually better than creating
1475    /// small files every few milliseconds.
1476    ///
1477    /// To achieve such input/output decoupling, users can enable output buffering by
1478    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
1479    /// updates produced by the pipeline are consolidated in an internal buffer and are
1480    /// pushed to the output transport when one of several conditions is satisfied:
1481    ///
1482    /// * data has been accumulated in the buffer for more than `max_output_buffer_time_millis`
1483    ///   milliseconds.
1484    /// * buffer size exceeds `max_output_buffer_size_records` records.
1485    ///
1486    /// This flag is `false` by default.
1487    // TODO: on-demand output triggered via the API.
1488    pub enable_output_buffer: bool,
1489
1490    /// Maximum time in milliseconds data is kept in the output buffer.
1491    ///
1492    /// By default, data is kept in the buffer indefinitely until one of
1493    /// the other output conditions is satisfied.  When this option is
1494    /// set the buffer will be flushed at most every
1495    /// `max_output_buffer_time_millis` milliseconds.
1496    ///
1497    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1498    /// to be set.
1499    pub max_output_buffer_time_millis: usize,
1500
1501    /// Maximum number of updates to be kept in the output buffer.
1502    ///
1503    /// This parameter bounds the maximal size of the buffer.
1504    /// Note that the size of the buffer is not always equal to the
1505    /// total number of updates output by the pipeline. Updates to the
1506    /// same record can overwrite or cancel previous updates.
1507    ///
1508    /// By default, the buffer can grow indefinitely until one of
1509    /// the other output conditions is satisfied.
1510    ///
1511    /// NOTE: this configuration option requires the `enable_output_buffer` flag
1512    /// to be set.
1513    pub max_output_buffer_size_records: usize,
1514}
1515
1516impl Default for OutputBufferConfig {
1517    fn default() -> Self {
1518        Self {
1519            enable_output_buffer: false,
1520            max_output_buffer_size_records: usize::MAX,
1521            max_output_buffer_time_millis: usize::MAX,
1522        }
1523    }
1524}
1525
1526impl OutputBufferConfig {
1527    pub fn validate(&self) -> Result<(), String> {
1528        if self.enable_output_buffer
1529            && self.max_output_buffer_size_records == Self::default().max_output_buffer_size_records
1530            && self.max_output_buffer_time_millis == Self::default().max_output_buffer_time_millis
1531        {
1532            return Err(
1533                "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"
1534                    .to_string(),
1535            );
1536        }
1537
1538        Ok(())
1539    }
1540}
1541
1542/// Describes an output connector configuration
1543#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1544pub struct OutputEndpointConfig {
1545    /// The name of the output stream of the circuit that this endpoint is
1546    /// connected to.
1547    pub stream: Cow<'static, str>,
1548
1549    /// Connector configuration.
1550    #[serde(flatten)]
1551    pub connector_config: ConnectorConfig,
1552}
1553
1554/// Transport-specific endpoint configuration passed to
1555/// `crate::OutputTransport::new_endpoint`
1556/// and `crate::InputTransport::new_endpoint`.
1557#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1558#[serde(tag = "name", content = "config", rename_all = "snake_case")]
1559pub enum TransportConfig {
1560    FileInput(FileInputConfig),
1561    FileOutput(FileOutputConfig),
1562    NatsInput(NatsInputConfig),
1563    KafkaInput(KafkaInputConfig),
1564    KafkaOutput(KafkaOutputConfig),
1565    PubSubInput(PubSubInputConfig),
1566    UrlInput(UrlInputConfig),
1567    S3Input(S3InputConfig),
1568    DeltaTableInput(DeltaTableReaderConfig),
1569    DeltaTableOutput(DeltaTableWriterConfig),
1570    RedisOutput(RedisOutputConfig),
1571    // Prevent rust from complaining about large size difference between enum variants.
1572    IcebergInput(Box<IcebergReaderConfig>),
1573    PostgresInput(PostgresReaderConfig),
1574    PostgresOutput(PostgresWriterConfig),
1575    Datagen(DatagenInputConfig),
1576    Nexmark(NexmarkInputConfig),
1577    /// Direct HTTP input: cannot be instantiated through API
1578    HttpInput(HttpInputConfig),
1579    /// Direct HTTP output: cannot be instantiated through API
1580    HttpOutput,
1581    /// Ad hoc input: cannot be instantiated through API
1582    AdHocInput(AdHocInputConfig),
1583    ClockInput(ClockConfig),
1584}
1585
1586impl TransportConfig {
1587    pub fn name(&self) -> String {
1588        match self {
1589            TransportConfig::FileInput(_) => "file_input".to_string(),
1590            TransportConfig::FileOutput(_) => "file_output".to_string(),
1591            TransportConfig::NatsInput(_) => "nats_input".to_string(),
1592            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
1593            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
1594            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
1595            TransportConfig::UrlInput(_) => "url_input".to_string(),
1596            TransportConfig::S3Input(_) => "s3_input".to_string(),
1597            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
1598            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
1599            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
1600            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
1601            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
1602            TransportConfig::Datagen(_) => "datagen".to_string(),
1603            TransportConfig::Nexmark(_) => "nexmark".to_string(),
1604            TransportConfig::HttpInput(_) => "http_input".to_string(),
1605            TransportConfig::HttpOutput => "http_output".to_string(),
1606            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
1607            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
1608            TransportConfig::ClockInput(_) => "clock".to_string(),
1609        }
1610    }
1611
1612    /// Returns true if the connector is transient, i.e., is created and destroyed
1613    /// at runtime on demand, rather than being configured as part of the pipeline.
1614    pub fn is_transient(&self) -> bool {
1615        matches!(
1616            self,
1617            TransportConfig::AdHocInput(_)
1618                | TransportConfig::HttpInput(_)
1619                | TransportConfig::HttpOutput
1620                | TransportConfig::ClockInput(_)
1621        )
1622    }
1623}
1624
1625/// Data format specification used to parse raw data received from the
1626/// endpoint or to encode data sent to the endpoint.
1627#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
1628pub struct FormatConfig {
1629    /// Format name, e.g., "csv", "json", "bincode", etc.
1630    pub name: Cow<'static, str>,
1631
1632    /// Format-specific parser or encoder configuration.
1633    #[serde(default)]
1634    #[schema(value_type = Object)]
1635    pub config: JsonValue,
1636}
1637
1638#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
1639#[serde(default)]
1640pub struct ResourceConfig {
1641    /// The minimum number of CPU cores to reserve
1642    /// for an instance of this pipeline
1643    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
1644    pub cpu_cores_min: Option<f64>,
1645
1646    /// The maximum number of CPU cores to reserve
1647    /// for an instance of this pipeline
1648    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
1649    pub cpu_cores_max: Option<f64>,
1650
1651    /// The minimum memory in Megabytes to reserve
1652    /// for an instance of this pipeline
1653    pub memory_mb_min: Option<u64>,
1654
1655    /// The maximum memory in Megabytes to reserve
1656    /// for an instance of this pipeline
1657    pub memory_mb_max: Option<u64>,
1658
1659    /// The total storage in Megabytes to reserve
1660    /// for an instance of this pipeline
1661    pub storage_mb_max: Option<u64>,
1662
1663    /// Storage class to use for an instance of this pipeline.
1664    /// The class determines storage performance such as IOPS and throughput.
1665    pub storage_class: Option<String>,
1666
1667    /// Kubernetes service account name to use for an instance of this pipeline.
1668    /// The account determines permissions and access controls.
1669    pub service_account_name: Option<String>,
1670
1671    /// Kubernetes namespace to use for an instance of this pipeline.
1672    /// The namespace determines the scope of names for resources created
1673    /// for the pipeline.
1674    /// If not set, the pipeline will be deployed in the same namespace
1675    /// as the control-plane.
1676    pub namespace: Option<String>,
1677}