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