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 {
348 let summary = serde_json::json!({
350 "name": self.name,
351 "given_name": self.given_name,
352 "global": self.global,
353 "storage_config": self.storage_config,
354 "secrets_dir": self.secrets_dir,
355 "inputs": self.inputs,
356 "outputs": self.outputs
357 });
358
359 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
360 }
361}
362
363#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
371pub struct PipelineConfigProgramInfo {
372 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
374
375 #[serde(default)]
377 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
378
379 #[serde(default)]
381 pub program_ir: Option<ProgramIr>,
382}
383
384#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
388pub struct MultihostConfig {
389 pub hosts: usize,
395}
396
397impl Default for MultihostConfig {
398 fn default() -> Self {
399 Self { hosts: 1 }
400 }
401}
402
403#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
405pub struct StorageConfig {
406 pub path: String,
415
416 #[serde(default)]
418 pub cache: StorageCacheConfig,
419}
420
421impl StorageConfig {
422 pub fn path(&self) -> &Path {
423 Path::new(&self.path)
424 }
425}
426
427#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
429#[serde(rename_all = "snake_case")]
430pub enum StorageCacheConfig {
431 #[default]
436 PageCache,
437
438 FelderaCache,
443}
444
445impl StorageCacheConfig {
446 #[cfg(unix)]
447 pub fn to_custom_open_flags(&self) -> i32 {
448 match self {
449 StorageCacheConfig::PageCache => (),
450 StorageCacheConfig::FelderaCache => {
451 #[cfg(target_os = "linux")]
452 return libc::O_DIRECT;
453 }
454 }
455 0
456 }
457}
458
459#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
461#[serde(default)]
462pub struct StorageOptions {
463 pub backend: StorageBackendConfig,
465
466 #[serde(
480 alias = "min_storage_bytes",
481 deserialize_with = "size_min_spill_size",
482 skip_serializing_if = "Option::is_none"
483 )]
484 #[schema(value_type = Option<String>)]
485 pub min_spill_size: Option<ConfigSize>,
486
487 #[serde(
501 alias = "min_step_storage_bytes",
502 deserialize_with = "size_min_step_spill_size",
503 skip_serializing_if = "Option::is_none"
504 )]
505 #[schema(value_type = Option<String>)]
506 pub min_step_spill_size: Option<ConfigSize>,
507
508 pub compression: StorageCompression,
514
515 pub compression_level: Option<i32>,
526
527 #[serde(
536 alias = "cache_mib",
537 deserialize_with = "size_cache_size",
538 skip_serializing_if = "Option::is_none"
539 )]
540 #[schema(value_type = Option<String>)]
541 pub cache_size: Option<ConfigSize>,
542
543 #[serde(skip_serializing_if = "Option::is_none")]
558 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
559 pub bloom_false_positive_rate: Option<f64>,
560}
561
562impl Eq for StorageOptions {}
565
566#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
568#[serde(tag = "name", content = "config", rename_all = "snake_case")]
569pub enum StorageBackendConfig {
570 #[default]
574 Default,
575
576 File(Box<FileBackendConfig>),
580
581 Object(ObjectStorageConfig),
583}
584
585impl Display for StorageBackendConfig {
586 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
587 match self {
588 StorageBackendConfig::Default => write!(f, "default"),
589 StorageBackendConfig::File(_) => write!(f, "file"),
590 StorageBackendConfig::Object(_) => write!(f, "object"),
591 }
592 }
593}
594
595#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
597#[serde(rename_all = "snake_case")]
598pub enum StorageCompression {
599 #[default]
604 Default,
605
606 None,
608
609 Snappy,
611
612 Lz4,
617
618 Zstd,
624}
625
626#[derive(Debug, Clone, Eq, PartialEq)]
627pub enum StartFromCheckpoint {
628 Latest,
629 Uuid(uuid::Uuid),
630}
631
632impl ToSchema<'_> for StartFromCheckpoint {
633 fn schema() -> (
634 &'static str,
635 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
636 ) {
637 (
638 "StartFromCheckpoint",
639 utoipa::openapi::RefOr::T(Schema::OneOf(
640 OneOfBuilder::new()
641 .item(
642 ObjectBuilder::new()
643 .schema_type(SchemaType::String)
644 .enum_values(Some(["latest"].into_iter()))
645 .build(),
646 )
647 .item(
648 ObjectBuilder::new()
649 .schema_type(SchemaType::String)
650 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
651 utoipa::openapi::KnownFormat::Uuid,
652 )))
653 .build(),
654 )
655 .nullable(true)
656 .build(),
657 )),
658 )
659 }
660}
661
662impl<'de> Deserialize<'de> for StartFromCheckpoint {
663 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
664 where
665 D: Deserializer<'de>,
666 {
667 struct StartFromCheckpointVisitor;
668
669 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
670 type Value = StartFromCheckpoint;
671
672 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
673 formatter.write_str("a UUID string or the string \"latest\"")
674 }
675
676 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
677 where
678 E: de::Error,
679 {
680 if value == "latest" {
681 Ok(StartFromCheckpoint::Latest)
682 } else {
683 uuid::Uuid::parse_str(value)
684 .map(StartFromCheckpoint::Uuid)
685 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
686 }
687 }
688 }
689
690 deserializer.deserialize_str(StartFromCheckpointVisitor)
691 }
692}
693
694impl Serialize for StartFromCheckpoint {
695 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
696 where
697 S: serde::Serializer,
698 {
699 match self {
700 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
701 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
702 }
703 }
704}
705
706#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
707pub struct SyncConfig {
708 pub endpoint: Option<String>,
721
722 pub bucket: String,
736
737 pub region: Option<String>,
741
742 pub provider: Option<String>,
749
750 pub access_key: Option<String>,
758
759 pub secret_key: Option<String>,
769
770 pub start_from_checkpoint: Option<StartFromCheckpoint>,
775
776 #[schema(default = std::primitive::bool::default)]
782 #[serde(default)]
783 pub fail_if_no_checkpoint: bool,
784
785 pub transfers: Option<u8>,
788
789 pub checkers: Option<u8>,
792
793 pub ignore_checksum: Option<bool>,
797
798 pub multi_thread_streams: Option<u8>,
801
802 pub multi_thread_cutoff: Option<String>,
807
808 #[schema(default = default_optimize_download_resources)]
819 #[serde(default = "default_optimize_download_resources")]
820 pub optimize_download_resources: bool,
821
822 pub upload_concurrency: Option<u8>,
825
826 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
828 #[schema(default = std::primitive::bool::default)]
829 #[serde(default)]
830 pub standby: bool,
831
832 #[serde(
838 default,
839 alias = "pull_interval",
840 deserialize_with = "duration_standby_pull_interval",
841 skip_serializing_if = "Option::is_none"
842 )]
843 #[schema(value_type = Option<String>, default = default_pull_interval)]
844 pub standby_pull_interval: Option<ConfigDuration>,
845
846 #[serde(
852 default,
853 alias = "push_interval",
854 deserialize_with = "duration_checkpoint_push_interval",
855 skip_serializing_if = "Option::is_none"
856 )]
857 #[schema(value_type = Option<String>)]
858 pub checkpoint_push_interval: Option<ConfigDuration>,
859
860 pub flags: Option<Vec<String>>,
869
870 #[schema(default = default_retention_min_count)]
875 #[serde(default = "default_retention_min_count")]
876 pub retention_min_count: u32,
877
878 #[serde(
882 default,
883 alias = "retention_min_age",
884 deserialize_with = "duration_min_retention",
885 skip_serializing_if = "Option::is_none"
886 )]
887 #[schema(value_type = Option<String>, default = default_retention_min_age)]
888 pub min_retention: Option<ConfigDuration>,
889
890 #[serde(default)]
904 pub read_bucket: Option<String>,
905
906 #[schema(default = std::primitive::bool::default)]
932 #[serde(default)]
933 pub take_bucket_ownership: bool,
934}
935
936fn default_retention_min_count() -> u32 {
937 10
938}
939
940fn default_optimize_download_resources() -> bool {
941 true
942}
943
944impl SyncConfig {
945 pub fn standby_pull_interval(&self) -> ConfigDuration {
952 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
953 }
954
955 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
957 self.checkpoint_push_interval
958 }
959
960 pub fn min_retention(&self) -> ConfigDuration {
963 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
964 }
965
966 pub fn validate(&self) -> Result<(), String> {
967 #[allow(deprecated)]
968 if self.standby {
969 return Err(
970 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
971 );
972 }
973
974 if let Some(ref rb) = self.read_bucket {
975 if rb == &self.bucket {
976 return Err(
977 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
978 .to_owned(),
979 );
980 }
981 if SyncObjectStore::of(rb) != SyncObjectStore::of(&self.bucket) {
984 return Err(format!(
985 "invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage, both with `az://` for Azure Blob Storage, or neither for S3",
986 self.bucket, rb
987 ));
988 }
989 }
990
991 if SyncObjectStore::of(&self.bucket) == SyncObjectStore::AzureBlob
994 && self.access_key.as_deref().is_none_or(str::is_empty)
995 {
996 return Err(format!(
997 "invalid sync config: `bucket` ('{}') is in Azure Blob Storage, which needs the name of the storage account; set `access_key` to it",
998 self.bucket
999 ));
1000 }
1001
1002 for (field, bucket) in [
1003 ("bucket", Some(&self.bucket)),
1004 ("read_bucket", self.read_bucket.as_ref()),
1005 ] {
1006 if let Some(bucket) = bucket
1007 && azure_container(bucket) == Some("")
1008 {
1009 return Err(format!(
1010 "invalid sync config: `{field}` ('{bucket}') does not name a container; write it as `az://<container>[/<path>]`"
1011 ));
1012 }
1013 }
1014
1015 Ok(())
1016 }
1017}
1018
1019#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1021enum SyncObjectStore {
1022 S3,
1023 Gcs,
1024 AzureBlob,
1025}
1026
1027impl SyncObjectStore {
1028 fn of(bucket: &str) -> Self {
1029 if bucket.starts_with("gs://") {
1030 Self::Gcs
1031 } else if bucket.starts_with("az://") {
1032 Self::AzureBlob
1033 } else {
1034 Self::S3
1035 }
1036 }
1037}
1038
1039fn azure_container(bucket: &str) -> Option<&str> {
1042 let path = bucket.strip_prefix("az://")?;
1043 Some(path.split('/').next().unwrap_or_default())
1044}
1045
1046#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
1082pub struct PipelineTemplateConfig {
1083 pub name: String,
1085 #[schema(default = default_pipeline_template_key)]
1089 #[serde(default = "default_pipeline_template_key")]
1090 pub key: String,
1091}
1092
1093fn default_pipeline_template_key() -> String {
1094 "pipelineTemplate".to_string()
1095}
1096
1097#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1098pub struct ObjectStorageConfig {
1099 pub url: String,
1128
1129 #[serde(flatten)]
1162 pub other_options: BTreeMap<String, String>,
1163}
1164
1165#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1167#[serde(default)]
1168pub struct FileBackendConfig {
1169 pub async_threads: Option<bool>,
1175
1176 #[serde(
1181 default,
1182 alias = "ioop_delay",
1183 deserialize_with = "duration_ioop_latency",
1184 skip_serializing_if = "Option::is_none"
1185 )]
1186 #[schema(value_type = Option<String>)]
1187 pub ioop_latency: Option<ConfigDuration>,
1188
1189 pub sync: Option<SyncConfig>,
1191
1192 pub sync_mode: Option<StorageSyncMode>,
1197}
1198
1199#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1205#[serde(rename_all = "snake_case")]
1206pub enum StorageSyncMode {
1207 #[default]
1210 Auto,
1211
1212 Syncfs,
1222
1223 PerFile,
1228}
1229
1230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1233#[serde(default)]
1234pub struct RuntimeConfig {
1235 pub workers: u16,
1245
1246 #[serde(
1275 default,
1276 alias = "max_rss_mb",
1277 deserialize_with = "size_max_rss",
1278 skip_serializing_if = "Option::is_none"
1279 )]
1280 #[schema(value_type = Option<String>)]
1281 pub max_rss: Option<ConfigSize>,
1282
1283 #[serde(
1306 default,
1307 alias = "datafusion_memory_mb",
1308 deserialize_with = "size_datafusion_memory",
1309 skip_serializing_if = "Option::is_none"
1310 )]
1311 #[schema(value_type = Option<String>)]
1312 pub datafusion_memory: Option<ConfigSize>,
1313
1314 pub hosts: usize,
1321
1322 #[serde(deserialize_with = "deserialize_storage_options")]
1334 pub storage: Option<StorageOptions>,
1335
1336 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1338 pub fault_tolerance: FtConfig,
1339
1340 pub cpu_profiler: bool,
1344
1345 pub tracing: bool,
1347
1348 pub tracing_endpoint_jaeger: String,
1350
1351 pub min_batch_size_records: u64,
1359
1360 #[serde(
1363 default,
1364 alias = "max_buffering_delay_usecs",
1365 deserialize_with = "duration_max_buffering_delay",
1366 skip_serializing_if = "Option::is_none"
1367 )]
1368 #[schema(value_type = Option<String>)]
1369 pub max_buffering_delay: Option<ConfigDuration>,
1370
1371 pub resources: ResourceConfig,
1374
1375 #[serde(
1385 default,
1386 alias = "clock_resolution_usecs",
1387 deserialize_with = "duration_clock_resolution",
1388 skip_serializing_if = "Option::is_none"
1389 )]
1390 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1391 pub clock_resolution: Option<ConfigDuration>,
1392
1393 #[schema(value_type = Option<String>, example = "+05:30")]
1404 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1405
1406 pub pin_cpus: Vec<usize>,
1415
1416 #[serde(
1419 default,
1420 alias = "provisioning_timeout_secs",
1421 deserialize_with = "duration_provisioning_timeout",
1422 skip_serializing_if = "Option::is_none"
1423 )]
1424 #[schema(value_type = Option<String>)]
1425 pub provisioning_timeout: Option<ConfigDuration>,
1426
1427 pub max_parallel_connector_init: Option<u64>,
1438
1439 pub init_containers: Option<serde_json::Value>,
1441
1442 pub checkpoint_during_suspend: bool,
1444
1445 pub http_workers: Option<u64>,
1453
1454 pub io_workers: Option<u64>,
1465
1466 #[serde(default)]
1473 pub env: BTreeMap<String, String>,
1474
1475 pub dev_tweaks: DevTweaks,
1477
1478 pub logging: Option<String>,
1487
1488 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1496}
1497
1498fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1500where
1501 D: Deserializer<'de>,
1502{
1503 struct BoolOrStruct;
1504
1505 impl<'de> Visitor<'de> for BoolOrStruct {
1506 type Value = Option<StorageOptions>;
1507
1508 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1509 formatter.write_str("boolean or StorageOptions")
1510 }
1511
1512 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1513 where
1514 E: de::Error,
1515 {
1516 match v {
1517 false => Ok(None),
1518 true => Ok(Some(StorageOptions::default())),
1519 }
1520 }
1521
1522 fn visit_unit<E>(self) -> Result<Self::Value, E>
1523 where
1524 E: de::Error,
1525 {
1526 Ok(None)
1527 }
1528
1529 fn visit_none<E>(self) -> Result<Self::Value, E>
1530 where
1531 E: de::Error,
1532 {
1533 Ok(None)
1534 }
1535
1536 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1537 where
1538 M: MapAccess<'de>,
1539 {
1540 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1541 }
1542 }
1543
1544 deserializer.deserialize_any(BoolOrStruct)
1545}
1546
1547fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1555where
1556 D: Deserializer<'de>,
1557{
1558 struct StringOrStruct;
1559
1560 impl<'de> Visitor<'de> for StringOrStruct {
1561 type Value = FtConfig;
1562
1563 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1564 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1565 }
1566
1567 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1568 where
1569 E: de::Error,
1570 {
1571 match v {
1572 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1573 model: Some(FtModel::default()),
1574 ..FtConfig::default()
1575 }),
1576 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1577 }
1578 }
1579
1580 fn visit_unit<E>(self) -> Result<Self::Value, E>
1581 where
1582 E: de::Error,
1583 {
1584 Ok(FtConfig::default())
1585 }
1586
1587 fn visit_none<E>(self) -> Result<Self::Value, E>
1588 where
1589 E: de::Error,
1590 {
1591 Ok(FtConfig::default())
1592 }
1593
1594 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1595 where
1596 M: MapAccess<'de>,
1597 {
1598 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1599 }
1600 }
1601
1602 deserializer.deserialize_any(StringOrStruct)
1603}
1604
1605impl Default for RuntimeConfig {
1606 fn default() -> Self {
1607 Self {
1608 workers: 8,
1609 max_rss: None,
1610 datafusion_memory: None,
1611 hosts: 1,
1612 storage: Some(StorageOptions::default()),
1613 fault_tolerance: FtConfig::default(),
1614 cpu_profiler: true,
1615 tracing: {
1616 false
1619 },
1620 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1621 min_batch_size_records: 0,
1622 max_buffering_delay: None,
1623 resources: ResourceConfig::default(),
1624 clock_resolution: None,
1625 clock_timezone_offset: None,
1626 pin_cpus: Vec::new(),
1627 provisioning_timeout: None,
1628 max_parallel_connector_init: None,
1629 init_containers: None,
1630 checkpoint_during_suspend: true,
1631 io_workers: None,
1632 http_workers: None,
1633 env: BTreeMap::default(),
1634 dev_tweaks: DevTweaks::default(),
1635 logging: None,
1636 pipeline_template_configmap: None,
1637 }
1638 }
1639}
1640
1641pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1645
1646pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1649
1650impl RuntimeConfig {
1651 pub fn max_buffering_delay(&self) -> ConfigDuration {
1653 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1654 }
1655
1656 pub fn clock_resolution(&self) -> ConfigDuration {
1658 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1659 }
1660
1661 pub fn effective_memory(&self) -> Option<ConfigSize> {
1664 self.max_rss
1665 .into_iter()
1666 .chain(self.resources.memory_max)
1667 .min()
1668 }
1669
1670 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1675 if let Some(explicit) = self.datafusion_memory {
1676 return Some(explicit);
1677 }
1678 let effective = self.effective_memory()?.as_bytes();
1679 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1681 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1682 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1683 }
1684
1685 pub fn datafusion_memory_exceeding_budget(&self) -> Option<(ConfigSize, ConfigSize)> {
1688 let budget = self.effective_memory()?;
1689 let datafusion = self.resolved_datafusion_memory()?;
1690 (datafusion >= budget).then_some((datafusion, budget))
1691 }
1692}
1693
1694#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1705#[serde(rename_all = "snake_case")]
1706pub struct FtConfig {
1707 #[serde(with = "none_as_string")]
1709 #[serde(default = "default_model")]
1710 #[schema(
1711 schema_with = none_as_string_schema::<FtModel>,
1712 )]
1713 pub model: Option<FtModel>,
1714
1715 #[serde(
1722 default,
1723 alias = "checkpoint_interval_secs",
1724 deserialize_with = "duration_checkpoint_interval",
1725 skip_serializing_if = "Option::is_none"
1726 )]
1727 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1728 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1729}
1730
1731fn default_model() -> Option<FtModel> {
1732 Some(FtModel::default())
1733}
1734
1735pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1755 use crate::duration::LegacyUnit;
1756 use serde_json::{Map, Value};
1757
1758 struct Rule {
1760 new: &'static str,
1761 old: &'static str,
1762 unit: LegacyUnit,
1763 max: u64,
1765 null_allowed: bool,
1768 }
1769 const fn rule(
1770 new: &'static str,
1771 old: &'static str,
1772 unit: LegacyUnit,
1773 max: u64,
1774 null_allowed: bool,
1775 ) -> Rule {
1776 Rule {
1777 new,
1778 old,
1779 unit,
1780 max,
1781 null_allowed,
1782 }
1783 }
1784 const U32: u64 = u32::MAX as u64;
1785 const U64: u64 = u64::MAX;
1786 use LegacyUnit::{Days, Micros, Millis, Secs};
1787
1788 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1789 for rule in rules {
1790 let Some(value) = object.remove(rule.new) else {
1791 continue;
1792 };
1793 let legacy = match &value {
1794 Value::String(text) => match text.parse::<ConfigDuration>() {
1795 Ok(duration) => {
1796 let nanos = std::time::Duration::from(duration).as_nanos();
1797 let unit_nanos = u128::from(rule.unit.nanos());
1798 let whole = nanos.div_ceil(unit_nanos);
1799 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1800 }
1801 Err(_) => {
1802 object.insert(rule.new.to_string(), value);
1803 continue;
1804 }
1805 },
1806 Value::Null if !rule.null_allowed => continue,
1807 other => other.clone(),
1809 };
1810 object.insert(rule.old.to_string(), legacy);
1811 }
1812 }
1813 fn child<'a>(
1814 object: &'a mut Map<String, Value>,
1815 key: &str,
1816 ) -> Option<&'a mut Map<String, Value>> {
1817 object.get_mut(key).and_then(Value::as_object_mut)
1818 }
1819 fn max_expiry(consumer: &mut Map<String, Value>) {
1822 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1823 return;
1824 };
1825 let Ok(duration) = text.parse::<ConfigDuration>() else {
1826 return;
1827 };
1828 let duration = std::time::Duration::from(duration);
1829 consumer.remove("max_expiry");
1830 consumer.insert(
1831 "max_expires".to_string(),
1832 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1833 );
1834 }
1835 fn nats_connection(transport: &mut Map<String, Value>) {
1837 if let Some(connection) = child(transport, "connection_config") {
1838 apply(
1839 connection,
1840 &[
1841 rule(
1842 "connection_timeout",
1843 "connection_timeout_secs",
1844 Secs,
1845 U64,
1846 false,
1847 ),
1848 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1849 ],
1850 );
1851 }
1852 }
1853 fn connector(endpoint: &mut Map<String, Value>) {
1855 apply(
1856 endpoint,
1857 &[rule(
1858 "max_output_buffer_time",
1859 "max_output_buffer_time_millis",
1860 Millis,
1861 U64,
1862 false,
1863 )],
1864 );
1865 let name = endpoint
1866 .get("transport")
1867 .and_then(|transport| transport.get("name"))
1868 .and_then(Value::as_str)
1869 .map(str::to_string);
1870 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1871 match name.as_deref() {
1872 Some("url_input") => apply(
1873 transport,
1874 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1875 ),
1876 Some("kafka_input") => apply(
1877 transport,
1878 &[rule(
1879 "group_join_timeout",
1880 "group_join_timeout_secs",
1881 Secs,
1882 U32,
1883 false,
1884 )],
1885 ),
1886 Some("kafka_output") => apply(
1887 transport,
1888 &[rule(
1889 "initialization_timeout",
1890 "initialization_timeout_secs",
1891 Secs,
1892 U32,
1893 false,
1894 )],
1895 ),
1896 Some("clock_input") => apply(
1897 transport,
1898 &[rule(
1899 "clock_resolution",
1900 "clock_resolution_usecs",
1901 Micros,
1902 U64,
1903 false,
1904 )],
1905 ),
1906 Some("pub_sub_input") => apply(
1907 transport,
1908 &[
1909 rule("timeout", "timeout_seconds", Secs, U32, true),
1910 rule(
1911 "connect_timeout",
1912 "connect_timeout_seconds",
1913 Secs,
1914 U32,
1915 true,
1916 ),
1917 ],
1918 ),
1919 Some("nats_input") => {
1920 apply(
1921 transport,
1922 &[
1923 rule(
1924 "inactivity_timeout",
1925 "inactivity_timeout_secs",
1926 Secs,
1927 U64,
1928 false,
1929 ),
1930 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1931 ],
1932 );
1933 nats_connection(transport);
1934 if let Some(consumer) = child(transport, "consumer_config") {
1935 max_expiry(consumer);
1936 }
1937 }
1938 Some("nats_output") => {
1939 apply(
1940 transport,
1941 &[rule(
1942 "publish_timeout",
1943 "publish_timeout_secs",
1944 Secs,
1945 U64,
1946 false,
1947 )],
1948 );
1949 nats_connection(transport);
1950 }
1951 _ => {}
1952 }
1953 }
1954 let is_avro = endpoint
1955 .get("format")
1956 .and_then(|format| format.get("name"))
1957 .and_then(Value::as_str)
1958 == Some("avro");
1959 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1960 {
1961 apply(
1962 format,
1963 &[rule(
1964 "registry_timeout",
1965 "registry_timeout_secs",
1966 Secs,
1967 U64,
1968 true,
1969 )],
1970 );
1971 }
1972 }
1973
1974 let Some(global) = config.as_object_mut() else {
1975 return;
1976 };
1977 apply(
1978 global,
1979 &[
1980 rule(
1981 "clock_resolution",
1982 "clock_resolution_usecs",
1983 Micros,
1984 U64,
1985 true,
1986 ),
1987 rule(
1988 "max_buffering_delay",
1989 "max_buffering_delay_usecs",
1990 Micros,
1991 U64,
1992 false,
1993 ),
1994 rule(
1995 "provisioning_timeout",
1996 "provisioning_timeout_secs",
1997 Secs,
1998 U64,
1999 true,
2000 ),
2001 ],
2002 );
2003 if let Some(ft) = child(global, "fault_tolerance") {
2004 apply(
2006 ft,
2007 &[rule(
2008 "checkpoint_interval",
2009 "checkpoint_interval_secs",
2010 Secs,
2011 U64,
2012 true,
2013 )],
2014 );
2015 }
2016 let backend = child(global, "storage")
2017 .and_then(|storage| child(storage, "backend"))
2018 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
2019 .and_then(|backend| child(backend, "config"));
2020 if let Some(file) = backend {
2021 apply(
2022 file,
2023 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
2024 );
2025 if let Some(sync) = child(file, "sync") {
2026 apply(
2027 sync,
2028 &[
2029 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
2030 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
2031 rule("min_retention", "retention_min_age", Days, U32, false),
2032 ],
2033 );
2034 }
2035 }
2036 for endpoints in ["inputs", "outputs"] {
2037 if let Some(endpoints) = child(global, endpoints) {
2038 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2039 connector(endpoint);
2040 }
2041 }
2042 }
2043}
2044
2045#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
2051pub struct LegacySpelling {
2052 pub durations: bool,
2054 pub sizes: bool,
2056}
2057
2058impl LegacySpelling {
2059 pub const NONE: LegacySpelling = LegacySpelling {
2061 durations: false,
2062 sizes: false,
2063 };
2064
2065 pub fn any(self) -> bool {
2067 self.durations || self.sizes
2068 }
2069
2070 pub fn apply(self, config: &mut serde_json::Value) {
2073 if self.durations {
2074 to_legacy_duration_spelling(config);
2075 }
2076 if self.sizes {
2077 to_legacy_size_spelling(config);
2078 }
2079 }
2080}
2081
2082pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
2093 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
2094 use serde_json::{Map, Value};
2095
2096 struct Rule {
2098 new: &'static str,
2099 old: &'static str,
2100 unit: LegacySizeUnit,
2101 }
2102 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2103 Rule { new, old, unit }
2104 }
2105
2106 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2107 for rule in rules {
2108 let Some(value) = object.remove(rule.new) else {
2109 continue;
2110 };
2111 let legacy = match &value {
2112 Value::String(text) => match text.parse::<ConfigSize>() {
2113 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2114 Err(_) => {
2115 object.insert(rule.new.to_string(), value);
2116 continue;
2117 }
2118 },
2119 Value::Null => continue,
2121 other => other.clone(),
2123 };
2124 object.insert(rule.old.to_string(), legacy);
2125 }
2126 }
2127 fn child<'a>(
2128 object: &'a mut Map<String, Value>,
2129 key: &str,
2130 ) -> Option<&'a mut Map<String, Value>> {
2131 object.get_mut(key).and_then(Value::as_object_mut)
2132 }
2133 fn connector(endpoint: &mut Map<String, Value>) {
2135 apply(
2136 endpoint,
2137 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2138 );
2139 let name = endpoint
2140 .get("transport")
2141 .and_then(|transport| transport.get("name"))
2142 .and_then(Value::as_str)
2143 .map(str::to_string);
2144 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2145 match name.as_deref() {
2146 Some("file_input") => apply(
2147 transport,
2148 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2149 ),
2150 Some("dynamodb_output" | "postgres_output") => apply(
2151 transport,
2152 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2153 ),
2154 Some("postgres_cdc_input") => {
2155 if let Some(batch) = child(transport, "batch") {
2156 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2157 }
2158 }
2159 _ => {}
2160 }
2161 }
2162 }
2163
2164 let Some(global) = config.as_object_mut() else {
2165 return;
2166 };
2167 apply(
2168 global,
2169 &[
2170 rule("max_rss", "max_rss_mb", Megabytes),
2171 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2172 ],
2173 );
2174 if let Some(storage) = child(global, "storage") {
2175 apply(
2176 storage,
2177 &[
2178 rule("cache_size", "cache_mib", Mebibytes),
2179 rule("min_spill_size", "min_storage_bytes", Bytes),
2180 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2181 ],
2182 );
2183 }
2184 if let Some(resources) = child(global, "resources") {
2185 apply(
2186 resources,
2187 &[
2188 rule("memory_min", "memory_mb_min", Megabytes),
2189 rule("memory_max", "memory_mb_max", Megabytes),
2190 rule("storage_min", "storage_mb_min", Megabytes),
2191 rule("storage_max", "storage_mb_max", Megabytes),
2192 ],
2193 );
2194 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2195 apply(
2196 storage,
2197 &[rule(
2198 "scale_threshold_available",
2199 "scale_threshold_available_mb",
2200 Megabytes,
2201 )],
2202 );
2203 }
2204 }
2205 if let Some(tweaks) = child(global, "dev_tweaks") {
2206 apply(
2207 tweaks,
2208 &[
2209 rule("storage_max", "storage_mb_max", Mebibytes),
2210 rule(
2211 "fbuf_slab_size_per_class",
2212 "fbuf_slab_bytes_per_class",
2213 Bytes,
2214 ),
2215 rule(
2216 "lazy_input_map_key_block_size",
2217 "lazy_input_map_key_block_bytes",
2218 Bytes,
2219 ),
2220 rule(
2221 "exchange_channel_capacity",
2222 "exchange_channel_capacity_bytes",
2223 Bytes,
2224 ),
2225 ],
2226 );
2227 }
2228 for endpoints in ["inputs", "outputs"] {
2229 if let Some(endpoints) = child(global, endpoints) {
2230 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2231 connector(endpoint);
2232 }
2233 }
2234 }
2235}
2236
2237#[cfg(test)]
2238mod test {
2239 use super::deserialize_fault_tolerance;
2240 use crate::config::{
2241 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2242 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2243 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2244 StorageOptions, SyncConfig, TransportConfig,
2245 };
2246 use crate::duration::ConfigDuration;
2247 use crate::size::ConfigSize;
2248 use serde::{Deserialize, Serialize};
2249 use serde_json::json;
2250 use std::time::Duration;
2251
2252 fn assert_reloads<T>(value: serde_json::Value)
2255 where
2256 T: Serialize + for<'de> Deserialize<'de>,
2257 {
2258 let first: T = serde_json::from_value(value.clone())
2259 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2260 let written = serde_json::to_value(&first).unwrap();
2261 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2262 panic!("{value} is written as {written}, which does not load: {e}")
2263 });
2264 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2265 }
2266
2267 #[test]
2272 fn size_settings_reload_from_what_is_written() {
2273 use crate::transport::dynamodb::DynamoDBWriterConfig;
2274 use crate::transport::file::FileInputConfig;
2275 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2276
2277 for number in [0u64, 1, 1_100, u64::MAX] {
2280 assert_reloads::<RuntimeConfig>(json!({
2281 "max_rss_mb": number,
2282 "datafusion_memory_mb": number,
2283 "storage": {"cache_mib": number, "min_storage_bytes": number},
2284 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2285 "dev_tweaks": {"storage_mb_max": number},
2286 }));
2287 }
2288
2289 let max = format!("{}B", u64::MAX);
2290 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2291 assert_reloads::<RuntimeConfig>(json!({
2292 "max_rss": size,
2293 "datafusion_memory": size,
2294 "storage": {
2295 "cache_size": size,
2296 "min_spill_size": size,
2297 "min_step_spill_size": size,
2298 },
2299 "resources": {
2300 "memory_min": size,
2301 "memory_max": size,
2302 "storage_min": size,
2303 "storage_max": size,
2304 "autoscaling": {"storage": {"scale_threshold_available": size}},
2305 },
2306 "dev_tweaks": {
2307 "storage_max": size,
2308 "fbuf_slab_size_per_class": size,
2309 "exchange_channel_capacity": size,
2310 },
2311 }));
2312 assert_reloads::<ConnectorConfig>(json!({
2313 "transport": {
2314 "name": "file_input",
2315 "config": {"path": "input.csv", "buffer_size": size},
2316 },
2317 "max_queued_size": size,
2318 }));
2319 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2320 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2321 assert_reloads::<PostgresWriterConfig>(json!({
2322 "uri": "postgres://localhost/db",
2323 "table": "t",
2324 "max_buffer_size": size,
2325 }));
2326 assert_reloads::<DynamoDBWriterConfig>(json!({
2327 "table": "t",
2328 "region": "us-east-1",
2329 "max_buffer_size": size,
2330 }));
2331 }
2332 }
2333
2334 #[test]
2339 fn soft_delete_is_backward_compatible() {
2340 let config: ConnectorConfig = serde_json::from_value(json!({
2341 "transport": {"name": "empty_input"}
2342 }))
2343 .unwrap();
2344 assert!(!config.soft_delete);
2345
2346 let serialized = serde_json::to_value(&config).unwrap();
2347 assert_eq!(serialized.get("soft_delete"), None);
2348
2349 let config: ConnectorConfig = serde_json::from_value(json!({
2350 "transport": {"name": "empty_input"},
2351 "soft_delete": true
2352 }))
2353 .unwrap();
2354 assert!(config.soft_delete);
2355 assert_eq!(
2356 serde_json::to_value(&config).unwrap().get("soft_delete"),
2357 Some(&json!(true))
2358 );
2359 }
2360
2361 #[test]
2364 fn soft_delete_invalidates_checkpointed_connector_state() {
2365 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2366 let mut soft_delete = config.clone();
2367 soft_delete.soft_delete = true;
2368
2369 assert!(config.equal_for_input_checkpoint_replay(&config));
2370 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2371 }
2372
2373 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2374 PipelineConfig {
2375 global: RuntimeConfig::default(),
2376 multihost: None,
2377 name: name.map(str::to_string),
2378 given_name: None,
2379 storage_config: None,
2380 secrets_dir: None,
2381 inputs: Default::default(),
2382 outputs: Default::default(),
2383 program_ir: None,
2384 }
2385 }
2386
2387 #[test]
2388 fn pipeline_identity_uses_system_and_given_names() {
2389 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2390 config.given_name = Some("my-pipeline".to_string());
2391
2392 let metadata = config.pipeline_identity().unwrap();
2393 assert_eq!(
2394 metadata.name,
2395 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2396 );
2397 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2398 }
2399
2400 #[test]
2401 fn pipeline_identity_is_none_without_system_name() {
2402 assert_eq!(config_with_name(None).pipeline_identity(), None);
2403 }
2404
2405 #[test]
2406 fn resolved_datafusion_memory_explicit_passes_through() {
2407 let config = RuntimeConfig {
2408 max_rss: Some(ConfigSize::from_mb(8_000)),
2409 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2410 ..Default::default()
2411 };
2412 assert_eq!(
2413 config.resolved_datafusion_memory(),
2414 Some(ConfigSize::from_mb(1_500))
2415 );
2416 }
2417
2418 #[test]
2419 fn effective_memory_is_the_smaller_budget() {
2420 let mb = |mb: Option<u64>| mb.map(ConfigSize::from_mb);
2421 for (max_rss, memory_max, expected) in [
2422 (None, None, None),
2423 (Some(8_000), None, Some(8_000)),
2424 (None, Some(4_000), Some(4_000)),
2425 (Some(8_000), Some(4_000), Some(4_000)),
2426 (Some(2_000), Some(4_000), Some(2_000)),
2427 ] {
2428 let config = RuntimeConfig {
2429 max_rss: mb(max_rss),
2430 resources: ResourceConfig {
2431 memory_max: mb(memory_max),
2432 ..Default::default()
2433 },
2434 ..Default::default()
2435 };
2436 assert_eq!(
2437 config.effective_memory(),
2438 mb(expected),
2439 "{max_rss:?}, {memory_max:?}"
2440 );
2441 }
2442 }
2443
2444 #[test]
2445 fn resolved_datafusion_memory_unconfigured_returns_none() {
2446 let config = RuntimeConfig::default();
2447 assert!(config.max_rss.is_none());
2448 assert!(config.resources.memory_max.is_none());
2449 assert_eq!(config.resolved_datafusion_memory(), None);
2450 }
2451
2452 #[test]
2453 fn resolved_datafusion_memory_small_budget_scales_down() {
2454 let config = RuntimeConfig {
2456 max_rss: Some(ConfigSize::from_mb(256)),
2457 ..Default::default()
2458 };
2459 assert_eq!(
2460 config.resolved_datafusion_memory(),
2461 Some(ConfigSize::from_bytes(12_800_000))
2462 );
2463
2464 let config = RuntimeConfig {
2465 max_rss: Some(ConfigSize::from_mb(512)),
2466 ..Default::default()
2467 };
2468 assert_eq!(
2469 config.resolved_datafusion_memory(),
2470 Some(ConfigSize::from_bytes(25_600_000))
2471 );
2472 }
2473
2474 #[test]
2475 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2476 let config = RuntimeConfig {
2478 max_rss: Some(ConfigSize::from_mb(64_000)),
2479 ..Default::default()
2480 };
2481 assert_eq!(
2482 config.resolved_datafusion_memory(),
2483 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2484 );
2485 }
2486
2487 #[test]
2488 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2489 let config = RuntimeConfig {
2491 max_rss: Some(ConfigSize::from_mb(16_000)),
2492 ..Default::default()
2493 };
2494 assert_eq!(
2495 config.resolved_datafusion_memory(),
2496 Some(ConfigSize::from_mb(800))
2497 );
2498 }
2499
2500 #[test]
2501 fn resolved_datafusion_memory_falls_back_to_resources() {
2502 let config = RuntimeConfig {
2504 max_rss: None,
2505 resources: ResourceConfig {
2506 memory_max: Some(ConfigSize::from_mb(16_000)),
2507 ..Default::default()
2508 },
2509 ..Default::default()
2510 };
2511 assert_eq!(
2512 config.resolved_datafusion_memory(),
2513 Some(ConfigSize::from_mb(800))
2514 );
2515 }
2516
2517 #[test]
2518 fn ft_config() {
2519 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2520 #[serde(default)]
2521 struct Wrapper {
2522 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2523 config: FtConfig,
2524 }
2525
2526 for s in [
2529 "{}",
2530 r#"{"config": null}"#,
2531 r#"{"config": {"model": "none"}}"#,
2532 ] {
2533 let config: Wrapper = serde_json::from_str(s).unwrap();
2534 assert_eq!(config.config.model, None);
2535 assert_eq!(config.config.checkpoint_interval(), None);
2536 }
2537
2538 let s = serde_json::to_string(&Wrapper {
2540 config: FtConfig::default(),
2541 })
2542 .unwrap();
2543 assert!(s.contains("\"none\""));
2544
2545 for s in [
2548 r#"{}"#,
2549 r#"{"checkpoint_interval": "60s"}"#,
2550 r#"{"checkpoint_interval_secs": 60}"#,
2551 ] {
2552 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2553 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2554 assert_eq!(
2555 config.checkpoint_interval(),
2556 Some(Duration::from_secs(60)),
2557 "parsing {s}"
2558 );
2559 }
2560
2561 for s in [
2564 r#"{"checkpoint_interval": null}"#,
2565 r#"{"checkpoint_interval_secs": null}"#,
2566 ] {
2567 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2568 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2569 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2570 }
2571
2572 let error = serde_json::from_str::<FtConfig>(
2575 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2576 )
2577 .unwrap_err()
2578 .to_string();
2579 assert!(error.contains("duplicate field"), "{error}");
2580
2581 for (json, expected_secs) in [
2583 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2584 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2585 ] {
2586 assert_eq!(
2587 serde_json::from_str::<FtConfig>(json)
2588 .unwrap()
2589 .checkpoint_interval(),
2590 Some(Duration::from_secs(expected_secs)),
2591 "parsing {json}"
2592 );
2593 }
2594 }
2595
2596 #[test]
2600 fn legacy_duration_spelling_uses_the_older_keys() {
2601 let mut config = serde_json::json!({
2602 "workers": 2,
2603 "clock_resolution": "250ms",
2604 "max_buffering_delay": "3ms",
2605 "provisioning_timeout": "15m",
2606 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2607 "storage": {"backend": {"name": "file", "config": {
2608 "ioop_latency": "5ms",
2609 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2610 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2611 });
2612 super::to_legacy_duration_spelling(&mut config);
2613 assert_eq!(
2614 config,
2615 serde_json::json!({
2616 "workers": 2,
2617 "clock_resolution_usecs": 250_000,
2618 "max_buffering_delay_usecs": 3_000,
2619 "provisioning_timeout_secs": 900,
2620 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2621 "storage": {"backend": {"name": "file", "config": {
2622 "ioop_delay": 5,
2623 "sync": {"bucket": "b", "pull_interval": 10,
2624 "push_interval": 3_600, "retention_min_age": 30}}}},
2625 })
2626 );
2627 }
2628
2629 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2631 serde_json::json!({
2632 "name": "p",
2633 "clock_resolution": "250ms",
2634 "inputs": {
2635 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2636 "topic": "t", "group_join_timeout": "30s"}}},
2637 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2638 "path": "http://x", "pause_linger": "7s"}}},
2639 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2640 "connection_config": {"server_url": "nats://x",
2641 "connection_timeout": "5s", "request_timeout": "6s"},
2642 "stream_name": "s",
2643 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2644 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2645 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2646 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2647 },
2648 "outputs": {
2649 "v.kafka": {"stream": "v",
2650 "transport": {"name": "kafka_output", "config": {
2651 "topic": "v", "initialization_timeout": "40s"}},
2652 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2653 "registry_timeout": "8s"}},
2654 "enable_output_buffer": true,
2655 "max_output_buffer_time": "500ms"},
2656 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2657 "connection_config": {"server_url": "nats://x",
2658 "connection_timeout": "5s", "request_timeout": "6s"},
2659 "subject": "s", "publish_timeout": "9s"}}},
2660 },
2661 })
2662 }
2663
2664 #[test]
2668 fn legacy_duration_spelling_rewrites_every_connector() {
2669 let mut config = pipeline_with_every_duration_connector();
2670 super::to_legacy_duration_spelling(&mut config);
2671 let i = &config["inputs"];
2672 assert_eq!(
2673 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2674 30
2675 );
2676 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2677 let nats = &i["t.nats"]["transport"]["config"];
2678 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2679 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2680 assert_eq!(nats["inactivity_timeout_secs"], 90);
2681 assert_eq!(nats["retry_interval_secs"], 3);
2682 assert_eq!(
2683 nats["consumer_config"]["max_expires"],
2684 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2685 );
2686 let pubsub = &i["t.pubsub"]["transport"]["config"];
2687 assert_eq!(pubsub["timeout_seconds"], 20);
2688 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2689 let out = &config["outputs"]["v.kafka"];
2690 assert_eq!(
2691 out["transport"]["config"]["initialization_timeout_secs"],
2692 40
2693 );
2694 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2695 assert_eq!(out["max_output_buffer_time_millis"], 500);
2696 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2697 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2698 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2699 assert_eq!(nats["publish_timeout_secs"], 9);
2700
2701 let text = config.to_string();
2703 for new in [
2704 "\"group_join_timeout\"",
2705 "\"pause_linger\"",
2706 "\"connection_timeout\"",
2707 "\"request_timeout\"",
2708 "\"inactivity_timeout\"",
2709 "\"retry_interval\"",
2710 "\"max_expiry\"",
2711 "\"timeout\"",
2712 "\"connect_timeout\"",
2713 "\"initialization_timeout\"",
2714 "\"registry_timeout\"",
2715 "\"max_output_buffer_time\"",
2716 "\"publish_timeout\"",
2717 "\"clock_resolution\"",
2718 ] {
2719 assert!(!text.contains(new), "{new} survived in {text}");
2720 }
2721 }
2722
2723 #[test]
2725 fn legacy_duration_spelling_round_trips_connectors() {
2726 let original: PipelineConfig =
2727 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2728 let mut value = serde_json::to_value(&original).unwrap();
2729 super::to_legacy_duration_spelling(&mut value);
2730 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2731
2732 let registry = |config: &PipelineConfig| {
2735 let format = config.outputs["v.kafka"]
2736 .connector_config
2737 .format
2738 .clone()
2739 .unwrap();
2740 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2741 .unwrap()
2742 .registry_config
2743 .registry_timeout
2744 };
2745 assert_eq!(registry(&reread), registry(&original));
2746 let mut original = original;
2747 for config in [&mut reread, &mut original] {
2748 config
2749 .outputs
2750 .get_mut("v.kafka")
2751 .unwrap()
2752 .connector_config
2753 .format = None;
2754 }
2755 assert_eq!(reread, original);
2756 }
2757
2758 #[test]
2762 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2763 let mut config = serde_json::json!({
2764 "inputs": {
2765 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2766 "group_join_timeout": "100000000000s"}}},
2767 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2768 },
2769 "storage": {"backend": {"name": "file", "config": {
2770 "sync": {"min_retention": "100000000000d"}}}},
2771 });
2772 super::to_legacy_duration_spelling(&mut config);
2773 let i = &config["inputs"];
2774 assert_eq!(
2775 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2776 u64::from(u32::MAX)
2777 );
2778 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2779 assert_eq!(
2780 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2781 u64::from(u32::MAX)
2782 );
2783 }
2784
2785 #[test]
2789 fn legacy_duration_spelling_round_trips() {
2790 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2791 "clock_resolution": "250ms",
2792 "max_buffering_delay": "3ms",
2793 "provisioning_timeout": "15m",
2794 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2795 }))
2796 .unwrap();
2797 let mut value = serde_json::to_value(&original).unwrap();
2798 super::to_legacy_duration_spelling(&mut value);
2799 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2800 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2801 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2802 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2803 assert_eq!(
2804 reread.fault_tolerance.checkpoint_interval(),
2805 original.fault_tolerance.checkpoint_interval()
2806 );
2807 }
2808
2809 #[test]
2814 fn legacy_duration_spelling_edge_cases() {
2815 let mut config = serde_json::json!({
2816 "max_buffering_delay": null,
2817 "provisioning_timeout": "1.5s",
2818 "fault_tolerance": {"checkpoint_interval": null},
2819 "clock_resolution": "10sec",
2820 "storage": {"backend": {"name": "file", "config": {
2821 "ioop_latency": "400us",
2822 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2823 });
2824 super::to_legacy_duration_spelling(&mut config);
2825 assert_eq!(
2826 config,
2827 serde_json::json!({
2828 "provisioning_timeout_secs": 2,
2829 "fault_tolerance": {"checkpoint_interval_secs": null},
2830 "clock_resolution": "10sec",
2831 "storage": {"backend": {"name": "file", "config": {
2832 "ioop_delay": 1,
2833 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2834 })
2835 );
2836
2837 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2839 super::to_legacy_duration_spelling(&mut zero);
2840 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2841
2842 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2844 let mut again = legacy.clone();
2845 super::to_legacy_duration_spelling(&mut again);
2846 assert_eq!(again, legacy);
2847 }
2848
2849 #[test]
2853 fn legacy_size_spelling_uses_the_older_keys() {
2854 let mut config = serde_json::json!({
2855 "workers": 2,
2856 "max_rss": "16G",
2857 "datafusion_memory": "1.5G",
2858 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2859 "resources": {
2860 "memory_min": "4G", "memory_max": "16Gi",
2861 "storage_min": "100G", "storage_max": "400Gi",
2862 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2863 },
2864 "dev_tweaks": {
2865 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2866 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2867 },
2868 "inputs": {
2869 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2870 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2871 "t.cdc": {"stream": "t",
2872 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2873 },
2874 "outputs": {
2875 "v.ddb": {"stream": "v",
2876 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2877 "v.pg": {"stream": "v",
2878 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2879 },
2880 });
2881 super::to_legacy_size_spelling(&mut config);
2882 assert_eq!(
2883 config,
2884 serde_json::json!({
2885 "workers": 2,
2886 "max_rss_mb": 16_000,
2887 "datafusion_memory_mb": 1_500,
2888 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2889 "resources": {
2890 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2892 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2893 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2894 },
2895 "dev_tweaks": {
2896 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2897 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2898 },
2899 "inputs": {
2900 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2901 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2902 "t.cdc": {"stream": "t",
2903 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2904 },
2905 "outputs": {
2906 "v.ddb": {"stream": "v",
2907 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2908 "v.pg": {"stream": "v",
2909 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2910 },
2911 })
2912 );
2913 }
2914
2915 #[test]
2920 fn distributed_output_streams() {
2921 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2922 "name": "p",
2923 "inputs": {"t.kafka": {"stream": "t", "distributed": true,
2924 "transport": {"name": "kafka_input", "config": {
2925 "topic": "t", "bootstrap.servers": "localhost:9092"}}}},
2926 "outputs": {
2927 "a": {"stream": "A", "distributed": true,
2928 "transport": {"name": "delta_table_output", "config": {
2929 "uri": "memory://", "mode": "append"}}},
2930 "b": {"stream": "b", "distributed": true, "index": "B_Idx",
2931 "transport": {"name": "null_output"}},
2932 "c": {"stream": "c",
2933 "transport": {"name": "null_output"}},
2934 "d": {"stream": "d", "distributed": true,
2935 "transport": {"name": "delta_table_output", "config": {
2936 "uri": "memory://", "mode": "truncate"}}},
2937 },
2938 }))
2939 .unwrap();
2940 assert_eq!(
2941 config.distributed_output_streams(),
2942 std::collections::BTreeSet::from(["a".into(), "b_idx".into()])
2943 );
2944 }
2945
2946 #[test]
2949 fn legacy_size_spelling_round_trips() {
2950 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2951 "name": "p",
2952 "max_rss": "16G",
2953 "datafusion_memory": "1G",
2956 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2957 "resources": {"memory_max": "16G", "storage_max": "400G"},
2958 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2959 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2960 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2961 "outputs": {},
2962 }))
2963 .unwrap();
2964 let mut value = serde_json::to_value(&config).unwrap();
2965 super::to_legacy_size_spelling(&mut value);
2966 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2967 assert_eq!(
2968 value["inputs"]["t.file"]["max_queued_bytes"],
2969 serde_json::json!(1024 * 1024)
2970 );
2971 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2972 assert_eq!(reread, config);
2973 }
2974
2975 #[test]
2978 fn legacy_spelling_applies_each_rename_separately() {
2979 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2980 let mut both = current.clone();
2981 super::LegacySpelling {
2982 durations: true,
2983 sizes: true,
2984 }
2985 .apply(&mut both);
2986 assert_eq!(
2987 both,
2988 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2989 );
2990 let mut sizes_only = current.clone();
2991 super::LegacySpelling {
2992 durations: false,
2993 sizes: true,
2994 }
2995 .apply(&mut sizes_only);
2996 assert_eq!(
2997 sizes_only,
2998 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2999 );
3000 let mut none = current.clone();
3001 super::LegacySpelling::NONE.apply(&mut none);
3002 assert_eq!(none, current);
3003 assert!(!super::LegacySpelling::NONE.any());
3004 }
3005
3006 #[test]
3007 fn legacy_size_spelling_edge_cases() {
3008 let mut config = serde_json::json!({
3011 "max_rss": "lots",
3012 "resources": {"memory_max": null, "memory_min": 4000}
3013 });
3014 super::to_legacy_size_spelling(&mut config);
3015 assert_eq!(
3016 config,
3017 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
3018 );
3019
3020 let mut small = serde_json::json!({"max_rss": "1"});
3023 super::to_legacy_size_spelling(&mut small);
3024 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
3025
3026 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
3028 let mut again = legacy.clone();
3029 super::to_legacy_size_spelling(&mut again);
3030 assert_eq!(again, legacy);
3031 }
3032
3033 #[test]
3042 fn a_stored_default_matches_an_omitted_one() {
3043 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
3044 "transport": {
3045 "name": "url_input",
3046 "config": {"path": "http://example.com/x", "pause_timeout": 60},
3047 }
3048 }))
3049 .unwrap();
3050 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
3051 "transport": {
3052 "name": "url_input",
3053 "config": {"path": "http://example.com/x"},
3054 }
3055 }))
3056 .unwrap();
3057
3058 assert_ne!(stored, fresh);
3061 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
3062
3063 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
3065 "transport": {
3066 "name": "url_input",
3067 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
3068 }
3069 }))
3070 .unwrap();
3071 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
3072 }
3073
3074 #[test]
3082 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
3083 let connector = |registry: serde_json::Value| -> ConnectorConfig {
3084 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
3085 format
3086 .as_object_mut()
3087 .unwrap()
3088 .extend(registry.as_object().unwrap().clone());
3089 serde_json::from_value(serde_json::json!({
3090 "transport": {
3091 "name": "url_input",
3092 "config": {"path": "http://example.com/x"},
3093 },
3094 "format": {"name": "avro", "config": format},
3095 }))
3096 .unwrap()
3097 };
3098 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
3099 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
3100 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
3101 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
3102 let unset = connector(serde_json::json!({}));
3103
3104 assert!(stored.equal_modulo_paused(¤t));
3105 assert!(stored.equal_for_input_checkpoint_replay(¤t));
3106 assert!(current.equal_modulo_paused(&spelled_out));
3107 assert!(!stored.equal_modulo_paused(&changed));
3108 assert!(!stored.equal_modulo_paused(&unset));
3109 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
3111 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
3112 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
3113 }))
3114 .unwrap();
3115 assert!(!json.equal_modulo_paused(&stored));
3116 }
3117
3118 #[test]
3124 fn the_largest_legacy_defaults_still_load() {
3125 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
3126 "enable_output_buffer": false,
3127 "max_output_buffer_time_millis": u64::MAX,
3128 "max_output_buffer_size_records": 10_000_000u64,
3129 }))
3130 .unwrap();
3131 assert_eq!(
3132 buffer.max_output_buffer_time,
3133 Some(ConfigDuration::from_millis(u64::MAX))
3134 );
3135
3136 let sync: SyncConfig =
3138 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
3139 assert_eq!(
3140 sync.min_retention(),
3141 ConfigDuration::from_days(4_000_000_000)
3142 );
3143 }
3144
3145 #[test]
3149 fn a_legacy_number_past_u64_seconds_saturates() {
3150 let sync: SyncConfig =
3151 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
3152 .unwrap();
3153 assert_eq!(
3154 sync.min_retention(),
3155 ConfigDuration::from(std::time::Duration::MAX)
3156 );
3157 }
3158
3159 #[test]
3163 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3164 fn connector(value: serde_json::Value) -> ConnectorConfig {
3165 serde_json::from_value(value).unwrap()
3166 }
3167 fn secs(duration: ConfigDuration) -> u64 {
3168 std::time::Duration::from(duration).as_secs()
3169 }
3170 let fresh_kafka = connector(serde_json::json!({
3171 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3172 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3173 unreachable!()
3174 };
3175 let stored_kafka = connector(serde_json::json!({
3176 "transport": {"name": "kafka_input", "config": {
3177 "topic": "t",
3178 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3179 assert_ne!(stored_kafka, fresh_kafka);
3180 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3181
3182 let base = serde_json::json!({
3183 "connection_config": {"server_url": "nats://x"},
3184 "stream_name": "s",
3185 "consumer_config": {"deliver_policy": "All"}});
3186 let fresh_nats = connector(serde_json::json!({
3187 "transport": {"name": "nats_input", "config": base.clone()}}));
3188 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3189 unreachable!()
3190 };
3191 let mut spelled_out = base;
3192 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3193 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3194 spelled_out["connection_config"]["connection_timeout_secs"] =
3195 secs(nats.connection_config.connection_timeout()).into();
3196 spelled_out["connection_config"]["request_timeout_secs"] =
3197 secs(nats.connection_config.request_timeout()).into();
3198 let stored_nats = connector(serde_json::json!({
3199 "transport": {"name": "nats_input", "config": spelled_out}}));
3200 assert_ne!(stored_nats, fresh_nats);
3201 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3202 }
3203
3204 #[test]
3210 fn superseded_keys_are_normalised_by_a_round_trip() {
3211 let stored = serde_json::json!({
3212 "workers": 4,
3213 "clock_resolution_usecs": 100_000,
3214 "max_buffering_delay_usecs": 0,
3215 "provisioning_timeout_secs": 300,
3216 });
3217
3218 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3219 let written = serde_json::to_value(&config).unwrap();
3220
3221 assert_eq!(written["clock_resolution"], "100ms");
3222 assert_eq!(written["max_buffering_delay"], "0s");
3223 assert_eq!(written["provisioning_timeout"], "5m");
3224 for superseded in [
3225 "clock_resolution_usecs",
3226 "max_buffering_delay_usecs",
3227 "provisioning_timeout_secs",
3228 ] {
3229 assert!(
3230 written.get(superseded).is_none(),
3231 "`{superseded}` survived the round trip: {written}"
3232 );
3233 }
3234
3235 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3238 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3239 }
3240
3241 #[test]
3246 fn ioop_latency_accepts_both_spellings() {
3247 for (json, expected) in [
3248 (r#"{"name": "file", "config": {}}"#, None),
3249 (
3250 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3251 Some(ConfigDuration::from_millis(5)),
3252 ),
3253 (
3254 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3255 Some(ConfigDuration::from_millis(5)),
3256 ),
3257 (
3258 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3259 Some(ConfigDuration::from_secs(1)),
3260 ),
3261 ] {
3262 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3263 let StorageBackendConfig::File(file) = backend else {
3264 panic!("expected the file backend, parsing {json}");
3265 };
3266 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3267 }
3268 }
3269
3270 #[test]
3274 fn clock_resolution_falls_back_to_the_deprecated_field() {
3275 for (json, expected) in [
3276 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3277 (
3278 r#"{"clock_resolution": "100ms"}"#,
3279 ConfigDuration::from_millis(100),
3280 ),
3281 (
3282 r#"{"clock_resolution_usecs": 100000}"#,
3283 ConfigDuration::from_millis(100),
3284 ),
3285 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3286 (
3287 r#"{"clock_resolution_usecs": null}"#,
3288 DEFAULT_CLOCK_RESOLUTION,
3289 ),
3290 ] {
3291 assert_eq!(
3292 serde_json::from_str::<RuntimeConfig>(json)
3293 .unwrap()
3294 .clock_resolution(),
3295 expected,
3296 "parsing {json}"
3297 );
3298 }
3299 }
3300
3301 #[test]
3304 fn deprecated_duration_fields_still_work() {
3305 let runtime: RuntimeConfig = serde_json::from_str(
3306 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3307 )
3308 .unwrap();
3309 assert_eq!(
3310 runtime.max_buffering_delay(),
3311 ConfigDuration::from_millis(5)
3312 );
3313 assert_eq!(
3314 runtime.provisioning_timeout,
3315 Some(ConfigDuration::from_secs(1200))
3316 );
3317
3318 let sync: SyncConfig = serde_json::from_str(
3319 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3320 )
3321 .unwrap();
3322 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3323 assert_eq!(
3324 sync.checkpoint_push_interval(),
3325 Some(ConfigDuration::from_secs(300))
3326 );
3327 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3328
3329 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3330 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3331
3332 let buffer: OutputBufferConfig =
3333 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3334 assert_eq!(
3335 buffer.max_output_buffer_time(),
3336 ConfigDuration::from_millis(250)
3337 );
3338 }
3339
3340 #[test]
3343 fn duration_fields_default_when_unset() {
3344 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3345 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3346 assert_eq!(sync.checkpoint_push_interval(), None);
3347 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3348
3349 let runtime = RuntimeConfig::default();
3350 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3351 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3352 assert_eq!(runtime.provisioning_timeout, None);
3353 }
3354
3355 #[test]
3359 fn storage_options_f64_roundtrip_through_pipeline_config() {
3360 let pc = PipelineConfig {
3361 global: RuntimeConfig {
3362 storage: Some(StorageOptions {
3363 bloom_false_positive_rate: Some(0.01),
3364 ..Default::default()
3365 }),
3366 ..Default::default()
3367 },
3368 multihost: None,
3369 name: Some("test-pipeline".into()),
3370 given_name: None,
3371 storage_config: None,
3372 secrets_dir: None,
3373 inputs: Default::default(),
3374 outputs: Default::default(),
3375 program_ir: None,
3376 };
3377
3378 let json = serde_json::to_string_pretty(&pc).unwrap();
3380 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3381 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3382 );
3383 assert_eq!(
3384 pc2.global.storage.unwrap().bloom_false_positive_rate,
3385 Some(0.01)
3386 );
3387
3388 let value = serde_json::to_value(&pc).unwrap();
3390 let pc3: PipelineConfig = serde_json::from_value(value)
3391 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3392 assert_eq!(
3393 pc3.global.storage.unwrap().bloom_false_positive_rate,
3394 Some(0.01)
3395 );
3396 }
3397}
3398
3399impl FtConfig {
3400 pub fn is_enabled(&self) -> bool {
3401 self.model.is_some()
3402 }
3403
3404 pub fn checkpoint_interval(&self) -> Option<Duration> {
3411 if !self.is_enabled() {
3412 return None;
3413 }
3414
3415 let interval = self
3416 .checkpoint_interval
3417 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3418
3419 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3420 }
3421}
3422
3423mod none_as_string {
3430 use std::marker::PhantomData;
3431
3432 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3433 use serde::ser::{Serialize, Serializer};
3434
3435 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3436 where
3437 S: Serializer,
3438 T: Serialize,
3439 {
3440 match value.as_ref() {
3441 Some(value) => value.serialize(serializer),
3442 None => "none".serialize(serializer),
3443 }
3444 }
3445
3446 struct NoneAsString<T>(PhantomData<fn() -> T>);
3447
3448 impl<'de, T> Visitor<'de> for NoneAsString<T>
3449 where
3450 T: Deserialize<'de>,
3451 {
3452 type Value = Option<T>;
3453
3454 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3455 formatter.write_str("string")
3456 }
3457
3458 fn visit_none<E>(self) -> Result<Self::Value, E>
3459 where
3460 E: serde::de::Error,
3461 {
3462 Ok(None)
3463 }
3464
3465 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3466 where
3467 E: serde::de::Error,
3468 {
3469 if &value.to_ascii_lowercase() == "none" {
3470 Ok(None)
3471 } else {
3472 Ok(Some(T::deserialize(value.into_deserializer())?))
3473 }
3474 }
3475 }
3476
3477 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3478 where
3479 D: Deserializer<'de>,
3480 T: Deserialize<'de>,
3481 {
3482 deserializer.deserialize_str(NoneAsString(PhantomData))
3483 }
3484}
3485
3486fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3489 Schema::OneOf(
3490 OneOfBuilder::new()
3491 .item(RefOr::Ref(Ref::new(format!(
3492 "#/components/schemas/{}",
3493 T::schema().0
3494 ))))
3495 .item(
3496 ObjectBuilder::new()
3497 .schema_type(SchemaType::String)
3498 .enum_values(Some(vec!["none"])),
3499 )
3500 .default(Some(
3501 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3502 ))
3503 .build(),
3504 )
3505}
3506
3507#[derive(
3512 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3513)]
3514#[serde(rename_all = "snake_case")]
3515pub enum FtModel {
3516 AtLeastOnce,
3519
3520 #[default]
3523 ExactlyOnce,
3524}
3525
3526impl FtModel {
3527 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3528 value.map_or("no", |model| model.as_str())
3529 }
3530
3531 pub fn as_str(&self) -> &'static str {
3532 match self {
3533 FtModel::AtLeastOnce => "at_least_once",
3534 FtModel::ExactlyOnce => "exactly_once",
3535 }
3536 }
3537}
3538
3539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3541pub struct FtModelUnknown;
3542
3543impl std::fmt::Display for FtModelUnknown {
3544 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3545 f.write_str("expected `exactly_once` or `at_least_once`")
3546 }
3547}
3548
3549impl std::error::Error for FtModelUnknown {}
3550
3551impl FromStr for FtModel {
3552 type Err = FtModelUnknown;
3553
3554 fn from_str(s: &str) -> Result<Self, Self::Err> {
3555 match s.to_ascii_lowercase().as_str() {
3556 "exactly_once" => Ok(Self::ExactlyOnce),
3557 "at_least_once" => Ok(Self::AtLeastOnce),
3558 _ => Err(FtModelUnknown),
3559 }
3560 }
3561}
3562
3563#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3565pub struct InputEndpointConfig {
3566 pub stream: Cow<'static, str>,
3569
3570 #[serde(flatten)]
3572 pub connector_config: ConnectorConfig,
3573}
3574
3575impl InputEndpointConfig {
3576 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3577 Self {
3578 stream: stream.into(),
3579 connector_config,
3580 }
3581 }
3582}
3583
3584fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3588where
3589 D: Deserializer<'de>,
3590{
3591 let value = Option::<JsonValue>::deserialize(deserializer)?;
3592 match value {
3593 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3594 Some(JsonValue::Array(arr)) => {
3595 let vec = arr
3596 .into_iter()
3597 .map(|item| {
3598 item.as_str()
3599 .map(|s| s.to_string())
3600 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3601 })
3602 .collect::<Result<Vec<String>, _>>()?;
3603 Ok(Some(vec))
3604 }
3605 Some(JsonValue::Null) | None => Ok(None),
3606 _ => Err(serde::de::Error::custom(
3607 "invalid 'start_after' property: expected a string, an array of strings, or null",
3608 )),
3609 }
3610}
3611
3612#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3613pub struct ConnectorConfig {
3614 #[serde(default)]
3630 pub send_snapshot: bool,
3631
3632 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3649 pub soft_delete: bool,
3650
3651 pub transport: TransportConfig,
3653
3654 #[serde(skip_serializing_if = "Option::is_none")]
3656 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3657
3658 pub format: Option<FormatConfig>,
3660
3661 #[serde(skip_serializing_if = "Option::is_none")]
3663 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3664
3665 pub index: Option<String>,
3680
3681 #[serde(flatten)]
3683 pub output_buffer_config: OutputBufferConfig,
3684
3685 #[serde(skip_serializing_if = "Option::is_none")]
3698 pub max_batch_size: Option<u64>,
3699
3700 #[serde(skip_serializing_if = "Option::is_none")]
3713 pub max_worker_batch_size: Option<u64>,
3714
3715 #[serde(default = "default_max_queued_records")]
3736 pub max_queued_records: u64,
3737
3738 #[serde(
3761 default,
3762 alias = "max_queued_bytes",
3763 deserialize_with = "size_max_queued_size",
3764 skip_serializing_if = "Option::is_none"
3765 )]
3766 #[schema(value_type = Option<String>)]
3767 pub max_queued_size: Option<ConfigSize>,
3768
3769 #[serde(default)]
3780 pub paused: bool,
3781
3782 #[serde(default)]
3787 pub labels: Vec<String>,
3788
3789 #[serde(deserialize_with = "deserialize_start_after")]
3795 #[serde(default)]
3796 pub start_after: Option<Vec<String>>,
3797
3798 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3821 pub distributed: bool,
3822}
3823
3824impl ConnectorConfig {
3825 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3826 Self {
3827 send_snapshot: false,
3828 soft_delete: false,
3829 transport,
3830 preprocessor: None,
3831 format,
3832 postprocessor: None,
3833 index: None,
3834 output_buffer_config: Default::default(),
3835 max_batch_size: None,
3836 max_worker_batch_size: None,
3837 max_queued_records: default_max_queued_records(),
3838 max_queued_size: None,
3839 paused: false,
3840 labels: Vec::new(),
3841 start_after: None,
3842 distributed: false,
3843 }
3844 }
3845
3846 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3847 self.max_batch_size = max_batch_size;
3848 self
3849 }
3850
3851 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3852 self.max_queued_records = max_queued_records;
3853 self
3854 }
3855
3856 pub fn validate_queue_limits(&self) -> Result<(), String> {
3861 if self.max_queued_records == 0 {
3862 return Err("'max_queued_records' must be greater than 0".to_string());
3863 }
3864 if self.max_queued_size.is_some() && self.max_queued_bytes() == 0 {
3865 return Err("'max_queued_size' must be greater than 0".to_string());
3866 }
3867 Ok(())
3868 }
3869
3870 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3875 let mut a = self.clone();
3876 let mut b = other.clone();
3877 a.paused = false;
3878 b.paused = false;
3879 a.normalize_durations();
3880 b.normalize_durations();
3881 a == b
3882 }
3883
3884 fn normalize_durations(&mut self) {
3895 self.transport.normalize_durations();
3896 self.output_buffer_config.max_output_buffer_time =
3897 Some(self.output_buffer_config.max_output_buffer_time());
3898 if let Some(format) = &mut self.format {
3899 format.normalize_durations();
3900 }
3901 }
3902
3903 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3906 let mut a = self.clone();
3907 let mut b = other.clone();
3908 a.normalize_for_input_checkpoint_replay();
3909 b.normalize_for_input_checkpoint_replay();
3910 a == b
3911 }
3912
3913 fn normalize_for_input_checkpoint_replay(&mut self) {
3914 self.paused = false;
3915 self.max_batch_size = None;
3916 self.max_worker_batch_size = None;
3917 self.max_queued_records = default_max_queued_records();
3918 self.max_queued_size = None;
3919 self.normalize_durations();
3920 }
3921
3922 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3925 self.max_batch_size = other.max_batch_size;
3926 self.max_worker_batch_size = other.max_worker_batch_size;
3927 self.max_queued_records = other.max_queued_records;
3928 self.max_queued_size = other.max_queued_size;
3929 }
3930
3931 pub fn max_queued_records(&self) -> u64 {
3933 self.max_queued_records
3934 }
3935
3936 pub fn max_queued_bytes(&self) -> u64 {
3939 self.max_queued_size
3940 .map(ConfigSize::as_bytes)
3941 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3942 }
3943}
3944
3945#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3946#[serde(default)]
3947pub struct OutputBufferConfig {
3948 pub enable_output_buffer: bool,
3971
3972 #[serde(
3981 default,
3982 alias = "max_output_buffer_time_millis",
3983 deserialize_with = "duration_max_output_buffer_time",
3984 skip_serializing_if = "Option::is_none"
3985 )]
3986 #[schema(value_type = Option<String>)]
3987 pub max_output_buffer_time: Option<ConfigDuration>,
3988
3989 pub max_output_buffer_size_records: usize,
4001}
4002
4003impl OutputBufferConfig {
4004 pub fn max_output_buffer_time(&self) -> ConfigDuration {
4006 self.max_output_buffer_time
4007 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
4008 }
4009}
4010
4011impl Default for OutputBufferConfig {
4012 fn default() -> Self {
4013 Self {
4014 enable_output_buffer: false,
4015 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
4016 max_output_buffer_time: None,
4017 }
4018 }
4019}
4020
4021#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
4023pub struct OutputEndpointConfig {
4024 pub stream: Cow<'static, str>,
4027
4028 #[serde(flatten)]
4030 pub connector_config: ConnectorConfig,
4031}
4032
4033impl OutputEndpointConfig {
4034 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
4035 Self {
4036 stream: stream.into(),
4037 connector_config,
4038 }
4039 }
4040}
4041
4042#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
4046#[serde(tag = "name", content = "config", rename_all = "snake_case")]
4047pub enum TransportConfig {
4048 FileInput(FileInputConfig),
4049 FileOutput(FileOutputConfig),
4050 NatsInput(Box<NatsInputConfig>),
4053 NatsOutput(NatsOutputConfig),
4054 KafkaInput(KafkaInputConfig),
4055 KafkaOutput(KafkaOutputConfig),
4056 PubSubInput(PubSubInputConfig),
4057 UrlInput(UrlInputConfig),
4058 S3Input(S3InputConfig),
4059 DeltaTableInput(DeltaTableReaderConfig),
4060 DeltaTableOutput(DeltaTableWriterConfig),
4061 #[serde(rename = "dynamodb_output")]
4064 DynamoDBOutput(DynamoDBWriterConfig),
4065 RedisOutput(RedisOutputConfig),
4066 IcebergInput(Box<IcebergReaderConfig>),
4068 PostgresInput(PostgresReaderConfig),
4069 PostgresCdcInput(PostgresCdcReaderConfig),
4070 PostgresOutput(PostgresWriterConfig),
4071 Datagen(DatagenInputConfig),
4072 Nexmark(NexmarkInputConfig),
4073 HttpInput(HttpInputConfig),
4075 HttpOutput(HttpOutputConfig),
4077 AdHocInput(AdHocInputConfig),
4079 ClockInput(ClockConfig),
4080 S2Input(S2InputConfig),
4081 S2Output(S2OutputConfig),
4082 NullOutput,
4084 EmptyInput,
4086}
4087
4088pub const REFUSE_LOCAL_FILE_URIS_ENV: &str = "FELDERA_REFUSE_LOCAL_FILE_URIS";
4091
4092fn is_local_file_uri(location: &str) -> bool {
4094 let Some((scheme, _)) = location.split_once(':') else {
4095 return true;
4096 };
4097 let valid_scheme = scheme.len() > 1
4098 && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
4099 && scheme
4100 .chars()
4101 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
4102 !valid_scheme || scheme.eq_ignore_ascii_case("file")
4103}
4104
4105impl TransportConfig {
4106 pub fn local_file_uris(&self, resolved: bool) -> Vec<(&'static str, &str)> {
4110 let locations = match self {
4111 TransportConfig::DeltaTableInput(config) => vec![("uri", Some(&*config.uri))],
4112 TransportConfig::DeltaTableOutput(config) => vec![("uri", Some(&*config.uri))],
4113 TransportConfig::IcebergInput(config) => vec![
4114 ("metadata_location", config.metadata_location.as_deref()),
4115 (
4116 "glue.warehouse",
4117 config.glue_catalog_config.warehouse.as_deref(),
4118 ),
4119 ],
4120 _ => Vec::new(),
4121 };
4122 locations
4123 .into_iter()
4124 .filter_map(|(property, location)| Some((property, location?)))
4125 .filter(|(_, location)| {
4126 (resolved
4127 || matches!(
4128 MaybeSecretRef::new(location.to_string()),
4129 Ok(MaybeSecretRef::String(_))
4130 ))
4131 && is_local_file_uri(location)
4132 })
4133 .collect()
4134 }
4135
4136 pub fn normalize_durations(&mut self) {
4139 match self {
4140 TransportConfig::UrlInput(config) => {
4141 config.pause_linger = Some(config.pause_linger());
4142 }
4143 TransportConfig::KafkaInput(config) => {
4144 config.group_join_timeout = Some(config.group_join_timeout());
4145 }
4146 TransportConfig::KafkaOutput(config) => {
4147 config.initialization_timeout = Some(config.initialization_timeout());
4148 }
4149 TransportConfig::NatsInput(config) => {
4150 config.connection_config.connection_timeout =
4151 Some(config.connection_config.connection_timeout());
4152 config.connection_config.request_timeout =
4153 Some(config.connection_config.request_timeout());
4154 config.inactivity_timeout = Some(config.inactivity_timeout());
4155 config.retry_interval = Some(config.retry_interval());
4156 }
4157 TransportConfig::NatsOutput(config) => {
4158 config.connection_config.connection_timeout =
4159 Some(config.connection_config.connection_timeout());
4160 config.connection_config.request_timeout =
4161 Some(config.connection_config.request_timeout());
4162 config.publish_timeout = Some(config.publish_timeout());
4163 }
4164 _ => {}
4165 }
4166 }
4167
4168 pub fn name(&self) -> String {
4169 match self {
4170 TransportConfig::FileInput(_) => "file_input".to_string(),
4171 TransportConfig::FileOutput(_) => "file_output".to_string(),
4172 TransportConfig::NatsInput(_) => "nats_input".to_string(),
4173 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
4174 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
4175 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
4176 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
4177 TransportConfig::UrlInput(_) => "url_input".to_string(),
4178 TransportConfig::S3Input(_) => "s3_input".to_string(),
4179 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
4180 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
4181 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
4182 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
4183 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
4184 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
4185 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
4186 TransportConfig::Datagen(_) => "datagen".to_string(),
4187 TransportConfig::Nexmark(_) => "nexmark".to_string(),
4188 TransportConfig::HttpInput(_) => "http_input".to_string(),
4189 TransportConfig::HttpOutput(_) => "http_output".to_string(),
4190 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
4191 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
4192 TransportConfig::ClockInput(_) => "clock".to_string(),
4193 TransportConfig::S2Input(_) => "s2_input".to_string(),
4194 TransportConfig::S2Output(_) => "s2_output".to_string(),
4195 TransportConfig::NullOutput => "null_output".to_string(),
4196 TransportConfig::EmptyInput => "empty_input".to_string(),
4197 }
4198 }
4199
4200 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
4205 match self {
4206 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
4207 _ => None,
4208 }
4209 }
4210
4211 pub fn is_transient(&self) -> bool {
4214 matches!(
4215 self,
4216 TransportConfig::AdHocInput(_)
4217 | TransportConfig::HttpInput(_)
4218 | TransportConfig::HttpOutput(_)
4219 | TransportConfig::ClockInput(_)
4220 )
4221 }
4222
4223 pub fn is_http_input(&self) -> bool {
4224 matches!(self, TransportConfig::HttpInput(_))
4225 }
4226
4227 pub fn supports_distribution(&self) -> bool {
4231 matches!(
4232 self,
4233 TransportConfig::KafkaInput(_)
4234 | TransportConfig::DeltaTableInput(_)
4235 | TransportConfig::IcebergInput(_)
4236 )
4237 }
4238
4239 pub fn supports_output_distribution(&self) -> bool {
4242 match self {
4243 TransportConfig::NullOutput => true,
4244 TransportConfig::DeltaTableOutput(config) => {
4245 config.mode == DeltaTableWriteMode::Append
4246 && config.update_mode == DeltaTableUpdateMode::Cdc
4247 }
4248 _ => false,
4249 }
4250 }
4251
4252 pub fn needs_input_choice(&self) -> bool {
4264 matches!(
4265 self,
4266 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4267 )
4268 }
4269
4270 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4273 use crate::adapter_stats::FrontierMerge;
4274 match self {
4275 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4276 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4277 FrontierMerge::Shared
4278 }
4279 _ => FrontierMerge::Opaque,
4280 }
4281 }
4282}
4283
4284#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4287pub struct FormatConfig {
4288 pub name: Cow<'static, str>,
4290
4291 #[serde(default)]
4293 #[schema(value_type = Object)]
4294 pub config: JsonValue,
4295}
4296
4297impl FormatConfig {
4298 pub fn normalize_durations(&mut self) {
4305 if self.name != "avro" {
4306 return;
4307 }
4308 let has_timeout = self.config.as_object().is_some_and(|object| {
4309 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4310 });
4311 if !has_timeout {
4312 return;
4313 }
4314 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4315 self.config.clone(),
4316 ) else {
4317 return;
4318 };
4319 let object = self.config.as_object_mut().unwrap();
4320 object.remove("registry_timeout_secs");
4321 match registry.registry_timeout {
4322 Some(timeout) => object.insert(
4323 "registry_timeout".to_string(),
4324 JsonValue::String(timeout.to_string()),
4325 ),
4326 None => object.remove("registry_timeout"),
4327 };
4328 }
4329}
4330
4331#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4333#[serde(deny_unknown_fields)]
4334pub struct DynamicConfig {
4335 #[serde(default)]
4336 pub resources: DynamicResources,
4337}
4338
4339#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4342#[serde(deny_unknown_fields)]
4343pub struct DynamicResources {
4344 pub cpu_cores_min: Option<f64>,
4345 pub cpu_cores_max: Option<f64>,
4346 #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4349 #[schema(value_type = Option<String>)]
4350 pub memory_min: Option<ConfigSize>,
4351 #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4354 #[schema(value_type = Option<String>)]
4355 pub memory_max: Option<ConfigSize>,
4356 #[serde(
4361 default,
4362 alias = "storage_mb_min",
4363 deserialize_with = "size_storage_min",
4364 skip_serializing_if = "Option::is_none"
4365 )]
4366 #[schema(value_type = Option<String>)]
4367 pub storage_min: Option<ConfigSize>,
4368 #[serde(
4371 default,
4372 alias = "storage_mb_max",
4373 deserialize_with = "size_storage_max",
4374 skip_serializing_if = "Option::is_none"
4375 )]
4376 #[schema(value_type = Option<String>)]
4377 pub storage_max: Option<ConfigSize>,
4378 #[serde(default, skip_serializing_if = "Option::is_none")]
4381 pub volume_attributes_class: Option<String>,
4382}
4383
4384#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4385#[serde(default)]
4386pub struct ResourceConfig {
4387 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4390 pub cpu_cores_min: Option<f64>,
4391
4392 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4395 pub cpu_cores_max: Option<f64>,
4396
4397 #[serde(
4403 alias = "memory_mb_min",
4404 deserialize_with = "size_memory_min",
4405 skip_serializing_if = "Option::is_none"
4406 )]
4407 #[schema(value_type = Option<String>)]
4408 pub memory_min: Option<ConfigSize>,
4409
4410 #[serde(
4416 alias = "memory_mb_max",
4417 deserialize_with = "size_memory_max",
4418 skip_serializing_if = "Option::is_none"
4419 )]
4420 #[schema(value_type = Option<String>)]
4421 pub memory_max: Option<ConfigSize>,
4422
4423 #[serde(
4430 alias = "storage_mb_min",
4431 deserialize_with = "size_storage_min",
4432 skip_serializing_if = "Option::is_none"
4433 )]
4434 #[schema(value_type = Option<String>)]
4435 pub storage_min: Option<ConfigSize>,
4436
4437 #[serde(
4448 alias = "storage_mb_max",
4449 deserialize_with = "size_storage_max",
4450 skip_serializing_if = "Option::is_none"
4451 )]
4452 #[schema(value_type = Option<String>)]
4453 pub storage_max: Option<ConfigSize>,
4454
4455 #[serde(skip_serializing_if = "Option::is_none")]
4457 pub autoscaling: Option<AutoscalingConfig>,
4458
4459 pub storage_class: Option<String>,
4462
4463 #[serde(skip_serializing_if = "Option::is_none")]
4470 pub volume_attributes_class: Option<String>,
4471
4472 pub service_account_name: Option<String>,
4475
4476 pub namespace: Option<String>,
4484}
4485
4486#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4488#[serde(default)]
4489pub struct AutoscalingConfig {
4490 #[serde(skip_serializing_if = "Option::is_none")]
4492 pub storage: Option<StorageAutoscalingConfig>,
4493}
4494
4495#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4498#[serde(default)]
4499pub struct StorageAutoscalingConfig {
4500 #[serde(
4502 deserialize_with = "crate::serde_via_value::deserialize",
4503 skip_serializing_if = "Option::is_none"
4504 )]
4505 pub scale_threshold: Option<f64>,
4506
4507 #[serde(
4514 alias = "scale_threshold_available_mb",
4515 deserialize_with = "size_scale_threshold_available",
4516 skip_serializing_if = "Option::is_none"
4517 )]
4518 #[schema(value_type = Option<String>)]
4519 pub scale_threshold_available: Option<ConfigSize>,
4520
4521 #[serde(
4523 deserialize_with = "crate::serde_via_value::deserialize",
4524 skip_serializing_if = "Option::is_none"
4525 )]
4526 pub scale_factor: Option<f64>,
4527}
4528
4529#[cfg(test)]
4530mod resource_config_tests {
4531 use super::{
4532 AutoscalingConfig, DynamicConfig, DynamicResources, ResourceConfig,
4533 StorageAutoscalingConfig,
4534 };
4535 use crate::size::ConfigSize;
4536 use serde_json::json;
4537
4538 #[test]
4541 fn dynamic_config_leaves_out_unset_storage() {
4542 let update = DynamicConfig {
4543 resources: DynamicResources {
4544 memory_max: Some(ConfigSize::from_mb(1000)),
4545 ..Default::default()
4546 },
4547 };
4548 assert_eq!(
4549 serde_json::to_value(&update).unwrap(),
4550 json!({"resources": {
4551 "cpu_cores_min": null, "cpu_cores_max": null,
4552 "memory_min": null, "memory_max": "1G",
4553 }})
4554 );
4555 let resize = json!({"resources": {"storage_mb_min": 1000, "storage_max": "8G"}});
4556 let resize: DynamicConfig = serde_json::from_value(resize).unwrap();
4557 assert_eq!(
4558 resize.resources.storage_min,
4559 Some(ConfigSize::from_mb(1000))
4560 );
4561 assert_eq!(
4562 resize.resources.storage_max,
4563 Some(ConfigSize::from_mb(8000))
4564 );
4565 }
4566
4567 #[test]
4568 fn storage_autoscaling_round_trips_through_json() {
4569 let input = json!({
4570 "storage_min": "1G",
4571 "storage_max": "8G",
4572 "autoscaling": {
4573 "storage": {
4574 "scale_threshold": 0.8,
4575 "scale_threshold_available": "10G",
4576 "scale_factor": 2.0
4577 }
4578 }
4579 });
4580 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4581 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4582 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4583 assert_eq!(
4584 config.autoscaling,
4585 Some(AutoscalingConfig {
4586 storage: Some(StorageAutoscalingConfig {
4587 scale_threshold: Some(0.8),
4588 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4589 scale_factor: Some(2.0),
4590 }),
4591 })
4592 );
4593 let output = serde_json::to_value(&config).unwrap();
4594 assert_eq!(output["storage_min"], json!("1G"));
4595 assert_eq!(
4596 output["autoscaling"]["storage"]["scale_threshold"],
4597 json!(0.8)
4598 );
4599 assert_eq!(
4600 output["autoscaling"]["storage"]["scale_threshold_available"],
4601 json!("10G")
4602 );
4603 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4604 }
4605
4606 #[test]
4607 fn autoscaling_fields_default_to_none() {
4608 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4609 assert_eq!(config.storage_min, None);
4610 assert_eq!(config.autoscaling, None);
4611
4612 let output = serde_json::to_value(&config).unwrap();
4615 assert!(output.get("storage_min").is_none());
4616 assert!(output.get("autoscaling").is_none());
4617 assert!(output.get("storage_max").is_none());
4618
4619 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4621 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4622 let output = serde_json::to_value(&config).unwrap();
4623 assert_eq!(output["autoscaling"], input["autoscaling"]);
4624
4625 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4627 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4628 }
4629
4630 #[test]
4631 fn autoscaling_rejects_non_numeric_values() {
4632 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4633 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4634 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4635 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4636 let input = json!({ "storage_mb_min": -1 });
4637 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4638 }
4639}
4640
4641#[cfg(test)]
4642mod sync_config_tests {
4643 use super::SyncConfig;
4644
4645 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4646 SyncConfig {
4647 bucket: bucket.to_owned(),
4648 read_bucket: read_bucket.map(str::to_owned),
4649 ..Default::default()
4650 }
4651 }
4652
4653 #[test]
4654 fn read_bucket_must_differ_from_bucket() {
4655 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4656 assert!(err.contains("different locations"), "{err}");
4657 }
4658
4659 #[test]
4660 fn read_bucket_must_use_the_same_object_store() {
4661 let err = config("gs://ckpts/a", Some("ckpts/b"))
4662 .validate()
4663 .unwrap_err();
4664 assert!(err.contains("same object store"), "{err}");
4665 let err = config("ckpts/a", Some("gs://ckpts/b"))
4666 .validate()
4667 .unwrap_err();
4668 assert!(err.contains("same object store"), "{err}");
4669 for (bucket, read_bucket) in [
4670 ("az://ckpts/a", "ckpts/b"),
4671 ("ckpts/a", "az://ckpts/b"),
4672 ("az://ckpts/a", "gs://ckpts/b"),
4673 ] {
4674 let err = azure_config(bucket, Some(read_bucket))
4675 .validate()
4676 .unwrap_err();
4677 assert!(err.contains("same object store"), "{err}");
4678 }
4679 }
4680
4681 fn azure_config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4682 SyncConfig {
4683 access_key: Some("account".to_owned()),
4684 ..config(bucket, read_bucket)
4685 }
4686 }
4687
4688 #[test]
4689 fn azure_bucket_needs_the_storage_account_name() {
4690 azure_config("az://ckpts/a", Some("az://ckpts/b"))
4691 .validate()
4692 .unwrap();
4693
4694 let err = config("az://ckpts/a", None).validate().unwrap_err();
4695 assert!(err.contains("set `access_key`"), "{err}");
4696 let empty = SyncConfig {
4697 access_key: Some(String::new()),
4698 ..config("az://ckpts/a", None)
4699 };
4700 let err = empty.validate().unwrap_err();
4701 assert!(err.contains("set `access_key`"), "{err}");
4702 }
4703
4704 #[test]
4705 fn azure_bucket_needs_a_container_name() {
4706 for bucket in ["az://", "az:///dir"] {
4707 let err = azure_config(bucket, None).validate().unwrap_err();
4708 assert!(err.contains("`bucket`"), "{err}");
4709 assert!(err.contains("does not name a container"), "{err}");
4710
4711 let err = azure_config("az://ckpts/a", Some(bucket))
4712 .validate()
4713 .unwrap_err();
4714 assert!(err.contains("`read_bucket`"), "{err}");
4715 }
4716 azure_config("az://ckpts", None).validate().unwrap();
4717 azure_config("az://ckpts/", None).validate().unwrap();
4718 }
4719
4720 #[test]
4721 fn matching_object_stores_are_accepted() {
4722 config("gs://ckpts/a", Some("gs://ckpts/b"))
4723 .validate()
4724 .unwrap();
4725 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4726 config("gs://ckpts/a", None).validate().unwrap();
4727 }
4728
4729 #[test]
4730 fn take_bucket_ownership_defaults_to_false() {
4731 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4732 assert!(!sync.take_bucket_ownership);
4733
4734 let sync: SyncConfig =
4735 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4736 .unwrap();
4737 assert!(sync.take_bucket_ownership);
4738 }
4739}
4740
4741#[cfg(test)]
4742mod queue_limit_tests {
4743 use super::ConnectorConfig;
4744 use serde_json::json;
4745
4746 fn connector(extra: serde_json::Value) -> ConnectorConfig {
4747 let mut value = json!({"transport": {"name": "datagen", "config": {}}});
4748 value
4749 .as_object_mut()
4750 .unwrap()
4751 .extend(extra.as_object().unwrap().clone());
4752 serde_json::from_value(value).unwrap()
4753 }
4754
4755 #[test]
4756 fn zero_queue_limits_are_rejected() {
4757 let err = connector(json!({"max_queued_records": 0}))
4758 .validate_queue_limits()
4759 .unwrap_err();
4760 assert!(err.contains("max_queued_records"), "{err}");
4761
4762 for size in [json!(0), json!("0"), json!("0Mi")] {
4763 let err = connector(json!({"max_queued_size": size}))
4764 .validate_queue_limits()
4765 .unwrap_err();
4766 assert!(err.contains("max_queued_size"), "{err}");
4767 }
4768 let err = connector(json!({"max_queued_bytes": 0}))
4769 .validate_queue_limits()
4770 .unwrap_err();
4771 assert!(err.contains("max_queued_size"), "{err}");
4772 }
4773
4774 #[test]
4775 fn nonzero_queue_limits_are_accepted() {
4776 connector(json!({})).validate_queue_limits().unwrap();
4777 connector(json!({"max_queued_records": 1, "max_queued_size": 1}))
4778 .validate_queue_limits()
4779 .unwrap();
4780 }
4781}
4782
4783#[cfg(test)]
4784mod transport_metadata_tests {
4785 use super::TransportConfig;
4786 use serde_json::json;
4787
4788 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4789 serde_json::from_value(json!({
4790 "name": "nats_input",
4791 "config": {
4792 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4793 "stream_name": "orders",
4794 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4795 },
4796 }))
4797 .unwrap()
4798 }
4799
4800 #[test]
4801 fn nats_input_exposes_consumer_metadata() {
4802 let mut transport = nats_input(json!({ "team": "ingest" }));
4803 let metadata = transport.transport_metadata_mut().unwrap();
4804 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4805
4806 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4807 let TransportConfig::NatsInput(config) = &transport else {
4808 unreachable!()
4809 };
4810 assert_eq!(
4811 config
4812 .consumer_config
4813 .metadata
4814 .get("pipeline")
4815 .map(String::as_str),
4816 Some("orders_pipeline"),
4817 "writes through the returned map must reach the consumer config"
4818 );
4819 }
4820
4821 #[test]
4822 fn transports_without_metadata_return_none() {
4823 let mut transport: TransportConfig = serde_json::from_value(json!({
4824 "name": "file_input",
4825 "config": { "path": "/tmp/input.csv" },
4826 }))
4827 .unwrap();
4828 assert!(transport.transport_metadata_mut().is_none());
4829 }
4830}
4831
4832#[cfg(test)]
4833mod local_file_uri_tests {
4834 use super::TransportConfig;
4835 use serde_json::json;
4836
4837 #[test]
4838 fn local_file_uris() {
4839 let delta = |uri: &str| -> TransportConfig {
4840 serde_json::from_value(
4841 json!({"name": "delta_table_input", "config": {"uri": uri, "mode": "snapshot"}}),
4842 )
4843 .unwrap()
4844 };
4845 for uri in [
4846 "file:///etc",
4847 "FILE:/etc",
4848 "/etc",
4849 "./t",
4850 "",
4851 "c:/t",
4852 " file:///etc",
4853 ] {
4854 assert_eq!(delta(uri).local_file_uris(false), vec![("uri", uri)]);
4855 }
4856 for uri in [
4857 "s3://b/t",
4858 "gs://b/t",
4859 "az://c/t",
4860 "abfss://c@a/t",
4861 "uc://c.s.t",
4862 ] {
4863 assert!(delta(uri).local_file_uris(false).is_empty(), "{uri}");
4864 }
4865 assert!(delta("${env:X}").local_file_uris(false).is_empty());
4867 assert_eq!(
4868 delta("${env:X}").local_file_uris(true),
4869 vec![("uri", "${env:X}")]
4870 );
4871
4872 let iceberg: TransportConfig = serde_json::from_value(json!({"name": "iceberg_input",
4873 "config": {"mode": "snapshot", "metadata_location": "file:///t/m.json"}}))
4874 .unwrap();
4875 assert_eq!(
4876 iceberg.local_file_uris(false),
4877 vec![("metadata_location", "file:///t/m.json")]
4878 );
4879 }
4880}