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