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