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