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