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