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::duration::ConfigDuration;
9use crate::postprocess::PostprocessorConfig;
10use crate::preprocess::PreprocessorConfig;
11use crate::secret_resolver::default_secrets_directory;
12use crate::transport::adhoc::AdHocInputConfig;
13use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
14use crate::transport::datagen::DatagenInputConfig;
15use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
16use crate::transport::dynamodb::DynamoDBWriterConfig;
17use crate::transport::file::{FileInputConfig, FileOutputConfig};
18use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
19use crate::transport::iceberg::IcebergReaderConfig;
20use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
21use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
22use crate::transport::nexmark::NexmarkInputConfig;
23use crate::transport::postgres::{
24    PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
25};
26use crate::transport::pubsub::PubSubInputConfig;
27use crate::transport::redis::RedisOutputConfig;
28use crate::transport::s2::{S2InputConfig, S2OutputConfig};
29use crate::transport::s3::S3InputConfig;
30use crate::transport::url::UrlInputConfig;
31use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting};
32use core::fmt;
33use feldera_ir::{MirNode, MirNodeId};
34use serde::de::{self, MapAccess, Visitor};
35use serde::{Deserialize, Deserializer, Serialize};
36use serde_json::Value as JsonValue;
37use std::collections::HashMap;
38use std::fmt::Display;
39use std::path::Path;
40use std::str::FromStr;
41use std::time::Duration;
42use std::{borrow::Cow, cmp::max, collections::BTreeMap};
43use utoipa::ToSchema;
44use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
45
46pub mod dev_tweaks;
47pub use dev_tweaks::DevTweaks;
48
49const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
50
51/// Default maximum number of updates to be kept in the output buffer.
52const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
53
54/// Default value of `ConnectorConfig::max_queued_records`.
55pub const fn default_max_queued_records() -> u64 {
56    1_000_000
57}
58
59pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
60
61/// Default resolution of the real-time clock that drives SQL `NOW()`.
62pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
63
64/// Default interval between automatic checkpoints.
65pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
66
67/// Default interval between standby checkpoint fetches.
68pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
69
70/// Default minimum age a checkpoint reaches before it may be deleted.
71pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
72
73// The defaults as the OpenAPI schema shows them, one function per
74// `#[schema(default = ...)]`.
75fn default_clock_resolution() -> String {
76    DEFAULT_CLOCK_RESOLUTION.to_string()
77}
78fn default_checkpoint_interval() -> String {
79    DEFAULT_CHECKPOINT_INTERVAL.to_string()
80}
81fn default_pull_interval() -> String {
82    DEFAULT_PULL_INTERVAL.to_string()
83}
84fn default_retention_min_age() -> String {
85    DEFAULT_RETENTION_MIN_AGE.to_string()
86}
87
88duration_setting!(
89    duration_standby_pull_interval,
90    "standby_pull_interval",
91    LegacyUnit::Secs
92);
93duration_setting!(
94    duration_checkpoint_push_interval,
95    "checkpoint_push_interval",
96    LegacyUnit::Secs
97);
98duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
99duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
100duration_setting!(
101    duration_max_buffering_delay,
102    "max_buffering_delay",
103    LegacyUnit::Micros
104);
105duration_setting!(
106    duration_clock_resolution,
107    "clock_resolution",
108    LegacyUnit::Micros
109);
110duration_setting!(
111    duration_provisioning_timeout,
112    "provisioning_timeout",
113    LegacyUnit::Secs
114);
115nullable_duration_setting!(
116    duration_checkpoint_interval,
117    "checkpoint_interval",
118    LegacyUnit::Secs
119);
120duration_setting!(
121    duration_max_output_buffer_time,
122    "max_output_buffer_time",
123    LegacyUnit::Millis
124);
125
126/// Program information included in the pipeline configuration.
127#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
128pub struct ProgramIr {
129    /// The MIR of the program.
130    pub mir: HashMap<MirNodeId, MirNode>,
131    /// Program schema.
132    pub program_schema: serde_json::Value,
133    /// The circuit IR (the compiler's JIT `allOperators` form) that the Gen-2
134    /// engine lowers onto the runtime to build the circuit. `None` for
135    /// Rust-compiled pipelines, whose circuit is statically linked into the binary.
136    #[serde(default)]
137    pub circuit_ir: Option<serde_json::Value>,
138}
139
140/// Identity of a pipeline, used to record and check ownership of an S3
141/// checkpoint bucket.
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
143pub struct PipelineIdentity {
144    /// System-generated name of the pipeline (format `pipeline-<uuid>`).
145    pub name: String,
146    /// Name given to the pipeline by the tenant.
147    pub given_name: Option<String>,
148}
149
150impl Display for PipelineIdentity {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match &self.given_name {
153            Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
154            None => write!(f, "{}", self.name),
155        }
156    }
157}
158
159/// Pipeline deployment configuration.
160/// It represents configuration entries directly provided by the user
161/// (e.g., runtime configuration) and entries derived from the schema
162/// of the compiled program (e.g., connectors). Storage configuration,
163/// if applicable, is set by the runner.
164#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
165pub struct PipelineConfig {
166    /// Global controller configuration.
167    #[serde(flatten)]
168    #[schema(inline)]
169    pub global: RuntimeConfig,
170
171    /// Configuration for multihost pipelines.
172    ///
173    /// The presence of this field indicates that the pipeline is running in
174    /// multihost mode.  In the pod with ordinal 0, this triggers starting the
175    /// coordinator process.  In all pods, this tells the pipeline process to
176    /// await a connection from the coordinator instead of initializing the
177    /// pipeline immediately.
178    pub multihost: Option<MultihostConfig>,
179
180    /// Unique system-generated name of the pipeline (format: `pipeline-<uuid>`).
181    /// It is unique across all tenants and cannot be changed.
182    ///
183    /// The `<uuid>` is also used in the naming of various resources that back the pipeline,
184    /// and as such this name is useful to find/identify corresponding resources.
185    pub name: Option<String>,
186
187    /// Name given by the tenant to the pipeline. It is only unique within the same tenant, and can
188    /// be changed by the tenant when the pipeline is stopped.
189    ///
190    /// Given a specific tenant, it can be used to find/identify a specific pipeline of theirs.
191    pub given_name: Option<String>,
192
193    /// Configuration for persistent storage
194    ///
195    /// If `global.storage` is `Some(_)`, this field must be set to some
196    /// [`StorageConfig`].  If `global.storage` is `None``, the pipeline ignores
197    /// this field.
198    #[serde(default)]
199    pub storage_config: Option<StorageConfig>,
200
201    /// Directory containing values of secrets.
202    ///
203    /// If this is not set, a default directory is used.
204    pub secrets_dir: Option<String>,
205
206    /// Input endpoint configuration.
207    #[serde(default)]
208    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
209
210    /// Output endpoint configuration.
211    #[serde(default)]
212    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
213
214    /// Program information.
215    #[serde(default)]
216    pub program_ir: Option<ProgramIr>,
217}
218
219impl PipelineConfig {
220    pub fn max_parallel_connector_init(&self) -> u64 {
221        max(
222            self.global
223                .max_parallel_connector_init
224                .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
225            1,
226        )
227    }
228
229    /// Extract the compiler-generated subset of the configuration (connectors
230    /// and program IR) used to compute pipeline diffs.
231    pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
232        PipelineConfigProgramInfo {
233            inputs: self.inputs.clone(),
234            outputs: self.outputs.clone(),
235            program_ir: self.program_ir.clone(),
236        }
237    }
238
239    pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
240        let (storage_config, storage_options) = storage.unzip();
241        Self {
242            global: RuntimeConfig {
243                storage: storage_options,
244                ..self.global
245            },
246            storage_config,
247            ..self
248        }
249    }
250
251    pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
252        let storage_options = self.global.storage.as_ref();
253        let storage_config = self.storage_config.as_ref();
254        storage_config.zip(storage_options)
255    }
256
257    /// Returns this pipeline's [`PipelineIdentity`], used to identify the
258    /// pipeline that owns an S3 checkpoint bucket.
259    ///
260    /// Returns `None` when the pipeline has no system-generated [`name`](Self::name).
261    pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
262        self.name.as_ref().map(|name| PipelineIdentity {
263            name: name.clone(),
264            given_name: self.given_name.clone(),
265        })
266    }
267
268    /// Returns `self.secrets_dir`, or the default secrets directory if it isn't
269    /// set.
270    pub fn secrets_dir(&self) -> &Path {
271        match &self.secrets_dir {
272            Some(dir) => Path::new(dir.as_str()),
273            None => default_secrets_directory(),
274        }
275    }
276
277    /// Abbreviated config that can be printed in the log on pipeline startup.
278    pub fn display_summary(&self) -> String {
279        // TODO: we may want to further abbreviate connector config.
280        let summary = serde_json::json!({
281            "name": self.name,
282            "given_name": self.given_name,
283            "global": self.global,
284            "storage_config": self.storage_config,
285            "secrets_dir": self.secrets_dir,
286            "inputs": self.inputs,
287            "outputs": self.outputs
288        });
289
290        serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
291    }
292}
293
294/// A subset of fields in `PipelineConfig` that are generated by the compiler.
295/// These fields are shipped to the pipeline by the compilation server along with
296/// the program binary.
297// Note: An alternative would be to embed these fields in the program binary itself
298// as static strings. This would work well for program IR, but it would require recompiling
299// the program anytime a connector config changes, whereas today connector changes
300// do not require recompilation.
301#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
302pub struct PipelineConfigProgramInfo {
303    /// Input endpoint configuration.
304    pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
305
306    /// Output endpoint configuration.
307    #[serde(default)]
308    pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
309
310    /// Program information.
311    #[serde(default)]
312    pub program_ir: Option<ProgramIr>,
313}
314
315/// Configuration for a multihost Feldera pipeline.
316///
317/// This configuration is primarily for the coordinator.
318#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
319pub struct MultihostConfig {
320    /// Number of hosts to launch.
321    ///
322    /// For the configuration to be truly multihost, this should be at least 2.
323    /// A value of 1 still runs the multihost coordinator but it only
324    /// coordinates a single host.
325    pub hosts: usize,
326}
327
328impl Default for MultihostConfig {
329    fn default() -> Self {
330        Self { hosts: 1 }
331    }
332}
333
334/// Configuration for persistent storage in a [`PipelineConfig`].
335#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
336pub struct StorageConfig {
337    /// A directory to keep pipeline state, as a path on the filesystem of the
338    /// machine or container where the pipeline will run.
339    ///
340    /// When storage is enabled, this directory stores the data for
341    /// [StorageBackendConfig::Default].
342    ///
343    /// When fault tolerance is enabled, this directory stores checkpoints and
344    /// the log.
345    pub path: String,
346
347    /// How to cache access to storage in this pipeline.
348    #[serde(default)]
349    pub cache: StorageCacheConfig,
350}
351
352impl StorageConfig {
353    pub fn path(&self) -> &Path {
354        Path::new(&self.path)
355    }
356}
357
358/// How to cache access to storage within a Feldera pipeline.
359#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
360#[serde(rename_all = "snake_case")]
361pub enum StorageCacheConfig {
362    /// Use the operating system's page cache as the primary storage cache.
363    ///
364    /// This is the default because it currently performs better than
365    /// `FelderaCache`.
366    #[default]
367    PageCache,
368
369    /// Use Feldera's internal cache implementation.
370    ///
371    /// This is under development. It will become the default when its
372    /// performance exceeds that of `PageCache`.
373    FelderaCache,
374}
375
376impl StorageCacheConfig {
377    #[cfg(unix)]
378    pub fn to_custom_open_flags(&self) -> i32 {
379        match self {
380            StorageCacheConfig::PageCache => (),
381            StorageCacheConfig::FelderaCache => {
382                #[cfg(target_os = "linux")]
383                return libc::O_DIRECT;
384            }
385        }
386        0
387    }
388}
389
390/// Storage configuration for a pipeline.
391#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
392#[serde(default)]
393pub struct StorageOptions {
394    /// How to connect to the underlying storage.
395    pub backend: StorageBackendConfig,
396
397    /// For a batch of data maintained as part of a persistent index during a
398    /// pipeline run, the minimum estimated number of bytes to write it to
399    /// storage.
400    ///
401    /// This is provided for debugging and fine-tuning and should ordinarily be
402    /// left unset.
403    ///
404    /// A value of 0 will write even empty batches to storage, and nonzero
405    /// values provide a threshold.  `usize::MAX` would effectively disable
406    /// storage for such batches.  The default is 10,048,576 (10 MiB).
407    pub min_storage_bytes: Option<usize>,
408
409    /// For a batch of data passed through the pipeline during a single step,
410    /// the minimum estimated number of bytes to write it to storage.
411    ///
412    /// This is provided for debugging and fine-tuning and should ordinarily be
413    /// left unset.  A value of 0 writes every batch that holds anything to
414    /// storage; an empty batch stays in memory, since it has nothing to spill
415    /// and a layer file is not free.  Nonzero values provide a threshold.
416    /// `usize::MAX`, the default, effectively disables storage for such
417    /// batches.  If it is set to another value, it should ordinarily be
418    /// greater than or equal to `min_storage_bytes`.
419    pub min_step_storage_bytes: Option<usize>,
420
421    /// The form of compression to use in data batches.
422    ///
423    /// Compression has a CPU cost but it can take better advantage of limited
424    /// NVMe and network bandwidth, which means that it can increase overall
425    /// performance.
426    pub compression: StorageCompression,
427
428    /// Compression level, for compression algorithms that have one.
429    ///
430    /// Only `StorageCompression::Zstd` uses this. Higher levels compress
431    /// harder and more slowly; decompression speed is largely unaffected, so
432    /// the tradeoff is write throughput against stored size. Zstd accepts
433    /// roughly 1 to 22, and a value outside the range its build supports is
434    /// clamped into it.
435    ///
436    /// This is provided for fine-tuning and should ordinarily be left unset,
437    /// which selects the algorithm's own default.
438    pub compression_level: Option<i32>,
439
440    /// The maximum size of the in-memory storage cache, in MiB.
441    ///
442    /// If set, the specified cache size is spread across all the foreground and
443    /// background threads. If unset, each foreground or background thread cache
444    /// is limited to 256 MiB.
445    pub cache_mib: Option<usize>,
446
447    /// False-positive rate for Bloom filters on batches on storage, as a
448    /// fraction f, where 0 < f < 1.
449    ///
450    /// The false-positive rate trades off between the amount of memory used by
451    /// Bloom filters and how frequently storage needs to be searched for keys
452    /// that are not actually present.  Typical false-positive rates and their
453    /// corresponding memory costs are:
454    ///
455    /// - 0.1: 4.8 bits per key
456    /// - 0.01: 9.6 bits per key
457    /// - 0.001: 14.4 bits per key
458    /// - 0.0001: 19.2 bits per key (default)
459    ///
460    /// Values outside the valid range, such as 0.0, disable Bloom filters.
461    #[serde(skip_serializing_if = "Option::is_none")]
462    #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
463    pub bloom_false_positive_rate: Option<f64>,
464}
465
466// `f64` does not implement `Eq`, but `bloom_false_positive_rate` is always
467// finite, so `PartialEq` is an equivalence relation here.
468impl Eq for StorageOptions {}
469
470/// Backend storage configuration.
471#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
472#[serde(tag = "name", content = "config", rename_all = "snake_case")]
473pub enum StorageBackendConfig {
474    /// Use the default storage configuration.
475    ///
476    /// This currently uses the local file system.
477    #[default]
478    Default,
479
480    /// Use the local file system.
481    ///
482    /// This uses ordinary system file operations.
483    File(Box<FileBackendConfig>),
484
485    /// Object storage.
486    Object(ObjectStorageConfig),
487}
488
489impl Display for StorageBackendConfig {
490    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
491        match self {
492            StorageBackendConfig::Default => write!(f, "default"),
493            StorageBackendConfig::File(_) => write!(f, "file"),
494            StorageBackendConfig::Object(_) => write!(f, "object"),
495        }
496    }
497}
498
499/// Storage compression algorithm.
500#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
501#[serde(rename_all = "snake_case")]
502pub enum StorageCompression {
503    /// Use Feldera's default compression algorithm, currently [`Self::Lz4`].
504    ///
505    /// The default may change as Feldera's performance is tuned and new
506    /// algorithms are introduced.
507    #[default]
508    Default,
509
510    /// Do not compress.
511    None,
512
513    /// Use [Snappy](https://en.wikipedia.org/wiki/Snappy_(compression)) compression.
514    Snappy,
515
516    /// Use [LZ4](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm)) compression.
517    ///
518    /// Compresses better than Snappy and decompresses several times faster, at
519    /// a similar compression rate.
520    Lz4,
521
522    /// Use [Zstandard](https://en.wikipedia.org/wiki/Zstd) compression.
523    ///
524    /// Roughly halves LZ4's output at a comparable decompression rate, for
525    /// slower compression. `StorageOptions::compression_level` selects the
526    /// speed/size tradeoff.
527    Zstd,
528}
529
530#[derive(Debug, Clone, Eq, PartialEq)]
531pub enum StartFromCheckpoint {
532    Latest,
533    Uuid(uuid::Uuid),
534}
535
536impl ToSchema<'_> for StartFromCheckpoint {
537    fn schema() -> (
538        &'static str,
539        utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
540    ) {
541        (
542            "StartFromCheckpoint",
543            utoipa::openapi::RefOr::T(Schema::OneOf(
544                OneOfBuilder::new()
545                    .item(
546                        ObjectBuilder::new()
547                            .schema_type(SchemaType::String)
548                            .enum_values(Some(["latest"].into_iter()))
549                            .build(),
550                    )
551                    .item(
552                        ObjectBuilder::new()
553                            .schema_type(SchemaType::String)
554                            .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
555                                utoipa::openapi::KnownFormat::Uuid,
556                            )))
557                            .build(),
558                    )
559                    .nullable(true)
560                    .build(),
561            )),
562        )
563    }
564}
565
566impl<'de> Deserialize<'de> for StartFromCheckpoint {
567    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
568    where
569        D: Deserializer<'de>,
570    {
571        struct StartFromCheckpointVisitor;
572
573        impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
574            type Value = StartFromCheckpoint;
575
576            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
577                formatter.write_str("a UUID string or the string \"latest\"")
578            }
579
580            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
581            where
582                E: de::Error,
583            {
584                if value == "latest" {
585                    Ok(StartFromCheckpoint::Latest)
586                } else {
587                    uuid::Uuid::parse_str(value)
588                        .map(StartFromCheckpoint::Uuid)
589                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
590                }
591            }
592        }
593
594        deserializer.deserialize_str(StartFromCheckpointVisitor)
595    }
596}
597
598impl Serialize for StartFromCheckpoint {
599    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
600    where
601        S: serde::Serializer,
602    {
603        match self {
604            StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
605            StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
606        }
607    }
608}
609
610#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
611pub struct SyncConfig {
612    /// The endpoint URL for the storage service.
613    ///
614    /// This is typically required for custom or local S3-compatible storage providers like MinIO.
615    /// Example: `http://localhost:9000`
616    ///
617    /// For a `gs://` bucket this is the Google Cloud Storage JSON API base URL;
618    /// a bare host gets `/storage/v1/` appended. Leave empty for the public service.
619    ///
620    /// Relevant rclone config key: [`endpoint`](https://rclone.org/s3/#s3-endpoint)
621    pub endpoint: Option<String>,
622
623    /// The name of the storage bucket.
624    ///
625    /// This may include a path to a folder inside the bucket (e.g., `my-bucket/data`).
626    ///
627    /// Prefix it with `gs://` to sync to Google Cloud Storage through its native
628    /// API instead of S3. `provider`, `access_key`, and `secret_key` are then
629    /// ignored; rclone authenticates with Application Default Credentials, for
630    /// example a GKE Workload Identity.
631    pub bucket: String,
632
633    /// The region that this bucket is in.
634    ///
635    /// Leave empty for Minio or the default region (`us-east-1` for AWS).
636    pub region: Option<String>,
637
638    /// The name of the cloud storage provider (e.g., `"AWS"`, `"Minio"`).
639    ///
640    /// Used for provider-specific behavior in rclone.
641    /// If omitted, defaults to `"Other"`.
642    ///
643    /// See [rclone S3 provider documentation](https://rclone.org/s3/#s3-provider)
644    pub provider: Option<String>,
645
646    /// The access key used to authenticate with the storage provider.
647    ///
648    /// If not provided, rclone will fall back to environment-based credentials, such as
649    /// `RCLONE_S3_ACCESS_KEY_ID`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
650    /// this can be left empty to allow automatic authentication via the pod's service account.
651    pub access_key: Option<String>,
652
653    /// The secret key used together with the access key for authentication.
654    ///
655    /// If not provided, rclone will fall back to environment-based credentials, such as
656    /// `RCLONE_S3_SECRET_ACCESS_KEY`. In Kubernetes environments using IRSA (IAM Roles for Service Accounts),
657    /// this can be left empty to allow automatic authentication via the pod's service account.
658    pub secret_key: Option<String>,
659
660    /// When set, the pipeline will try fetch the specified checkpoint from the
661    /// object store.
662    ///
663    /// If `fail_if_no_checkpoint` is `true`, the pipeline will fail to initialize.
664    pub start_from_checkpoint: Option<StartFromCheckpoint>,
665
666    /// When true, the pipeline will fail to initialize if fetching the
667    /// specified checkpoint fails (missing, download error).
668    /// When false, the pipeline will start from scratch instead.
669    ///
670    /// False by default.
671    #[schema(default = std::primitive::bool::default)]
672    #[serde(default)]
673    pub fail_if_no_checkpoint: bool,
674
675    /// The number of file transfers to run in parallel.
676    /// Default: 20
677    pub transfers: Option<u8>,
678
679    /// The number of checkers to run in parallel.
680    /// Default: 20
681    pub checkers: Option<u8>,
682
683    /// Set to skip post copy check of checksums, and only check the file sizes.
684    /// This can significantly improve the throughput.
685    /// Defualt: false
686    pub ignore_checksum: Option<bool>,
687
688    /// Number of streams to use for multi-thread downloads.
689    /// Default: 10
690    pub multi_thread_streams: Option<u8>,
691
692    /// Use multi-thread download for files above this size.
693    /// Format: `[size][Suffix]` (Example: 1G, 500M)
694    /// Supported suffixes: k|M|G|T
695    /// Default: 100M
696    pub multi_thread_cutoff: Option<String>,
697
698    /// When true, checkpoint downloads use the maximum resources available on
699    /// the host: `transfers` and `checkers` are scaled to the number of CPUs,
700    /// and the download buffer is allowed to grow up to most of the available
701    /// memory. This maximizes download throughput at the cost of higher CPU and
702    /// memory usage during a pull.
703    ///
704    /// When false, downloads use the values configured via `transfers`,
705    /// `checkers`, and the rclone defaults instead.
706    ///
707    /// Default: true
708    #[schema(default = default_optimize_download_resources)]
709    #[serde(default = "default_optimize_download_resources")]
710    pub optimize_download_resources: bool,
711
712    /// The number of chunks of the same file that are uploaded for multipart uploads.
713    /// Default: 10
714    pub upload_concurrency: Option<u8>,
715
716    /// **Deprecated.** Use `initial=standby` when starting the pipeline instead.
717    #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
718    #[schema(default = std::primitive::bool::default)]
719    #[serde(default)]
720    pub standby: bool,
721
722    /// The interval between each attempt to fetch the latest checkpoint from
723    /// object store while in standby mode, for example `10s`.
724    ///
725    /// Applies only when `start_from_checkpoint` is set to `latest`. Unset
726    /// selects the default, `DEFAULT_PULL_INTERVAL`.
727    #[serde(
728        default,
729        alias = "pull_interval",
730        deserialize_with = "duration_standby_pull_interval",
731        skip_serializing_if = "Option::is_none"
732    )]
733    #[schema(value_type = Option<String>, default = default_pull_interval)]
734    pub standby_pull_interval: Option<ConfigDuration>,
735
736    /// The interval between each push of checkpoints to object store, for
737    /// example `1h`.
738    ///
739    /// The default is no periodic push; `null` disables periodic pushes
740    /// explicitly.
741    #[serde(
742        default,
743        alias = "push_interval",
744        deserialize_with = "duration_checkpoint_push_interval",
745        skip_serializing_if = "Option::is_none"
746    )]
747    #[schema(value_type = Option<String>)]
748    pub checkpoint_push_interval: Option<ConfigDuration>,
749
750    /// Extra flags to pass to `rclone`.
751    ///
752    /// WARNING: Supplying incorrect or conflicting flags can break `rclone`.
753    /// Use with caution.
754    ///
755    /// Refer to the docs to see the supported flags:
756    /// - [Global flags](https://rclone.org/flags/)
757    /// - [S3 specific flags](https://rclone.org/s3/)
758    pub flags: Option<Vec<String>>,
759
760    /// The minimum number of checkpoints to retain in object store.
761    /// No checkpoints will be deleted if the total count is below this threshold.
762    ///
763    /// Default: 10
764    #[schema(default = default_retention_min_count)]
765    #[serde(default = "default_retention_min_count")]
766    pub retention_min_count: u32,
767
768    /// The minimum age a checkpoint must reach before it becomes eligible for
769    /// deletion, for example `30d`. All younger checkpoints will be preserved.
770    /// Unset selects the default, `DEFAULT_RETENTION_MIN_AGE`.
771    #[serde(
772        default,
773        alias = "retention_min_age",
774        deserialize_with = "duration_min_retention",
775        skip_serializing_if = "Option::is_none"
776    )]
777    #[schema(value_type = Option<String>, default = default_retention_min_age)]
778    pub min_retention: Option<ConfigDuration>,
779
780    /// A read-only bucket used as a fallback checkpoint source.
781    ///
782    /// When the pipeline has no local checkpoint and `bucket` contains no
783    /// checkpoint either, it will attempt to fetch the checkpoint from this
784    /// location instead.  All connection settings (`endpoint`, `region`,
785    /// `provider`, `access_key`, `secret_key`) are shared with `bucket`. The
786    /// scheme is not: a `gs://` `bucket` needs a `gs://` `read_bucket` too,
787    /// because the prefix alone selects the object store.
788    ///
789    /// The pipeline **never writes** to `read_bucket`.
790    ///
791    /// Must point to a different location than `bucket`.
792    #[serde(default)]
793    pub read_bucket: Option<String>,
794
795    /// Take ownership of `bucket` when the pipeline starts, even if another
796    /// pipeline owns it.
797    ///
798    /// A pipeline records its ownership of `bucket` in an `owner.json` file
799    /// at the root of `bucket`, and a push fails without writing anything if
800    /// that file names a different pipeline.  When this is `true`, the
801    /// pipeline takes ownership as it starts (a standby pipeline, when it is
802    /// activated): it logs a warning naming the previous and new owners and
803    /// overwrites `owner.json`.  The previous owner's later pushes to
804    /// `bucket` then fail.
805    ///
806    /// This only applies at startup.  If another pipeline takes ownership of
807    /// `bucket` while this pipeline is running, this pipeline's pushes fail.
808    ///
809    /// Ownership changes before the pipeline opens its checkpoint, so it
810    /// sticks even if the pipeline then fails to start: the previous owner's
811    /// pushes keep failing.  To give `bucket` back, start the previous owner
812    /// with `take_bucket_ownership` set.
813    ///
814    /// Use this to hand a checkpoint location over to a pipeline that
815    /// replaces another one, e.g., after deleting and recreating a pipeline.
816    /// Stop the previous owner first, and set this on only one of the
817    /// pipelines that share a `bucket`.
818    ///
819    /// Default: false
820    #[schema(default = std::primitive::bool::default)]
821    #[serde(default)]
822    pub take_bucket_ownership: bool,
823}
824
825fn default_retention_min_count() -> u32 {
826    10
827}
828
829fn default_optimize_download_resources() -> bool {
830    true
831}
832
833impl SyncConfig {
834    /// The standby pull interval in effect, or [`DEFAULT_PULL_INTERVAL`].
835    ///
836    /// The enterprise crates read the sync durations through these accessors
837    /// rather than the fields, so that one version of them compiles against
838    /// every `feldera-types` a pinned runtime may bring: the accessors exist
839    /// with these names on both sides of the rename.
840    pub fn standby_pull_interval(&self) -> ConfigDuration {
841        self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
842    }
843
844    /// The interval between checkpoint pushes, or `None` for no periodic push.
845    pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
846        self.checkpoint_push_interval
847    }
848
849    /// The checkpoint retention age in effect, or
850    /// [`DEFAULT_RETENTION_MIN_AGE`].
851    pub fn min_retention(&self) -> ConfigDuration {
852        self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
853    }
854
855    pub fn validate(&self) -> Result<(), String> {
856        #[allow(deprecated)]
857        if self.standby {
858            return Err(
859                "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
860            );
861        }
862
863        if let Some(ref rb) = self.read_bucket {
864            if rb == &self.bucket {
865                return Err(
866                    "invalid sync config: `read_bucket` and `bucket` must point to different locations"
867                        .to_owned(),
868                );
869            }
870            // The `gs://` prefix selects the object store, so a mismatch would
871            // send the fallback pull to the wrong service.
872            if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
873                return Err(format!(
874                    "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",
875                    self.bucket, rb
876                ));
877            }
878        }
879
880        Ok(())
881    }
882}
883
884/// Whether a sync `bucket` names Google Cloud Storage rather than S3.
885fn is_gcs_bucket(bucket: &str) -> bool {
886    bucket.starts_with("gs://")
887}
888
889/// Configuration for supplying a custom pipeline StatefulSet template via a Kubernetes ConfigMap.
890///
891/// Operators can provide a custom StatefulSet YAML that the Kubernetes runner will use when
892/// creating pipeline StatefulSets for a pipeline. The custom template must be stored as the
893/// value of a key in a ConfigMap in the same namespace as the pipeline; set `name` to the
894/// ConfigMap name and `key` to the entry that contains the template.
895///
896/// Recommendations and requirements:
897/// - **Start from the default template and modify it as needed.** The default template is present
898///   in ConfigMap named as `<release-name>-pipeline-template`, with key `pipelineTemplate` in the release
899///   namespace and should be used as a reference.
900/// - The template must contain a valid Kubernetes `StatefulSet` manifest in YAML form. The
901///   runner substitutes variables in the template before parsing; therefore the final YAML
902///   must be syntactically valid.
903/// - The runner performs simple string substitution for the following placeholders. Please ensure these
904///   placeholders are placed at appropriate location for their semantics:
905///   - `{id}`: pipeline Kubernetes name (used for object names and labels)
906///   - `{namespace}`: Kubernetes namespace where the pipeline runs
907///   - `{pipeline_executor_image}`: container image used to run the pipeline executor
908///   - `{binary_ref}`: program binary reference passed as an argument
909///   - `{program_info_ref}`: program info reference passed as an argument
910///   - `{pipeline_storage_path}`: mount path for persistent pipeline storage
911///   - `{storage_class_name}`: storage class name to use for PVCs (if applicable)
912///   - `{deployment_id}`: UUID identifying the deployment instance
913///   - `{deployment_initial}`: initial desired runtime status (e.g., `provisioning`)
914///   - `{bootstrap_policy}`: bootstrap policy value when applicable
915#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
916pub struct PipelineTemplateConfig {
917    /// Name of the ConfigMap containing the pipeline template.
918    pub name: String,
919    /// Key in the ConfigMap containing the pipeline template.
920    ///
921    /// If not set, defaults to `pipelineTemplate`.
922    #[schema(default = default_pipeline_template_key)]
923    #[serde(default = "default_pipeline_template_key")]
924    pub key: String,
925}
926
927fn default_pipeline_template_key() -> String {
928    "pipelineTemplate".to_string()
929}
930
931#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
932pub struct ObjectStorageConfig {
933    /// URL.
934    ///
935    /// The following URL schemes are supported:
936    ///
937    /// * S3:
938    ///   - `s3://<bucket>/<path>`
939    ///   - `s3a://<bucket>/<path>`
940    ///   - `https://s3.<region>.amazonaws.com/<bucket>`
941    ///   - `https://<bucket>.s3.<region>.amazonaws.com`
942    ///   - `https://ACCOUNT_ID.r2.cloudflarestorage.com/bucket`
943    /// * Google Cloud Storage:
944    ///   - `gs://<bucket>/<path>`
945    /// * Microsoft Azure Blob Storage:
946    ///   - `abfs[s]://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
947    ///   - `abfs[s]://<file_system>@<account_name>.dfs.core.windows.net/<path>`
948    ///   - `abfs[s]://<file_system>@<account_name>.dfs.fabric.microsoft.com/<path>`
949    ///   - `az://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
950    ///   - `adl://<container>/<path>` (according to [fsspec](https://github.com/fsspec/adlfs))
951    ///   - `azure://<container>/<path>` (custom)
952    ///   - `https://<account>.dfs.core.windows.net`
953    ///   - `https://<account>.blob.core.windows.net`
954    ///   - `https://<account>.blob.core.windows.net/<container>`
955    ///   - `https://<account>.dfs.fabric.microsoft.com`
956    ///   - `https://<account>.dfs.fabric.microsoft.com/<container>`
957    ///   - `https://<account>.blob.fabric.microsoft.com`
958    ///   - `https://<account>.blob.fabric.microsoft.com/<container>`
959    ///
960    /// Settings derived from the URL will override other settings.
961    pub url: String,
962
963    /// Additional options as key-value pairs.
964    ///
965    /// The following keys are supported:
966    ///
967    /// * S3:
968    ///   - `access_key_id`: AWS Access Key.
969    ///   - `secret_access_key`: AWS Secret Access Key.
970    ///   - `region`: Region.
971    ///   - `default_region`: Default region.
972    ///   - `endpoint`: Custom endpoint for communicating with S3,
973    ///     e.g. `https://localhost:4566` for testing against a localstack
974    ///     instance.
975    ///   - `token`: Token to use for requests (passed to underlying provider).
976    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/aws/enum.AmazonS3ConfigKey.html#variants).
977    /// * Google Cloud Storage:
978    ///   - `service_account`: Path to the service account file.
979    ///   - `service_account_key`: The serialized service account key.
980    ///   - `google_application_credentials`: Application credentials path.
981    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/gcp/enum.GoogleConfigKey.html).
982    /// * Microsoft Azure Blob Storage:
983    ///   - `access_key`: Azure Access Key.
984    ///   - `container_name`: Azure Container Name.
985    ///   - `account`: Azure Account.
986    ///   - `bearer_token_authorization`: Static bearer token for authorizing requests.
987    ///   - `client_id`: Client ID for use in client secret or Kubernetes federated credential flow.
988    ///   - `client_secret`: Client secret for use in client secret flow.
989    ///   - `tenant_id`: Tenant ID for use in client secret or Kubernetes federated credential flow.
990    ///   - `endpoint`: Override the endpoint for communicating with blob storage.
991    ///   - [Other keys](https://docs.rs/object_store/latest/object_store/azure/enum.AzureConfigKey.html#variants).
992    ///
993    /// Options set through the URL take precedence over those set with these
994    /// options.
995    #[serde(flatten)]
996    pub other_options: BTreeMap<String, String>,
997}
998
999/// Configuration for local file system access.
1000#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1001#[serde(default)]
1002pub struct FileBackendConfig {
1003    /// Whether to use background threads for file I/O.
1004    ///
1005    /// Background threads should improve performance, but they can reduce
1006    /// performance if too few cores are available. This is provided for
1007    /// debugging and fine-tuning and should ordinarily be left unset.
1008    pub async_threads: Option<bool>,
1009
1010    /// Per-I/O operation sleep duration, for example `5ms`.
1011    ///
1012    /// This is for simulating slow storage devices.  Do not use this in
1013    /// production.
1014    #[serde(
1015        default,
1016        alias = "ioop_delay",
1017        deserialize_with = "duration_ioop_latency",
1018        skip_serializing_if = "Option::is_none"
1019    )]
1020    #[schema(value_type = Option<String>)]
1021    pub ioop_latency: Option<ConfigDuration>,
1022
1023    /// Configuration to synchronize checkpoints to object store.
1024    pub sync: Option<SyncConfig>,
1025
1026    /// How to make files durable when committing a checkpoint.
1027    ///
1028    /// This is provided for debugging and fine-tuning and should ordinarily be
1029    /// left unset.
1030    pub sync_mode: Option<StorageSyncMode>,
1031}
1032
1033/// How a pipeline makes its files durable when it commits a checkpoint.
1034///
1035/// A checkpoint can hold tens of thousands of files, so committing them one at
1036/// a time is the dominant cost of making one. Both alternatives below fix that,
1037/// but they suit different deployments.
1038#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1039#[serde(rename_all = "snake_case")]
1040pub enum StorageSyncMode {
1041    /// Use `syncfs` when storage has a filesystem to itself, and fsync files in
1042    /// parallel otherwise.
1043    #[default]
1044    Auto,
1045
1046    /// Always `syncfs`.
1047    ///
1048    /// One syscall makes the whole filesystem durable, which is the cheapest
1049    /// option by far when storage is a dedicated volume. On a filesystem shared
1050    /// with anything else, it also writes back that other data.
1051    ///
1052    /// A pipeline falls back to `per_file` where `syncfs` cannot report a failed
1053    /// writeback, rather than honoring this setting: off Linux, and before Linux
1054    /// 5.8, where `syncfs` returned success and discarded the error.
1055    Syncfs,
1056
1057    /// Always fsync each file, spread across several threads.
1058    ///
1059    /// Slower than `syncfs` on a dedicated volume, but it touches only this
1060    /// pipeline's files.
1061    PerFile,
1062}
1063
1064/// Global pipeline configuration settings. This is the publicly
1065/// exposed type for users to configure pipelines.
1066#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1067#[serde(default)]
1068pub struct RuntimeConfig {
1069    /// Number of DBSP worker threads.
1070    ///
1071    /// Each DBSP "foreground" worker thread is paired with a "background"
1072    /// thread for LSM merging, making the total number of threads twice the
1073    /// specified number.
1074    ///
1075    /// The typical sweet spot for the number of workers is between 4 and 16.
1076    /// Each worker increases overall memory consumption for data structures
1077    /// used during a step.
1078    pub workers: u16,
1079
1080    /// The maximum amount of memory, in Megabytes, that the pipeline is allowed to use
1081    /// on each host.
1082    ///
1083    /// Setting this property activates memory pressure monitoring and backpressure
1084    /// mechanisms. The pipeline will track the amount of remaining memory and
1085    /// report the memory pressure level via the `memory_pressure` metric.
1086    ///
1087    /// As the memory pressure increases, the system will apply increasing backpressure
1088    /// to push state cached in memory to storage, preventing the pipeline from running
1089    /// out of memory at the cost of some performance degradation.
1090    ///
1091    /// It is strongly recommended to set this property to prevent the pipeline from
1092    /// running out of memory. The setting should not exceed the memory limit of the pipeline
1093    /// instance.
1094    ///
1095    /// When `max_rss_mb` is not specified but `resources.memory_mb_max` is set, the
1096    /// latter is used as the effective memory cap for the pipeline.
1097    ///
1098    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
1099    /// for more details.
1100    pub max_rss_mb: Option<u64>,
1101
1102    /// DataFusion memory pool size, in MB, shared by the ad-hoc query
1103    /// engine and the Delta Lake / Iceberg connectors.
1104    ///
1105    /// Carved out of `max_rss_mb` (falling back to
1106    /// `resources.memory_mb_max`); the remainder goes to the DBSP circuit,
1107    /// so the two do not double-book RAM.
1108    ///
1109    /// Unset: defaults to 5% of the effective budget, capped at 2 GB.
1110    /// Pipelines that don't run heavy ad-hoc / Delta / Iceberg workloads
1111    /// can leave this unset.
1112    ///
1113    /// Set this explicitly for ad-hoc queries, or Delta / Iceberg scans,
1114    /// over data too large for the default share. A pool that cannot hold
1115    /// the query surfaces as `ResourcesExhausted` on that query alone; the
1116    /// pipeline keeps running.
1117    ///
1118    /// No pool limit applied if no overall budget is configured.
1119    ///
1120    /// See [documentation on the pipeline's memory usage](https://docs.feldera.com/operations/memory)
1121    /// for more details.
1122    pub datafusion_memory_mb: Option<u64>,
1123
1124    /// Number of DBSP hosts.
1125    ///
1126    /// The worker threads are evenly divided among the hosts.  For single-host
1127    /// deployments, this should be 1 (the default).
1128    ///
1129    /// Multihost pipelines are an enterprise-only preview feature.
1130    pub hosts: usize,
1131
1132    /// Storage configuration.
1133    ///
1134    /// - If this is `None`, the default, the pipeline's state is kept in
1135    ///   in-memory data-structures.  This is useful if the pipeline's state
1136    ///   will fit in memory and if the pipeline is ephemeral and does not need
1137    ///   to be recovered after a restart. The pipeline will most likely run
1138    ///   faster since it does not need to access storage.
1139    ///
1140    /// - If set, the pipeline's state is kept on storage.  This allows the
1141    ///   pipeline to work with state that will not fit into memory. It also
1142    ///   allows the state to be checkpointed and recovered across restarts.
1143    #[serde(deserialize_with = "deserialize_storage_options")]
1144    pub storage: Option<StorageOptions>,
1145
1146    /// Fault tolerance configuration.
1147    #[serde(deserialize_with = "deserialize_fault_tolerance")]
1148    pub fault_tolerance: FtConfig,
1149
1150    /// Enable CPU profiler.
1151    ///
1152    /// The default value is `true`.
1153    pub cpu_profiler: bool,
1154
1155    /// Enable pipeline tracing.
1156    pub tracing: bool,
1157
1158    /// Jaeger tracing endpoint to send tracing information to.
1159    pub tracing_endpoint_jaeger: String,
1160
1161    /// Minimal input batch size.
1162    ///
1163    /// The controller delays pushing input records to the circuit until at
1164    /// least `min_batch_size_records` records have been received (total
1165    /// across all endpoints) or `max_buffering_delay` has passed
1166    /// since the first input record was buffered.
1167    /// Defaults to 0.
1168    pub min_batch_size_records: u64,
1169
1170    /// Maximal delay to wait for `min_batch_size_records` to get buffered by
1171    /// the controller, for example `10ms`. Defaults to no delay.
1172    #[serde(
1173        default,
1174        alias = "max_buffering_delay_usecs",
1175        deserialize_with = "duration_max_buffering_delay",
1176        skip_serializing_if = "Option::is_none"
1177    )]
1178    #[schema(value_type = Option<String>)]
1179    pub max_buffering_delay: Option<ConfigDuration>,
1180
1181    /// Resource reservations and limits. This is enforced
1182    /// only in Feldera Cloud.
1183    pub resources: ResourceConfig,
1184
1185    /// Real-time clock resolution, for example `1s`.
1186    ///
1187    /// This parameter controls the execution of queries that use the `NOW()` function.  The output of such
1188    /// queries depends on the real-time clock and can change over time without any external
1189    /// inputs.  If the query uses `NOW()`, the pipeline will update the clock value and trigger incremental
1190    /// recomputation at most once per `clock_resolution`.  If the query does not use
1191    /// `NOW()`, then clock value updates are suppressed and the pipeline ignores this setting.
1192    ///
1193    /// Unset or `null` selects the default, `DEFAULT_CLOCK_RESOLUTION`.
1194    #[serde(
1195        default,
1196        alias = "clock_resolution_usecs",
1197        deserialize_with = "duration_clock_resolution",
1198        skip_serializing_if = "Option::is_none"
1199    )]
1200    #[schema(value_type = Option<String>, default = default_clock_resolution)]
1201    pub clock_resolution: Option<ConfigDuration>,
1202
1203    /// Fixed timezone offset for the SQL `NOW()` clock.
1204    ///
1205    /// An ISO-8601 UTC offset, for example `"+05:30"` or `"-08:00"`, that the
1206    /// clock connector adds to every `NOW()` value it emits, so `NOW()`
1207    /// returns local time in that fixed timezone instead of UTC.
1208    ///
1209    /// The offset is baked into the pipeline's checkpointed state and cannot
1210    /// be changed when the pipeline resumes from a checkpoint: the value from
1211    /// the checkpoint stays in effect, and a differing new value is ignored
1212    /// with a warning in the pipeline log.
1213    #[schema(value_type = Option<String>, example = "+05:30")]
1214    pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1215
1216    /// Optionally, a list of CPU numbers for CPUs to which the pipeline may pin
1217    /// its worker threads.  Specify at least twice as many CPU numbers as
1218    /// workers.  CPUs are generally numbered starting from 0.  The pipeline
1219    /// might not be able to honor CPU pinning requests.
1220    ///
1221    /// CPU pinning can make pipelines run faster and perform more consistently,
1222    /// as long as different pipelines running on the same machine are pinned to
1223    /// different CPUs.
1224    pub pin_cpus: Vec<usize>,
1225
1226    /// Timeout for the `Provisioning` phase of the pipeline, for example `5m`.
1227    /// Setting this value will override the default of the runner.
1228    #[serde(
1229        default,
1230        alias = "provisioning_timeout_secs",
1231        deserialize_with = "duration_provisioning_timeout",
1232        skip_serializing_if = "Option::is_none"
1233    )]
1234    #[schema(value_type = Option<String>)]
1235    pub provisioning_timeout: Option<ConfigDuration>,
1236
1237    /// The maximum number of connectors initialized in parallel during pipeline
1238    /// startup.
1239    ///
1240    /// At startup, the pipeline must initialize all of its input and output connectors.
1241    /// Depending on the number and types of connectors, this can take a long time.
1242    /// To accelerate the process, multiple connectors are initialized concurrently.
1243    /// This option controls the maximum number of connectors that can be initialized
1244    /// in parallel.
1245    ///
1246    /// The default is 10.
1247    pub max_parallel_connector_init: Option<u64>,
1248
1249    /// Specification of additional (sidecar) containers.
1250    pub init_containers: Option<serde_json::Value>,
1251
1252    /// Deprecated: setting this true or false does not have an effect anymore.
1253    pub checkpoint_during_suspend: bool,
1254
1255    /// Sets the number of available runtime threads for the http server.
1256    ///
1257    /// In most cases, this does not need to be set explicitly and
1258    /// the default is sufficient. Can be increased in case the
1259    /// pipeline HTTP API operations are a bottleneck.
1260    ///
1261    /// If not specified, the default is set to `workers`.
1262    pub http_workers: Option<u64>,
1263
1264    /// Sets the number of available runtime threads for async IO tasks.
1265    ///
1266    /// This affects some networking and file I/O operations
1267    /// especially adapters and ad-hoc queries.
1268    ///
1269    /// In most cases, this does not need to be set explicitly and
1270    /// the default is sufficient. Can be increased in case
1271    /// ingress, egress or ad-hoc queries are a bottleneck.
1272    ///
1273    /// If not specified, the default is set to `workers`.
1274    pub io_workers: Option<u64>,
1275
1276    /// Environment variables for the pipeline process.
1277    ///
1278    /// These are key-value pairs injected into the pipeline process environment.
1279    /// Some variable names are reserved by the platform and cannot be overridden
1280    /// (for example `RUST_LOG`, and variables in the `FELDERA_`,
1281    /// `KUBERNETES_`, and `TOKIO_` namespaces).
1282    #[serde(default)]
1283    pub env: BTreeMap<String, String>,
1284
1285    /// Optional settings for tweaking Feldera internals.
1286    pub dev_tweaks: DevTweaks,
1287
1288    /// Log filtering directives.
1289    ///
1290    /// If set to a valid [tracing-subscriber] filter, this controls the log
1291    /// messages emitted by the pipeline process.  Otherwise, or if the filter
1292    /// has invalid syntax, messages at "info" severity and higher are written
1293    /// to the log and all others are discarded.
1294    ///
1295    /// [tracing-subscriber]: https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html#directives
1296    pub logging: Option<String>,
1297
1298    /// ConfigMap containing a custom pipeline template (Enterprise only).
1299    ///
1300    /// This feature is only available in Feldera Enterprise. If set, the Kubernetes runner
1301    /// will read the template from the specified ConfigMap and use it instead of the default
1302    /// StatefulSet template for the configured pipeline.
1303    ///
1304    /// check [`PipelineTemplateConfig`] documentation for details.
1305    pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1306}
1307
1308/// Accepts "true" and "false" and converts them to the new format.
1309fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1310where
1311    D: Deserializer<'de>,
1312{
1313    struct BoolOrStruct;
1314
1315    impl<'de> Visitor<'de> for BoolOrStruct {
1316        type Value = Option<StorageOptions>;
1317
1318        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1319            formatter.write_str("boolean or StorageOptions")
1320        }
1321
1322        fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1323        where
1324            E: de::Error,
1325        {
1326            match v {
1327                false => Ok(None),
1328                true => Ok(Some(StorageOptions::default())),
1329            }
1330        }
1331
1332        fn visit_unit<E>(self) -> Result<Self::Value, E>
1333        where
1334            E: de::Error,
1335        {
1336            Ok(None)
1337        }
1338
1339        fn visit_none<E>(self) -> Result<Self::Value, E>
1340        where
1341            E: de::Error,
1342        {
1343            Ok(None)
1344        }
1345
1346        fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1347        where
1348            M: MapAccess<'de>,
1349        {
1350            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1351        }
1352    }
1353
1354    deserializer.deserialize_any(BoolOrStruct)
1355}
1356
1357/// Accepts very old 'initial_state' and 'latest_checkpoint' as enabling fault
1358/// tolerance.
1359///
1360/// Accepts `null` as disabling fault tolerance.
1361///
1362/// Otherwise, deserializes [FtConfig] in the way that one might otherwise
1363/// expect.
1364fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1365where
1366    D: Deserializer<'de>,
1367{
1368    struct StringOrStruct;
1369
1370    impl<'de> Visitor<'de> for StringOrStruct {
1371        type Value = FtConfig;
1372
1373        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1374            formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1375        }
1376
1377        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1378        where
1379            E: de::Error,
1380        {
1381            match v {
1382                "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1383                    model: Some(FtModel::default()),
1384                    ..FtConfig::default()
1385                }),
1386                _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1387            }
1388        }
1389
1390        fn visit_unit<E>(self) -> Result<Self::Value, E>
1391        where
1392            E: de::Error,
1393        {
1394            Ok(FtConfig::default())
1395        }
1396
1397        fn visit_none<E>(self) -> Result<Self::Value, E>
1398        where
1399            E: de::Error,
1400        {
1401            Ok(FtConfig::default())
1402        }
1403
1404        fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1405        where
1406            M: MapAccess<'de>,
1407        {
1408            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1409        }
1410    }
1411
1412    deserializer.deserialize_any(StringOrStruct)
1413}
1414
1415impl Default for RuntimeConfig {
1416    fn default() -> Self {
1417        Self {
1418            workers: 8,
1419            max_rss_mb: None,
1420            datafusion_memory_mb: None,
1421            hosts: 1,
1422            storage: Some(StorageOptions::default()),
1423            fault_tolerance: FtConfig::default(),
1424            cpu_profiler: true,
1425            tracing: {
1426                // We discovered that the jaeger crate can use up gigabytes of RAM, so it's not harmless
1427                // to keep it on by default.
1428                false
1429            },
1430            tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1431            min_batch_size_records: 0,
1432            max_buffering_delay: None,
1433            resources: ResourceConfig::default(),
1434            clock_resolution: None,
1435            clock_timezone_offset: None,
1436            pin_cpus: Vec::new(),
1437            provisioning_timeout: None,
1438            max_parallel_connector_init: None,
1439            init_containers: None,
1440            checkpoint_during_suspend: true,
1441            io_workers: None,
1442            http_workers: None,
1443            env: BTreeMap::default(),
1444            dev_tweaks: DevTweaks::default(),
1445            logging: None,
1446            pipeline_template_configmap: None,
1447        }
1448    }
1449}
1450
1451/// Upper bound on the default DataFusion pool size, in MB.
1452///
1453/// Spill-to-disk handles overflow; reserving more starves the circuit.
1454pub const DEFAULT_DATAFUSION_MEMORY_MB_CEILING: u64 = 2048;
1455
1456/// Default DataFusion pool size as a percentage of the pipeline's
1457/// effective memory budget. The remainder is left for the DBSP circuit.
1458pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1459
1460impl RuntimeConfig {
1461    /// The input buffering delay in effect, or no delay.
1462    pub fn max_buffering_delay(&self) -> ConfigDuration {
1463        self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1464    }
1465
1466    /// The clock resolution in effect, or [`DEFAULT_CLOCK_RESOLUTION`].
1467    pub fn clock_resolution(&self) -> ConfigDuration {
1468        self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1469    }
1470
1471    /// Pipeline's effective memory budget in MB: `max_rss_mb`, falling back
1472    /// to `resources.memory_mb_max` (the k8s pod limit).
1473    pub fn effective_memory_mb(&self) -> Option<u64> {
1474        self.max_rss_mb.or(self.resources.memory_mb_max)
1475    }
1476
1477    /// Resolved DataFusion pool size in MB: explicit `datafusion_memory_mb`
1478    /// if set, else 5% of the effective budget capped at
1479    /// `DEFAULT_DATAFUSION_MEMORY_MB_CEILING`. `None` if no budget is
1480    /// configured.
1481    pub fn resolved_datafusion_memory_mb(&self) -> Option<u64> {
1482        if let Some(explicit) = self.datafusion_memory_mb {
1483            return Some(explicit);
1484        }
1485        let effective = self.effective_memory_mb()?;
1486        let fraction = effective * DEFAULT_DATAFUSION_MEMORY_PERCENT / 100;
1487        Some(fraction.min(DEFAULT_DATAFUSION_MEMORY_MB_CEILING))
1488    }
1489}
1490
1491/// Fault-tolerance configuration.
1492///
1493/// The default [FtConfig] (via [FtConfig::default]) disables fault tolerance,
1494/// which is the configuration that one gets if [RuntimeConfig] omits fault
1495/// tolerance configuration.
1496///
1497/// The default value for [FtConfig::model] enables fault tolerance, as
1498/// `Some(FtModel::default())`.  This is the configuration that one gets if
1499/// [RuntimeConfig] includes a fault tolerance configuration but does not
1500/// specify a particular model.
1501#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1502#[serde(rename_all = "snake_case")]
1503pub struct FtConfig {
1504    /// Fault tolerance model to use.
1505    #[serde(with = "none_as_string")]
1506    #[serde(default = "default_model")]
1507    #[schema(
1508        schema_with = none_as_string_schema::<FtModel>,
1509    )]
1510    pub model: Option<FtModel>,
1511
1512    /// Interval between automatic checkpoints, for example `60s`.
1513    ///
1514    /// Unset selects the default, `DEFAULT_CHECKPOINT_INTERVAL`; `null`
1515    /// disables periodic checkpointing.
1516    /// Values less than 1 second or greater than 1 hour will be forced into
1517    /// that range.
1518    #[serde(
1519        default,
1520        alias = "checkpoint_interval_secs",
1521        deserialize_with = "duration_checkpoint_interval",
1522        skip_serializing_if = "Option::is_none"
1523    )]
1524    #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1525    pub checkpoint_interval: Option<Option<ConfigDuration>>,
1526}
1527
1528fn default_model() -> Option<FtModel> {
1529    Some(FtModel::default())
1530}
1531
1532/// Converts a JSON value to a YAML value, for the configuration file that
1533/// older pipelines read.
1534///
1535/// Re-parsing the JSON text as YAML is not lossless: YAML 1.1 folds a U+0085
1536/// (NEL) inside a string into a line break, and libyaml refuses a key longer
1537/// than 1024 bytes. Mapping the value directly keeps every string as it is.
1538/// Numbers go through their native types, which sidesteps the private map
1539/// that `serde_json`'s `arbitrary_precision` would otherwise serialize.
1540pub fn json_to_yaml_value(value: &serde_json::Value) -> serde_yaml::Value {
1541    use serde_json::Value as Json;
1542    use serde_yaml::Value as Yaml;
1543    match value {
1544        Json::Null => Yaml::Null,
1545        Json::Bool(bool) => Yaml::Bool(*bool),
1546        Json::Number(number) => Yaml::Number(if let Some(unsigned) = number.as_u64() {
1547            unsigned.into()
1548        } else if let Some(signed) = number.as_i64() {
1549            signed.into()
1550        } else {
1551            number.as_f64().unwrap_or(f64::NAN).into()
1552        }),
1553        Json::String(string) => Yaml::String(string.clone()),
1554        Json::Array(items) => Yaml::Sequence(items.iter().map(json_to_yaml_value).collect()),
1555        Json::Object(fields) => Yaml::Mapping(
1556            fields
1557                .iter()
1558                .map(|(key, value)| (Yaml::String(key.clone()), json_to_yaml_value(value)))
1559                .collect(),
1560        ),
1561    }
1562}
1563
1564/// Rewrites the duration settings of a serialized pipeline configuration in the
1565/// spelling that Feldera releases before the duration rename read: under the
1566/// older key, as a whole number of the unit that key named.
1567///
1568/// `config` is a serialized [`RuntimeConfig`], or a serialized
1569/// [`PipelineConfig`], which flattens one and carries the connectors in
1570/// `inputs` and `outputs`; both levels are rewritten. The pipeline manager
1571/// applies this to the configuration it hands a pipeline pinned to another
1572/// runtime version, or compiled by a platform before the rename and not yet
1573/// updated: such a runtime may predate the rename, and a runtime that does
1574/// ignores the current names and silently runs on its defaults, or, for a
1575/// Kafka connector, rejects them. Every Feldera release so far accepts the
1576/// older spelling, so writing it is safe whichever runtime runs.
1577///
1578/// A duration that is not a whole number of the older unit rounds up to the
1579/// next one, so a positive duration never becomes a `0` the older runtime
1580/// reads as "no timeout" or "pull without pause", and is capped at the largest
1581/// value the older field holds; a value that does not parse is left as it is,
1582/// for the runtime to reject.
1583pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1584    use crate::duration::LegacyUnit;
1585    use serde_json::{Map, Value};
1586
1587    /// How one setting is spelled before the rename.
1588    struct Rule {
1589        new: &'static str,
1590        old: &'static str,
1591        unit: LegacyUnit,
1592        /// The largest number the older field holds.
1593        max: u64,
1594        /// Whether the older field took a `null`; where it did not, a `null`
1595        /// meant "unset" and the key is dropped.
1596        null_allowed: bool,
1597    }
1598    const fn rule(
1599        new: &'static str,
1600        old: &'static str,
1601        unit: LegacyUnit,
1602        max: u64,
1603        null_allowed: bool,
1604    ) -> Rule {
1605        Rule {
1606            new,
1607            old,
1608            unit,
1609            max,
1610            null_allowed,
1611        }
1612    }
1613    const U32: u64 = u32::MAX as u64;
1614    const U64: u64 = u64::MAX;
1615    use LegacyUnit::{Days, Micros, Millis, Secs};
1616
1617    fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1618        for rule in rules {
1619            let Some(value) = object.remove(rule.new) else {
1620                continue;
1621            };
1622            let legacy = match &value {
1623                Value::String(text) => match text.parse::<ConfigDuration>() {
1624                    Ok(duration) => {
1625                        let nanos = std::time::Duration::from(duration).as_nanos();
1626                        let unit_nanos = u128::from(rule.unit.nanos());
1627                        let whole = nanos.div_ceil(unit_nanos);
1628                        Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1629                    }
1630                    Err(_) => {
1631                        object.insert(rule.new.to_string(), value);
1632                        continue;
1633                    }
1634                },
1635                Value::Null if !rule.null_allowed => continue,
1636                // A bare number or a null already has the older meaning.
1637                other => other.clone(),
1638            };
1639            object.insert(rule.old.to_string(), legacy);
1640        }
1641    }
1642    fn child<'a>(
1643        object: &'a mut Map<String, Value>,
1644        key: &str,
1645    ) -> Option<&'a mut Map<String, Value>> {
1646        object.get_mut(key).and_then(Value::as_object_mut)
1647    }
1648    /// The NATS consumer's expiry was a `std::time::Duration`, which serde
1649    /// writes as `{secs, nanos}`, rather than a number.
1650    fn max_expiry(consumer: &mut Map<String, Value>) {
1651        let Some(Value::String(text)) = consumer.get("max_expiry") else {
1652            return;
1653        };
1654        let Ok(duration) = text.parse::<ConfigDuration>() else {
1655            return;
1656        };
1657        let duration = std::time::Duration::from(duration);
1658        consumer.remove("max_expiry");
1659        consumer.insert(
1660            "max_expires".to_string(),
1661            serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1662        );
1663    }
1664    /// The connection options both NATS transports share.
1665    fn nats_connection(transport: &mut Map<String, Value>) {
1666        if let Some(connection) = child(transport, "connection_config") {
1667            apply(
1668                connection,
1669                &[
1670                    rule(
1671                        "connection_timeout",
1672                        "connection_timeout_secs",
1673                        Secs,
1674                        U64,
1675                        false,
1676                    ),
1677                    rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1678                ],
1679            );
1680        }
1681    }
1682    /// One connector of `inputs` or `outputs`.
1683    fn connector(endpoint: &mut Map<String, Value>) {
1684        apply(
1685            endpoint,
1686            &[rule(
1687                "max_output_buffer_time",
1688                "max_output_buffer_time_millis",
1689                Millis,
1690                U64,
1691                false,
1692            )],
1693        );
1694        let name = endpoint
1695            .get("transport")
1696            .and_then(|transport| transport.get("name"))
1697            .and_then(Value::as_str)
1698            .map(str::to_string);
1699        if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1700            match name.as_deref() {
1701                Some("url_input") => apply(
1702                    transport,
1703                    &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1704                ),
1705                Some("kafka_input") => apply(
1706                    transport,
1707                    &[rule(
1708                        "group_join_timeout",
1709                        "group_join_timeout_secs",
1710                        Secs,
1711                        U32,
1712                        false,
1713                    )],
1714                ),
1715                Some("kafka_output") => apply(
1716                    transport,
1717                    &[rule(
1718                        "initialization_timeout",
1719                        "initialization_timeout_secs",
1720                        Secs,
1721                        U32,
1722                        false,
1723                    )],
1724                ),
1725                Some("clock_input") => apply(
1726                    transport,
1727                    &[rule(
1728                        "clock_resolution",
1729                        "clock_resolution_usecs",
1730                        Micros,
1731                        U64,
1732                        false,
1733                    )],
1734                ),
1735                Some("pub_sub_input") => apply(
1736                    transport,
1737                    &[
1738                        rule("timeout", "timeout_seconds", Secs, U32, true),
1739                        rule(
1740                            "connect_timeout",
1741                            "connect_timeout_seconds",
1742                            Secs,
1743                            U32,
1744                            true,
1745                        ),
1746                    ],
1747                ),
1748                Some("nats_input") => {
1749                    apply(
1750                        transport,
1751                        &[
1752                            rule(
1753                                "inactivity_timeout",
1754                                "inactivity_timeout_secs",
1755                                Secs,
1756                                U64,
1757                                false,
1758                            ),
1759                            rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1760                        ],
1761                    );
1762                    nats_connection(transport);
1763                    if let Some(consumer) = child(transport, "consumer_config") {
1764                        max_expiry(consumer);
1765                    }
1766                }
1767                Some("nats_output") => {
1768                    apply(
1769                        transport,
1770                        &[rule(
1771                            "publish_timeout",
1772                            "publish_timeout_secs",
1773                            Secs,
1774                            U64,
1775                            false,
1776                        )],
1777                    );
1778                    nats_connection(transport);
1779                }
1780                _ => {}
1781            }
1782        }
1783        let is_avro = endpoint
1784            .get("format")
1785            .and_then(|format| format.get("name"))
1786            .and_then(Value::as_str)
1787            == Some("avro");
1788        if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1789        {
1790            apply(
1791                format,
1792                &[rule(
1793                    "registry_timeout",
1794                    "registry_timeout_secs",
1795                    Secs,
1796                    U64,
1797                    true,
1798                )],
1799            );
1800        }
1801    }
1802
1803    let Some(global) = config.as_object_mut() else {
1804        return;
1805    };
1806    apply(
1807        global,
1808        &[
1809            rule(
1810                "clock_resolution",
1811                "clock_resolution_usecs",
1812                Micros,
1813                U64,
1814                true,
1815            ),
1816            rule(
1817                "max_buffering_delay",
1818                "max_buffering_delay_usecs",
1819                Micros,
1820                U64,
1821                false,
1822            ),
1823            rule(
1824                "provisioning_timeout",
1825                "provisioning_timeout_secs",
1826                Secs,
1827                U64,
1828                true,
1829            ),
1830        ],
1831    );
1832    if let Some(ft) = child(global, "fault_tolerance") {
1833        // An explicit null disables periodic checkpoints under either key.
1834        apply(
1835            ft,
1836            &[rule(
1837                "checkpoint_interval",
1838                "checkpoint_interval_secs",
1839                Secs,
1840                U64,
1841                true,
1842            )],
1843        );
1844    }
1845    let backend = child(global, "storage")
1846        .and_then(|storage| child(storage, "backend"))
1847        .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1848        .and_then(|backend| child(backend, "config"));
1849    if let Some(file) = backend {
1850        apply(
1851            file,
1852            &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1853        );
1854        if let Some(sync) = child(file, "sync") {
1855            apply(
1856                sync,
1857                &[
1858                    rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1859                    rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1860                    rule("min_retention", "retention_min_age", Days, U32, false),
1861                ],
1862            );
1863        }
1864    }
1865    for endpoints in ["inputs", "outputs"] {
1866        if let Some(endpoints) = child(global, endpoints) {
1867            for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1868                connector(endpoint);
1869            }
1870        }
1871    }
1872}
1873
1874#[cfg(test)]
1875mod test {
1876    use super::deserialize_fault_tolerance;
1877    use crate::config::{
1878        ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_MB_CEILING,
1879        DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
1880        OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
1881        StorageOptions, SyncConfig, TransportConfig,
1882    };
1883    use crate::duration::ConfigDuration;
1884    use serde::{Deserialize, Serialize};
1885    use serde_json::json;
1886    use std::time::Duration;
1887
1888    /// A configuration written by an older version of Feldera carries no
1889    /// `soft_delete` field, and a connector that does not use soft deletes
1890    /// serializes exactly as it did before the field existed.  This keeps
1891    /// configurations readable and writable across versions.
1892    #[test]
1893    fn soft_delete_is_backward_compatible() {
1894        let config: ConnectorConfig = serde_json::from_value(json!({
1895            "transport": {"name": "empty_input"}
1896        }))
1897        .unwrap();
1898        assert!(!config.soft_delete);
1899
1900        let serialized = serde_json::to_value(&config).unwrap();
1901        assert_eq!(serialized.get("soft_delete"), None);
1902
1903        let config: ConnectorConfig = serde_json::from_value(json!({
1904            "transport": {"name": "empty_input"},
1905            "soft_delete": true
1906        }))
1907        .unwrap();
1908        assert!(config.soft_delete);
1909        assert_eq!(
1910            serde_json::to_value(&config).unwrap().get("soft_delete"),
1911            Some(&json!(true))
1912        );
1913    }
1914
1915    /// Soft deletes change how input is interpreted, so flipping the flag must
1916    /// count as a connector change even where flow-control settings do not.
1917    #[test]
1918    fn soft_delete_invalidates_checkpointed_connector_state() {
1919        let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
1920        let mut soft_delete = config.clone();
1921        soft_delete.soft_delete = true;
1922
1923        assert!(config.equal_for_input_checkpoint_replay(&config));
1924        assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
1925    }
1926
1927    fn config_with_name(name: Option<&str>) -> PipelineConfig {
1928        PipelineConfig {
1929            global: RuntimeConfig::default(),
1930            multihost: None,
1931            name: name.map(str::to_string),
1932            given_name: None,
1933            storage_config: None,
1934            secrets_dir: None,
1935            inputs: Default::default(),
1936            outputs: Default::default(),
1937            program_ir: None,
1938        }
1939    }
1940
1941    #[test]
1942    fn pipeline_identity_uses_system_and_given_names() {
1943        let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
1944        config.given_name = Some("my-pipeline".to_string());
1945
1946        let metadata = config.pipeline_identity().unwrap();
1947        assert_eq!(
1948            metadata.name,
1949            "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
1950        );
1951        assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
1952    }
1953
1954    #[test]
1955    fn pipeline_identity_is_none_without_system_name() {
1956        assert_eq!(config_with_name(None).pipeline_identity(), None);
1957    }
1958
1959    #[test]
1960    fn resolved_datafusion_memory_explicit_passes_through() {
1961        let config = RuntimeConfig {
1962            max_rss_mb: Some(8_000),
1963            datafusion_memory_mb: Some(1_500),
1964            ..Default::default()
1965        };
1966        assert_eq!(config.resolved_datafusion_memory_mb(), Some(1_500));
1967    }
1968
1969    #[test]
1970    fn resolved_datafusion_memory_unconfigured_returns_none() {
1971        let config = RuntimeConfig::default();
1972        assert!(config.max_rss_mb.is_none());
1973        assert!(config.resources.memory_mb_max.is_none());
1974        assert_eq!(config.resolved_datafusion_memory_mb(), None);
1975    }
1976
1977    #[test]
1978    fn resolved_datafusion_memory_small_budget_scales_down() {
1979        // Small pipelines must provision cleanly; the default just shrinks.
1980        let config = RuntimeConfig {
1981            max_rss_mb: Some(256),
1982            ..Default::default()
1983        };
1984        assert_eq!(config.resolved_datafusion_memory_mb(), Some(12));
1985
1986        let config = RuntimeConfig {
1987            max_rss_mb: Some(512),
1988            ..Default::default()
1989        };
1990        assert_eq!(config.resolved_datafusion_memory_mb(), Some(25));
1991    }
1992
1993    #[test]
1994    fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
1995        // 5% of 64 GB = 3.2 GB, above the 2 GB ceiling.
1996        let config = RuntimeConfig {
1997            max_rss_mb: Some(64_000),
1998            ..Default::default()
1999        };
2000        assert_eq!(
2001            config.resolved_datafusion_memory_mb(),
2002            Some(DEFAULT_DATAFUSION_MEMORY_MB_CEILING),
2003        );
2004    }
2005
2006    #[test]
2007    fn resolved_datafusion_memory_midrange_uses_five_percent() {
2008        // 5% of 16 GB = 800 MB, inside the clamp range.
2009        let config = RuntimeConfig {
2010            max_rss_mb: Some(16_000),
2011            ..Default::default()
2012        };
2013        assert_eq!(config.resolved_datafusion_memory_mb(), Some(800));
2014    }
2015
2016    #[test]
2017    fn resolved_datafusion_memory_falls_back_to_resources() {
2018        // No max_rss_mb, but resources.memory_mb_max is set.
2019        let config = RuntimeConfig {
2020            max_rss_mb: None,
2021            resources: ResourceConfig {
2022                memory_mb_max: Some(16_000),
2023                ..Default::default()
2024            },
2025            ..Default::default()
2026        };
2027        assert_eq!(config.resolved_datafusion_memory_mb(), Some(800));
2028    }
2029
2030    #[test]
2031    fn ft_config() {
2032        #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2033        #[serde(default)]
2034        struct Wrapper {
2035            #[serde(deserialize_with = "deserialize_fault_tolerance")]
2036            config: FtConfig,
2037        }
2038
2039        // Omitting FtConfig, or specifying null, or specifying model "none",
2040        // disables fault tolerance.
2041        for s in [
2042            "{}",
2043            r#"{"config": null}"#,
2044            r#"{"config": {"model": "none"}}"#,
2045        ] {
2046            let config: Wrapper = serde_json::from_str(s).unwrap();
2047            assert_eq!(config.config.model, None);
2048            assert_eq!(config.config.checkpoint_interval(), None);
2049        }
2050
2051        // Serializing disabled FT produces explicit "none" form.
2052        let s = serde_json::to_string(&Wrapper {
2053            config: FtConfig::default(),
2054        })
2055        .unwrap();
2056        assert!(s.contains("\"none\""));
2057
2058        // `{}` for FtConfig, or `{...}` with an interval but no `model`,
2059        // enables fault tolerance with a 60 second interval.
2060        for s in [
2061            r#"{}"#,
2062            r#"{"checkpoint_interval": "60s"}"#,
2063            r#"{"checkpoint_interval_secs": 60}"#,
2064        ] {
2065            let config = serde_json::from_str::<FtConfig>(s).unwrap();
2066            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2067            assert_eq!(
2068                config.checkpoint_interval(),
2069                Some(Duration::from_secs(60)),
2070                "parsing {s}"
2071            );
2072        }
2073
2074        // An explicit `null` interval disables periodic checkpointing, under
2075        // the current name and under the deprecated one.
2076        for s in [
2077            r#"{"checkpoint_interval": null}"#,
2078            r#"{"checkpoint_interval_secs": null}"#,
2079        ] {
2080            let config = serde_json::from_str::<FtConfig>(s).unwrap();
2081            assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2082            assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2083        }
2084
2085        // Both spellings reach one field, so writing both is a duplicate, not
2086        // a contest one of them wins.
2087        let error = serde_json::from_str::<FtConfig>(
2088            r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2089        )
2090        .unwrap_err()
2091        .to_string();
2092        assert!(error.contains("duplicate field"), "{error}");
2093
2094        // The interval is clamped to between one second and one hour.
2095        for (json, expected_secs) in [
2096            (r#"{"checkpoint_interval": "1ms"}"#, 1),
2097            (r#"{"checkpoint_interval": "10h"}"#, 3600),
2098        ] {
2099            assert_eq!(
2100                serde_json::from_str::<FtConfig>(json)
2101                    .unwrap()
2102                    .checkpoint_interval(),
2103                Some(Duration::from_secs(expected_secs)),
2104                "parsing {json}"
2105            );
2106        }
2107    }
2108
2109    /// The configuration handed to a pinned runtime carries every duration
2110    /// setting under its older key, in the older unit, and nothing under the
2111    /// current names, which a runtime older than the rename ignores.
2112    #[test]
2113    fn legacy_duration_spelling_uses_the_older_keys() {
2114        let mut config = serde_json::json!({
2115            "workers": 2,
2116            "clock_resolution": "250ms",
2117            "max_buffering_delay": "3ms",
2118            "provisioning_timeout": "15m",
2119            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2120            "storage": {"backend": {"name": "file", "config": {
2121                "ioop_latency": "5ms",
2122                "sync": {"bucket": "b", "standby_pull_interval": "10s",
2123                         "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2124        });
2125        super::to_legacy_duration_spelling(&mut config);
2126        assert_eq!(
2127            config,
2128            serde_json::json!({
2129                "workers": 2,
2130                "clock_resolution_usecs": 250_000,
2131                "max_buffering_delay_usecs": 3_000,
2132                "provisioning_timeout_secs": 900,
2133                "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2134                "storage": {"backend": {"name": "file", "config": {
2135                    "ioop_delay": 5,
2136                    "sync": {"bucket": "b", "pull_interval": 10,
2137                             "push_interval": 3_600, "retention_min_age": 30}}}},
2138            })
2139        );
2140    }
2141
2142    /// Every connector that has a duration setting, in the current spelling.
2143    fn pipeline_with_every_duration_connector() -> serde_json::Value {
2144        serde_json::json!({
2145            "name": "p",
2146            "clock_resolution": "250ms",
2147            "inputs": {
2148                "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2149                    "topic": "t", "group_join_timeout": "30s"}}},
2150                "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2151                    "path": "http://x", "pause_linger": "7s"}}},
2152                "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2153                    "connection_config": {"server_url": "nats://x",
2154                        "connection_timeout": "5s", "request_timeout": "6s"},
2155                    "stream_name": "s",
2156                    "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2157                    "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2158                "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2159                    "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2160            },
2161            "outputs": {
2162                "v.kafka": {"stream": "v",
2163                    "transport": {"name": "kafka_output", "config": {
2164                        "topic": "v", "initialization_timeout": "40s"}},
2165                    "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2166                        "registry_timeout": "8s"}},
2167                    "enable_output_buffer": true,
2168                    "max_output_buffer_time": "500ms"},
2169                "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2170                    "connection_config": {"server_url": "nats://x",
2171                        "connection_timeout": "5s", "request_timeout": "6s"},
2172                    "subject": "s", "publish_timeout": "9s"}}},
2173            },
2174        })
2175    }
2176
2177    /// Connectors are rewritten too, each under the key and in the unit its
2178    /// transport used before the rename; the NATS expiry becomes the
2179    /// `{secs, nanos}` object it was.
2180    #[test]
2181    fn legacy_duration_spelling_rewrites_every_connector() {
2182        let mut config = pipeline_with_every_duration_connector();
2183        super::to_legacy_duration_spelling(&mut config);
2184        let i = &config["inputs"];
2185        assert_eq!(
2186            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2187            30
2188        );
2189        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2190        let nats = &i["t.nats"]["transport"]["config"];
2191        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2192        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2193        assert_eq!(nats["inactivity_timeout_secs"], 90);
2194        assert_eq!(nats["retry_interval_secs"], 3);
2195        assert_eq!(
2196            nats["consumer_config"]["max_expires"],
2197            serde_json::json!({"secs": 45, "nanos": 500_000_000})
2198        );
2199        let pubsub = &i["t.pubsub"]["transport"]["config"];
2200        assert_eq!(pubsub["timeout_seconds"], 20);
2201        assert_eq!(pubsub["connect_timeout_seconds"], 4);
2202        let out = &config["outputs"]["v.kafka"];
2203        assert_eq!(
2204            out["transport"]["config"]["initialization_timeout_secs"],
2205            40
2206        );
2207        assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2208        assert_eq!(out["max_output_buffer_time_millis"], 500);
2209        let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2210        assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2211        assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2212        assert_eq!(nats["publish_timeout_secs"], 9);
2213
2214        // No current name survives anywhere in the file.
2215        let text = config.to_string();
2216        for new in [
2217            "\"group_join_timeout\"",
2218            "\"pause_linger\"",
2219            "\"connection_timeout\"",
2220            "\"request_timeout\"",
2221            "\"inactivity_timeout\"",
2222            "\"retry_interval\"",
2223            "\"max_expiry\"",
2224            "\"timeout\"",
2225            "\"connect_timeout\"",
2226            "\"initialization_timeout\"",
2227            "\"registry_timeout\"",
2228            "\"max_output_buffer_time\"",
2229            "\"publish_timeout\"",
2230            "\"clock_resolution\"",
2231        ] {
2232            assert!(!text.contains(new), "{new} survived in {text}");
2233        }
2234    }
2235
2236    /// The YAML written for an older runtime decodes to the same value as the
2237    /// JSON, for the strings and keys that re-parsing the JSON text as YAML
2238    /// would change or refuse: a NEL, a tab, an emoji, a key over libyaml's
2239    /// 1024-byte simple-key limit, and numbers of every kind.
2240    #[test]
2241    fn json_to_yaml_is_lossless() {
2242        let long_key = "k".repeat(1100);
2243        let original = serde_json::json!({
2244            "nel": "a\u{85}b",
2245            "tab": "a\tb",
2246            "emoji": "caf\u{e9} \u{1F680}",
2247            "newline": "a\nb",
2248            long_key.as_str(): 1,
2249            "unsigned": u64::MAX,
2250            "signed": -5,
2251            "float": 2.5,
2252            "null": null,
2253            "bools": [true, false],
2254            "nested": {"list": [{"x": 1}, "two", 3.0]},
2255        });
2256        // The JSON text read as YAML loses the NEL and refuses the long key.
2257        assert!(serde_yaml::from_str::<serde_yaml::Value>(&original.to_string()).is_err());
2258
2259        let yaml = serde_yaml::to_string(&super::json_to_yaml_value(&original)).unwrap();
2260        let reread: serde_yaml::Value = serde_yaml::from_str(&yaml).unwrap();
2261        assert_eq!(serde_json::to_value(reread).unwrap(), original, "{yaml}");
2262    }
2263
2264    /// The rewritten connectors mean the same to this release as the originals.
2265    #[test]
2266    fn legacy_duration_spelling_round_trips_connectors() {
2267        let original: PipelineConfig =
2268            serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2269        let mut value = serde_json::to_value(&original).unwrap();
2270        super::to_legacy_duration_spelling(&mut value);
2271        let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2272
2273        // The format config stays raw JSON until the encoder parses it, so
2274        // compare it the way the encoder reads it.
2275        let registry = |config: &PipelineConfig| {
2276            let format = config.outputs["v.kafka"]
2277                .connector_config
2278                .format
2279                .clone()
2280                .unwrap();
2281            serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2282                .unwrap()
2283                .registry_config
2284                .registry_timeout
2285        };
2286        assert_eq!(registry(&reread), registry(&original));
2287        let mut original = original;
2288        for config in [&mut reread, &mut original] {
2289            config
2290                .outputs
2291                .get_mut("v.kafka")
2292                .unwrap()
2293                .connector_config
2294                .format = None;
2295        }
2296        assert_eq!(reread, original);
2297    }
2298
2299    /// A duration too long for the older field is capped at the largest value
2300    /// it holds, rather than wrapping; a bare number already under the current
2301    /// key keeps its value, since it already counts the older unit.
2302    #[test]
2303    fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2304        let mut config = serde_json::json!({
2305            "inputs": {
2306                "t.kafka": {"transport": {"name": "kafka_input", "config": {
2307                    "group_join_timeout": "100000000000s"}}},
2308                "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2309            },
2310            "storage": {"backend": {"name": "file", "config": {
2311                "sync": {"min_retention": "100000000000d"}}}},
2312        });
2313        super::to_legacy_duration_spelling(&mut config);
2314        let i = &config["inputs"];
2315        assert_eq!(
2316            i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2317            u64::from(u32::MAX)
2318        );
2319        assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2320        assert_eq!(
2321            config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2322            u64::from(u32::MAX)
2323        );
2324    }
2325
2326    /// The older spelling means the same settings to this release, so the
2327    /// rewrite changes what an older runtime reads without changing what a
2328    /// newer one does.
2329    #[test]
2330    fn legacy_duration_spelling_round_trips() {
2331        let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2332            "clock_resolution": "250ms",
2333            "max_buffering_delay": "3ms",
2334            "provisioning_timeout": "15m",
2335            "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2336        }))
2337        .unwrap();
2338        let mut value = serde_json::to_value(&original).unwrap();
2339        super::to_legacy_duration_spelling(&mut value);
2340        let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2341        assert_eq!(reread.clock_resolution(), original.clock_resolution());
2342        assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2343        assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2344        assert_eq!(
2345            reread.fault_tolerance.checkpoint_interval(),
2346            original.fault_tolerance.checkpoint_interval()
2347        );
2348    }
2349
2350    /// Durations that are not a whole number of the older unit round up, so a
2351    /// short timeout never becomes a zero one; a disabled checkpoint stays
2352    /// disabled; an unset required field is dropped rather than written as
2353    /// `null`; a value that does not parse is left for the runtime to reject.
2354    #[test]
2355    fn legacy_duration_spelling_edge_cases() {
2356        let mut config = serde_json::json!({
2357            "max_buffering_delay": null,
2358            "provisioning_timeout": "1.5s",
2359            "fault_tolerance": {"checkpoint_interval": null},
2360            "clock_resolution": "10sec",
2361            "storage": {"backend": {"name": "file", "config": {
2362                "ioop_latency": "400us",
2363                "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2364        });
2365        super::to_legacy_duration_spelling(&mut config);
2366        assert_eq!(
2367            config,
2368            serde_json::json!({
2369                "provisioning_timeout_secs": 2,
2370                "fault_tolerance": {"checkpoint_interval_secs": null},
2371                "clock_resolution": "10sec",
2372                "storage": {"backend": {"name": "file", "config": {
2373                    "ioop_delay": 1,
2374                    "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2375            })
2376        );
2377
2378        // A zero stays a zero: only a positive duration is pushed up to one unit.
2379        let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2380        super::to_legacy_duration_spelling(&mut zero);
2381        assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2382
2383        // Already in the older spelling: nothing to do.
2384        let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2385        let mut again = legacy.clone();
2386        super::to_legacy_duration_spelling(&mut again);
2387        assert_eq!(again, legacy);
2388    }
2389
2390    /// A connector nobody touched compares equal across the rename.
2391    ///
2392    /// A configuration stored by an older release carries each duration at its
2393    /// default, because the fields it used could not be absent. A freshly
2394    /// parsed one leaves them out. Both mean the same thing, and the diff that
2395    /// decides whether to keep a connector's checkpointed position has to agree
2396    /// with that: otherwise the connector reads as modified and the controller
2397    /// restarts its ingestion from the beginning.
2398    #[test]
2399    fn a_stored_default_matches_an_omitted_one() {
2400        let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2401            "transport": {
2402                "name": "url_input",
2403                "config": {"path": "http://example.com/x", "pause_timeout": 60},
2404            }
2405        }))
2406        .unwrap();
2407        let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2408            "transport": {
2409                "name": "url_input",
2410                "config": {"path": "http://example.com/x"},
2411            }
2412        }))
2413        .unwrap();
2414
2415        // The two differ field by field, which is what the derived `PartialEq`
2416        // sees, yet they configure the same connector.
2417        assert_ne!(stored, fresh);
2418        assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2419
2420        // A real difference still reads as one.
2421        let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2422            "transport": {
2423                "name": "url_input",
2424                "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2425            }
2426        }))
2427        .unwrap();
2428        assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2429    }
2430
2431    /// An Avro schema registry timeout compares equal across the rename.
2432    ///
2433    /// The format configuration stays raw JSON until the format parses it, so
2434    /// the connector comparison has to read the timeout the way the format
2435    /// does: otherwise following the deprecation warning, from
2436    /// `registry_timeout_secs: 10` to `registry_timeout: "10s"`, reads as a
2437    /// modified connector and an Avro input is read again from the beginning.
2438    #[test]
2439    fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2440        let connector = |registry: serde_json::Value| -> ConnectorConfig {
2441            let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2442            format
2443                .as_object_mut()
2444                .unwrap()
2445                .extend(registry.as_object().unwrap().clone());
2446            serde_json::from_value(serde_json::json!({
2447                "transport": {
2448                    "name": "url_input",
2449                    "config": {"path": "http://example.com/x"},
2450                },
2451                "format": {"name": "avro", "config": format},
2452            }))
2453            .unwrap()
2454        };
2455        let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2456        let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2457        let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2458        let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2459        let unset = connector(serde_json::json!({}));
2460
2461        assert!(stored.equal_modulo_paused(&current));
2462        assert!(stored.equal_for_input_checkpoint_replay(&current));
2463        assert!(current.equal_modulo_paused(&spelled_out));
2464        assert!(!stored.equal_modulo_paused(&changed));
2465        assert!(!stored.equal_modulo_paused(&unset));
2466        // The other formats carry no duration and are left alone.
2467        let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2468            "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2469            "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2470        }))
2471        .unwrap();
2472        assert!(!json.equal_modulo_paused(&stored));
2473    }
2474
2475    /// The defaults an older release wrote out still load.
2476    ///
2477    /// `max_output_buffer_time_millis` defaulted to `usize::MAX` and was
2478    /// serialized into every output connector, so scaling it into nanoseconds
2479    /// has to survive rather than reject the configuration.
2480    #[test]
2481    fn the_largest_legacy_defaults_still_load() {
2482        let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
2483            "enable_output_buffer": false,
2484            "max_output_buffer_time_millis": u64::MAX,
2485            "max_output_buffer_size_records": 10_000_000u64,
2486        }))
2487        .unwrap();
2488        assert_eq!(
2489            buffer.max_output_buffer_time,
2490            Some(ConfigDuration::from_millis(u64::MAX))
2491        );
2492
2493        // The widest legacy unit, days, also survives.
2494        let sync: SyncConfig =
2495            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
2496        assert_eq!(
2497            sync.min_retention(),
2498            ConfigDuration::from_days(4_000_000_000)
2499        );
2500    }
2501
2502    /// A legacy number too large for a `u64` of seconds saturates at the
2503    /// longest duration there is rather than failing to load: an older
2504    /// release accepted it.
2505    #[test]
2506    fn a_legacy_number_past_u64_seconds_saturates() {
2507        let sync: SyncConfig =
2508            serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
2509                .unwrap();
2510        assert_eq!(
2511            sync.min_retention(),
2512            ConfigDuration::from(std::time::Duration::MAX)
2513        );
2514    }
2515
2516    /// Kafka input and NATS connectors stored by an older release carry their
2517    /// duration defaults spelled out; a fresh configuration leaves them out.
2518    /// The checkpoint replay comparison must see the two as the same connector.
2519    #[test]
2520    fn spelled_out_defaults_match_for_kafka_input_and_nats() {
2521        fn connector(value: serde_json::Value) -> ConnectorConfig {
2522            serde_json::from_value(value).unwrap()
2523        }
2524        fn secs(duration: ConfigDuration) -> u64 {
2525            std::time::Duration::from(duration).as_secs()
2526        }
2527        let fresh_kafka = connector(serde_json::json!({
2528            "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
2529        let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
2530            unreachable!()
2531        };
2532        let stored_kafka = connector(serde_json::json!({
2533            "transport": {"name": "kafka_input", "config": {
2534                "topic": "t",
2535                "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
2536        assert_ne!(stored_kafka, fresh_kafka);
2537        assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
2538
2539        let base = serde_json::json!({
2540            "connection_config": {"server_url": "nats://x"},
2541            "stream_name": "s",
2542            "consumer_config": {"deliver_policy": "All"}});
2543        let fresh_nats = connector(serde_json::json!({
2544            "transport": {"name": "nats_input", "config": base.clone()}}));
2545        let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
2546            unreachable!()
2547        };
2548        let mut spelled_out = base;
2549        spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
2550        spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
2551        spelled_out["connection_config"]["connection_timeout_secs"] =
2552            secs(nats.connection_config.connection_timeout()).into();
2553        spelled_out["connection_config"]["request_timeout_secs"] =
2554            secs(nats.connection_config.request_timeout()).into();
2555        let stored_nats = connector(serde_json::json!({
2556            "transport": {"name": "nats_input", "config": spelled_out}}));
2557        assert_ne!(stored_nats, fresh_nats);
2558        assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
2559    }
2560
2561    /// A configuration written before the rename converts itself: the manager
2562    /// deserializes it and writes it back (`validate_runtime_config`, then
2563    /// `serde_json::to_value`), so the superseded keys disappear and the
2564    /// current ones take their place with the same lengths of time. Only then
2565    /// does the pipeline stop warning about a configuration nobody has edited.
2566    #[test]
2567    fn superseded_keys_are_normalised_by_a_round_trip() {
2568        let stored = serde_json::json!({
2569            "workers": 4,
2570            "clock_resolution_usecs": 100_000,
2571            "max_buffering_delay_usecs": 0,
2572            "provisioning_timeout_secs": 300,
2573        });
2574
2575        let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
2576        let written = serde_json::to_value(&config).unwrap();
2577
2578        assert_eq!(written["clock_resolution"], "100ms");
2579        assert_eq!(written["max_buffering_delay"], "0s");
2580        assert_eq!(written["provisioning_timeout"], "5m");
2581        for superseded in [
2582            "clock_resolution_usecs",
2583            "max_buffering_delay_usecs",
2584            "provisioning_timeout_secs",
2585        ] {
2586            assert!(
2587                written.get(superseded).is_none(),
2588                "`{superseded}` survived the round trip: {written}"
2589            );
2590        }
2591
2592        // The round trip is a fixed point: reading what was written back gives
2593        // the same document, so a configuration converts once and then settles.
2594        let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
2595        assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
2596    }
2597
2598    /// The simulated per-I/O delay reads back from both spellings. Its
2599    /// superseded name counted milliseconds, one of only two settings that
2600    /// did, so the unit is worth pinning: `ioop_delay: 5` is five
2601    /// milliseconds, not five seconds.
2602    #[test]
2603    fn ioop_latency_accepts_both_spellings() {
2604        for (json, expected) in [
2605            (r#"{"name": "file", "config": {}}"#, None),
2606            (
2607                r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
2608                Some(ConfigDuration::from_millis(5)),
2609            ),
2610            (
2611                r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
2612                Some(ConfigDuration::from_millis(5)),
2613            ),
2614            (
2615                r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
2616                Some(ConfigDuration::from_secs(1)),
2617            ),
2618        ] {
2619            let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
2620            let StorageBackendConfig::File(file) = backend else {
2621                panic!("expected the file backend, parsing {json}");
2622            };
2623            assert_eq!(file.ioop_latency, expected, "parsing {json}");
2624        }
2625    }
2626
2627    /// The clock resolution reads back from both the current field and the one
2628    /// it deprecates. An explicit `null` selects the default, which is what the
2629    /// deprecated field did before it gained a replacement.
2630    #[test]
2631    fn clock_resolution_falls_back_to_the_deprecated_field() {
2632        for (json, expected) in [
2633            (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
2634            (
2635                r#"{"clock_resolution": "100ms"}"#,
2636                ConfigDuration::from_millis(100),
2637            ),
2638            (
2639                r#"{"clock_resolution_usecs": 100000}"#,
2640                ConfigDuration::from_millis(100),
2641            ),
2642            (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
2643            (
2644                r#"{"clock_resolution_usecs": null}"#,
2645                DEFAULT_CLOCK_RESOLUTION,
2646            ),
2647        ] {
2648            assert_eq!(
2649                serde_json::from_str::<RuntimeConfig>(json)
2650                    .unwrap()
2651                    .clock_resolution(),
2652                expected,
2653                "parsing {json}"
2654            );
2655        }
2656    }
2657
2658    /// Every duration field reads back from the field it deprecates, in the
2659    /// unit that field used.
2660    #[test]
2661    fn deprecated_duration_fields_still_work() {
2662        let runtime: RuntimeConfig = serde_json::from_str(
2663            r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
2664        )
2665        .unwrap();
2666        assert_eq!(
2667            runtime.max_buffering_delay(),
2668            ConfigDuration::from_millis(5)
2669        );
2670        assert_eq!(
2671            runtime.provisioning_timeout,
2672            Some(ConfigDuration::from_secs(1200))
2673        );
2674
2675        let sync: SyncConfig = serde_json::from_str(
2676            r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
2677        )
2678        .unwrap();
2679        assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
2680        assert_eq!(
2681            sync.checkpoint_push_interval(),
2682            Some(ConfigDuration::from_secs(300))
2683        );
2684        assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
2685
2686        let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
2687        assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
2688
2689        let buffer: OutputBufferConfig =
2690            serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
2691        assert_eq!(
2692            buffer.max_output_buffer_time(),
2693            ConfigDuration::from_millis(250)
2694        );
2695    }
2696
2697    /// Defaults apply when neither the current field nor the deprecated one is
2698    /// set.
2699    #[test]
2700    fn duration_fields_default_when_unset() {
2701        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
2702        assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
2703        assert_eq!(sync.checkpoint_push_interval(), None);
2704        assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
2705
2706        let runtime = RuntimeConfig::default();
2707        assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
2708        assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
2709        assert_eq!(runtime.provisioning_timeout, None);
2710    }
2711
2712    /// Regression test: `Option<f64>` fields inside `StorageOptions` must
2713    /// survive a JSON-string round-trip through `PipelineConfig`, which uses
2714    /// `#[serde(flatten)]` on `RuntimeConfig`.
2715    #[test]
2716    fn storage_options_f64_roundtrip_through_pipeline_config() {
2717        let pc = PipelineConfig {
2718            global: RuntimeConfig {
2719                storage: Some(StorageOptions {
2720                    bloom_false_positive_rate: Some(0.01),
2721                    ..Default::default()
2722                }),
2723                ..Default::default()
2724            },
2725            multihost: None,
2726            name: Some("test-pipeline".into()),
2727            given_name: None,
2728            storage_config: None,
2729            secrets_dir: None,
2730            inputs: Default::default(),
2731            outputs: Default::default(),
2732            program_ir: None,
2733        };
2734
2735        // JSON string round-trip (the path the pipeline process takes).
2736        let json = serde_json::to_string_pretty(&pc).unwrap();
2737        let pc2: PipelineConfig = serde_json::from_str(&json).expect(
2738            "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
2739        );
2740        assert_eq!(
2741            pc2.global.storage.unwrap().bloom_false_positive_rate,
2742            Some(0.01)
2743        );
2744
2745        // serde_json::Value round-trip (the path the pipeline manager takes).
2746        let value = serde_json::to_value(&pc).unwrap();
2747        let pc3: PipelineConfig = serde_json::from_value(value)
2748            .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
2749        assert_eq!(
2750            pc3.global.storage.unwrap().bloom_false_positive_rate,
2751            Some(0.01)
2752        );
2753    }
2754}
2755
2756impl FtConfig {
2757    pub fn is_enabled(&self) -> bool {
2758        self.model.is_some()
2759    }
2760
2761    /// Returns the checkpoint interval, if fault tolerance is enabled, and
2762    /// otherwise `None`.
2763    ///
2764    /// Falls back to the deprecated `checkpoint_interval_secs` and then to
2765    /// [`DEFAULT_CHECKPOINT_INTERVAL`]. The interval is clamped to between one
2766    /// second and one hour.
2767    pub fn checkpoint_interval(&self) -> Option<Duration> {
2768        if !self.is_enabled() {
2769            return None;
2770        }
2771
2772        let interval = self
2773            .checkpoint_interval
2774            .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
2775
2776        Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
2777    }
2778}
2779
2780/// Serde implementation for de/serializing a string into `Option<T>` where
2781/// `"none"` indicates `None` and any other string indicates `Some`.
2782///
2783/// This could be extended to handle non-strings by adding more forwarding
2784/// `visit_*` methods to the Visitor implementation.  I don't see a way to write
2785/// them automatically.
2786mod none_as_string {
2787    use std::marker::PhantomData;
2788
2789    use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
2790    use serde::ser::{Serialize, Serializer};
2791
2792    pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
2793    where
2794        S: Serializer,
2795        T: Serialize,
2796    {
2797        match value.as_ref() {
2798            Some(value) => value.serialize(serializer),
2799            None => "none".serialize(serializer),
2800        }
2801    }
2802
2803    struct NoneAsString<T>(PhantomData<fn() -> T>);
2804
2805    impl<'de, T> Visitor<'de> for NoneAsString<T>
2806    where
2807        T: Deserialize<'de>,
2808    {
2809        type Value = Option<T>;
2810
2811        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
2812            formatter.write_str("string")
2813        }
2814
2815        fn visit_none<E>(self) -> Result<Self::Value, E>
2816        where
2817            E: serde::de::Error,
2818        {
2819            Ok(None)
2820        }
2821
2822        fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
2823        where
2824            E: serde::de::Error,
2825        {
2826            if &value.to_ascii_lowercase() == "none" {
2827                Ok(None)
2828            } else {
2829                Ok(Some(T::deserialize(value.into_deserializer())?))
2830            }
2831        }
2832    }
2833
2834    pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
2835    where
2836        D: Deserializer<'de>,
2837        T: Deserialize<'de>,
2838    {
2839        deserializer.deserialize_str(NoneAsString(PhantomData))
2840    }
2841}
2842
2843/// Generates an OpenAPI schema for an `Option<T>` field serialized with `none_as_string`.
2844/// The schema is a `oneOf` with a reference to `T`'s schema and a `"none"` string enum.
2845fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
2846    Schema::OneOf(
2847        OneOfBuilder::new()
2848            .item(RefOr::Ref(Ref::new(format!(
2849                "#/components/schemas/{}",
2850                T::schema().0
2851            ))))
2852            .item(
2853                ObjectBuilder::new()
2854                    .schema_type(SchemaType::String)
2855                    .enum_values(Some(vec!["none"])),
2856            )
2857            .default(Some(
2858                serde_json::to_value(T::default()).expect("Failed to serialize default value"),
2859            ))
2860            .build(),
2861    )
2862}
2863
2864/// Fault tolerance model.
2865///
2866/// The ordering is significant: we consider [Self::ExactlyOnce] to be a "higher
2867/// level" of fault tolerance than [Self::AtLeastOnce].
2868#[derive(
2869    Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
2870)]
2871#[serde(rename_all = "snake_case")]
2872pub enum FtModel {
2873    /// Each record is output at least once.  Crashes may duplicate output, but
2874    /// no input or output is dropped.
2875    AtLeastOnce,
2876
2877    /// Each record is output exactly once.  Crashes do not drop or duplicate
2878    /// input or output.
2879    #[default]
2880    ExactlyOnce,
2881}
2882
2883impl FtModel {
2884    pub fn option_as_str(value: Option<FtModel>) -> &'static str {
2885        value.map_or("no", |model| model.as_str())
2886    }
2887
2888    pub fn as_str(&self) -> &'static str {
2889        match self {
2890            FtModel::AtLeastOnce => "at_least_once",
2891            FtModel::ExactlyOnce => "exactly_once",
2892        }
2893    }
2894}
2895
2896/// The string does not name a fault tolerance model.
2897#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2898pub struct FtModelUnknown;
2899
2900impl std::fmt::Display for FtModelUnknown {
2901    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2902        f.write_str("expected `exactly_once` or `at_least_once`")
2903    }
2904}
2905
2906impl std::error::Error for FtModelUnknown {}
2907
2908impl FromStr for FtModel {
2909    type Err = FtModelUnknown;
2910
2911    fn from_str(s: &str) -> Result<Self, Self::Err> {
2912        match s.to_ascii_lowercase().as_str() {
2913            "exactly_once" => Ok(Self::ExactlyOnce),
2914            "at_least_once" => Ok(Self::AtLeastOnce),
2915            _ => Err(FtModelUnknown),
2916        }
2917    }
2918}
2919
2920/// Describes an input connector configuration
2921#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
2922pub struct InputEndpointConfig {
2923    /// The name of the input stream of the circuit that this endpoint is
2924    /// connected to.
2925    pub stream: Cow<'static, str>,
2926
2927    /// Connector configuration.
2928    #[serde(flatten)]
2929    pub connector_config: ConnectorConfig,
2930}
2931
2932impl InputEndpointConfig {
2933    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
2934        Self {
2935            stream: stream.into(),
2936            connector_config,
2937        }
2938    }
2939}
2940
2941/// Deserialize the `start_after` property of a connector configuration.
2942/// It requires a non-standard deserialization because we want to accept
2943/// either a string or an array of strings.
2944fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
2945where
2946    D: Deserializer<'de>,
2947{
2948    let value = Option::<JsonValue>::deserialize(deserializer)?;
2949    match value {
2950        Some(JsonValue::String(s)) => Ok(Some(vec![s])),
2951        Some(JsonValue::Array(arr)) => {
2952            let vec = arr
2953                .into_iter()
2954                .map(|item| {
2955                    item.as_str()
2956                        .map(|s| s.to_string())
2957                        .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
2958                })
2959                .collect::<Result<Vec<String>, _>>()?;
2960            Ok(Some(vec))
2961        }
2962        Some(JsonValue::Null) | None => Ok(None),
2963        _ => Err(serde::de::Error::custom(
2964            "invalid 'start_after' property: expected a string, an array of strings, or null",
2965        )),
2966    }
2967}
2968
2969#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
2970pub struct ConnectorConfig {
2971    /// Send a full snapshot of a materialized view when the connector first
2972    /// starts. Valid for output connectors only.
2973    ///
2974    /// When `true`, the pipeline emits the current contents of the view as the
2975    /// initial batch the first time the connector runs. The view must be
2976    /// materialized (declared with `CREATE MATERIALIZED VIEW`).
2977    ///
2978    /// The snapshot is sent exactly once per connector lifetime: it does not
2979    /// fire again when the pipeline resumes from a checkpoint. Modifying the
2980    /// connector configuration or invoking the reset API triggers a fresh
2981    /// snapshot when the connector supports reset (e.g., Delta Lake in
2982    /// `truncate` mode and Postgres).
2983    #[serde(default)]
2984    pub send_snapshot: bool,
2985
2986    /// Ingest deletions as insertions, recording the original polarity in the
2987    /// `is_delete` metadata attribute. Valid for input connectors only.
2988    ///
2989    /// When `true`, a delete received by the connector is pushed to the table
2990    /// as an insertion of the same record, and the connector attaches the
2991    /// `is_delete` metadata attribute set to `true` to it. Insertions carry no
2992    /// `is_delete` attribute, so a column declared as
2993    /// `DEFAULT CAST(CONNECTOR_METADATA()['is_delete'] AS BOOLEAN)` is `NULL`
2994    /// for them. The table then contains the entire history of the input
2995    /// stream instead of tracking its current contents.
2996    ///
2997    /// Only tables without a primary key support this mode, since deletions in
2998    /// a table with a primary key delete a key rather than a record.
2999    ///
3000    /// Versions of Feldera that predate this option ignore it and apply
3001    /// deletions as regular deletions.
3002    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3003    pub soft_delete: bool,
3004
3005    /// Transport endpoint configuration.
3006    pub transport: TransportConfig,
3007
3008    /// Optional preprocessor configuration
3009    #[serde(skip_serializing_if = "Option::is_none")]
3010    pub preprocessor: Option<Vec<PreprocessorConfig>>,
3011
3012    /// Parser configuration.
3013    pub format: Option<FormatConfig>,
3014
3015    /// Optional postprocessor configuration
3016    #[serde(skip_serializing_if = "Option::is_none")]
3017    pub postprocessor: Option<Vec<PostprocessorConfig>>,
3018
3019    /// Name of the index that the connector is attached to.
3020    ///
3021    /// This property is valid for output connectors only.  It is used with data
3022    /// transports and formats that expect output updates in the form of key/value
3023    /// pairs, where the key typically represents a unique id associated with the
3024    /// table or view.
3025    ///
3026    /// To support such output formats, an output connector can be attached to an
3027    /// index created using the SQL CREATE INDEX statement.  An index of a table
3028    /// or view contains the same updates as the table or view itself, indexed by
3029    /// one or more key columns.
3030    ///
3031    /// See individual connector documentation for details on how they work
3032    /// with indexes.
3033    pub index: Option<String>,
3034
3035    /// Output buffer configuration.
3036    #[serde(flatten)]
3037    pub output_buffer_config: OutputBufferConfig,
3038
3039    /// Maximum number of records from this connector to process in a single batch.
3040    ///
3041    /// When set, this caps how many records are taken from the connector’s input
3042    /// buffer and pushed through the circuit at once.
3043    ///
3044    /// This is typically configured lower than `max_queued_records` to allow the
3045    /// connector time to restart and refill its buffer while a batch is being
3046    /// processed.
3047    ///
3048    /// Not all input adapters honor this limit.
3049    ///
3050    /// If this is not set, the batch size is derived from `max_worker_batch_size`.
3051    #[serde(skip_serializing_if = "Option::is_none")]
3052    pub max_batch_size: Option<u64>,
3053
3054    /// Maximum number of records processed per batch, per worker thread.
3055    ///
3056    /// When `max_batch_size` is not set, this setting is used to cap
3057    /// the number of records that can be taken from the connector’s input
3058    /// buffer and pushed through the circuit at once.  The effective batch size is computed as:
3059    /// `max_worker_batch_size × workers`.
3060    ///
3061    /// This provides an alternative to `max_batch_size` that automatically adjusts batch
3062    /// size as the number of worker threads changes to maintain constant amount of
3063    /// work per worker per batch.
3064    ///
3065    /// Defaults to 10,000 records per worker.
3066    #[serde(skip_serializing_if = "Option::is_none")]
3067    pub max_worker_batch_size: Option<u64>,
3068
3069    /// Backpressure threshold, in records.
3070    ///
3071    /// Maximal number of records queued by the endpoint before the endpoint
3072    /// is paused by the backpressure mechanism.
3073    ///
3074    /// For input endpoints, this setting bounds the number of records that have
3075    /// been received from the input transport but haven't yet been consumed by
3076    /// the circuit, since the circuit is still busy processing previous inputs.
3077    ///
3078    /// For output endpoints, this setting bounds the number of records that have
3079    /// been produced by the circuit but not yet sent via the output transport endpoint
3080    /// nor stored in the output buffer (see `enable_output_buffer`).
3081    ///
3082    /// Note that this is not a hard bound: there can be a small delay between
3083    /// the backpressure mechanism is triggered and the endpoint is paused, during
3084    /// which more data may be queued.
3085    ///
3086    /// The default is 1 million.
3087    #[serde(default = "default_max_queued_records")]
3088    pub max_queued_records: u64,
3089
3090    /// Backpressure threshold, in bytes.
3091    ///
3092    /// Maximal number of bytes queued by the endpoint before the endpoint
3093    /// is paused by the backpressure mechanism.
3094    ///
3095    /// For input endpoints, this setting bounds the number of bytes that have
3096    /// been received from the input transport but haven't yet been consumed by
3097    /// the circuit since the circuit, since the circuit is still busy processing
3098    /// previous inputs.
3099    ///
3100    /// This setting is not yet implemented for output endpoints.
3101    ///
3102    /// Note that this is not a hard bound: there can be a small delay between
3103    /// the backpressure mechanism is triggered and the endpoint is paused, during
3104    /// which more data may be queued.
3105    ///
3106    /// When this is unspecified, it defaults to `1000 * max_queued_records`.
3107    #[serde(skip_serializing_if = "Option::is_none")]
3108    pub max_queued_bytes: Option<u64>,
3109
3110    /// Create connector in paused state.
3111    ///
3112    /// A paused input connector does not fetch data from its source. A paused
3113    /// output connector discards the output it receives instead of sending it
3114    /// to its sink.
3115    ///
3116    /// A connector is started at runtime with the `start` action of the
3117    /// connector API and paused again with `pause`.
3118    ///
3119    /// The default is `false`.
3120    #[serde(default)]
3121    pub paused: bool,
3122
3123    /// Arbitrary user-defined text labels associated with the connector.
3124    ///
3125    /// These labels can be used in conjunction with the `start_after` property
3126    /// to control the start order of connectors.
3127    #[serde(default)]
3128    pub labels: Vec<String>,
3129
3130    /// Start the connector after all connectors with specified labels.
3131    ///
3132    /// This property is used to control the start order of connectors.
3133    /// The connector will not start until all connectors with the specified
3134    /// labels have finished processing all inputs.
3135    #[serde(deserialize_with = "deserialize_start_after")]
3136    #[serde(default)]
3137    pub start_after: Option<Vec<String>>,
3138}
3139
3140impl ConnectorConfig {
3141    pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3142        Self {
3143            send_snapshot: false,
3144            soft_delete: false,
3145            transport,
3146            preprocessor: None,
3147            format,
3148            postprocessor: None,
3149            index: None,
3150            output_buffer_config: Default::default(),
3151            max_batch_size: None,
3152            max_worker_batch_size: None,
3153            max_queued_records: default_max_queued_records(),
3154            max_queued_bytes: None,
3155            paused: false,
3156            labels: Vec::new(),
3157            start_after: None,
3158        }
3159    }
3160
3161    pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3162        self.max_batch_size = max_batch_size;
3163        self
3164    }
3165
3166    pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3167        self.max_queued_records = max_queued_records;
3168        self
3169    }
3170
3171    /// Compare two configs modulo the `paused` field and how their duration
3172    /// settings are spelled.
3173    ///
3174    /// Used to compare checkpointed and current connector configs.
3175    pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3176        let mut a = self.clone();
3177        let mut b = other.clone();
3178        a.paused = false;
3179        b.paused = false;
3180        a.normalize_durations();
3181        b.normalize_durations();
3182        a == b
3183    }
3184
3185    /// Writes each duration setting out as the value in effect.
3186    ///
3187    /// A setting left out and the same setting written explicitly at its
3188    /// default mean the same thing, but the derived `PartialEq` sees `None`
3189    /// against `Some(default)` and calls them different. Configurations stored
3190    /// before the rename carry the defaults explicitly, because the fields they
3191    /// used had no way to be absent: every output connector, for instance,
3192    /// carries `max_output_buffer_time_millis` at `u64::MAX`. Without this a
3193    /// connector nobody touched compares as modified, and the pipeline diff that
3194    /// follows an upgrade is never empty.
3195    fn normalize_durations(&mut self) {
3196        self.transport.normalize_durations();
3197        self.output_buffer_config.max_output_buffer_time =
3198            Some(self.output_buffer_config.max_output_buffer_time());
3199        if let Some(format) = &mut self.format {
3200            format.normalize_durations();
3201        }
3202    }
3203
3204    /// Compare two input connector configs modulo fields that only affect
3205    /// runtime flow control and do not invalidate checkpointed connector state.
3206    pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3207        let mut a = self.clone();
3208        let mut b = other.clone();
3209        a.normalize_for_input_checkpoint_replay();
3210        b.normalize_for_input_checkpoint_replay();
3211        a == b
3212    }
3213
3214    fn normalize_for_input_checkpoint_replay(&mut self) {
3215        self.paused = false;
3216        self.max_batch_size = None;
3217        self.max_worker_batch_size = None;
3218        self.max_queued_records = default_max_queued_records();
3219        self.max_queued_bytes = None;
3220        self.normalize_durations();
3221    }
3222
3223    /// Adopt input connector settings that are safe to change while replaying
3224    /// checkpointed connector state.
3225    pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3226        self.max_batch_size = other.max_batch_size;
3227        self.max_worker_batch_size = other.max_worker_batch_size;
3228        self.max_queued_records = other.max_queued_records;
3229        self.max_queued_bytes = other.max_queued_bytes;
3230    }
3231
3232    /// Returns `max_queued_records` or, if it is not set, the default.
3233    pub fn max_queued_records(&self) -> u64 {
3234        self.max_queued_records
3235    }
3236
3237    /// Returns `max_queued_bytes` or, if it is not set, the default based on
3238    /// `max_queued_records`.
3239    pub fn max_queued_bytes(&self) -> u64 {
3240        self.max_queued_bytes
3241            .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3242    }
3243}
3244
3245#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3246#[serde(default)]
3247pub struct OutputBufferConfig {
3248    /// Enable output buffering.
3249    ///
3250    /// The output buffering mechanism allows decoupling the rate at which the pipeline
3251    /// pushes changes to the output transport from the rate of input changes.
3252    ///
3253    /// By default, output updates produced by the pipeline are pushed directly to
3254    /// the output transport. Some destinations may prefer to receive updates in fewer
3255    /// bigger batches. For instance, when writing Parquet files, producing
3256    /// one bigger file every few minutes is usually better than creating
3257    /// small files every few milliseconds.
3258    ///
3259    /// To achieve such input/output decoupling, users can enable output buffering by
3260    /// setting the `enable_output_buffer` flag to `true`.  When buffering is enabled, output
3261    /// updates produced by the pipeline are consolidated in an internal buffer and are
3262    /// pushed to the output transport when one of several conditions is satisfied:
3263    ///
3264    /// * data has been accumulated in the buffer for longer than
3265    ///   `max_output_buffer_time`.
3266    /// * buffer size exceeds `max_output_buffer_size_records` records.
3267    ///
3268    /// This flag is `false` by default.
3269    // TODO: on-demand output triggered via the API.
3270    pub enable_output_buffer: bool,
3271
3272    /// Maximum time data is kept in the output buffer, for example `500ms`.
3273    ///
3274    /// By default, data is kept in the buffer indefinitely until one of
3275    /// the other output conditions is satisfied.  When this option is
3276    /// set the buffer will be flushed at least that often.
3277    ///
3278    /// NOTE: this configuration option requires the `enable_output_buffer` flag
3279    /// to be set.
3280    #[serde(
3281        default,
3282        alias = "max_output_buffer_time_millis",
3283        deserialize_with = "duration_max_output_buffer_time",
3284        skip_serializing_if = "Option::is_none"
3285    )]
3286    #[schema(value_type = Option<String>)]
3287    pub max_output_buffer_time: Option<ConfigDuration>,
3288
3289    /// Maximum number of updates to be kept in the output buffer.
3290    ///
3291    /// This parameter bounds the maximal size of the buffer.
3292    /// Note that the size of the buffer is not always equal to the
3293    /// total number of updates output by the pipeline. Updates to the
3294    /// same record can overwrite or cancel previous updates.
3295    ///
3296    /// The default is 10,000,000.
3297    ///
3298    /// NOTE: this configuration option requires the `enable_output_buffer` flag
3299    /// to be set.
3300    pub max_output_buffer_size_records: usize,
3301}
3302
3303impl OutputBufferConfig {
3304    /// The output buffering time limit in effect, or no limit.
3305    pub fn max_output_buffer_time(&self) -> ConfigDuration {
3306        self.max_output_buffer_time
3307            .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3308    }
3309}
3310
3311impl Default for OutputBufferConfig {
3312    fn default() -> Self {
3313        Self {
3314            enable_output_buffer: false,
3315            max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3316            max_output_buffer_time: None,
3317        }
3318    }
3319}
3320
3321/// Describes an output connector configuration
3322#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3323pub struct OutputEndpointConfig {
3324    /// The name of the output stream of the circuit that this endpoint is
3325    /// connected to.
3326    pub stream: Cow<'static, str>,
3327
3328    /// Connector configuration.
3329    #[serde(flatten)]
3330    pub connector_config: ConnectorConfig,
3331}
3332
3333impl OutputEndpointConfig {
3334    pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3335        Self {
3336            stream: stream.into(),
3337            connector_config,
3338        }
3339    }
3340}
3341
3342/// Transport-specific endpoint configuration passed to
3343/// `crate::OutputTransport::new_endpoint`
3344/// and `crate::InputTransport::new_endpoint`.
3345#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3346#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3347pub enum TransportConfig {
3348    FileInput(FileInputConfig),
3349    FileOutput(FileOutputConfig),
3350    // Boxed: `NatsInputConfig` is far larger than any other variant, and an
3351    // unboxed copy would set the size of every `TransportConfig`.
3352    NatsInput(Box<NatsInputConfig>),
3353    NatsOutput(NatsOutputConfig),
3354    KafkaInput(KafkaInputConfig),
3355    KafkaOutput(KafkaOutputConfig),
3356    PubSubInput(PubSubInputConfig),
3357    UrlInput(UrlInputConfig),
3358    S3Input(S3InputConfig),
3359    DeltaTableInput(DeltaTableReaderConfig),
3360    DeltaTableOutput(DeltaTableWriterConfig),
3361    // Snake case would rename "DynamoDBOutput" to `dynamo_db_output`.
3362    // However, DynamoDB is a single word, so override the tag to `dynamodb_output`.
3363    #[serde(rename = "dynamodb_output")]
3364    DynamoDBOutput(DynamoDBWriterConfig),
3365    RedisOutput(RedisOutputConfig),
3366    // Prevent rust from complaining about large size difference between enum variants.
3367    IcebergInput(Box<IcebergReaderConfig>),
3368    PostgresInput(PostgresReaderConfig),
3369    PostgresCdcInput(PostgresCdcReaderConfig),
3370    PostgresOutput(PostgresWriterConfig),
3371    Datagen(DatagenInputConfig),
3372    Nexmark(NexmarkInputConfig),
3373    /// Direct HTTP input: cannot be instantiated through API
3374    HttpInput(HttpInputConfig),
3375    /// Direct HTTP output: cannot be instantiated through API
3376    HttpOutput(HttpOutputConfig),
3377    /// Ad hoc input: cannot be instantiated through API
3378    AdHocInput(AdHocInputConfig),
3379    ClockInput(ClockConfig),
3380    S2Input(S2InputConfig),
3381    S2Output(S2OutputConfig),
3382    /// Output connector that discards all data.
3383    NullOutput,
3384    /// Input connector that produces no data.
3385    EmptyInput,
3386}
3387
3388impl TransportConfig {
3389    /// Writes each of the transport's duration settings out as the value in
3390    /// effect; see `ConnectorConfig::normalize_durations`.
3391    pub fn normalize_durations(&mut self) {
3392        match self {
3393            TransportConfig::UrlInput(config) => {
3394                config.pause_linger = Some(config.pause_linger());
3395            }
3396            TransportConfig::KafkaInput(config) => {
3397                config.group_join_timeout = Some(config.group_join_timeout());
3398            }
3399            TransportConfig::KafkaOutput(config) => {
3400                config.initialization_timeout = Some(config.initialization_timeout());
3401            }
3402            TransportConfig::NatsInput(config) => {
3403                config.connection_config.connection_timeout =
3404                    Some(config.connection_config.connection_timeout());
3405                config.connection_config.request_timeout =
3406                    Some(config.connection_config.request_timeout());
3407                config.inactivity_timeout = Some(config.inactivity_timeout());
3408                config.retry_interval = Some(config.retry_interval());
3409            }
3410            TransportConfig::NatsOutput(config) => {
3411                config.connection_config.connection_timeout =
3412                    Some(config.connection_config.connection_timeout());
3413                config.connection_config.request_timeout =
3414                    Some(config.connection_config.request_timeout());
3415                config.publish_timeout = Some(config.publish_timeout());
3416            }
3417            _ => {}
3418        }
3419    }
3420
3421    pub fn name(&self) -> String {
3422        match self {
3423            TransportConfig::FileInput(_) => "file_input".to_string(),
3424            TransportConfig::FileOutput(_) => "file_output".to_string(),
3425            TransportConfig::NatsInput(_) => "nats_input".to_string(),
3426            TransportConfig::NatsOutput(_) => "nats_output".to_string(),
3427            TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
3428            TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
3429            TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
3430            TransportConfig::UrlInput(_) => "url_input".to_string(),
3431            TransportConfig::S3Input(_) => "s3_input".to_string(),
3432            TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
3433            TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
3434            TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
3435            TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
3436            TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
3437            TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
3438            TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
3439            TransportConfig::Datagen(_) => "datagen".to_string(),
3440            TransportConfig::Nexmark(_) => "nexmark".to_string(),
3441            TransportConfig::HttpInput(_) => "http_input".to_string(),
3442            TransportConfig::HttpOutput(_) => "http_output".to_string(),
3443            TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
3444            TransportConfig::RedisOutput(_) => "redis_output".to_string(),
3445            TransportConfig::ClockInput(_) => "clock".to_string(),
3446            TransportConfig::S2Input(_) => "s2_input".to_string(),
3447            TransportConfig::S2Output(_) => "s2_output".to_string(),
3448            TransportConfig::NullOutput => "null_output".to_string(),
3449            TransportConfig::EmptyInput => "empty_input".to_string(),
3450        }
3451    }
3452
3453    /// Returns true if the connector is transient, i.e., is created and destroyed
3454    /// at runtime on demand, rather than being configured as part of the pipeline.
3455    pub fn is_transient(&self) -> bool {
3456        matches!(
3457            self,
3458            TransportConfig::AdHocInput(_)
3459                | TransportConfig::HttpInput(_)
3460                | TransportConfig::HttpOutput(_)
3461                | TransportConfig::ClockInput(_)
3462        )
3463    }
3464
3465    pub fn is_http_input(&self) -> bool {
3466        matches!(self, TransportConfig::HttpInput(_))
3467    }
3468}
3469
3470/// Data format specification used to parse raw data received from the
3471/// endpoint or to encode data sent to the endpoint.
3472#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
3473pub struct FormatConfig {
3474    /// Format name, e.g., "csv", "json", "bincode", etc.
3475    pub name: Cow<'static, str>,
3476
3477    /// Format-specific parser or encoder configuration.
3478    #[serde(default)]
3479    #[schema(value_type = Object)]
3480    pub config: JsonValue,
3481}
3482
3483impl FormatConfig {
3484    /// Writes the Avro schema registry timeout, the one duration a format
3485    /// carries, in one spelling; see `ConnectorConfig::normalize_durations`.
3486    ///
3487    /// The format configuration stays raw JSON until the format parses it, so
3488    /// the timeout is read the way the format reads it and written back under
3489    /// the current key. A configuration the format would reject is left alone.
3490    pub fn normalize_durations(&mut self) {
3491        if self.name != "avro" {
3492            return;
3493        }
3494        let has_timeout = self.config.as_object().is_some_and(|object| {
3495            object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
3496        });
3497        if !has_timeout {
3498            return;
3499        }
3500        let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
3501            self.config.clone(),
3502        ) else {
3503            return;
3504        };
3505        let object = self.config.as_object_mut().unwrap();
3506        object.remove("registry_timeout_secs");
3507        match registry.registry_timeout {
3508            Some(timeout) => object.insert(
3509                "registry_timeout".to_string(),
3510                JsonValue::String(timeout.to_string()),
3511            ),
3512            None => object.remove("registry_timeout"),
3513        };
3514    }
3515}
3516
3517#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
3518#[serde(default)]
3519pub struct ResourceConfig {
3520    /// The minimum number of CPU cores to reserve
3521    /// for an instance of this pipeline
3522    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
3523    pub cpu_cores_min: Option<f64>,
3524
3525    /// The maximum number of CPU cores to reserve
3526    /// for an instance of this pipeline
3527    #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
3528    pub cpu_cores_max: Option<f64>,
3529
3530    /// The minimum memory in Megabytes to reserve
3531    /// for an instance of this pipeline
3532    pub memory_mb_min: Option<u64>,
3533
3534    /// The maximum memory in Megabytes to reserve
3535    /// for an instance of this pipeline
3536    pub memory_mb_max: Option<u64>,
3537
3538    /// The initial storage in Megabytes to reserve for an instance of this
3539    /// pipeline. Set together with `storage_mb_max` to enable storage
3540    /// autoscaling.
3541    #[serde(skip_serializing_if = "Option::is_none")]
3542    pub storage_mb_min: Option<u64>,
3543
3544    /// The maximum storage in Megabytes for an instance of this pipeline.
3545    ///
3546    /// Without `storage_mb_min`, this much storage is reserved up front.
3547    ///
3548    /// With `storage_mb_min`, storage starts there and autoscaling expands it
3549    /// up to this limit.
3550    pub storage_mb_max: Option<u64>,
3551
3552    /// Autoscaling policy for an instance of this pipeline.
3553    #[serde(skip_serializing_if = "Option::is_none")]
3554    pub autoscaling: Option<AutoscalingConfig>,
3555
3556    /// Storage class to use for an instance of this pipeline.
3557    /// The class determines storage performance such as IOPS and throughput.
3558    pub storage_class: Option<String>,
3559
3560    /// Kubernetes volume attributes class to use for the storage of an
3561    /// instance of this pipeline. The class sets mutable storage parameters
3562    /// such as IOPS and throughput. Requires Kubernetes 1.34 or later (or
3563    /// the `VolumeAttributesClass` feature gate) and CSI driver support.
3564    /// A change takes effect on the next start, also for existing storage.
3565    #[serde(skip_serializing_if = "Option::is_none")]
3566    pub volume_attributes_class: Option<String>,
3567
3568    /// Kubernetes service account name to use for an instance of this pipeline.
3569    /// The account determines permissions and access controls.
3570    pub service_account_name: Option<String>,
3571
3572    /// Kubernetes namespace to use for an instance of this pipeline.
3573    /// The namespace determines the scope of names for resources created
3574    /// for the pipeline.
3575    /// If not set, the pipeline will be deployed in the same namespace
3576    /// as the control-plane.
3577    // The type of this field should not be backward incompatibly changed, and its location in the
3578    // runtime configuration JSON (`runtime_config.resources.namespace`) should not be changed.
3579    pub namespace: Option<String>,
3580}
3581
3582/// Autoscaling policy for an instance of a pipeline.
3583#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
3584#[serde(default)]
3585pub struct AutoscalingConfig {
3586    /// Storage autoscaling policy.
3587    #[serde(skip_serializing_if = "Option::is_none")]
3588    pub storage: Option<StorageAutoscalingConfig>,
3589}
3590
3591/// Storage autoscaling policy: expand storage from `storage_mb_min` toward
3592/// `storage_mb_max` as it fills up.
3593#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
3594#[serde(default)]
3595pub struct StorageAutoscalingConfig {
3596    /// Usage fraction that triggers expansion. Defaults to 0.8.
3597    #[serde(
3598        deserialize_with = "crate::serde_via_value::deserialize",
3599        skip_serializing_if = "Option::is_none"
3600    )]
3601    pub scale_threshold: Option<f64>,
3602
3603    /// Expand storage when available space falls below this many MB, even if
3604    /// usage is still under `scale_threshold`. Either condition triggers
3605    /// expansion. Unset by default.
3606    #[serde(
3607        deserialize_with = "crate::serde_via_value::deserialize",
3608        skip_serializing_if = "Option::is_none"
3609    )]
3610    pub scale_threshold_available_mb: Option<u64>,
3611
3612    /// Expansion multiplier. Defaults to 2.0.
3613    #[serde(
3614        deserialize_with = "crate::serde_via_value::deserialize",
3615        skip_serializing_if = "Option::is_none"
3616    )]
3617    pub scale_factor: Option<f64>,
3618}
3619
3620#[cfg(test)]
3621mod resource_config_tests {
3622    use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
3623    use serde_json::json;
3624
3625    #[test]
3626    fn storage_autoscaling_round_trips_through_json() {
3627        let input = json!({
3628            "storage_mb_min": 1000,
3629            "storage_mb_max": 8000,
3630            "autoscaling": {
3631                "storage": {
3632                    "scale_threshold": 0.8,
3633                    "scale_threshold_available_mb": 10000,
3634                    "scale_factor": 2.0
3635                }
3636            }
3637        });
3638        let config: ResourceConfig = serde_json::from_value(input).unwrap();
3639        assert_eq!(config.storage_mb_min, Some(1000));
3640        assert_eq!(config.storage_mb_max, Some(8000));
3641        assert_eq!(
3642            config.autoscaling,
3643            Some(AutoscalingConfig {
3644                storage: Some(StorageAutoscalingConfig {
3645                    scale_threshold: Some(0.8),
3646                    scale_threshold_available_mb: Some(10000),
3647                    scale_factor: Some(2.0),
3648                }),
3649            })
3650        );
3651        let output = serde_json::to_value(&config).unwrap();
3652        assert_eq!(output["storage_mb_min"], json!(1000));
3653        assert_eq!(
3654            output["autoscaling"]["storage"]["scale_threshold"],
3655            json!(0.8)
3656        );
3657        assert_eq!(
3658            output["autoscaling"]["storage"]["scale_threshold_available_mb"],
3659            json!(10000)
3660        );
3661        assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
3662    }
3663
3664    #[test]
3665    fn autoscaling_fields_default_to_none() {
3666        let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
3667        assert_eq!(config.storage_mb_min, None);
3668        assert_eq!(config.autoscaling, None);
3669
3670        // Unset autoscaling fields stay out of the serialized config so they
3671        // do not clutter configs of users who never touch them.
3672        let output = serde_json::to_value(&config).unwrap();
3673        assert!(output.get("storage_mb_min").is_none());
3674        assert!(output.get("autoscaling").is_none());
3675        assert!(output.get("storage_mb_max").is_some());
3676
3677        // A partially set policy serializes only the fields the user set.
3678        let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
3679        let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
3680        let output = serde_json::to_value(&config).unwrap();
3681        assert_eq!(output["autoscaling"], input["autoscaling"]);
3682
3683        // A policy object with no storage section is accepted as-is.
3684        let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
3685        assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
3686    }
3687
3688    #[test]
3689    fn autoscaling_rejects_non_numeric_values() {
3690        let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
3691        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
3692        let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
3693        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
3694        let input = json!({ "storage_mb_min": -1 });
3695        assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
3696    }
3697}
3698
3699#[cfg(test)]
3700mod sync_config_tests {
3701    use super::SyncConfig;
3702
3703    fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
3704        SyncConfig {
3705            bucket: bucket.to_owned(),
3706            read_bucket: read_bucket.map(str::to_owned),
3707            ..Default::default()
3708        }
3709    }
3710
3711    #[test]
3712    fn read_bucket_must_differ_from_bucket() {
3713        let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
3714        assert!(err.contains("different locations"), "{err}");
3715    }
3716
3717    #[test]
3718    fn read_bucket_must_use_the_same_object_store() {
3719        let err = config("gs://ckpts/a", Some("ckpts/b"))
3720            .validate()
3721            .unwrap_err();
3722        assert!(err.contains("same object store"), "{err}");
3723        let err = config("ckpts/a", Some("gs://ckpts/b"))
3724            .validate()
3725            .unwrap_err();
3726        assert!(err.contains("same object store"), "{err}");
3727    }
3728
3729    #[test]
3730    fn matching_object_stores_are_accepted() {
3731        config("gs://ckpts/a", Some("gs://ckpts/b"))
3732            .validate()
3733            .unwrap();
3734        config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
3735        config("gs://ckpts/a", None).validate().unwrap();
3736    }
3737
3738    #[test]
3739    fn take_bucket_ownership_defaults_to_false() {
3740        let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
3741        assert!(!sync.take_bucket_ownership);
3742
3743        let sync: SyncConfig =
3744            serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
3745                .unwrap();
3746        assert!(sync.take_bucket_ownership);
3747    }
3748}