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