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