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