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