1use 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
57const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
59
60pub const fn default_max_queued_records() -> u64 {
62 1_000_000
63}
64
65pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
66
67pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
69
70pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
72
73pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
75
76pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
78
79fn 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#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
161pub struct ProgramIr {
162 pub mir: HashMap<MirNodeId, MirNode>,
164 pub program_schema: serde_json::Value,
166 #[serde(default)]
170 pub circuit_ir: Option<serde_json::Value>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub udf_library: Option<UdfLibrary>,
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
180pub struct UdfLibrary {
181 pub source_checksum: String,
183 pub integrity_checksum: String,
185}
186
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190pub struct PipelineIdentity {
191 pub name: String,
193 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#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
212pub struct PipelineConfig {
213 #[serde(flatten)]
215 #[schema(inline)]
216 pub global: RuntimeConfig,
217
218 pub multihost: Option<MultihostConfig>,
226
227 pub name: Option<String>,
233
234 pub given_name: Option<String>,
239
240 #[serde(default)]
246 pub storage_config: Option<StorageConfig>,
247
248 pub secrets_dir: Option<String>,
252
253 #[serde(default)]
255 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
256
257 #[serde(default)]
259 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
260
261 #[serde(default)]
263 pub program_ir: Option<ProgramIr>,
264}
265
266impl PipelineConfig {
267 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 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 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 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 pub fn display_summary(&self) -> String {
352 let endpoint = |stream: &str, connector: &ConnectorConfig| {
353 serde_json::json!({
354 "stream": stream,
355 "transport": connector.transport.name(),
356 "format": connector.format.as_ref().map(|format| format.name.as_ref()),
357 })
358 };
359 let inputs: BTreeMap<_, _> = self
360 .inputs
361 .iter()
362 .map(|(name, input)| (name, endpoint(&input.stream, &input.connector_config)))
363 .collect();
364 let outputs: BTreeMap<_, _> = self
365 .outputs
366 .iter()
367 .map(|(name, output)| (name, endpoint(&output.stream, &output.connector_config)))
368 .collect();
369
370 let summary = serde_json::json!({
371 "name": self.name,
372 "given_name": self.given_name,
373 "global": self.global.display_summary(),
374 "storage_config": self.storage_config,
375 "secrets_dir": self.secrets_dir,
376 "inputs": inputs,
377 "outputs": outputs
378 });
379
380 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
381 }
382}
383
384#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
392pub struct PipelineConfigProgramInfo {
393 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
395
396 #[serde(default)]
398 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
399
400 #[serde(default)]
402 pub program_ir: Option<ProgramIr>,
403}
404
405#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
409pub struct MultihostConfig {
410 pub hosts: usize,
416}
417
418impl Default for MultihostConfig {
419 fn default() -> Self {
420 Self { hosts: 1 }
421 }
422}
423
424#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
426pub struct StorageConfig {
427 pub path: String,
436
437 #[serde(default)]
439 pub cache: StorageCacheConfig,
440}
441
442impl StorageConfig {
443 pub fn path(&self) -> &Path {
444 Path::new(&self.path)
445 }
446}
447
448#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
450#[serde(rename_all = "snake_case")]
451pub enum StorageCacheConfig {
452 #[default]
457 PageCache,
458
459 FelderaCache,
464}
465
466impl StorageCacheConfig {
467 #[cfg(unix)]
468 pub fn to_custom_open_flags(&self) -> i32 {
469 match self {
470 StorageCacheConfig::PageCache => (),
471 StorageCacheConfig::FelderaCache => {
472 #[cfg(target_os = "linux")]
473 return libc::O_DIRECT;
474 }
475 }
476 0
477 }
478}
479
480#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
482#[serde(default)]
483pub struct StorageOptions {
484 pub backend: StorageBackendConfig,
486
487 #[serde(
501 alias = "min_storage_bytes",
502 deserialize_with = "size_min_spill_size",
503 skip_serializing_if = "Option::is_none"
504 )]
505 #[schema(value_type = Option<String>)]
506 pub min_spill_size: Option<ConfigSize>,
507
508 #[serde(
522 alias = "min_step_storage_bytes",
523 deserialize_with = "size_min_step_spill_size",
524 skip_serializing_if = "Option::is_none"
525 )]
526 #[schema(value_type = Option<String>)]
527 pub min_step_spill_size: Option<ConfigSize>,
528
529 pub compression: StorageCompression,
535
536 pub compression_level: Option<i32>,
547
548 #[serde(
557 alias = "cache_mib",
558 deserialize_with = "size_cache_size",
559 skip_serializing_if = "Option::is_none"
560 )]
561 #[schema(value_type = Option<String>)]
562 pub cache_size: Option<ConfigSize>,
563
564 #[serde(skip_serializing_if = "Option::is_none")]
579 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
580 pub bloom_false_positive_rate: Option<f64>,
581}
582
583impl Eq for StorageOptions {}
586
587#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
589#[serde(tag = "name", content = "config", rename_all = "snake_case")]
590pub enum StorageBackendConfig {
591 #[default]
595 Default,
596
597 File(Box<FileBackendConfig>),
601
602 Object(ObjectStorageConfig),
604}
605
606impl Display for StorageBackendConfig {
607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 match self {
609 StorageBackendConfig::Default => write!(f, "default"),
610 StorageBackendConfig::File(_) => write!(f, "file"),
611 StorageBackendConfig::Object(_) => write!(f, "object"),
612 }
613 }
614}
615
616#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
618#[serde(rename_all = "snake_case")]
619pub enum StorageCompression {
620 #[default]
625 Default,
626
627 None,
629
630 Snappy,
632
633 Lz4,
638
639 Zstd,
645}
646
647#[derive(Debug, Clone, Eq, PartialEq)]
648pub enum StartFromCheckpoint {
649 Latest,
650 Uuid(uuid::Uuid),
651}
652
653impl ToSchema<'_> for StartFromCheckpoint {
654 fn schema() -> (
655 &'static str,
656 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
657 ) {
658 (
659 "StartFromCheckpoint",
660 utoipa::openapi::RefOr::T(Schema::OneOf(
661 OneOfBuilder::new()
662 .item(
663 ObjectBuilder::new()
664 .schema_type(SchemaType::String)
665 .enum_values(Some(["latest"].into_iter()))
666 .build(),
667 )
668 .item(
669 ObjectBuilder::new()
670 .schema_type(SchemaType::String)
671 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
672 utoipa::openapi::KnownFormat::Uuid,
673 )))
674 .build(),
675 )
676 .nullable(true)
677 .build(),
678 )),
679 )
680 }
681}
682
683impl<'de> Deserialize<'de> for StartFromCheckpoint {
684 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
685 where
686 D: Deserializer<'de>,
687 {
688 struct StartFromCheckpointVisitor;
689
690 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
691 type Value = StartFromCheckpoint;
692
693 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
694 formatter.write_str("a UUID string or the string \"latest\"")
695 }
696
697 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
698 where
699 E: de::Error,
700 {
701 if value == "latest" {
702 Ok(StartFromCheckpoint::Latest)
703 } else {
704 uuid::Uuid::parse_str(value)
705 .map(StartFromCheckpoint::Uuid)
706 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
707 }
708 }
709 }
710
711 deserializer.deserialize_str(StartFromCheckpointVisitor)
712 }
713}
714
715impl Serialize for StartFromCheckpoint {
716 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
717 where
718 S: serde::Serializer,
719 {
720 match self {
721 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
722 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
723 }
724 }
725}
726
727#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
728pub struct SyncConfig {
729 pub endpoint: Option<String>,
742
743 pub bucket: String,
757
758 pub region: Option<String>,
762
763 pub provider: Option<String>,
770
771 pub access_key: Option<String>,
779
780 pub secret_key: Option<String>,
790
791 pub start_from_checkpoint: Option<StartFromCheckpoint>,
796
797 #[schema(default = std::primitive::bool::default)]
803 #[serde(default)]
804 pub fail_if_no_checkpoint: bool,
805
806 pub transfers: Option<u8>,
809
810 pub checkers: Option<u8>,
813
814 pub ignore_checksum: Option<bool>,
818
819 pub multi_thread_streams: Option<u8>,
822
823 pub multi_thread_cutoff: Option<String>,
828
829 #[schema(default = default_optimize_download_resources)]
840 #[serde(default = "default_optimize_download_resources")]
841 pub optimize_download_resources: bool,
842
843 pub upload_concurrency: Option<u8>,
846
847 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
849 #[schema(default = std::primitive::bool::default)]
850 #[serde(default)]
851 pub standby: bool,
852
853 #[serde(
859 default,
860 alias = "pull_interval",
861 deserialize_with = "duration_standby_pull_interval",
862 skip_serializing_if = "Option::is_none"
863 )]
864 #[schema(value_type = Option<String>, default = default_pull_interval)]
865 pub standby_pull_interval: Option<ConfigDuration>,
866
867 #[serde(
873 default,
874 alias = "push_interval",
875 deserialize_with = "duration_checkpoint_push_interval",
876 skip_serializing_if = "Option::is_none"
877 )]
878 #[schema(value_type = Option<String>)]
879 pub checkpoint_push_interval: Option<ConfigDuration>,
880
881 pub flags: Option<Vec<String>>,
890
891 #[schema(default = default_retention_min_count)]
896 #[serde(default = "default_retention_min_count")]
897 pub retention_min_count: u32,
898
899 #[serde(
903 default,
904 alias = "retention_min_age",
905 deserialize_with = "duration_min_retention",
906 skip_serializing_if = "Option::is_none"
907 )]
908 #[schema(value_type = Option<String>, default = default_retention_min_age)]
909 pub min_retention: Option<ConfigDuration>,
910
911 #[serde(default)]
925 pub read_bucket: Option<String>,
926
927 #[schema(default = std::primitive::bool::default)]
953 #[serde(default)]
954 pub take_bucket_ownership: bool,
955}
956
957fn default_retention_min_count() -> u32 {
958 10
959}
960
961fn default_optimize_download_resources() -> bool {
962 true
963}
964
965impl SyncConfig {
966 pub fn standby_pull_interval(&self) -> ConfigDuration {
973 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
974 }
975
976 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
978 self.checkpoint_push_interval
979 }
980
981 pub fn min_retention(&self) -> ConfigDuration {
984 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
985 }
986
987 pub fn validate(&self) -> Result<(), String> {
988 #[allow(deprecated)]
989 if self.standby {
990 return Err(
991 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
992 );
993 }
994
995 if let Some(ref rb) = self.read_bucket {
996 if rb == &self.bucket {
997 return Err(
998 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
999 .to_owned(),
1000 );
1001 }
1002 if SyncObjectStore::of(rb) != SyncObjectStore::of(&self.bucket) {
1005 return Err(format!(
1006 "invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage, both with `az://` for Azure Blob Storage, or neither for S3",
1007 self.bucket, rb
1008 ));
1009 }
1010 }
1011
1012 if SyncObjectStore::of(&self.bucket) == SyncObjectStore::AzureBlob
1015 && self.access_key.as_deref().is_none_or(str::is_empty)
1016 {
1017 return Err(format!(
1018 "invalid sync config: `bucket` ('{}') is in Azure Blob Storage, which needs the name of the storage account; set `access_key` to it",
1019 self.bucket
1020 ));
1021 }
1022
1023 for (field, bucket) in [
1024 ("bucket", Some(&self.bucket)),
1025 ("read_bucket", self.read_bucket.as_ref()),
1026 ] {
1027 if let Some(bucket) = bucket
1028 && azure_container(bucket) == Some("")
1029 {
1030 return Err(format!(
1031 "invalid sync config: `{field}` ('{bucket}') does not name a container; write it as `az://<container>[/<path>]`"
1032 ));
1033 }
1034 }
1035
1036 Ok(())
1037 }
1038}
1039
1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1042enum SyncObjectStore {
1043 S3,
1044 Gcs,
1045 AzureBlob,
1046}
1047
1048impl SyncObjectStore {
1049 fn of(bucket: &str) -> Self {
1050 if bucket.starts_with("gs://") {
1051 Self::Gcs
1052 } else if bucket.starts_with("az://") {
1053 Self::AzureBlob
1054 } else {
1055 Self::S3
1056 }
1057 }
1058}
1059
1060fn azure_container(bucket: &str) -> Option<&str> {
1063 let path = bucket.strip_prefix("az://")?;
1064 Some(path.split('/').next().unwrap_or_default())
1065}
1066
1067#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1103pub struct PipelineTemplateConfig {
1104 pub name: String,
1106 #[schema(default = default_pipeline_template_key)]
1110 #[serde(default = "default_pipeline_template_key")]
1111 pub key: String,
1112}
1113
1114fn default_pipeline_template_key() -> String {
1115 "pipelineTemplate".to_string()
1116}
1117
1118#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1119pub struct ObjectStorageConfig {
1120 pub url: String,
1149
1150 #[serde(flatten)]
1183 pub other_options: BTreeMap<String, String>,
1184}
1185
1186#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1188#[serde(default)]
1189pub struct FileBackendConfig {
1190 pub async_threads: Option<bool>,
1196
1197 #[serde(
1202 default,
1203 alias = "ioop_delay",
1204 deserialize_with = "duration_ioop_latency",
1205 skip_serializing_if = "Option::is_none"
1206 )]
1207 #[schema(value_type = Option<String>)]
1208 pub ioop_latency: Option<ConfigDuration>,
1209
1210 pub sync: Option<SyncConfig>,
1212
1213 pub sync_mode: Option<StorageSyncMode>,
1218}
1219
1220#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1226#[serde(rename_all = "snake_case")]
1227pub enum StorageSyncMode {
1228 #[default]
1231 Auto,
1232
1233 Syncfs,
1243
1244 PerFile,
1249}
1250
1251#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1254#[serde(default)]
1255pub struct RuntimeConfig {
1256 pub workers: u16,
1266
1267 #[serde(
1296 default,
1297 alias = "max_rss_mb",
1298 deserialize_with = "size_max_rss",
1299 skip_serializing_if = "Option::is_none"
1300 )]
1301 #[schema(value_type = Option<String>)]
1302 pub max_rss: Option<ConfigSize>,
1303
1304 #[serde(
1327 default,
1328 alias = "datafusion_memory_mb",
1329 deserialize_with = "size_datafusion_memory",
1330 skip_serializing_if = "Option::is_none"
1331 )]
1332 #[schema(value_type = Option<String>)]
1333 pub datafusion_memory: Option<ConfigSize>,
1334
1335 pub hosts: usize,
1342
1343 #[serde(deserialize_with = "deserialize_storage_options")]
1355 pub storage: Option<StorageOptions>,
1356
1357 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1359 pub fault_tolerance: FtConfig,
1360
1361 pub cpu_profiler: bool,
1365
1366 pub tracing: bool,
1368
1369 pub tracing_endpoint_jaeger: String,
1371
1372 pub min_batch_size_records: u64,
1380
1381 #[serde(
1384 default,
1385 alias = "max_buffering_delay_usecs",
1386 deserialize_with = "duration_max_buffering_delay",
1387 skip_serializing_if = "Option::is_none"
1388 )]
1389 #[schema(value_type = Option<String>)]
1390 pub max_buffering_delay: Option<ConfigDuration>,
1391
1392 pub resources: ResourceConfig,
1395
1396 #[serde(
1406 default,
1407 alias = "clock_resolution_usecs",
1408 deserialize_with = "duration_clock_resolution",
1409 skip_serializing_if = "Option::is_none"
1410 )]
1411 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1412 pub clock_resolution: Option<ConfigDuration>,
1413
1414 #[schema(value_type = Option<String>, example = "+05:30")]
1425 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1426
1427 pub pin_cpus: Vec<usize>,
1436
1437 #[serde(
1440 default,
1441 alias = "provisioning_timeout_secs",
1442 deserialize_with = "duration_provisioning_timeout",
1443 skip_serializing_if = "Option::is_none"
1444 )]
1445 #[schema(value_type = Option<String>)]
1446 pub provisioning_timeout: Option<ConfigDuration>,
1447
1448 pub max_parallel_connector_init: Option<u64>,
1459
1460 pub init_containers: Option<serde_json::Value>,
1462
1463 pub checkpoint_during_suspend: bool,
1465
1466 pub http_workers: Option<u64>,
1474
1475 pub io_workers: Option<u64>,
1486
1487 #[serde(default)]
1494 pub env: BTreeMap<String, String>,
1495
1496 pub dev_tweaks: DevTweaks,
1498
1499 pub logging: Option<String>,
1508
1509 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1517}
1518
1519fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1521where
1522 D: Deserializer<'de>,
1523{
1524 struct BoolOrStruct;
1525
1526 impl<'de> Visitor<'de> for BoolOrStruct {
1527 type Value = Option<StorageOptions>;
1528
1529 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1530 formatter.write_str("boolean or StorageOptions")
1531 }
1532
1533 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1534 where
1535 E: de::Error,
1536 {
1537 match v {
1538 false => Ok(None),
1539 true => Ok(Some(StorageOptions::default())),
1540 }
1541 }
1542
1543 fn visit_unit<E>(self) -> Result<Self::Value, E>
1544 where
1545 E: de::Error,
1546 {
1547 Ok(None)
1548 }
1549
1550 fn visit_none<E>(self) -> Result<Self::Value, E>
1551 where
1552 E: de::Error,
1553 {
1554 Ok(None)
1555 }
1556
1557 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1558 where
1559 M: MapAccess<'de>,
1560 {
1561 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1562 }
1563 }
1564
1565 deserializer.deserialize_any(BoolOrStruct)
1566}
1567
1568fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1576where
1577 D: Deserializer<'de>,
1578{
1579 struct StringOrStruct;
1580
1581 impl<'de> Visitor<'de> for StringOrStruct {
1582 type Value = FtConfig;
1583
1584 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1585 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1586 }
1587
1588 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1589 where
1590 E: de::Error,
1591 {
1592 match v {
1593 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1594 model: Some(FtModel::default()),
1595 ..FtConfig::default()
1596 }),
1597 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1598 }
1599 }
1600
1601 fn visit_unit<E>(self) -> Result<Self::Value, E>
1602 where
1603 E: de::Error,
1604 {
1605 Ok(FtConfig::default())
1606 }
1607
1608 fn visit_none<E>(self) -> Result<Self::Value, E>
1609 where
1610 E: de::Error,
1611 {
1612 Ok(FtConfig::default())
1613 }
1614
1615 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1616 where
1617 M: MapAccess<'de>,
1618 {
1619 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1620 }
1621 }
1622
1623 deserializer.deserialize_any(StringOrStruct)
1624}
1625
1626const RUNTIME_CONFIG_SUMMARY_FIELDS: &[&str] = &[
1630 "workers",
1631 "hosts",
1632 "max_rss",
1633 "datafusion_memory",
1634 "fault_tolerance",
1635 "cpu_profiler",
1636 "tracing",
1637 "min_batch_size_records",
1638 "max_buffering_delay",
1639 "resources",
1640 "clock_resolution",
1641 "clock_timezone_offset",
1642 "pin_cpus",
1643 "provisioning_timeout",
1644 "max_parallel_connector_init",
1645 "checkpoint_during_suspend",
1646 "http_workers",
1647 "io_workers",
1648 "dev_tweaks",
1649 "logging",
1650];
1651
1652impl RuntimeConfig {
1653 pub fn display_summary(&self) -> serde_json::Value {
1658 let mut summary = serde_json::Map::new();
1659 if let Ok(serde_json::Value::Object(fields)) = serde_json::to_value(self) {
1660 for (name, value) in fields {
1661 if RUNTIME_CONFIG_SUMMARY_FIELDS.contains(&name.as_str()) {
1662 summary.insert(name, value);
1663 }
1664 }
1665 }
1666 summary.insert(
1667 "storage".to_string(),
1668 serde_json::json!(self.storage.as_ref().map(|storage| {
1669 serde_json::json!({
1670 "backend": storage.backend.to_string(),
1671 "min_spill_size": storage.min_spill_size,
1672 })
1673 })),
1674 );
1675 summary.insert(
1676 "env".to_string(),
1677 serde_json::json!(self.env.keys().collect::<Vec<_>>()),
1678 );
1679 serde_json::Value::Object(summary)
1680 }
1681}
1682
1683impl Default for RuntimeConfig {
1684 fn default() -> Self {
1685 Self {
1686 workers: 8,
1687 max_rss: None,
1688 datafusion_memory: None,
1689 hosts: 1,
1690 storage: Some(StorageOptions::default()),
1691 fault_tolerance: FtConfig::default(),
1692 cpu_profiler: true,
1693 tracing: {
1694 false
1697 },
1698 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1699 min_batch_size_records: 0,
1700 max_buffering_delay: None,
1701 resources: ResourceConfig::default(),
1702 clock_resolution: None,
1703 clock_timezone_offset: None,
1704 pin_cpus: Vec::new(),
1705 provisioning_timeout: None,
1706 max_parallel_connector_init: None,
1707 init_containers: None,
1708 checkpoint_during_suspend: true,
1709 io_workers: None,
1710 http_workers: None,
1711 env: BTreeMap::default(),
1712 dev_tweaks: DevTweaks::default(),
1713 logging: None,
1714 pipeline_template_configmap: None,
1715 }
1716 }
1717}
1718
1719pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1723
1724pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1727
1728impl RuntimeConfig {
1729 pub fn max_buffering_delay(&self) -> ConfigDuration {
1731 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1732 }
1733
1734 pub fn clock_resolution(&self) -> ConfigDuration {
1736 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1737 }
1738
1739 pub fn effective_memory(&self) -> Option<ConfigSize> {
1742 self.max_rss
1743 .into_iter()
1744 .chain(self.resources.memory_max)
1745 .min()
1746 }
1747
1748 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1753 if let Some(explicit) = self.datafusion_memory {
1754 return Some(explicit);
1755 }
1756 let effective = self.effective_memory()?.as_bytes();
1757 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1759 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1760 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1761 }
1762
1763 pub fn datafusion_memory_exceeding_budget(&self) -> Option<(ConfigSize, ConfigSize)> {
1766 let budget = self.effective_memory()?;
1767 let datafusion = self.resolved_datafusion_memory()?;
1768 (datafusion >= budget).then_some((datafusion, budget))
1769 }
1770}
1771
1772#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1783#[serde(rename_all = "snake_case")]
1784pub struct FtConfig {
1785 #[serde(with = "none_as_string")]
1787 #[serde(default = "default_model")]
1788 #[schema(
1789 schema_with = none_as_string_schema::<FtModel>,
1790 )]
1791 pub model: Option<FtModel>,
1792
1793 #[serde(
1800 default,
1801 alias = "checkpoint_interval_secs",
1802 deserialize_with = "duration_checkpoint_interval",
1803 skip_serializing_if = "Option::is_none"
1804 )]
1805 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1806 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1807}
1808
1809fn default_model() -> Option<FtModel> {
1810 Some(FtModel::default())
1811}
1812
1813pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1833 use crate::duration::LegacyUnit;
1834 use serde_json::{Map, Value};
1835
1836 struct Rule {
1838 new: &'static str,
1839 old: &'static str,
1840 unit: LegacyUnit,
1841 max: u64,
1843 null_allowed: bool,
1846 }
1847 const fn rule(
1848 new: &'static str,
1849 old: &'static str,
1850 unit: LegacyUnit,
1851 max: u64,
1852 null_allowed: bool,
1853 ) -> Rule {
1854 Rule {
1855 new,
1856 old,
1857 unit,
1858 max,
1859 null_allowed,
1860 }
1861 }
1862 const U32: u64 = u32::MAX as u64;
1863 const U64: u64 = u64::MAX;
1864 use LegacyUnit::{Days, Micros, Millis, Secs};
1865
1866 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1867 for rule in rules {
1868 let Some(value) = object.remove(rule.new) else {
1869 continue;
1870 };
1871 let legacy = match &value {
1872 Value::String(text) => match text.parse::<ConfigDuration>() {
1873 Ok(duration) => {
1874 let nanos = std::time::Duration::from(duration).as_nanos();
1875 let unit_nanos = u128::from(rule.unit.nanos());
1876 let whole = nanos.div_ceil(unit_nanos);
1877 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1878 }
1879 Err(_) => {
1880 object.insert(rule.new.to_string(), value);
1881 continue;
1882 }
1883 },
1884 Value::Null if !rule.null_allowed => continue,
1885 other => other.clone(),
1887 };
1888 object.insert(rule.old.to_string(), legacy);
1889 }
1890 }
1891 fn child<'a>(
1892 object: &'a mut Map<String, Value>,
1893 key: &str,
1894 ) -> Option<&'a mut Map<String, Value>> {
1895 object.get_mut(key).and_then(Value::as_object_mut)
1896 }
1897 fn max_expiry(consumer: &mut Map<String, Value>) {
1900 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1901 return;
1902 };
1903 let Ok(duration) = text.parse::<ConfigDuration>() else {
1904 return;
1905 };
1906 let duration = std::time::Duration::from(duration);
1907 consumer.remove("max_expiry");
1908 consumer.insert(
1909 "max_expires".to_string(),
1910 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1911 );
1912 }
1913 fn nats_connection(transport: &mut Map<String, Value>) {
1915 if let Some(connection) = child(transport, "connection_config") {
1916 apply(
1917 connection,
1918 &[
1919 rule(
1920 "connection_timeout",
1921 "connection_timeout_secs",
1922 Secs,
1923 U64,
1924 false,
1925 ),
1926 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1927 ],
1928 );
1929 }
1930 }
1931 fn connector(endpoint: &mut Map<String, Value>) {
1933 apply(
1934 endpoint,
1935 &[rule(
1936 "max_output_buffer_time",
1937 "max_output_buffer_time_millis",
1938 Millis,
1939 U64,
1940 false,
1941 )],
1942 );
1943 let name = endpoint
1944 .get("transport")
1945 .and_then(|transport| transport.get("name"))
1946 .and_then(Value::as_str)
1947 .map(str::to_string);
1948 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1949 match name.as_deref() {
1950 Some("url_input") => apply(
1951 transport,
1952 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1953 ),
1954 Some("kafka_input") => apply(
1955 transport,
1956 &[rule(
1957 "group_join_timeout",
1958 "group_join_timeout_secs",
1959 Secs,
1960 U32,
1961 false,
1962 )],
1963 ),
1964 Some("kafka_output") => apply(
1965 transport,
1966 &[rule(
1967 "initialization_timeout",
1968 "initialization_timeout_secs",
1969 Secs,
1970 U32,
1971 false,
1972 )],
1973 ),
1974 Some("clock_input") => apply(
1975 transport,
1976 &[rule(
1977 "clock_resolution",
1978 "clock_resolution_usecs",
1979 Micros,
1980 U64,
1981 false,
1982 )],
1983 ),
1984 Some("pub_sub_input") => apply(
1985 transport,
1986 &[
1987 rule("timeout", "timeout_seconds", Secs, U32, true),
1988 rule(
1989 "connect_timeout",
1990 "connect_timeout_seconds",
1991 Secs,
1992 U32,
1993 true,
1994 ),
1995 ],
1996 ),
1997 Some("nats_input") => {
1998 apply(
1999 transport,
2000 &[
2001 rule(
2002 "inactivity_timeout",
2003 "inactivity_timeout_secs",
2004 Secs,
2005 U64,
2006 false,
2007 ),
2008 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
2009 ],
2010 );
2011 nats_connection(transport);
2012 if let Some(consumer) = child(transport, "consumer_config") {
2013 max_expiry(consumer);
2014 }
2015 }
2016 Some("nats_output") => {
2017 apply(
2018 transport,
2019 &[rule(
2020 "publish_timeout",
2021 "publish_timeout_secs",
2022 Secs,
2023 U64,
2024 false,
2025 )],
2026 );
2027 nats_connection(transport);
2028 }
2029 _ => {}
2030 }
2031 }
2032 let is_avro = endpoint
2033 .get("format")
2034 .and_then(|format| format.get("name"))
2035 .and_then(Value::as_str)
2036 == Some("avro");
2037 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
2038 {
2039 apply(
2040 format,
2041 &[rule(
2042 "registry_timeout",
2043 "registry_timeout_secs",
2044 Secs,
2045 U64,
2046 true,
2047 )],
2048 );
2049 }
2050 }
2051
2052 let Some(global) = config.as_object_mut() else {
2053 return;
2054 };
2055 apply(
2056 global,
2057 &[
2058 rule(
2059 "clock_resolution",
2060 "clock_resolution_usecs",
2061 Micros,
2062 U64,
2063 true,
2064 ),
2065 rule(
2066 "max_buffering_delay",
2067 "max_buffering_delay_usecs",
2068 Micros,
2069 U64,
2070 false,
2071 ),
2072 rule(
2073 "provisioning_timeout",
2074 "provisioning_timeout_secs",
2075 Secs,
2076 U64,
2077 true,
2078 ),
2079 ],
2080 );
2081 if let Some(ft) = child(global, "fault_tolerance") {
2082 apply(
2084 ft,
2085 &[rule(
2086 "checkpoint_interval",
2087 "checkpoint_interval_secs",
2088 Secs,
2089 U64,
2090 true,
2091 )],
2092 );
2093 }
2094 let backend = child(global, "storage")
2095 .and_then(|storage| child(storage, "backend"))
2096 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
2097 .and_then(|backend| child(backend, "config"));
2098 if let Some(file) = backend {
2099 apply(
2100 file,
2101 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
2102 );
2103 if let Some(sync) = child(file, "sync") {
2104 apply(
2105 sync,
2106 &[
2107 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
2108 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
2109 rule("min_retention", "retention_min_age", Days, U32, false),
2110 ],
2111 );
2112 }
2113 }
2114 for endpoints in ["inputs", "outputs"] {
2115 if let Some(endpoints) = child(global, endpoints) {
2116 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2117 connector(endpoint);
2118 }
2119 }
2120 }
2121}
2122
2123#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2129pub struct LegacySpelling {
2130 pub durations: bool,
2132 pub sizes: bool,
2134}
2135
2136impl LegacySpelling {
2137 pub const NONE: LegacySpelling = LegacySpelling {
2139 durations: false,
2140 sizes: false,
2141 };
2142
2143 pub fn any(self) -> bool {
2145 self.durations || self.sizes
2146 }
2147
2148 pub fn apply(self, config: &mut serde_json::Value) {
2151 if self.durations {
2152 to_legacy_duration_spelling(config);
2153 }
2154 if self.sizes {
2155 to_legacy_size_spelling(config);
2156 }
2157 }
2158}
2159
2160pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
2171 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
2172 use serde_json::{Map, Value};
2173
2174 struct Rule {
2176 new: &'static str,
2177 old: &'static str,
2178 unit: LegacySizeUnit,
2179 }
2180 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2181 Rule { new, old, unit }
2182 }
2183
2184 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2185 for rule in rules {
2186 let Some(value) = object.remove(rule.new) else {
2187 continue;
2188 };
2189 let legacy = match &value {
2190 Value::String(text) => match text.parse::<ConfigSize>() {
2191 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2192 Err(_) => {
2193 object.insert(rule.new.to_string(), value);
2194 continue;
2195 }
2196 },
2197 Value::Null => continue,
2199 other => other.clone(),
2201 };
2202 object.insert(rule.old.to_string(), legacy);
2203 }
2204 }
2205 fn child<'a>(
2206 object: &'a mut Map<String, Value>,
2207 key: &str,
2208 ) -> Option<&'a mut Map<String, Value>> {
2209 object.get_mut(key).and_then(Value::as_object_mut)
2210 }
2211 fn connector(endpoint: &mut Map<String, Value>) {
2213 apply(
2214 endpoint,
2215 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2216 );
2217 let name = endpoint
2218 .get("transport")
2219 .and_then(|transport| transport.get("name"))
2220 .and_then(Value::as_str)
2221 .map(str::to_string);
2222 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2223 match name.as_deref() {
2224 Some("file_input") => apply(
2225 transport,
2226 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2227 ),
2228 Some("dynamodb_output" | "postgres_output") => apply(
2229 transport,
2230 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2231 ),
2232 Some("postgres_cdc_input") => {
2233 if let Some(batch) = child(transport, "batch") {
2234 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2235 }
2236 }
2237 _ => {}
2238 }
2239 }
2240 }
2241
2242 let Some(global) = config.as_object_mut() else {
2243 return;
2244 };
2245 apply(
2246 global,
2247 &[
2248 rule("max_rss", "max_rss_mb", Megabytes),
2249 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2250 ],
2251 );
2252 if let Some(storage) = child(global, "storage") {
2253 apply(
2254 storage,
2255 &[
2256 rule("cache_size", "cache_mib", Mebibytes),
2257 rule("min_spill_size", "min_storage_bytes", Bytes),
2258 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2259 ],
2260 );
2261 }
2262 if let Some(resources) = child(global, "resources") {
2263 apply(
2264 resources,
2265 &[
2266 rule("memory_min", "memory_mb_min", Megabytes),
2267 rule("memory_max", "memory_mb_max", Megabytes),
2268 rule("storage_min", "storage_mb_min", Megabytes),
2269 rule("storage_max", "storage_mb_max", Megabytes),
2270 ],
2271 );
2272 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2273 apply(
2274 storage,
2275 &[rule(
2276 "scale_threshold_available",
2277 "scale_threshold_available_mb",
2278 Megabytes,
2279 )],
2280 );
2281 }
2282 }
2283 if let Some(tweaks) = child(global, "dev_tweaks") {
2284 apply(
2285 tweaks,
2286 &[
2287 rule("storage_max", "storage_mb_max", Mebibytes),
2288 rule(
2289 "fbuf_slab_size_per_class",
2290 "fbuf_slab_bytes_per_class",
2291 Bytes,
2292 ),
2293 rule(
2294 "lazy_input_map_key_block_size",
2295 "lazy_input_map_key_block_bytes",
2296 Bytes,
2297 ),
2298 rule(
2299 "exchange_channel_capacity",
2300 "exchange_channel_capacity_bytes",
2301 Bytes,
2302 ),
2303 ],
2304 );
2305 }
2306 for endpoints in ["inputs", "outputs"] {
2307 if let Some(endpoints) = child(global, endpoints) {
2308 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2309 connector(endpoint);
2310 }
2311 }
2312 }
2313}
2314
2315#[cfg(test)]
2316mod test {
2317 use super::deserialize_fault_tolerance;
2318
2319 use crate::config::{
2320 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2321 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2322 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2323 StorageOptions, SyncConfig, TransportConfig,
2324 };
2325 use crate::duration::ConfigDuration;
2326 use crate::size::ConfigSize;
2327 use serde::{Deserialize, Serialize};
2328 use serde_json::json;
2329 use std::time::Duration;
2330
2331 fn assert_reloads<T>(value: serde_json::Value)
2334 where
2335 T: Serialize + for<'de> Deserialize<'de>,
2336 {
2337 let first: T = serde_json::from_value(value.clone())
2338 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2339 let written = serde_json::to_value(&first).unwrap();
2340 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2341 panic!("{value} is written as {written}, which does not load: {e}")
2342 });
2343 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2344 }
2345
2346 #[test]
2351 fn size_settings_reload_from_what_is_written() {
2352 use crate::transport::dynamodb::DynamoDBWriterConfig;
2353 use crate::transport::file::FileInputConfig;
2354 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2355
2356 for number in [0u64, 1, 1_100, u64::MAX] {
2359 assert_reloads::<RuntimeConfig>(json!({
2360 "max_rss_mb": number,
2361 "datafusion_memory_mb": number,
2362 "storage": {"cache_mib": number, "min_storage_bytes": number},
2363 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2364 "dev_tweaks": {"storage_mb_max": number},
2365 }));
2366 }
2367
2368 let max = format!("{}B", u64::MAX);
2369 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2370 assert_reloads::<RuntimeConfig>(json!({
2371 "max_rss": size,
2372 "datafusion_memory": size,
2373 "storage": {
2374 "cache_size": size,
2375 "min_spill_size": size,
2376 "min_step_spill_size": size,
2377 },
2378 "resources": {
2379 "memory_min": size,
2380 "memory_max": size,
2381 "storage_min": size,
2382 "storage_max": size,
2383 "autoscaling": {"storage": {"scale_threshold_available": size}},
2384 },
2385 "dev_tweaks": {
2386 "storage_max": size,
2387 "fbuf_slab_size_per_class": size,
2388 "exchange_channel_capacity": size,
2389 },
2390 }));
2391 assert_reloads::<ConnectorConfig>(json!({
2392 "transport": {
2393 "name": "file_input",
2394 "config": {"path": "input.csv", "buffer_size": size},
2395 },
2396 "max_queued_size": size,
2397 }));
2398 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2399 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2400 assert_reloads::<PostgresWriterConfig>(json!({
2401 "uri": "postgres://localhost/db",
2402 "table": "t",
2403 "max_buffer_size": size,
2404 }));
2405 assert_reloads::<DynamoDBWriterConfig>(json!({
2406 "table": "t",
2407 "region": "us-east-1",
2408 "max_buffer_size": size,
2409 }));
2410 }
2411 }
2412
2413 #[test]
2418 fn soft_delete_is_backward_compatible() {
2419 let config: ConnectorConfig = serde_json::from_value(json!({
2420 "transport": {"name": "empty_input"}
2421 }))
2422 .unwrap();
2423 assert!(!config.soft_delete);
2424
2425 let serialized = serde_json::to_value(&config).unwrap();
2426 assert_eq!(serialized.get("soft_delete"), None);
2427
2428 let config: ConnectorConfig = serde_json::from_value(json!({
2429 "transport": {"name": "empty_input"},
2430 "soft_delete": true
2431 }))
2432 .unwrap();
2433 assert!(config.soft_delete);
2434 assert_eq!(
2435 serde_json::to_value(&config).unwrap().get("soft_delete"),
2436 Some(&json!(true))
2437 );
2438 }
2439
2440 #[test]
2443 fn soft_delete_invalidates_checkpointed_connector_state() {
2444 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2445 let mut soft_delete = config.clone();
2446 soft_delete.soft_delete = true;
2447
2448 assert!(config.equal_for_input_checkpoint_replay(&config));
2449 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2450 }
2451
2452 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2453 PipelineConfig {
2454 global: RuntimeConfig::default(),
2455 multihost: None,
2456 name: name.map(str::to_string),
2457 given_name: None,
2458 storage_config: None,
2459 secrets_dir: None,
2460 inputs: Default::default(),
2461 outputs: Default::default(),
2462 program_ir: None,
2463 }
2464 }
2465
2466 #[test]
2467 fn pipeline_identity_uses_system_and_given_names() {
2468 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2469 config.given_name = Some("my-pipeline".to_string());
2470
2471 let metadata = config.pipeline_identity().unwrap();
2472 assert_eq!(
2473 metadata.name,
2474 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2475 );
2476 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2477 }
2478
2479 #[test]
2480 fn pipeline_identity_is_none_without_system_name() {
2481 assert_eq!(config_with_name(None).pipeline_identity(), None);
2482 }
2483
2484 #[test]
2485 fn resolved_datafusion_memory_explicit_passes_through() {
2486 let config = RuntimeConfig {
2487 max_rss: Some(ConfigSize::from_mb(8_000)),
2488 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2489 ..Default::default()
2490 };
2491 assert_eq!(
2492 config.resolved_datafusion_memory(),
2493 Some(ConfigSize::from_mb(1_500))
2494 );
2495 }
2496
2497 #[test]
2498 fn effective_memory_is_the_smaller_budget() {
2499 let mb = |mb: Option<u64>| mb.map(ConfigSize::from_mb);
2500 for (max_rss, memory_max, expected) in [
2501 (None, None, None),
2502 (Some(8_000), None, Some(8_000)),
2503 (None, Some(4_000), Some(4_000)),
2504 (Some(8_000), Some(4_000), Some(4_000)),
2505 (Some(2_000), Some(4_000), Some(2_000)),
2506 ] {
2507 let config = RuntimeConfig {
2508 max_rss: mb(max_rss),
2509 resources: ResourceConfig {
2510 memory_max: mb(memory_max),
2511 ..Default::default()
2512 },
2513 ..Default::default()
2514 };
2515 assert_eq!(
2516 config.effective_memory(),
2517 mb(expected),
2518 "{max_rss:?}, {memory_max:?}"
2519 );
2520 }
2521 }
2522
2523 #[test]
2524 fn resolved_datafusion_memory_unconfigured_returns_none() {
2525 let config = RuntimeConfig::default();
2526 assert!(config.max_rss.is_none());
2527 assert!(config.resources.memory_max.is_none());
2528 assert_eq!(config.resolved_datafusion_memory(), None);
2529 }
2530
2531 #[test]
2532 fn resolved_datafusion_memory_small_budget_scales_down() {
2533 let config = RuntimeConfig {
2535 max_rss: Some(ConfigSize::from_mb(256)),
2536 ..Default::default()
2537 };
2538 assert_eq!(
2539 config.resolved_datafusion_memory(),
2540 Some(ConfigSize::from_bytes(12_800_000))
2541 );
2542
2543 let config = RuntimeConfig {
2544 max_rss: Some(ConfigSize::from_mb(512)),
2545 ..Default::default()
2546 };
2547 assert_eq!(
2548 config.resolved_datafusion_memory(),
2549 Some(ConfigSize::from_bytes(25_600_000))
2550 );
2551 }
2552
2553 #[test]
2554 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2555 let config = RuntimeConfig {
2557 max_rss: Some(ConfigSize::from_mb(64_000)),
2558 ..Default::default()
2559 };
2560 assert_eq!(
2561 config.resolved_datafusion_memory(),
2562 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2563 );
2564 }
2565
2566 #[test]
2567 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2568 let config = RuntimeConfig {
2570 max_rss: Some(ConfigSize::from_mb(16_000)),
2571 ..Default::default()
2572 };
2573 assert_eq!(
2574 config.resolved_datafusion_memory(),
2575 Some(ConfigSize::from_mb(800))
2576 );
2577 }
2578
2579 #[test]
2580 fn resolved_datafusion_memory_falls_back_to_resources() {
2581 let config = RuntimeConfig {
2583 max_rss: None,
2584 resources: ResourceConfig {
2585 memory_max: Some(ConfigSize::from_mb(16_000)),
2586 ..Default::default()
2587 },
2588 ..Default::default()
2589 };
2590 assert_eq!(
2591 config.resolved_datafusion_memory(),
2592 Some(ConfigSize::from_mb(800))
2593 );
2594 }
2595
2596 #[test]
2597 fn ft_config() {
2598 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2599 #[serde(default)]
2600 struct Wrapper {
2601 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2602 config: FtConfig,
2603 }
2604
2605 for s in [
2608 "{}",
2609 r#"{"config": null}"#,
2610 r#"{"config": {"model": "none"}}"#,
2611 ] {
2612 let config: Wrapper = serde_json::from_str(s).unwrap();
2613 assert_eq!(config.config.model, None);
2614 assert_eq!(config.config.checkpoint_interval(), None);
2615 }
2616
2617 let s = serde_json::to_string(&Wrapper {
2619 config: FtConfig::default(),
2620 })
2621 .unwrap();
2622 assert!(s.contains("\"none\""));
2623
2624 for s in [
2627 r#"{}"#,
2628 r#"{"checkpoint_interval": "60s"}"#,
2629 r#"{"checkpoint_interval_secs": 60}"#,
2630 ] {
2631 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2632 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2633 assert_eq!(
2634 config.checkpoint_interval(),
2635 Some(Duration::from_secs(60)),
2636 "parsing {s}"
2637 );
2638 }
2639
2640 for s in [
2643 r#"{"checkpoint_interval": null}"#,
2644 r#"{"checkpoint_interval_secs": null}"#,
2645 ] {
2646 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2647 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2648 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2649 }
2650
2651 let error = serde_json::from_str::<FtConfig>(
2654 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2655 )
2656 .unwrap_err()
2657 .to_string();
2658 assert!(error.contains("duplicate field"), "{error}");
2659
2660 for (json, expected_secs) in [
2662 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2663 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2664 ] {
2665 assert_eq!(
2666 serde_json::from_str::<FtConfig>(json)
2667 .unwrap()
2668 .checkpoint_interval(),
2669 Some(Duration::from_secs(expected_secs)),
2670 "parsing {json}"
2671 );
2672 }
2673 }
2674
2675 #[test]
2679 fn legacy_duration_spelling_uses_the_older_keys() {
2680 let mut config = serde_json::json!({
2681 "workers": 2,
2682 "clock_resolution": "250ms",
2683 "max_buffering_delay": "3ms",
2684 "provisioning_timeout": "15m",
2685 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2686 "storage": {"backend": {"name": "file", "config": {
2687 "ioop_latency": "5ms",
2688 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2689 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2690 });
2691 super::to_legacy_duration_spelling(&mut config);
2692 assert_eq!(
2693 config,
2694 serde_json::json!({
2695 "workers": 2,
2696 "clock_resolution_usecs": 250_000,
2697 "max_buffering_delay_usecs": 3_000,
2698 "provisioning_timeout_secs": 900,
2699 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2700 "storage": {"backend": {"name": "file", "config": {
2701 "ioop_delay": 5,
2702 "sync": {"bucket": "b", "pull_interval": 10,
2703 "push_interval": 3_600, "retention_min_age": 30}}}},
2704 })
2705 );
2706 }
2707
2708 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2710 serde_json::json!({
2711 "name": "p",
2712 "clock_resolution": "250ms",
2713 "inputs": {
2714 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2715 "topic": "t", "group_join_timeout": "30s"}}},
2716 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2717 "path": "http://x", "pause_linger": "7s"}}},
2718 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2719 "connection_config": {"server_url": "nats://x",
2720 "connection_timeout": "5s", "request_timeout": "6s"},
2721 "stream_name": "s",
2722 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2723 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2724 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2725 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2726 },
2727 "outputs": {
2728 "v.kafka": {"stream": "v",
2729 "transport": {"name": "kafka_output", "config": {
2730 "topic": "v", "initialization_timeout": "40s"}},
2731 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2732 "registry_timeout": "8s"}},
2733 "enable_output_buffer": true,
2734 "max_output_buffer_time": "500ms"},
2735 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2736 "connection_config": {"server_url": "nats://x",
2737 "connection_timeout": "5s", "request_timeout": "6s"},
2738 "subject": "s", "publish_timeout": "9s"}}},
2739 },
2740 })
2741 }
2742
2743 #[test]
2747 fn legacy_duration_spelling_rewrites_every_connector() {
2748 let mut config = pipeline_with_every_duration_connector();
2749 super::to_legacy_duration_spelling(&mut config);
2750 let i = &config["inputs"];
2751 assert_eq!(
2752 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2753 30
2754 );
2755 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2756 let nats = &i["t.nats"]["transport"]["config"];
2757 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2758 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2759 assert_eq!(nats["inactivity_timeout_secs"], 90);
2760 assert_eq!(nats["retry_interval_secs"], 3);
2761 assert_eq!(
2762 nats["consumer_config"]["max_expires"],
2763 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2764 );
2765 let pubsub = &i["t.pubsub"]["transport"]["config"];
2766 assert_eq!(pubsub["timeout_seconds"], 20);
2767 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2768 let out = &config["outputs"]["v.kafka"];
2769 assert_eq!(
2770 out["transport"]["config"]["initialization_timeout_secs"],
2771 40
2772 );
2773 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2774 assert_eq!(out["max_output_buffer_time_millis"], 500);
2775 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2776 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2777 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2778 assert_eq!(nats["publish_timeout_secs"], 9);
2779
2780 let text = config.to_string();
2782 for new in [
2783 "\"group_join_timeout\"",
2784 "\"pause_linger\"",
2785 "\"connection_timeout\"",
2786 "\"request_timeout\"",
2787 "\"inactivity_timeout\"",
2788 "\"retry_interval\"",
2789 "\"max_expiry\"",
2790 "\"timeout\"",
2791 "\"connect_timeout\"",
2792 "\"initialization_timeout\"",
2793 "\"registry_timeout\"",
2794 "\"max_output_buffer_time\"",
2795 "\"publish_timeout\"",
2796 "\"clock_resolution\"",
2797 ] {
2798 assert!(!text.contains(new), "{new} survived in {text}");
2799 }
2800 }
2801
2802 #[test]
2804 fn legacy_duration_spelling_round_trips_connectors() {
2805 let original: PipelineConfig =
2806 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2807 let mut value = serde_json::to_value(&original).unwrap();
2808 super::to_legacy_duration_spelling(&mut value);
2809 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2810
2811 let registry = |config: &PipelineConfig| {
2814 let format = config.outputs["v.kafka"]
2815 .connector_config
2816 .format
2817 .clone()
2818 .unwrap();
2819 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2820 .unwrap()
2821 .registry_config
2822 .registry_timeout
2823 };
2824 assert_eq!(registry(&reread), registry(&original));
2825 let mut original = original;
2826 for config in [&mut reread, &mut original] {
2827 config
2828 .outputs
2829 .get_mut("v.kafka")
2830 .unwrap()
2831 .connector_config
2832 .format = None;
2833 }
2834 assert_eq!(reread, original);
2835 }
2836
2837 #[test]
2841 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2842 let mut config = serde_json::json!({
2843 "inputs": {
2844 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2845 "group_join_timeout": "100000000000s"}}},
2846 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2847 },
2848 "storage": {"backend": {"name": "file", "config": {
2849 "sync": {"min_retention": "100000000000d"}}}},
2850 });
2851 super::to_legacy_duration_spelling(&mut config);
2852 let i = &config["inputs"];
2853 assert_eq!(
2854 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2855 u64::from(u32::MAX)
2856 );
2857 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2858 assert_eq!(
2859 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2860 u64::from(u32::MAX)
2861 );
2862 }
2863
2864 #[test]
2868 fn legacy_duration_spelling_round_trips() {
2869 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2870 "clock_resolution": "250ms",
2871 "max_buffering_delay": "3ms",
2872 "provisioning_timeout": "15m",
2873 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2874 }))
2875 .unwrap();
2876 let mut value = serde_json::to_value(&original).unwrap();
2877 super::to_legacy_duration_spelling(&mut value);
2878 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2879 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2880 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2881 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2882 assert_eq!(
2883 reread.fault_tolerance.checkpoint_interval(),
2884 original.fault_tolerance.checkpoint_interval()
2885 );
2886 }
2887
2888 #[test]
2893 fn legacy_duration_spelling_edge_cases() {
2894 let mut config = serde_json::json!({
2895 "max_buffering_delay": null,
2896 "provisioning_timeout": "1.5s",
2897 "fault_tolerance": {"checkpoint_interval": null},
2898 "clock_resolution": "10sec",
2899 "storage": {"backend": {"name": "file", "config": {
2900 "ioop_latency": "400us",
2901 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2902 });
2903 super::to_legacy_duration_spelling(&mut config);
2904 assert_eq!(
2905 config,
2906 serde_json::json!({
2907 "provisioning_timeout_secs": 2,
2908 "fault_tolerance": {"checkpoint_interval_secs": null},
2909 "clock_resolution": "10sec",
2910 "storage": {"backend": {"name": "file", "config": {
2911 "ioop_delay": 1,
2912 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2913 })
2914 );
2915
2916 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2918 super::to_legacy_duration_spelling(&mut zero);
2919 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2920
2921 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2923 let mut again = legacy.clone();
2924 super::to_legacy_duration_spelling(&mut again);
2925 assert_eq!(again, legacy);
2926 }
2927
2928 #[test]
2932 fn legacy_size_spelling_uses_the_older_keys() {
2933 let mut config = serde_json::json!({
2934 "workers": 2,
2935 "max_rss": "16G",
2936 "datafusion_memory": "1.5G",
2937 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2938 "resources": {
2939 "memory_min": "4G", "memory_max": "16Gi",
2940 "storage_min": "100G", "storage_max": "400Gi",
2941 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2942 },
2943 "dev_tweaks": {
2944 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2945 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2946 },
2947 "inputs": {
2948 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2949 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2950 "t.cdc": {"stream": "t",
2951 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2952 },
2953 "outputs": {
2954 "v.ddb": {"stream": "v",
2955 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2956 "v.pg": {"stream": "v",
2957 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2958 },
2959 });
2960 super::to_legacy_size_spelling(&mut config);
2961 assert_eq!(
2962 config,
2963 serde_json::json!({
2964 "workers": 2,
2965 "max_rss_mb": 16_000,
2966 "datafusion_memory_mb": 1_500,
2967 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2968 "resources": {
2969 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2971 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2972 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2973 },
2974 "dev_tweaks": {
2975 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2976 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2977 },
2978 "inputs": {
2979 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2980 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2981 "t.cdc": {"stream": "t",
2982 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2983 },
2984 "outputs": {
2985 "v.ddb": {"stream": "v",
2986 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2987 "v.pg": {"stream": "v",
2988 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2989 },
2990 })
2991 );
2992 }
2993
2994 #[test]
2999 fn distributed_output_streams() {
3000 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
3001 "name": "p",
3002 "inputs": {"t.kafka": {"stream": "t", "distributed": true,
3003 "transport": {"name": "kafka_input", "config": {
3004 "topic": "t", "bootstrap.servers": "localhost:9092"}}}},
3005 "outputs": {
3006 "a": {"stream": "A", "distributed": true,
3007 "transport": {"name": "delta_table_output", "config": {
3008 "uri": "memory://", "mode": "append"}}},
3009 "b": {"stream": "b", "distributed": true, "index": "B_Idx",
3010 "transport": {"name": "null_output"}},
3011 "c": {"stream": "c",
3012 "transport": {"name": "null_output"}},
3013 "d": {"stream": "d", "distributed": true,
3014 "transport": {"name": "delta_table_output", "config": {
3015 "uri": "memory://", "mode": "truncate"}}},
3016 },
3017 }))
3018 .unwrap();
3019 assert_eq!(
3020 config.distributed_output_streams(),
3021 std::collections::BTreeSet::from(["a".into(), "b_idx".into()])
3022 );
3023 }
3024
3025 #[test]
3028 fn legacy_size_spelling_round_trips() {
3029 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
3030 "name": "p",
3031 "max_rss": "16G",
3032 "datafusion_memory": "1G",
3035 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
3036 "resources": {"memory_max": "16G", "storage_max": "400G"},
3037 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
3038 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
3039 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
3040 "outputs": {},
3041 }))
3042 .unwrap();
3043 let mut value = serde_json::to_value(&config).unwrap();
3044 super::to_legacy_size_spelling(&mut value);
3045 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
3046 assert_eq!(
3047 value["inputs"]["t.file"]["max_queued_bytes"],
3048 serde_json::json!(1024 * 1024)
3049 );
3050 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
3051 assert_eq!(reread, config);
3052 }
3053
3054 #[test]
3057 fn legacy_spelling_applies_each_rename_separately() {
3058 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
3059 let mut both = current.clone();
3060 super::LegacySpelling {
3061 durations: true,
3062 sizes: true,
3063 }
3064 .apply(&mut both);
3065 assert_eq!(
3066 both,
3067 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
3068 );
3069 let mut sizes_only = current.clone();
3070 super::LegacySpelling {
3071 durations: false,
3072 sizes: true,
3073 }
3074 .apply(&mut sizes_only);
3075 assert_eq!(
3076 sizes_only,
3077 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
3078 );
3079 let mut none = current.clone();
3080 super::LegacySpelling::NONE.apply(&mut none);
3081 assert_eq!(none, current);
3082 assert!(!super::LegacySpelling::NONE.any());
3083 }
3084
3085 #[test]
3086 fn legacy_size_spelling_edge_cases() {
3087 let mut config = serde_json::json!({
3090 "max_rss": "lots",
3091 "resources": {"memory_max": null, "memory_min": 4000}
3092 });
3093 super::to_legacy_size_spelling(&mut config);
3094 assert_eq!(
3095 config,
3096 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
3097 );
3098
3099 let mut small = serde_json::json!({"max_rss": "1"});
3102 super::to_legacy_size_spelling(&mut small);
3103 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
3104
3105 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
3107 let mut again = legacy.clone();
3108 super::to_legacy_size_spelling(&mut again);
3109 assert_eq!(again, legacy);
3110 }
3111
3112 #[test]
3121 fn a_stored_default_matches_an_omitted_one() {
3122 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
3123 "transport": {
3124 "name": "url_input",
3125 "config": {"path": "http://example.com/x", "pause_timeout": 60},
3126 }
3127 }))
3128 .unwrap();
3129 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
3130 "transport": {
3131 "name": "url_input",
3132 "config": {"path": "http://example.com/x"},
3133 }
3134 }))
3135 .unwrap();
3136
3137 assert_ne!(stored, fresh);
3140 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
3141
3142 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
3144 "transport": {
3145 "name": "url_input",
3146 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
3147 }
3148 }))
3149 .unwrap();
3150 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
3151 }
3152
3153 #[test]
3161 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
3162 let connector = |registry: serde_json::Value| -> ConnectorConfig {
3163 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
3164 format
3165 .as_object_mut()
3166 .unwrap()
3167 .extend(registry.as_object().unwrap().clone());
3168 serde_json::from_value(serde_json::json!({
3169 "transport": {
3170 "name": "url_input",
3171 "config": {"path": "http://example.com/x"},
3172 },
3173 "format": {"name": "avro", "config": format},
3174 }))
3175 .unwrap()
3176 };
3177 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
3178 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
3179 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
3180 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
3181 let unset = connector(serde_json::json!({}));
3182
3183 assert!(stored.equal_modulo_paused(¤t));
3184 assert!(stored.equal_for_input_checkpoint_replay(¤t));
3185 assert!(current.equal_modulo_paused(&spelled_out));
3186 assert!(!stored.equal_modulo_paused(&changed));
3187 assert!(!stored.equal_modulo_paused(&unset));
3188 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
3190 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
3191 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
3192 }))
3193 .unwrap();
3194 assert!(!json.equal_modulo_paused(&stored));
3195 }
3196
3197 #[test]
3203 fn the_largest_legacy_defaults_still_load() {
3204 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
3205 "enable_output_buffer": false,
3206 "max_output_buffer_time_millis": u64::MAX,
3207 "max_output_buffer_size_records": 10_000_000u64,
3208 }))
3209 .unwrap();
3210 assert_eq!(
3211 buffer.max_output_buffer_time,
3212 Some(ConfigDuration::from_millis(u64::MAX))
3213 );
3214
3215 let sync: SyncConfig =
3217 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
3218 assert_eq!(
3219 sync.min_retention(),
3220 ConfigDuration::from_days(4_000_000_000)
3221 );
3222 }
3223
3224 #[test]
3228 fn a_legacy_number_past_u64_seconds_saturates() {
3229 let sync: SyncConfig =
3230 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
3231 .unwrap();
3232 assert_eq!(
3233 sync.min_retention(),
3234 ConfigDuration::from(std::time::Duration::MAX)
3235 );
3236 }
3237
3238 #[test]
3242 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3243 fn connector(value: serde_json::Value) -> ConnectorConfig {
3244 serde_json::from_value(value).unwrap()
3245 }
3246 fn secs(duration: ConfigDuration) -> u64 {
3247 std::time::Duration::from(duration).as_secs()
3248 }
3249 let fresh_kafka = connector(serde_json::json!({
3250 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3251 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3252 unreachable!()
3253 };
3254 let stored_kafka = connector(serde_json::json!({
3255 "transport": {"name": "kafka_input", "config": {
3256 "topic": "t",
3257 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3258 assert_ne!(stored_kafka, fresh_kafka);
3259 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3260
3261 let base = serde_json::json!({
3262 "connection_config": {"server_url": "nats://x"},
3263 "stream_name": "s",
3264 "consumer_config": {"deliver_policy": "All"}});
3265 let fresh_nats = connector(serde_json::json!({
3266 "transport": {"name": "nats_input", "config": base.clone()}}));
3267 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3268 unreachable!()
3269 };
3270 let mut spelled_out = base;
3271 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3272 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3273 spelled_out["connection_config"]["connection_timeout_secs"] =
3274 secs(nats.connection_config.connection_timeout()).into();
3275 spelled_out["connection_config"]["request_timeout_secs"] =
3276 secs(nats.connection_config.request_timeout()).into();
3277 let stored_nats = connector(serde_json::json!({
3278 "transport": {"name": "nats_input", "config": spelled_out}}));
3279 assert_ne!(stored_nats, fresh_nats);
3280 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3281 }
3282
3283 #[test]
3289 fn superseded_keys_are_normalised_by_a_round_trip() {
3290 let stored = serde_json::json!({
3291 "workers": 4,
3292 "clock_resolution_usecs": 100_000,
3293 "max_buffering_delay_usecs": 0,
3294 "provisioning_timeout_secs": 300,
3295 });
3296
3297 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3298 let written = serde_json::to_value(&config).unwrap();
3299
3300 assert_eq!(written["clock_resolution"], "100ms");
3301 assert_eq!(written["max_buffering_delay"], "0s");
3302 assert_eq!(written["provisioning_timeout"], "5m");
3303 for superseded in [
3304 "clock_resolution_usecs",
3305 "max_buffering_delay_usecs",
3306 "provisioning_timeout_secs",
3307 ] {
3308 assert!(
3309 written.get(superseded).is_none(),
3310 "`{superseded}` survived the round trip: {written}"
3311 );
3312 }
3313
3314 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3317 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3318 }
3319
3320 #[test]
3325 fn ioop_latency_accepts_both_spellings() {
3326 for (json, expected) in [
3327 (r#"{"name": "file", "config": {}}"#, None),
3328 (
3329 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3330 Some(ConfigDuration::from_millis(5)),
3331 ),
3332 (
3333 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3334 Some(ConfigDuration::from_millis(5)),
3335 ),
3336 (
3337 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3338 Some(ConfigDuration::from_secs(1)),
3339 ),
3340 ] {
3341 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3342 let StorageBackendConfig::File(file) = backend else {
3343 panic!("expected the file backend, parsing {json}");
3344 };
3345 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3346 }
3347 }
3348
3349 #[test]
3353 fn clock_resolution_falls_back_to_the_deprecated_field() {
3354 for (json, expected) in [
3355 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3356 (
3357 r#"{"clock_resolution": "100ms"}"#,
3358 ConfigDuration::from_millis(100),
3359 ),
3360 (
3361 r#"{"clock_resolution_usecs": 100000}"#,
3362 ConfigDuration::from_millis(100),
3363 ),
3364 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3365 (
3366 r#"{"clock_resolution_usecs": null}"#,
3367 DEFAULT_CLOCK_RESOLUTION,
3368 ),
3369 ] {
3370 assert_eq!(
3371 serde_json::from_str::<RuntimeConfig>(json)
3372 .unwrap()
3373 .clock_resolution(),
3374 expected,
3375 "parsing {json}"
3376 );
3377 }
3378 }
3379
3380 #[test]
3383 fn deprecated_duration_fields_still_work() {
3384 let runtime: RuntimeConfig = serde_json::from_str(
3385 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3386 )
3387 .unwrap();
3388 assert_eq!(
3389 runtime.max_buffering_delay(),
3390 ConfigDuration::from_millis(5)
3391 );
3392 assert_eq!(
3393 runtime.provisioning_timeout,
3394 Some(ConfigDuration::from_secs(1200))
3395 );
3396
3397 let sync: SyncConfig = serde_json::from_str(
3398 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3399 )
3400 .unwrap();
3401 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3402 assert_eq!(
3403 sync.checkpoint_push_interval(),
3404 Some(ConfigDuration::from_secs(300))
3405 );
3406 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3407
3408 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3409 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3410
3411 let buffer: OutputBufferConfig =
3412 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3413 assert_eq!(
3414 buffer.max_output_buffer_time(),
3415 ConfigDuration::from_millis(250)
3416 );
3417 }
3418
3419 #[test]
3422 fn duration_fields_default_when_unset() {
3423 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3424 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3425 assert_eq!(sync.checkpoint_push_interval(), None);
3426 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3427
3428 let runtime = RuntimeConfig::default();
3429 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3430 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3431 assert_eq!(runtime.provisioning_timeout, None);
3432 }
3433
3434 #[test]
3438 fn storage_options_f64_roundtrip_through_pipeline_config() {
3439 let pc = PipelineConfig {
3440 global: RuntimeConfig {
3441 storage: Some(StorageOptions {
3442 bloom_false_positive_rate: Some(0.01),
3443 ..Default::default()
3444 }),
3445 ..Default::default()
3446 },
3447 multihost: None,
3448 name: Some("test-pipeline".into()),
3449 given_name: None,
3450 storage_config: None,
3451 secrets_dir: None,
3452 inputs: Default::default(),
3453 outputs: Default::default(),
3454 program_ir: None,
3455 };
3456
3457 let json = serde_json::to_string_pretty(&pc).unwrap();
3459 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3460 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3461 );
3462 assert_eq!(
3463 pc2.global.storage.unwrap().bloom_false_positive_rate,
3464 Some(0.01)
3465 );
3466
3467 let value = serde_json::to_value(&pc).unwrap();
3469 let pc3: PipelineConfig = serde_json::from_value(value)
3470 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3471 assert_eq!(
3472 pc3.global.storage.unwrap().bloom_false_positive_rate,
3473 Some(0.01)
3474 );
3475 }
3476
3477 #[test]
3480 fn display_summary_omits_secrets() {
3481 let config: PipelineConfig = serde_json::from_value(json!({
3482 "env": {"PGPASSWORD": "env-secret"},
3483 "storage": {"backend": {"name": "file", "config": {
3484 "sync": {"bucket": "b", "access_key": "ak", "secret_key": "storage-secret"}
3485 }}},
3486 "inputs": {"pg_in": {
3487 "stream": "t",
3488 "transport": {"name": "kafka_input", "config": {
3489 "topic": "t",
3490 "sasl.password": "kafka-secret"
3491 }},
3492 "format": {"name": "json", "config": {}}
3493 }},
3494 "outputs": {"pg_out": {
3495 "stream": "v",
3496 "transport": {"name": "postgres_output", "config": {
3497 "uri": "postgresql://u:pg-secret@h/db", "table": "v"
3498 }}
3499 }}
3500 }))
3501 .unwrap();
3502
3503 let summary = config.display_summary();
3504 for secret in [
3505 "env-secret",
3506 "storage-secret",
3507 "kafka-secret",
3508 "pg-secret",
3509 "sasl",
3510 ] {
3511 assert!(!summary.contains(secret), "{secret} in summary: {summary}");
3512 }
3513 for expected in [
3514 "pg_in",
3515 "kafka_input",
3516 "json",
3517 "pg_out",
3518 "postgres_output",
3519 "PGPASSWORD",
3520 "file",
3521 ] {
3522 assert!(summary.contains(expected), "{expected} missing: {summary}");
3523 }
3524 }
3525
3526 #[test]
3530 fn summary_allowlist_matches_runtime_config() {
3531 use std::collections::BTreeSet;
3532
3533 let config: RuntimeConfig = serde_json::from_value(json!({
3535 "max_rss": "1Gi",
3536 "datafusion_memory": "1Gi",
3537 "max_buffering_delay": "1s",
3538 "clock_resolution": "1s",
3539 "provisioning_timeout": "1s",
3540 }))
3541 .unwrap();
3542 let fields: BTreeSet<String> = match serde_json::to_value(&config).unwrap() {
3543 serde_json::Value::Object(fields) => fields.keys().cloned().collect(),
3544 other => panic!("not an object: {other}"),
3545 };
3546 let left_out = [
3548 "storage",
3549 "env",
3550 "tracing_endpoint_jaeger",
3551 "init_containers",
3552 "pipeline_template_configmap",
3553 ];
3554 let decided: BTreeSet<String> = super::RUNTIME_CONFIG_SUMMARY_FIELDS
3555 .iter()
3556 .chain(left_out.iter())
3557 .map(|name| name.to_string())
3558 .collect();
3559 assert_eq!(decided, fields);
3560 }
3561}
3562
3563impl FtConfig {
3564 pub fn is_enabled(&self) -> bool {
3565 self.model.is_some()
3566 }
3567
3568 pub fn checkpoint_interval(&self) -> Option<Duration> {
3575 if !self.is_enabled() {
3576 return None;
3577 }
3578
3579 let interval = self
3580 .checkpoint_interval
3581 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3582
3583 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3584 }
3585}
3586
3587mod none_as_string {
3594 use std::marker::PhantomData;
3595
3596 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3597 use serde::ser::{Serialize, Serializer};
3598
3599 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3600 where
3601 S: Serializer,
3602 T: Serialize,
3603 {
3604 match value.as_ref() {
3605 Some(value) => value.serialize(serializer),
3606 None => "none".serialize(serializer),
3607 }
3608 }
3609
3610 struct NoneAsString<T>(PhantomData<fn() -> T>);
3611
3612 impl<'de, T> Visitor<'de> for NoneAsString<T>
3613 where
3614 T: Deserialize<'de>,
3615 {
3616 type Value = Option<T>;
3617
3618 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3619 formatter.write_str("string")
3620 }
3621
3622 fn visit_none<E>(self) -> Result<Self::Value, E>
3623 where
3624 E: serde::de::Error,
3625 {
3626 Ok(None)
3627 }
3628
3629 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3630 where
3631 E: serde::de::Error,
3632 {
3633 if &value.to_ascii_lowercase() == "none" {
3634 Ok(None)
3635 } else {
3636 Ok(Some(T::deserialize(value.into_deserializer())?))
3637 }
3638 }
3639 }
3640
3641 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3642 where
3643 D: Deserializer<'de>,
3644 T: Deserialize<'de>,
3645 {
3646 deserializer.deserialize_str(NoneAsString(PhantomData))
3647 }
3648}
3649
3650fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3653 Schema::OneOf(
3654 OneOfBuilder::new()
3655 .item(RefOr::Ref(Ref::new(format!(
3656 "#/components/schemas/{}",
3657 T::schema().0
3658 ))))
3659 .item(
3660 ObjectBuilder::new()
3661 .schema_type(SchemaType::String)
3662 .enum_values(Some(vec!["none"])),
3663 )
3664 .default(Some(
3665 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3666 ))
3667 .build(),
3668 )
3669}
3670
3671#[derive(
3676 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3677)]
3678#[serde(rename_all = "snake_case")]
3679pub enum FtModel {
3680 AtLeastOnce,
3683
3684 #[default]
3687 ExactlyOnce,
3688}
3689
3690impl FtModel {
3691 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3692 value.map_or("no", |model| model.as_str())
3693 }
3694
3695 pub fn as_str(&self) -> &'static str {
3696 match self {
3697 FtModel::AtLeastOnce => "at_least_once",
3698 FtModel::ExactlyOnce => "exactly_once",
3699 }
3700 }
3701}
3702
3703#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3705pub struct FtModelUnknown;
3706
3707impl std::fmt::Display for FtModelUnknown {
3708 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3709 f.write_str("expected `exactly_once` or `at_least_once`")
3710 }
3711}
3712
3713impl std::error::Error for FtModelUnknown {}
3714
3715impl FromStr for FtModel {
3716 type Err = FtModelUnknown;
3717
3718 fn from_str(s: &str) -> Result<Self, Self::Err> {
3719 match s.to_ascii_lowercase().as_str() {
3720 "exactly_once" => Ok(Self::ExactlyOnce),
3721 "at_least_once" => Ok(Self::AtLeastOnce),
3722 _ => Err(FtModelUnknown),
3723 }
3724 }
3725}
3726
3727#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3729pub struct InputEndpointConfig {
3730 pub stream: Cow<'static, str>,
3733
3734 #[serde(flatten)]
3736 pub connector_config: ConnectorConfig,
3737}
3738
3739impl InputEndpointConfig {
3740 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3741 Self {
3742 stream: stream.into(),
3743 connector_config,
3744 }
3745 }
3746}
3747
3748fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3752where
3753 D: Deserializer<'de>,
3754{
3755 let value = Option::<JsonValue>::deserialize(deserializer)?;
3756 match value {
3757 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3758 Some(JsonValue::Array(arr)) => {
3759 let vec = arr
3760 .into_iter()
3761 .map(|item| {
3762 item.as_str()
3763 .map(|s| s.to_string())
3764 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3765 })
3766 .collect::<Result<Vec<String>, _>>()?;
3767 Ok(Some(vec))
3768 }
3769 Some(JsonValue::Null) | None => Ok(None),
3770 _ => Err(serde::de::Error::custom(
3771 "invalid 'start_after' property: expected a string, an array of strings, or null",
3772 )),
3773 }
3774}
3775
3776#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3777pub struct ConnectorConfig {
3778 #[serde(default)]
3794 pub send_snapshot: bool,
3795
3796 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3813 pub soft_delete: bool,
3814
3815 pub transport: TransportConfig,
3817
3818 #[serde(skip_serializing_if = "Option::is_none")]
3820 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3821
3822 pub format: Option<FormatConfig>,
3824
3825 #[serde(skip_serializing_if = "Option::is_none")]
3827 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3828
3829 pub index: Option<String>,
3844
3845 #[serde(flatten)]
3847 pub output_buffer_config: OutputBufferConfig,
3848
3849 #[serde(skip_serializing_if = "Option::is_none")]
3862 pub max_batch_size: Option<u64>,
3863
3864 #[serde(skip_serializing_if = "Option::is_none")]
3877 pub max_worker_batch_size: Option<u64>,
3878
3879 #[serde(default = "default_max_queued_records")]
3900 pub max_queued_records: u64,
3901
3902 #[serde(
3925 default,
3926 alias = "max_queued_bytes",
3927 deserialize_with = "size_max_queued_size",
3928 skip_serializing_if = "Option::is_none"
3929 )]
3930 #[schema(value_type = Option<String>)]
3931 pub max_queued_size: Option<ConfigSize>,
3932
3933 #[serde(default)]
3944 pub paused: bool,
3945
3946 #[serde(default)]
3951 pub labels: Vec<String>,
3952
3953 #[serde(deserialize_with = "deserialize_start_after")]
3959 #[serde(default)]
3960 pub start_after: Option<Vec<String>>,
3961
3962 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3985 pub distributed: bool,
3986}
3987
3988impl ConnectorConfig {
3989 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3990 Self {
3991 send_snapshot: false,
3992 soft_delete: false,
3993 transport,
3994 preprocessor: None,
3995 format,
3996 postprocessor: None,
3997 index: None,
3998 output_buffer_config: Default::default(),
3999 max_batch_size: None,
4000 max_worker_batch_size: None,
4001 max_queued_records: default_max_queued_records(),
4002 max_queued_size: None,
4003 paused: false,
4004 labels: Vec::new(),
4005 start_after: None,
4006 distributed: false,
4007 }
4008 }
4009
4010 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
4011 self.max_batch_size = max_batch_size;
4012 self
4013 }
4014
4015 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
4016 self.max_queued_records = max_queued_records;
4017 self
4018 }
4019
4020 pub fn validate_queue_limits(&self) -> Result<(), String> {
4025 if self.max_queued_records == 0 {
4026 return Err("'max_queued_records' must be greater than 0".to_string());
4027 }
4028 if self.max_queued_size.is_some() && self.max_queued_bytes() == 0 {
4029 return Err("'max_queued_size' must be greater than 0".to_string());
4030 }
4031 Ok(())
4032 }
4033
4034 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
4039 let mut a = self.clone();
4040 let mut b = other.clone();
4041 a.paused = false;
4042 b.paused = false;
4043 a.normalize_durations();
4044 b.normalize_durations();
4045 a == b
4046 }
4047
4048 fn normalize_durations(&mut self) {
4059 self.transport.normalize_durations();
4060 self.output_buffer_config.max_output_buffer_time =
4061 Some(self.output_buffer_config.max_output_buffer_time());
4062 if let Some(format) = &mut self.format {
4063 format.normalize_durations();
4064 }
4065 }
4066
4067 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
4070 let mut a = self.clone();
4071 let mut b = other.clone();
4072 a.normalize_for_input_checkpoint_replay();
4073 b.normalize_for_input_checkpoint_replay();
4074 a == b
4075 }
4076
4077 fn normalize_for_input_checkpoint_replay(&mut self) {
4078 self.paused = false;
4079 self.max_batch_size = None;
4080 self.max_worker_batch_size = None;
4081 self.max_queued_records = default_max_queued_records();
4082 self.max_queued_size = None;
4083 self.normalize_durations();
4084 }
4085
4086 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
4089 self.max_batch_size = other.max_batch_size;
4090 self.max_worker_batch_size = other.max_worker_batch_size;
4091 self.max_queued_records = other.max_queued_records;
4092 self.max_queued_size = other.max_queued_size;
4093 }
4094
4095 pub fn max_queued_records(&self) -> u64 {
4097 self.max_queued_records
4098 }
4099
4100 pub fn max_queued_bytes(&self) -> u64 {
4103 self.max_queued_size
4104 .map(ConfigSize::as_bytes)
4105 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
4106 }
4107}
4108
4109#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
4110#[serde(default)]
4111pub struct OutputBufferConfig {
4112 pub enable_output_buffer: bool,
4135
4136 #[serde(
4145 default,
4146 alias = "max_output_buffer_time_millis",
4147 deserialize_with = "duration_max_output_buffer_time",
4148 skip_serializing_if = "Option::is_none"
4149 )]
4150 #[schema(value_type = Option<String>)]
4151 pub max_output_buffer_time: Option<ConfigDuration>,
4152
4153 pub max_output_buffer_size_records: usize,
4165}
4166
4167impl OutputBufferConfig {
4168 pub fn max_output_buffer_time(&self) -> ConfigDuration {
4170 self.max_output_buffer_time
4171 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
4172 }
4173}
4174
4175impl Default for OutputBufferConfig {
4176 fn default() -> Self {
4177 Self {
4178 enable_output_buffer: false,
4179 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
4180 max_output_buffer_time: None,
4181 }
4182 }
4183}
4184
4185#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
4187pub struct OutputEndpointConfig {
4188 pub stream: Cow<'static, str>,
4191
4192 #[serde(flatten)]
4194 pub connector_config: ConnectorConfig,
4195}
4196
4197impl OutputEndpointConfig {
4198 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
4199 Self {
4200 stream: stream.into(),
4201 connector_config,
4202 }
4203 }
4204}
4205
4206#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
4210#[serde(tag = "name", content = "config", rename_all = "snake_case")]
4211pub enum TransportConfig {
4212 FileInput(FileInputConfig),
4213 FileOutput(FileOutputConfig),
4214 NatsInput(Box<NatsInputConfig>),
4217 NatsOutput(NatsOutputConfig),
4218 KafkaInput(KafkaInputConfig),
4219 KafkaOutput(KafkaOutputConfig),
4220 PubSubInput(PubSubInputConfig),
4221 UrlInput(UrlInputConfig),
4222 S3Input(S3InputConfig),
4223 DeltaTableInput(DeltaTableReaderConfig),
4224 DeltaTableOutput(DeltaTableWriterConfig),
4225 #[serde(rename = "dynamodb_output")]
4228 DynamoDBOutput(DynamoDBWriterConfig),
4229 RedisOutput(RedisOutputConfig),
4230 IcebergInput(Box<IcebergReaderConfig>),
4232 PostgresInput(PostgresReaderConfig),
4233 PostgresCdcInput(PostgresCdcReaderConfig),
4234 PostgresOutput(PostgresWriterConfig),
4235 Datagen(DatagenInputConfig),
4236 Nexmark(NexmarkInputConfig),
4237 HttpInput(HttpInputConfig),
4239 HttpOutput(HttpOutputConfig),
4241 AdHocInput(AdHocInputConfig),
4243 ClockInput(ClockConfig),
4244 S2Input(S2InputConfig),
4245 S2Output(S2OutputConfig),
4246 NullOutput,
4248 EmptyInput,
4250}
4251
4252pub const REFUSE_LOCAL_FILE_URIS_ENV: &str = "FELDERA_REFUSE_LOCAL_FILE_URIS";
4255
4256fn is_local_file_uri(location: &str) -> bool {
4258 let Some((scheme, _)) = location.split_once(':') else {
4259 return true;
4260 };
4261 let valid_scheme = scheme.len() > 1
4262 && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
4263 && scheme
4264 .chars()
4265 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
4266 !valid_scheme || scheme.eq_ignore_ascii_case("file")
4267}
4268
4269impl TransportConfig {
4270 pub fn local_file_uris(&self, resolved: bool) -> Vec<(&'static str, &str)> {
4274 let locations = match self {
4275 TransportConfig::DeltaTableInput(config) => vec![("uri", Some(&*config.uri))],
4276 TransportConfig::DeltaTableOutput(config) => vec![("uri", Some(&*config.uri))],
4277 TransportConfig::IcebergInput(config) => vec![
4278 ("metadata_location", config.metadata_location.as_deref()),
4279 (
4280 "glue.warehouse",
4281 config.glue_catalog_config.warehouse.as_deref(),
4282 ),
4283 ],
4284 _ => Vec::new(),
4285 };
4286 locations
4287 .into_iter()
4288 .filter_map(|(property, location)| Some((property, location?)))
4289 .filter(|(_, location)| {
4290 (resolved
4291 || matches!(
4292 MaybeSecretRef::new(location.to_string()),
4293 Ok(MaybeSecretRef::String(_))
4294 ))
4295 && is_local_file_uri(location)
4296 })
4297 .collect()
4298 }
4299
4300 pub fn normalize_durations(&mut self) {
4303 match self {
4304 TransportConfig::UrlInput(config) => {
4305 config.pause_linger = Some(config.pause_linger());
4306 }
4307 TransportConfig::KafkaInput(config) => {
4308 config.group_join_timeout = Some(config.group_join_timeout());
4309 }
4310 TransportConfig::KafkaOutput(config) => {
4311 config.initialization_timeout = Some(config.initialization_timeout());
4312 }
4313 TransportConfig::NatsInput(config) => {
4314 config.connection_config.connection_timeout =
4315 Some(config.connection_config.connection_timeout());
4316 config.connection_config.request_timeout =
4317 Some(config.connection_config.request_timeout());
4318 config.inactivity_timeout = Some(config.inactivity_timeout());
4319 config.retry_interval = Some(config.retry_interval());
4320 }
4321 TransportConfig::NatsOutput(config) => {
4322 config.connection_config.connection_timeout =
4323 Some(config.connection_config.connection_timeout());
4324 config.connection_config.request_timeout =
4325 Some(config.connection_config.request_timeout());
4326 config.publish_timeout = Some(config.publish_timeout());
4327 }
4328 _ => {}
4329 }
4330 }
4331
4332 pub fn name(&self) -> String {
4333 match self {
4334 TransportConfig::FileInput(_) => "file_input".to_string(),
4335 TransportConfig::FileOutput(_) => "file_output".to_string(),
4336 TransportConfig::NatsInput(_) => "nats_input".to_string(),
4337 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
4338 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
4339 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
4340 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
4341 TransportConfig::UrlInput(_) => "url_input".to_string(),
4342 TransportConfig::S3Input(_) => "s3_input".to_string(),
4343 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
4344 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
4345 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
4346 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
4347 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
4348 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
4349 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
4350 TransportConfig::Datagen(_) => "datagen".to_string(),
4351 TransportConfig::Nexmark(_) => "nexmark".to_string(),
4352 TransportConfig::HttpInput(_) => "http_input".to_string(),
4353 TransportConfig::HttpOutput(_) => "http_output".to_string(),
4354 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
4355 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
4356 TransportConfig::ClockInput(_) => "clock".to_string(),
4357 TransportConfig::S2Input(_) => "s2_input".to_string(),
4358 TransportConfig::S2Output(_) => "s2_output".to_string(),
4359 TransportConfig::NullOutput => "null_output".to_string(),
4360 TransportConfig::EmptyInput => "empty_input".to_string(),
4361 }
4362 }
4363
4364 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
4369 match self {
4370 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
4371 _ => None,
4372 }
4373 }
4374
4375 pub fn is_transient(&self) -> bool {
4378 matches!(
4379 self,
4380 TransportConfig::AdHocInput(_)
4381 | TransportConfig::HttpInput(_)
4382 | TransportConfig::HttpOutput(_)
4383 | TransportConfig::ClockInput(_)
4384 )
4385 }
4386
4387 pub fn is_http_input(&self) -> bool {
4388 matches!(self, TransportConfig::HttpInput(_))
4389 }
4390
4391 pub fn supports_distribution(&self) -> bool {
4395 matches!(
4396 self,
4397 TransportConfig::KafkaInput(_)
4398 | TransportConfig::DeltaTableInput(_)
4399 | TransportConfig::IcebergInput(_)
4400 )
4401 }
4402
4403 pub fn supports_output_distribution(&self) -> bool {
4406 match self {
4407 TransportConfig::NullOutput => true,
4408 TransportConfig::DeltaTableOutput(config) => {
4409 config.mode == DeltaTableWriteMode::Append
4410 && config.update_mode == DeltaTableUpdateMode::Cdc
4411 }
4412 _ => false,
4413 }
4414 }
4415
4416 pub fn needs_input_choice(&self) -> bool {
4428 matches!(
4429 self,
4430 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4431 )
4432 }
4433
4434 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4437 use crate::adapter_stats::FrontierMerge;
4438 match self {
4439 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4440 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4441 FrontierMerge::Shared
4442 }
4443 _ => FrontierMerge::Opaque,
4444 }
4445 }
4446}
4447
4448#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4451pub struct FormatConfig {
4452 pub name: Cow<'static, str>,
4454
4455 #[serde(default)]
4457 #[schema(value_type = Object)]
4458 pub config: JsonValue,
4459}
4460
4461impl FormatConfig {
4462 pub fn normalize_durations(&mut self) {
4469 if self.name != "avro" {
4470 return;
4471 }
4472 let has_timeout = self.config.as_object().is_some_and(|object| {
4473 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4474 });
4475 if !has_timeout {
4476 return;
4477 }
4478 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4479 self.config.clone(),
4480 ) else {
4481 return;
4482 };
4483 let object = self.config.as_object_mut().unwrap();
4484 object.remove("registry_timeout_secs");
4485 match registry.registry_timeout {
4486 Some(timeout) => object.insert(
4487 "registry_timeout".to_string(),
4488 JsonValue::String(timeout.to_string()),
4489 ),
4490 None => object.remove("registry_timeout"),
4491 };
4492 }
4493}
4494
4495#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4497#[serde(deny_unknown_fields)]
4498pub struct DynamicConfig {
4499 #[serde(default)]
4500 pub resources: DynamicResources,
4501}
4502
4503#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4506#[serde(deny_unknown_fields)]
4507pub struct DynamicResources {
4508 pub cpu_cores_min: Option<f64>,
4509 pub cpu_cores_max: Option<f64>,
4510 #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4513 #[schema(value_type = Option<String>)]
4514 pub memory_min: Option<ConfigSize>,
4515 #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4518 #[schema(value_type = Option<String>)]
4519 pub memory_max: Option<ConfigSize>,
4520 #[serde(
4525 default,
4526 alias = "storage_mb_min",
4527 deserialize_with = "size_storage_min",
4528 skip_serializing_if = "Option::is_none"
4529 )]
4530 #[schema(value_type = Option<String>)]
4531 pub storage_min: Option<ConfigSize>,
4532 #[serde(
4535 default,
4536 alias = "storage_mb_max",
4537 deserialize_with = "size_storage_max",
4538 skip_serializing_if = "Option::is_none"
4539 )]
4540 #[schema(value_type = Option<String>)]
4541 pub storage_max: Option<ConfigSize>,
4542 #[serde(default, skip_serializing_if = "Option::is_none")]
4545 pub volume_attributes_class: Option<String>,
4546}
4547
4548#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4549#[serde(default)]
4550pub struct ResourceConfig {
4551 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4554 pub cpu_cores_min: Option<f64>,
4555
4556 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4559 pub cpu_cores_max: Option<f64>,
4560
4561 #[serde(
4567 alias = "memory_mb_min",
4568 deserialize_with = "size_memory_min",
4569 skip_serializing_if = "Option::is_none"
4570 )]
4571 #[schema(value_type = Option<String>)]
4572 pub memory_min: Option<ConfigSize>,
4573
4574 #[serde(
4580 alias = "memory_mb_max",
4581 deserialize_with = "size_memory_max",
4582 skip_serializing_if = "Option::is_none"
4583 )]
4584 #[schema(value_type = Option<String>)]
4585 pub memory_max: Option<ConfigSize>,
4586
4587 #[serde(
4594 alias = "storage_mb_min",
4595 deserialize_with = "size_storage_min",
4596 skip_serializing_if = "Option::is_none"
4597 )]
4598 #[schema(value_type = Option<String>)]
4599 pub storage_min: Option<ConfigSize>,
4600
4601 #[serde(
4612 alias = "storage_mb_max",
4613 deserialize_with = "size_storage_max",
4614 skip_serializing_if = "Option::is_none"
4615 )]
4616 #[schema(value_type = Option<String>)]
4617 pub storage_max: Option<ConfigSize>,
4618
4619 #[serde(skip_serializing_if = "Option::is_none")]
4621 pub autoscaling: Option<AutoscalingConfig>,
4622
4623 pub storage_class: Option<String>,
4626
4627 #[serde(skip_serializing_if = "Option::is_none")]
4634 pub volume_attributes_class: Option<String>,
4635
4636 pub service_account_name: Option<String>,
4639
4640 pub namespace: Option<String>,
4648}
4649
4650#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4652#[serde(default)]
4653pub struct AutoscalingConfig {
4654 #[serde(skip_serializing_if = "Option::is_none")]
4656 pub storage: Option<StorageAutoscalingConfig>,
4657}
4658
4659#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4662#[serde(default)]
4663pub struct StorageAutoscalingConfig {
4664 #[serde(
4666 deserialize_with = "crate::serde_via_value::deserialize",
4667 skip_serializing_if = "Option::is_none"
4668 )]
4669 pub scale_threshold: Option<f64>,
4670
4671 #[serde(
4678 alias = "scale_threshold_available_mb",
4679 deserialize_with = "size_scale_threshold_available",
4680 skip_serializing_if = "Option::is_none"
4681 )]
4682 #[schema(value_type = Option<String>)]
4683 pub scale_threshold_available: Option<ConfigSize>,
4684
4685 #[serde(
4687 deserialize_with = "crate::serde_via_value::deserialize",
4688 skip_serializing_if = "Option::is_none"
4689 )]
4690 pub scale_factor: Option<f64>,
4691}
4692
4693#[cfg(test)]
4694mod resource_config_tests {
4695 use super::{
4696 AutoscalingConfig, DynamicConfig, DynamicResources, ResourceConfig,
4697 StorageAutoscalingConfig,
4698 };
4699 use crate::size::ConfigSize;
4700 use serde_json::json;
4701
4702 #[test]
4705 fn dynamic_config_leaves_out_unset_storage() {
4706 let update = DynamicConfig {
4707 resources: DynamicResources {
4708 memory_max: Some(ConfigSize::from_mb(1000)),
4709 ..Default::default()
4710 },
4711 };
4712 assert_eq!(
4713 serde_json::to_value(&update).unwrap(),
4714 json!({"resources": {
4715 "cpu_cores_min": null, "cpu_cores_max": null,
4716 "memory_min": null, "memory_max": "1G",
4717 }})
4718 );
4719 let resize = json!({"resources": {"storage_mb_min": 1000, "storage_max": "8G"}});
4720 let resize: DynamicConfig = serde_json::from_value(resize).unwrap();
4721 assert_eq!(
4722 resize.resources.storage_min,
4723 Some(ConfigSize::from_mb(1000))
4724 );
4725 assert_eq!(
4726 resize.resources.storage_max,
4727 Some(ConfigSize::from_mb(8000))
4728 );
4729 }
4730
4731 #[test]
4732 fn storage_autoscaling_round_trips_through_json() {
4733 let input = json!({
4734 "storage_min": "1G",
4735 "storage_max": "8G",
4736 "autoscaling": {
4737 "storage": {
4738 "scale_threshold": 0.8,
4739 "scale_threshold_available": "10G",
4740 "scale_factor": 2.0
4741 }
4742 }
4743 });
4744 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4745 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4746 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4747 assert_eq!(
4748 config.autoscaling,
4749 Some(AutoscalingConfig {
4750 storage: Some(StorageAutoscalingConfig {
4751 scale_threshold: Some(0.8),
4752 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4753 scale_factor: Some(2.0),
4754 }),
4755 })
4756 );
4757 let output = serde_json::to_value(&config).unwrap();
4758 assert_eq!(output["storage_min"], json!("1G"));
4759 assert_eq!(
4760 output["autoscaling"]["storage"]["scale_threshold"],
4761 json!(0.8)
4762 );
4763 assert_eq!(
4764 output["autoscaling"]["storage"]["scale_threshold_available"],
4765 json!("10G")
4766 );
4767 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4768 }
4769
4770 #[test]
4771 fn autoscaling_fields_default_to_none() {
4772 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4773 assert_eq!(config.storage_min, None);
4774 assert_eq!(config.autoscaling, None);
4775
4776 let output = serde_json::to_value(&config).unwrap();
4779 assert!(output.get("storage_min").is_none());
4780 assert!(output.get("autoscaling").is_none());
4781 assert!(output.get("storage_max").is_none());
4782
4783 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4785 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4786 let output = serde_json::to_value(&config).unwrap();
4787 assert_eq!(output["autoscaling"], input["autoscaling"]);
4788
4789 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4791 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4792 }
4793
4794 #[test]
4795 fn autoscaling_rejects_non_numeric_values() {
4796 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4797 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4798 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4799 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4800 let input = json!({ "storage_mb_min": -1 });
4801 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4802 }
4803}
4804
4805#[cfg(test)]
4806mod sync_config_tests {
4807 use super::SyncConfig;
4808
4809 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4810 SyncConfig {
4811 bucket: bucket.to_owned(),
4812 read_bucket: read_bucket.map(str::to_owned),
4813 ..Default::default()
4814 }
4815 }
4816
4817 #[test]
4818 fn read_bucket_must_differ_from_bucket() {
4819 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4820 assert!(err.contains("different locations"), "{err}");
4821 }
4822
4823 #[test]
4824 fn read_bucket_must_use_the_same_object_store() {
4825 let err = config("gs://ckpts/a", Some("ckpts/b"))
4826 .validate()
4827 .unwrap_err();
4828 assert!(err.contains("same object store"), "{err}");
4829 let err = config("ckpts/a", Some("gs://ckpts/b"))
4830 .validate()
4831 .unwrap_err();
4832 assert!(err.contains("same object store"), "{err}");
4833 for (bucket, read_bucket) in [
4834 ("az://ckpts/a", "ckpts/b"),
4835 ("ckpts/a", "az://ckpts/b"),
4836 ("az://ckpts/a", "gs://ckpts/b"),
4837 ] {
4838 let err = azure_config(bucket, Some(read_bucket))
4839 .validate()
4840 .unwrap_err();
4841 assert!(err.contains("same object store"), "{err}");
4842 }
4843 }
4844
4845 fn azure_config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4846 SyncConfig {
4847 access_key: Some("account".to_owned()),
4848 ..config(bucket, read_bucket)
4849 }
4850 }
4851
4852 #[test]
4853 fn azure_bucket_needs_the_storage_account_name() {
4854 azure_config("az://ckpts/a", Some("az://ckpts/b"))
4855 .validate()
4856 .unwrap();
4857
4858 let err = config("az://ckpts/a", None).validate().unwrap_err();
4859 assert!(err.contains("set `access_key`"), "{err}");
4860 let empty = SyncConfig {
4861 access_key: Some(String::new()),
4862 ..config("az://ckpts/a", None)
4863 };
4864 let err = empty.validate().unwrap_err();
4865 assert!(err.contains("set `access_key`"), "{err}");
4866 }
4867
4868 #[test]
4869 fn azure_bucket_needs_a_container_name() {
4870 for bucket in ["az://", "az:///dir"] {
4871 let err = azure_config(bucket, None).validate().unwrap_err();
4872 assert!(err.contains("`bucket`"), "{err}");
4873 assert!(err.contains("does not name a container"), "{err}");
4874
4875 let err = azure_config("az://ckpts/a", Some(bucket))
4876 .validate()
4877 .unwrap_err();
4878 assert!(err.contains("`read_bucket`"), "{err}");
4879 }
4880 azure_config("az://ckpts", None).validate().unwrap();
4881 azure_config("az://ckpts/", None).validate().unwrap();
4882 }
4883
4884 #[test]
4885 fn matching_object_stores_are_accepted() {
4886 config("gs://ckpts/a", Some("gs://ckpts/b"))
4887 .validate()
4888 .unwrap();
4889 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4890 config("gs://ckpts/a", None).validate().unwrap();
4891 }
4892
4893 #[test]
4894 fn take_bucket_ownership_defaults_to_false() {
4895 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4896 assert!(!sync.take_bucket_ownership);
4897
4898 let sync: SyncConfig =
4899 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4900 .unwrap();
4901 assert!(sync.take_bucket_ownership);
4902 }
4903}
4904
4905#[cfg(test)]
4906mod queue_limit_tests {
4907 use super::ConnectorConfig;
4908 use serde_json::json;
4909
4910 fn connector(extra: serde_json::Value) -> ConnectorConfig {
4911 let mut value = json!({"transport": {"name": "datagen", "config": {}}});
4912 value
4913 .as_object_mut()
4914 .unwrap()
4915 .extend(extra.as_object().unwrap().clone());
4916 serde_json::from_value(value).unwrap()
4917 }
4918
4919 #[test]
4920 fn zero_queue_limits_are_rejected() {
4921 let err = connector(json!({"max_queued_records": 0}))
4922 .validate_queue_limits()
4923 .unwrap_err();
4924 assert!(err.contains("max_queued_records"), "{err}");
4925
4926 for size in [json!(0), json!("0"), json!("0Mi")] {
4927 let err = connector(json!({"max_queued_size": size}))
4928 .validate_queue_limits()
4929 .unwrap_err();
4930 assert!(err.contains("max_queued_size"), "{err}");
4931 }
4932 let err = connector(json!({"max_queued_bytes": 0}))
4933 .validate_queue_limits()
4934 .unwrap_err();
4935 assert!(err.contains("max_queued_size"), "{err}");
4936 }
4937
4938 #[test]
4939 fn nonzero_queue_limits_are_accepted() {
4940 connector(json!({})).validate_queue_limits().unwrap();
4941 connector(json!({"max_queued_records": 1, "max_queued_size": 1}))
4942 .validate_queue_limits()
4943 .unwrap();
4944 }
4945}
4946
4947#[cfg(test)]
4948mod transport_metadata_tests {
4949 use super::TransportConfig;
4950 use serde_json::json;
4951
4952 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4953 serde_json::from_value(json!({
4954 "name": "nats_input",
4955 "config": {
4956 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4957 "stream_name": "orders",
4958 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4959 },
4960 }))
4961 .unwrap()
4962 }
4963
4964 #[test]
4965 fn nats_input_exposes_consumer_metadata() {
4966 let mut transport = nats_input(json!({ "team": "ingest" }));
4967 let metadata = transport.transport_metadata_mut().unwrap();
4968 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4969
4970 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4971 let TransportConfig::NatsInput(config) = &transport else {
4972 unreachable!()
4973 };
4974 assert_eq!(
4975 config
4976 .consumer_config
4977 .metadata
4978 .get("pipeline")
4979 .map(String::as_str),
4980 Some("orders_pipeline"),
4981 "writes through the returned map must reach the consumer config"
4982 );
4983 }
4984
4985 #[test]
4986 fn transports_without_metadata_return_none() {
4987 let mut transport: TransportConfig = serde_json::from_value(json!({
4988 "name": "file_input",
4989 "config": { "path": "/tmp/input.csv" },
4990 }))
4991 .unwrap();
4992 assert!(transport.transport_metadata_mut().is_none());
4993 }
4994}
4995
4996#[cfg(test)]
4997mod local_file_uri_tests {
4998 use super::TransportConfig;
4999 use serde_json::json;
5000
5001 #[test]
5002 fn local_file_uris() {
5003 let delta = |uri: &str| -> TransportConfig {
5004 serde_json::from_value(
5005 json!({"name": "delta_table_input", "config": {"uri": uri, "mode": "snapshot"}}),
5006 )
5007 .unwrap()
5008 };
5009 for uri in [
5010 "file:///etc",
5011 "FILE:/etc",
5012 "/etc",
5013 "./t",
5014 "",
5015 "c:/t",
5016 " file:///etc",
5017 ] {
5018 assert_eq!(delta(uri).local_file_uris(false), vec![("uri", uri)]);
5019 }
5020 for uri in [
5021 "s3://b/t",
5022 "gs://b/t",
5023 "az://c/t",
5024 "abfss://c@a/t",
5025 "uc://c.s.t",
5026 ] {
5027 assert!(delta(uri).local_file_uris(false).is_empty(), "{uri}");
5028 }
5029 assert!(delta("${env:X}").local_file_uris(false).is_empty());
5031 assert_eq!(
5032 delta("${env:X}").local_file_uris(true),
5033 vec![("uri", "${env:X}")]
5034 );
5035
5036 let iceberg: TransportConfig = serde_json::from_value(json!({"name": "iceberg_input",
5037 "config": {"mode": "snapshot", "metadata_location": "file:///t/m.json"}}))
5038 .unwrap();
5039 assert_eq!(
5040 iceberg.local_file_uris(false),
5041 vec![("metadata_location", "file:///t/m.json")]
5042 );
5043 }
5044}