Skip to main content

feldera_types/
config.rs

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