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