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