1use crate::duration::ConfigDuration;
9use crate::postprocess::PostprocessorConfig;
10use crate::preprocess::PreprocessorConfig;
11use crate::secret_ref::MaybeSecretRef;
12use crate::secret_resolver::default_secrets_directory;
13use crate::size::{ConfigSize, LegacySizeUnit};
14use crate::transport::adhoc::AdHocInputConfig;
15use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
16use crate::transport::datagen::DatagenInputConfig;
17use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
18use crate::transport::dynamodb::DynamoDBWriterConfig;
19use crate::transport::file::{FileInputConfig, FileOutputConfig};
20use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
21use crate::transport::iceberg::IcebergReaderConfig;
22use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
23use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
24use crate::transport::nexmark::NexmarkInputConfig;
25use crate::transport::postgres::{
26 PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
27};
28use crate::transport::pubsub::PubSubInputConfig;
29use crate::transport::redis::RedisOutputConfig;
30use crate::transport::s2::{S2InputConfig, S2OutputConfig};
31use crate::transport::s3::S3InputConfig;
32use crate::transport::url::UrlInputConfig;
33use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting, size_setting};
34use core::fmt;
35use feldera_ir::{MirNode, MirNodeId};
36use serde::de::{self, MapAccess, Visitor};
37use serde::{Deserialize, Deserializer, Serialize};
38use serde_json::Value as JsonValue;
39use std::collections::HashMap;
40use std::fmt::Display;
41use std::path::Path;
42use std::str::FromStr;
43use std::time::Duration;
44use std::{borrow::Cow, cmp::max, collections::BTreeMap};
45use utoipa::ToSchema;
46use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
47
48pub mod dev_tweaks;
49pub mod ignored;
50pub use dev_tweaks::DevTweaks;
51
52const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
53
54const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
56
57pub const fn default_max_queued_records() -> u64 {
59 1_000_000
60}
61
62pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
63
64pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
66
67pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
69
70pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
72
73pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
75
76fn default_clock_resolution() -> String {
79 DEFAULT_CLOCK_RESOLUTION.to_string()
80}
81fn default_checkpoint_interval() -> String {
82 DEFAULT_CHECKPOINT_INTERVAL.to_string()
83}
84fn default_pull_interval() -> String {
85 DEFAULT_PULL_INTERVAL.to_string()
86}
87fn default_retention_min_age() -> String {
88 DEFAULT_RETENTION_MIN_AGE.to_string()
89}
90
91duration_setting!(
92 duration_standby_pull_interval,
93 "standby_pull_interval",
94 LegacyUnit::Secs
95);
96duration_setting!(
97 duration_checkpoint_push_interval,
98 "checkpoint_push_interval",
99 LegacyUnit::Secs
100);
101duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
102duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
103duration_setting!(
104 duration_max_buffering_delay,
105 "max_buffering_delay",
106 LegacyUnit::Micros
107);
108duration_setting!(
109 duration_clock_resolution,
110 "clock_resolution",
111 LegacyUnit::Micros
112);
113duration_setting!(
114 duration_provisioning_timeout,
115 "provisioning_timeout",
116 LegacyUnit::Secs
117);
118nullable_duration_setting!(
119 duration_checkpoint_interval,
120 "checkpoint_interval",
121 LegacyUnit::Secs
122);
123duration_setting!(
124 duration_max_output_buffer_time,
125 "max_output_buffer_time",
126 LegacyUnit::Millis
127);
128size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
129size_setting!(
130 size_datafusion_memory,
131 "datafusion_memory",
132 LegacySizeUnit::Megabytes
133);
134size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
135size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
136size_setting!(
137 size_min_step_spill_size,
138 "min_step_spill_size",
139 LegacySizeUnit::Bytes
140);
141size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
142size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
143size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
144size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
145size_setting!(
146 size_scale_threshold_available,
147 "scale_threshold_available",
148 LegacySizeUnit::Megabytes
149);
150size_setting!(
151 size_max_queued_size,
152 "max_queued_size",
153 LegacySizeUnit::Bytes
154);
155
156#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
158pub struct ProgramIr {
159 pub mir: HashMap<MirNodeId, MirNode>,
161 pub program_schema: serde_json::Value,
163 #[serde(default)]
167 pub circuit_ir: Option<serde_json::Value>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub udf_library: Option<UdfLibrary>,
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
177pub struct UdfLibrary {
178 pub source_checksum: String,
180 pub integrity_checksum: String,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
187pub struct PipelineIdentity {
188 pub name: String,
190 pub given_name: Option<String>,
192}
193
194impl Display for PipelineIdentity {
195 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 match &self.given_name {
197 Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
198 None => write!(f, "{}", self.name),
199 }
200 }
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
209pub struct PipelineConfig {
210 #[serde(flatten)]
212 #[schema(inline)]
213 pub global: RuntimeConfig,
214
215 pub multihost: Option<MultihostConfig>,
223
224 pub name: Option<String>,
230
231 pub given_name: Option<String>,
236
237 #[serde(default)]
243 pub storage_config: Option<StorageConfig>,
244
245 pub secrets_dir: Option<String>,
249
250 #[serde(default)]
252 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
253
254 #[serde(default)]
256 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
257
258 #[serde(default)]
260 pub program_ir: Option<ProgramIr>,
261}
262
263impl PipelineConfig {
264 pub fn max_parallel_connector_init(&self) -> u64 {
265 max(
266 self.global
267 .max_parallel_connector_init
268 .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
269 1,
270 )
271 }
272
273 pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
276 PipelineConfigProgramInfo {
277 inputs: self.inputs.clone(),
278 outputs: self.outputs.clone(),
279 program_ir: self.program_ir.clone(),
280 }
281 }
282
283 pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
284 let (storage_config, storage_options) = storage.unzip();
285 Self {
286 global: RuntimeConfig {
287 storage: storage_options,
288 ..self.global
289 },
290 storage_config,
291 ..self
292 }
293 }
294
295 pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
296 let storage_options = self.global.storage.as_ref();
297 let storage_config = self.storage_config.as_ref();
298 storage_config.zip(storage_options)
299 }
300
301 pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
306 self.name.as_ref().map(|name| PipelineIdentity {
307 name: name.clone(),
308 given_name: self.given_name.clone(),
309 })
310 }
311
312 pub fn secrets_dir(&self) -> &Path {
315 match &self.secrets_dir {
316 Some(dir) => Path::new(dir.as_str()),
317 None => default_secrets_directory(),
318 }
319 }
320
321 pub fn display_summary(&self) -> String {
323 let summary = serde_json::json!({
325 "name": self.name,
326 "given_name": self.given_name,
327 "global": self.global,
328 "storage_config": self.storage_config,
329 "secrets_dir": self.secrets_dir,
330 "inputs": self.inputs,
331 "outputs": self.outputs
332 });
333
334 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
335 }
336}
337
338#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
346pub struct PipelineConfigProgramInfo {
347 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
349
350 #[serde(default)]
352 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
353
354 #[serde(default)]
356 pub program_ir: Option<ProgramIr>,
357}
358
359#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
363pub struct MultihostConfig {
364 pub hosts: usize,
370}
371
372impl Default for MultihostConfig {
373 fn default() -> Self {
374 Self { hosts: 1 }
375 }
376}
377
378#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
380pub struct StorageConfig {
381 pub path: String,
390
391 #[serde(default)]
393 pub cache: StorageCacheConfig,
394}
395
396impl StorageConfig {
397 pub fn path(&self) -> &Path {
398 Path::new(&self.path)
399 }
400}
401
402#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
404#[serde(rename_all = "snake_case")]
405pub enum StorageCacheConfig {
406 #[default]
411 PageCache,
412
413 FelderaCache,
418}
419
420impl StorageCacheConfig {
421 #[cfg(unix)]
422 pub fn to_custom_open_flags(&self) -> i32 {
423 match self {
424 StorageCacheConfig::PageCache => (),
425 StorageCacheConfig::FelderaCache => {
426 #[cfg(target_os = "linux")]
427 return libc::O_DIRECT;
428 }
429 }
430 0
431 }
432}
433
434#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
436#[serde(default)]
437pub struct StorageOptions {
438 pub backend: StorageBackendConfig,
440
441 #[serde(
455 alias = "min_storage_bytes",
456 deserialize_with = "size_min_spill_size",
457 skip_serializing_if = "Option::is_none"
458 )]
459 #[schema(value_type = Option<String>)]
460 pub min_spill_size: Option<ConfigSize>,
461
462 #[serde(
476 alias = "min_step_storage_bytes",
477 deserialize_with = "size_min_step_spill_size",
478 skip_serializing_if = "Option::is_none"
479 )]
480 #[schema(value_type = Option<String>)]
481 pub min_step_spill_size: Option<ConfigSize>,
482
483 pub compression: StorageCompression,
489
490 pub compression_level: Option<i32>,
501
502 #[serde(
511 alias = "cache_mib",
512 deserialize_with = "size_cache_size",
513 skip_serializing_if = "Option::is_none"
514 )]
515 #[schema(value_type = Option<String>)]
516 pub cache_size: Option<ConfigSize>,
517
518 #[serde(skip_serializing_if = "Option::is_none")]
533 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
534 pub bloom_false_positive_rate: Option<f64>,
535}
536
537impl Eq for StorageOptions {}
540
541#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
543#[serde(tag = "name", content = "config", rename_all = "snake_case")]
544pub enum StorageBackendConfig {
545 #[default]
549 Default,
550
551 File(Box<FileBackendConfig>),
555
556 Object(ObjectStorageConfig),
558}
559
560impl Display for StorageBackendConfig {
561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562 match self {
563 StorageBackendConfig::Default => write!(f, "default"),
564 StorageBackendConfig::File(_) => write!(f, "file"),
565 StorageBackendConfig::Object(_) => write!(f, "object"),
566 }
567 }
568}
569
570#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
572#[serde(rename_all = "snake_case")]
573pub enum StorageCompression {
574 #[default]
579 Default,
580
581 None,
583
584 Snappy,
586
587 Lz4,
592
593 Zstd,
599}
600
601#[derive(Debug, Clone, Eq, PartialEq)]
602pub enum StartFromCheckpoint {
603 Latest,
604 Uuid(uuid::Uuid),
605}
606
607impl ToSchema<'_> for StartFromCheckpoint {
608 fn schema() -> (
609 &'static str,
610 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
611 ) {
612 (
613 "StartFromCheckpoint",
614 utoipa::openapi::RefOr::T(Schema::OneOf(
615 OneOfBuilder::new()
616 .item(
617 ObjectBuilder::new()
618 .schema_type(SchemaType::String)
619 .enum_values(Some(["latest"].into_iter()))
620 .build(),
621 )
622 .item(
623 ObjectBuilder::new()
624 .schema_type(SchemaType::String)
625 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
626 utoipa::openapi::KnownFormat::Uuid,
627 )))
628 .build(),
629 )
630 .nullable(true)
631 .build(),
632 )),
633 )
634 }
635}
636
637impl<'de> Deserialize<'de> for StartFromCheckpoint {
638 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
639 where
640 D: Deserializer<'de>,
641 {
642 struct StartFromCheckpointVisitor;
643
644 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
645 type Value = StartFromCheckpoint;
646
647 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
648 formatter.write_str("a UUID string or the string \"latest\"")
649 }
650
651 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
652 where
653 E: de::Error,
654 {
655 if value == "latest" {
656 Ok(StartFromCheckpoint::Latest)
657 } else {
658 uuid::Uuid::parse_str(value)
659 .map(StartFromCheckpoint::Uuid)
660 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
661 }
662 }
663 }
664
665 deserializer.deserialize_str(StartFromCheckpointVisitor)
666 }
667}
668
669impl Serialize for StartFromCheckpoint {
670 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
671 where
672 S: serde::Serializer,
673 {
674 match self {
675 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
676 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
677 }
678 }
679}
680
681#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
682pub struct SyncConfig {
683 pub endpoint: Option<String>,
693
694 pub bucket: String,
703
704 pub region: Option<String>,
708
709 pub provider: Option<String>,
716
717 pub access_key: Option<String>,
723
724 pub secret_key: Option<String>,
730
731 pub start_from_checkpoint: Option<StartFromCheckpoint>,
736
737 #[schema(default = std::primitive::bool::default)]
743 #[serde(default)]
744 pub fail_if_no_checkpoint: bool,
745
746 pub transfers: Option<u8>,
749
750 pub checkers: Option<u8>,
753
754 pub ignore_checksum: Option<bool>,
758
759 pub multi_thread_streams: Option<u8>,
762
763 pub multi_thread_cutoff: Option<String>,
768
769 #[schema(default = default_optimize_download_resources)]
780 #[serde(default = "default_optimize_download_resources")]
781 pub optimize_download_resources: bool,
782
783 pub upload_concurrency: Option<u8>,
786
787 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
789 #[schema(default = std::primitive::bool::default)]
790 #[serde(default)]
791 pub standby: bool,
792
793 #[serde(
799 default,
800 alias = "pull_interval",
801 deserialize_with = "duration_standby_pull_interval",
802 skip_serializing_if = "Option::is_none"
803 )]
804 #[schema(value_type = Option<String>, default = default_pull_interval)]
805 pub standby_pull_interval: Option<ConfigDuration>,
806
807 #[serde(
813 default,
814 alias = "push_interval",
815 deserialize_with = "duration_checkpoint_push_interval",
816 skip_serializing_if = "Option::is_none"
817 )]
818 #[schema(value_type = Option<String>)]
819 pub checkpoint_push_interval: Option<ConfigDuration>,
820
821 pub flags: Option<Vec<String>>,
830
831 #[schema(default = default_retention_min_count)]
836 #[serde(default = "default_retention_min_count")]
837 pub retention_min_count: u32,
838
839 #[serde(
843 default,
844 alias = "retention_min_age",
845 deserialize_with = "duration_min_retention",
846 skip_serializing_if = "Option::is_none"
847 )]
848 #[schema(value_type = Option<String>, default = default_retention_min_age)]
849 pub min_retention: Option<ConfigDuration>,
850
851 #[serde(default)]
864 pub read_bucket: Option<String>,
865
866 #[schema(default = std::primitive::bool::default)]
892 #[serde(default)]
893 pub take_bucket_ownership: bool,
894}
895
896fn default_retention_min_count() -> u32 {
897 10
898}
899
900fn default_optimize_download_resources() -> bool {
901 true
902}
903
904impl SyncConfig {
905 pub fn standby_pull_interval(&self) -> ConfigDuration {
912 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
913 }
914
915 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
917 self.checkpoint_push_interval
918 }
919
920 pub fn min_retention(&self) -> ConfigDuration {
923 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
924 }
925
926 pub fn validate(&self) -> Result<(), String> {
927 #[allow(deprecated)]
928 if self.standby {
929 return Err(
930 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
931 );
932 }
933
934 if let Some(ref rb) = self.read_bucket {
935 if rb == &self.bucket {
936 return Err(
937 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
938 .to_owned(),
939 );
940 }
941 if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
944 return Err(format!(
945 "invalid sync config: `bucket` ('{}') and `read_bucket` ('{}') must use the same object store; prefix both with `gs://` for Google Cloud Storage or neither for S3",
946 self.bucket, rb
947 ));
948 }
949 }
950
951 Ok(())
952 }
953}
954
955fn is_gcs_bucket(bucket: &str) -> bool {
957 bucket.starts_with("gs://")
958}
959
960#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
996pub struct PipelineTemplateConfig {
997 pub name: String,
999 #[schema(default = default_pipeline_template_key)]
1003 #[serde(default = "default_pipeline_template_key")]
1004 pub key: String,
1005}
1006
1007fn default_pipeline_template_key() -> String {
1008 "pipelineTemplate".to_string()
1009}
1010
1011#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1012pub struct ObjectStorageConfig {
1013 pub url: String,
1042
1043 #[serde(flatten)]
1076 pub other_options: BTreeMap<String, String>,
1077}
1078
1079#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1081#[serde(default)]
1082pub struct FileBackendConfig {
1083 pub async_threads: Option<bool>,
1089
1090 #[serde(
1095 default,
1096 alias = "ioop_delay",
1097 deserialize_with = "duration_ioop_latency",
1098 skip_serializing_if = "Option::is_none"
1099 )]
1100 #[schema(value_type = Option<String>)]
1101 pub ioop_latency: Option<ConfigDuration>,
1102
1103 pub sync: Option<SyncConfig>,
1105
1106 pub sync_mode: Option<StorageSyncMode>,
1111}
1112
1113#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1119#[serde(rename_all = "snake_case")]
1120pub enum StorageSyncMode {
1121 #[default]
1124 Auto,
1125
1126 Syncfs,
1136
1137 PerFile,
1142}
1143
1144#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1147#[serde(default)]
1148pub struct RuntimeConfig {
1149 pub workers: u16,
1159
1160 #[serde(
1189 default,
1190 alias = "max_rss_mb",
1191 deserialize_with = "size_max_rss",
1192 skip_serializing_if = "Option::is_none"
1193 )]
1194 #[schema(value_type = Option<String>)]
1195 pub max_rss: Option<ConfigSize>,
1196
1197 #[serde(
1220 default,
1221 alias = "datafusion_memory_mb",
1222 deserialize_with = "size_datafusion_memory",
1223 skip_serializing_if = "Option::is_none"
1224 )]
1225 #[schema(value_type = Option<String>)]
1226 pub datafusion_memory: Option<ConfigSize>,
1227
1228 pub hosts: usize,
1235
1236 #[serde(deserialize_with = "deserialize_storage_options")]
1248 pub storage: Option<StorageOptions>,
1249
1250 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1252 pub fault_tolerance: FtConfig,
1253
1254 pub cpu_profiler: bool,
1258
1259 pub tracing: bool,
1261
1262 pub tracing_endpoint_jaeger: String,
1264
1265 pub min_batch_size_records: u64,
1273
1274 #[serde(
1277 default,
1278 alias = "max_buffering_delay_usecs",
1279 deserialize_with = "duration_max_buffering_delay",
1280 skip_serializing_if = "Option::is_none"
1281 )]
1282 #[schema(value_type = Option<String>)]
1283 pub max_buffering_delay: Option<ConfigDuration>,
1284
1285 pub resources: ResourceConfig,
1288
1289 #[serde(
1299 default,
1300 alias = "clock_resolution_usecs",
1301 deserialize_with = "duration_clock_resolution",
1302 skip_serializing_if = "Option::is_none"
1303 )]
1304 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1305 pub clock_resolution: Option<ConfigDuration>,
1306
1307 #[schema(value_type = Option<String>, example = "+05:30")]
1318 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1319
1320 pub pin_cpus: Vec<usize>,
1329
1330 #[serde(
1333 default,
1334 alias = "provisioning_timeout_secs",
1335 deserialize_with = "duration_provisioning_timeout",
1336 skip_serializing_if = "Option::is_none"
1337 )]
1338 #[schema(value_type = Option<String>)]
1339 pub provisioning_timeout: Option<ConfigDuration>,
1340
1341 pub max_parallel_connector_init: Option<u64>,
1352
1353 pub init_containers: Option<serde_json::Value>,
1355
1356 pub checkpoint_during_suspend: bool,
1358
1359 pub http_workers: Option<u64>,
1367
1368 pub io_workers: Option<u64>,
1379
1380 #[serde(default)]
1387 pub env: BTreeMap<String, String>,
1388
1389 pub dev_tweaks: DevTweaks,
1391
1392 pub logging: Option<String>,
1401
1402 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1410}
1411
1412fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1414where
1415 D: Deserializer<'de>,
1416{
1417 struct BoolOrStruct;
1418
1419 impl<'de> Visitor<'de> for BoolOrStruct {
1420 type Value = Option<StorageOptions>;
1421
1422 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1423 formatter.write_str("boolean or StorageOptions")
1424 }
1425
1426 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1427 where
1428 E: de::Error,
1429 {
1430 match v {
1431 false => Ok(None),
1432 true => Ok(Some(StorageOptions::default())),
1433 }
1434 }
1435
1436 fn visit_unit<E>(self) -> Result<Self::Value, E>
1437 where
1438 E: de::Error,
1439 {
1440 Ok(None)
1441 }
1442
1443 fn visit_none<E>(self) -> Result<Self::Value, E>
1444 where
1445 E: de::Error,
1446 {
1447 Ok(None)
1448 }
1449
1450 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1451 where
1452 M: MapAccess<'de>,
1453 {
1454 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1455 }
1456 }
1457
1458 deserializer.deserialize_any(BoolOrStruct)
1459}
1460
1461fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1469where
1470 D: Deserializer<'de>,
1471{
1472 struct StringOrStruct;
1473
1474 impl<'de> Visitor<'de> for StringOrStruct {
1475 type Value = FtConfig;
1476
1477 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1478 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1479 }
1480
1481 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1482 where
1483 E: de::Error,
1484 {
1485 match v {
1486 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1487 model: Some(FtModel::default()),
1488 ..FtConfig::default()
1489 }),
1490 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1491 }
1492 }
1493
1494 fn visit_unit<E>(self) -> Result<Self::Value, E>
1495 where
1496 E: de::Error,
1497 {
1498 Ok(FtConfig::default())
1499 }
1500
1501 fn visit_none<E>(self) -> Result<Self::Value, E>
1502 where
1503 E: de::Error,
1504 {
1505 Ok(FtConfig::default())
1506 }
1507
1508 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1509 where
1510 M: MapAccess<'de>,
1511 {
1512 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1513 }
1514 }
1515
1516 deserializer.deserialize_any(StringOrStruct)
1517}
1518
1519impl Default for RuntimeConfig {
1520 fn default() -> Self {
1521 Self {
1522 workers: 8,
1523 max_rss: None,
1524 datafusion_memory: None,
1525 hosts: 1,
1526 storage: Some(StorageOptions::default()),
1527 fault_tolerance: FtConfig::default(),
1528 cpu_profiler: true,
1529 tracing: {
1530 false
1533 },
1534 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1535 min_batch_size_records: 0,
1536 max_buffering_delay: None,
1537 resources: ResourceConfig::default(),
1538 clock_resolution: None,
1539 clock_timezone_offset: None,
1540 pin_cpus: Vec::new(),
1541 provisioning_timeout: None,
1542 max_parallel_connector_init: None,
1543 init_containers: None,
1544 checkpoint_during_suspend: true,
1545 io_workers: None,
1546 http_workers: None,
1547 env: BTreeMap::default(),
1548 dev_tweaks: DevTweaks::default(),
1549 logging: None,
1550 pipeline_template_configmap: None,
1551 }
1552 }
1553}
1554
1555pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1559
1560pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1563
1564impl RuntimeConfig {
1565 pub fn max_buffering_delay(&self) -> ConfigDuration {
1567 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1568 }
1569
1570 pub fn clock_resolution(&self) -> ConfigDuration {
1572 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1573 }
1574
1575 pub fn effective_memory(&self) -> Option<ConfigSize> {
1578 self.max_rss
1579 .into_iter()
1580 .chain(self.resources.memory_max)
1581 .min()
1582 }
1583
1584 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1589 if let Some(explicit) = self.datafusion_memory {
1590 return Some(explicit);
1591 }
1592 let effective = self.effective_memory()?.as_bytes();
1593 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1595 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1596 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1597 }
1598
1599 pub fn datafusion_memory_exceeding_budget(&self) -> Option<(ConfigSize, ConfigSize)> {
1602 let budget = self.effective_memory()?;
1603 let datafusion = self.resolved_datafusion_memory()?;
1604 (datafusion >= budget).then_some((datafusion, budget))
1605 }
1606}
1607
1608#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1619#[serde(rename_all = "snake_case")]
1620pub struct FtConfig {
1621 #[serde(with = "none_as_string")]
1623 #[serde(default = "default_model")]
1624 #[schema(
1625 schema_with = none_as_string_schema::<FtModel>,
1626 )]
1627 pub model: Option<FtModel>,
1628
1629 #[serde(
1636 default,
1637 alias = "checkpoint_interval_secs",
1638 deserialize_with = "duration_checkpoint_interval",
1639 skip_serializing_if = "Option::is_none"
1640 )]
1641 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1642 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1643}
1644
1645fn default_model() -> Option<FtModel> {
1646 Some(FtModel::default())
1647}
1648
1649pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1669 use crate::duration::LegacyUnit;
1670 use serde_json::{Map, Value};
1671
1672 struct Rule {
1674 new: &'static str,
1675 old: &'static str,
1676 unit: LegacyUnit,
1677 max: u64,
1679 null_allowed: bool,
1682 }
1683 const fn rule(
1684 new: &'static str,
1685 old: &'static str,
1686 unit: LegacyUnit,
1687 max: u64,
1688 null_allowed: bool,
1689 ) -> Rule {
1690 Rule {
1691 new,
1692 old,
1693 unit,
1694 max,
1695 null_allowed,
1696 }
1697 }
1698 const U32: u64 = u32::MAX as u64;
1699 const U64: u64 = u64::MAX;
1700 use LegacyUnit::{Days, Micros, Millis, Secs};
1701
1702 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1703 for rule in rules {
1704 let Some(value) = object.remove(rule.new) else {
1705 continue;
1706 };
1707 let legacy = match &value {
1708 Value::String(text) => match text.parse::<ConfigDuration>() {
1709 Ok(duration) => {
1710 let nanos = std::time::Duration::from(duration).as_nanos();
1711 let unit_nanos = u128::from(rule.unit.nanos());
1712 let whole = nanos.div_ceil(unit_nanos);
1713 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1714 }
1715 Err(_) => {
1716 object.insert(rule.new.to_string(), value);
1717 continue;
1718 }
1719 },
1720 Value::Null if !rule.null_allowed => continue,
1721 other => other.clone(),
1723 };
1724 object.insert(rule.old.to_string(), legacy);
1725 }
1726 }
1727 fn child<'a>(
1728 object: &'a mut Map<String, Value>,
1729 key: &str,
1730 ) -> Option<&'a mut Map<String, Value>> {
1731 object.get_mut(key).and_then(Value::as_object_mut)
1732 }
1733 fn max_expiry(consumer: &mut Map<String, Value>) {
1736 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1737 return;
1738 };
1739 let Ok(duration) = text.parse::<ConfigDuration>() else {
1740 return;
1741 };
1742 let duration = std::time::Duration::from(duration);
1743 consumer.remove("max_expiry");
1744 consumer.insert(
1745 "max_expires".to_string(),
1746 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1747 );
1748 }
1749 fn nats_connection(transport: &mut Map<String, Value>) {
1751 if let Some(connection) = child(transport, "connection_config") {
1752 apply(
1753 connection,
1754 &[
1755 rule(
1756 "connection_timeout",
1757 "connection_timeout_secs",
1758 Secs,
1759 U64,
1760 false,
1761 ),
1762 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1763 ],
1764 );
1765 }
1766 }
1767 fn connector(endpoint: &mut Map<String, Value>) {
1769 apply(
1770 endpoint,
1771 &[rule(
1772 "max_output_buffer_time",
1773 "max_output_buffer_time_millis",
1774 Millis,
1775 U64,
1776 false,
1777 )],
1778 );
1779 let name = endpoint
1780 .get("transport")
1781 .and_then(|transport| transport.get("name"))
1782 .and_then(Value::as_str)
1783 .map(str::to_string);
1784 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1785 match name.as_deref() {
1786 Some("url_input") => apply(
1787 transport,
1788 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1789 ),
1790 Some("kafka_input") => apply(
1791 transport,
1792 &[rule(
1793 "group_join_timeout",
1794 "group_join_timeout_secs",
1795 Secs,
1796 U32,
1797 false,
1798 )],
1799 ),
1800 Some("kafka_output") => apply(
1801 transport,
1802 &[rule(
1803 "initialization_timeout",
1804 "initialization_timeout_secs",
1805 Secs,
1806 U32,
1807 false,
1808 )],
1809 ),
1810 Some("clock_input") => apply(
1811 transport,
1812 &[rule(
1813 "clock_resolution",
1814 "clock_resolution_usecs",
1815 Micros,
1816 U64,
1817 false,
1818 )],
1819 ),
1820 Some("pub_sub_input") => apply(
1821 transport,
1822 &[
1823 rule("timeout", "timeout_seconds", Secs, U32, true),
1824 rule(
1825 "connect_timeout",
1826 "connect_timeout_seconds",
1827 Secs,
1828 U32,
1829 true,
1830 ),
1831 ],
1832 ),
1833 Some("nats_input") => {
1834 apply(
1835 transport,
1836 &[
1837 rule(
1838 "inactivity_timeout",
1839 "inactivity_timeout_secs",
1840 Secs,
1841 U64,
1842 false,
1843 ),
1844 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1845 ],
1846 );
1847 nats_connection(transport);
1848 if let Some(consumer) = child(transport, "consumer_config") {
1849 max_expiry(consumer);
1850 }
1851 }
1852 Some("nats_output") => {
1853 apply(
1854 transport,
1855 &[rule(
1856 "publish_timeout",
1857 "publish_timeout_secs",
1858 Secs,
1859 U64,
1860 false,
1861 )],
1862 );
1863 nats_connection(transport);
1864 }
1865 _ => {}
1866 }
1867 }
1868 let is_avro = endpoint
1869 .get("format")
1870 .and_then(|format| format.get("name"))
1871 .and_then(Value::as_str)
1872 == Some("avro");
1873 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1874 {
1875 apply(
1876 format,
1877 &[rule(
1878 "registry_timeout",
1879 "registry_timeout_secs",
1880 Secs,
1881 U64,
1882 true,
1883 )],
1884 );
1885 }
1886 }
1887
1888 let Some(global) = config.as_object_mut() else {
1889 return;
1890 };
1891 apply(
1892 global,
1893 &[
1894 rule(
1895 "clock_resolution",
1896 "clock_resolution_usecs",
1897 Micros,
1898 U64,
1899 true,
1900 ),
1901 rule(
1902 "max_buffering_delay",
1903 "max_buffering_delay_usecs",
1904 Micros,
1905 U64,
1906 false,
1907 ),
1908 rule(
1909 "provisioning_timeout",
1910 "provisioning_timeout_secs",
1911 Secs,
1912 U64,
1913 true,
1914 ),
1915 ],
1916 );
1917 if let Some(ft) = child(global, "fault_tolerance") {
1918 apply(
1920 ft,
1921 &[rule(
1922 "checkpoint_interval",
1923 "checkpoint_interval_secs",
1924 Secs,
1925 U64,
1926 true,
1927 )],
1928 );
1929 }
1930 let backend = child(global, "storage")
1931 .and_then(|storage| child(storage, "backend"))
1932 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1933 .and_then(|backend| child(backend, "config"));
1934 if let Some(file) = backend {
1935 apply(
1936 file,
1937 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1938 );
1939 if let Some(sync) = child(file, "sync") {
1940 apply(
1941 sync,
1942 &[
1943 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1944 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1945 rule("min_retention", "retention_min_age", Days, U32, false),
1946 ],
1947 );
1948 }
1949 }
1950 for endpoints in ["inputs", "outputs"] {
1951 if let Some(endpoints) = child(global, endpoints) {
1952 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1953 connector(endpoint);
1954 }
1955 }
1956 }
1957}
1958
1959#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1965pub struct LegacySpelling {
1966 pub durations: bool,
1968 pub sizes: bool,
1970}
1971
1972impl LegacySpelling {
1973 pub const NONE: LegacySpelling = LegacySpelling {
1975 durations: false,
1976 sizes: false,
1977 };
1978
1979 pub fn any(self) -> bool {
1981 self.durations || self.sizes
1982 }
1983
1984 pub fn apply(self, config: &mut serde_json::Value) {
1987 if self.durations {
1988 to_legacy_duration_spelling(config);
1989 }
1990 if self.sizes {
1991 to_legacy_size_spelling(config);
1992 }
1993 }
1994}
1995
1996pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
2007 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
2008 use serde_json::{Map, Value};
2009
2010 struct Rule {
2012 new: &'static str,
2013 old: &'static str,
2014 unit: LegacySizeUnit,
2015 }
2016 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2017 Rule { new, old, unit }
2018 }
2019
2020 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2021 for rule in rules {
2022 let Some(value) = object.remove(rule.new) else {
2023 continue;
2024 };
2025 let legacy = match &value {
2026 Value::String(text) => match text.parse::<ConfigSize>() {
2027 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2028 Err(_) => {
2029 object.insert(rule.new.to_string(), value);
2030 continue;
2031 }
2032 },
2033 Value::Null => continue,
2035 other => other.clone(),
2037 };
2038 object.insert(rule.old.to_string(), legacy);
2039 }
2040 }
2041 fn child<'a>(
2042 object: &'a mut Map<String, Value>,
2043 key: &str,
2044 ) -> Option<&'a mut Map<String, Value>> {
2045 object.get_mut(key).and_then(Value::as_object_mut)
2046 }
2047 fn connector(endpoint: &mut Map<String, Value>) {
2049 apply(
2050 endpoint,
2051 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2052 );
2053 let name = endpoint
2054 .get("transport")
2055 .and_then(|transport| transport.get("name"))
2056 .and_then(Value::as_str)
2057 .map(str::to_string);
2058 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2059 match name.as_deref() {
2060 Some("file_input") => apply(
2061 transport,
2062 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2063 ),
2064 Some("dynamodb_output" | "postgres_output") => apply(
2065 transport,
2066 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2067 ),
2068 Some("postgres_cdc_input") => {
2069 if let Some(batch) = child(transport, "batch") {
2070 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2071 }
2072 }
2073 _ => {}
2074 }
2075 }
2076 }
2077
2078 let Some(global) = config.as_object_mut() else {
2079 return;
2080 };
2081 apply(
2082 global,
2083 &[
2084 rule("max_rss", "max_rss_mb", Megabytes),
2085 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2086 ],
2087 );
2088 if let Some(storage) = child(global, "storage") {
2089 apply(
2090 storage,
2091 &[
2092 rule("cache_size", "cache_mib", Mebibytes),
2093 rule("min_spill_size", "min_storage_bytes", Bytes),
2094 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2095 ],
2096 );
2097 }
2098 if let Some(resources) = child(global, "resources") {
2099 apply(
2100 resources,
2101 &[
2102 rule("memory_min", "memory_mb_min", Megabytes),
2103 rule("memory_max", "memory_mb_max", Megabytes),
2104 rule("storage_min", "storage_mb_min", Megabytes),
2105 rule("storage_max", "storage_mb_max", Megabytes),
2106 ],
2107 );
2108 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2109 apply(
2110 storage,
2111 &[rule(
2112 "scale_threshold_available",
2113 "scale_threshold_available_mb",
2114 Megabytes,
2115 )],
2116 );
2117 }
2118 }
2119 if let Some(tweaks) = child(global, "dev_tweaks") {
2120 apply(
2121 tweaks,
2122 &[
2123 rule("storage_max", "storage_mb_max", Mebibytes),
2124 rule(
2125 "fbuf_slab_size_per_class",
2126 "fbuf_slab_bytes_per_class",
2127 Bytes,
2128 ),
2129 rule(
2130 "lazy_input_map_key_block_size",
2131 "lazy_input_map_key_block_bytes",
2132 Bytes,
2133 ),
2134 rule(
2135 "exchange_channel_capacity",
2136 "exchange_channel_capacity_bytes",
2137 Bytes,
2138 ),
2139 ],
2140 );
2141 }
2142 for endpoints in ["inputs", "outputs"] {
2143 if let Some(endpoints) = child(global, endpoints) {
2144 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2145 connector(endpoint);
2146 }
2147 }
2148 }
2149}
2150
2151#[cfg(test)]
2152mod test {
2153 use super::deserialize_fault_tolerance;
2154 use crate::config::{
2155 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2156 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2157 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2158 StorageOptions, SyncConfig, TransportConfig,
2159 };
2160 use crate::duration::ConfigDuration;
2161 use crate::size::ConfigSize;
2162 use serde::{Deserialize, Serialize};
2163 use serde_json::json;
2164 use std::time::Duration;
2165
2166 fn assert_reloads<T>(value: serde_json::Value)
2169 where
2170 T: Serialize + for<'de> Deserialize<'de>,
2171 {
2172 let first: T = serde_json::from_value(value.clone())
2173 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2174 let written = serde_json::to_value(&first).unwrap();
2175 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2176 panic!("{value} is written as {written}, which does not load: {e}")
2177 });
2178 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2179 }
2180
2181 #[test]
2186 fn size_settings_reload_from_what_is_written() {
2187 use crate::transport::dynamodb::DynamoDBWriterConfig;
2188 use crate::transport::file::FileInputConfig;
2189 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2190
2191 for number in [0u64, 1, 1_100, u64::MAX] {
2194 assert_reloads::<RuntimeConfig>(json!({
2195 "max_rss_mb": number,
2196 "datafusion_memory_mb": number,
2197 "storage": {"cache_mib": number, "min_storage_bytes": number},
2198 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2199 "dev_tweaks": {"storage_mb_max": number},
2200 }));
2201 }
2202
2203 let max = format!("{}B", u64::MAX);
2204 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2205 assert_reloads::<RuntimeConfig>(json!({
2206 "max_rss": size,
2207 "datafusion_memory": size,
2208 "storage": {
2209 "cache_size": size,
2210 "min_spill_size": size,
2211 "min_step_spill_size": size,
2212 },
2213 "resources": {
2214 "memory_min": size,
2215 "memory_max": size,
2216 "storage_min": size,
2217 "storage_max": size,
2218 "autoscaling": {"storage": {"scale_threshold_available": size}},
2219 },
2220 "dev_tweaks": {
2221 "storage_max": size,
2222 "fbuf_slab_size_per_class": size,
2223 "exchange_channel_capacity": size,
2224 },
2225 }));
2226 assert_reloads::<ConnectorConfig>(json!({
2227 "transport": {
2228 "name": "file_input",
2229 "config": {"path": "input.csv", "buffer_size": size},
2230 },
2231 "max_queued_size": size,
2232 }));
2233 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2234 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2235 assert_reloads::<PostgresWriterConfig>(json!({
2236 "uri": "postgres://localhost/db",
2237 "table": "t",
2238 "max_buffer_size": size,
2239 }));
2240 assert_reloads::<DynamoDBWriterConfig>(json!({
2241 "table": "t",
2242 "region": "us-east-1",
2243 "max_buffer_size": size,
2244 }));
2245 }
2246 }
2247
2248 #[test]
2253 fn soft_delete_is_backward_compatible() {
2254 let config: ConnectorConfig = serde_json::from_value(json!({
2255 "transport": {"name": "empty_input"}
2256 }))
2257 .unwrap();
2258 assert!(!config.soft_delete);
2259
2260 let serialized = serde_json::to_value(&config).unwrap();
2261 assert_eq!(serialized.get("soft_delete"), None);
2262
2263 let config: ConnectorConfig = serde_json::from_value(json!({
2264 "transport": {"name": "empty_input"},
2265 "soft_delete": true
2266 }))
2267 .unwrap();
2268 assert!(config.soft_delete);
2269 assert_eq!(
2270 serde_json::to_value(&config).unwrap().get("soft_delete"),
2271 Some(&json!(true))
2272 );
2273 }
2274
2275 #[test]
2278 fn soft_delete_invalidates_checkpointed_connector_state() {
2279 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2280 let mut soft_delete = config.clone();
2281 soft_delete.soft_delete = true;
2282
2283 assert!(config.equal_for_input_checkpoint_replay(&config));
2284 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2285 }
2286
2287 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2288 PipelineConfig {
2289 global: RuntimeConfig::default(),
2290 multihost: None,
2291 name: name.map(str::to_string),
2292 given_name: None,
2293 storage_config: None,
2294 secrets_dir: None,
2295 inputs: Default::default(),
2296 outputs: Default::default(),
2297 program_ir: None,
2298 }
2299 }
2300
2301 #[test]
2302 fn pipeline_identity_uses_system_and_given_names() {
2303 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2304 config.given_name = Some("my-pipeline".to_string());
2305
2306 let metadata = config.pipeline_identity().unwrap();
2307 assert_eq!(
2308 metadata.name,
2309 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2310 );
2311 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2312 }
2313
2314 #[test]
2315 fn pipeline_identity_is_none_without_system_name() {
2316 assert_eq!(config_with_name(None).pipeline_identity(), None);
2317 }
2318
2319 #[test]
2320 fn resolved_datafusion_memory_explicit_passes_through() {
2321 let config = RuntimeConfig {
2322 max_rss: Some(ConfigSize::from_mb(8_000)),
2323 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2324 ..Default::default()
2325 };
2326 assert_eq!(
2327 config.resolved_datafusion_memory(),
2328 Some(ConfigSize::from_mb(1_500))
2329 );
2330 }
2331
2332 #[test]
2333 fn effective_memory_is_the_smaller_budget() {
2334 let mb = |mb: Option<u64>| mb.map(ConfigSize::from_mb);
2335 for (max_rss, memory_max, expected) in [
2336 (None, None, None),
2337 (Some(8_000), None, Some(8_000)),
2338 (None, Some(4_000), Some(4_000)),
2339 (Some(8_000), Some(4_000), Some(4_000)),
2340 (Some(2_000), Some(4_000), Some(2_000)),
2341 ] {
2342 let config = RuntimeConfig {
2343 max_rss: mb(max_rss),
2344 resources: ResourceConfig {
2345 memory_max: mb(memory_max),
2346 ..Default::default()
2347 },
2348 ..Default::default()
2349 };
2350 assert_eq!(
2351 config.effective_memory(),
2352 mb(expected),
2353 "{max_rss:?}, {memory_max:?}"
2354 );
2355 }
2356 }
2357
2358 #[test]
2359 fn resolved_datafusion_memory_unconfigured_returns_none() {
2360 let config = RuntimeConfig::default();
2361 assert!(config.max_rss.is_none());
2362 assert!(config.resources.memory_max.is_none());
2363 assert_eq!(config.resolved_datafusion_memory(), None);
2364 }
2365
2366 #[test]
2367 fn resolved_datafusion_memory_small_budget_scales_down() {
2368 let config = RuntimeConfig {
2370 max_rss: Some(ConfigSize::from_mb(256)),
2371 ..Default::default()
2372 };
2373 assert_eq!(
2374 config.resolved_datafusion_memory(),
2375 Some(ConfigSize::from_bytes(12_800_000))
2376 );
2377
2378 let config = RuntimeConfig {
2379 max_rss: Some(ConfigSize::from_mb(512)),
2380 ..Default::default()
2381 };
2382 assert_eq!(
2383 config.resolved_datafusion_memory(),
2384 Some(ConfigSize::from_bytes(25_600_000))
2385 );
2386 }
2387
2388 #[test]
2389 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2390 let config = RuntimeConfig {
2392 max_rss: Some(ConfigSize::from_mb(64_000)),
2393 ..Default::default()
2394 };
2395 assert_eq!(
2396 config.resolved_datafusion_memory(),
2397 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2398 );
2399 }
2400
2401 #[test]
2402 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2403 let config = RuntimeConfig {
2405 max_rss: Some(ConfigSize::from_mb(16_000)),
2406 ..Default::default()
2407 };
2408 assert_eq!(
2409 config.resolved_datafusion_memory(),
2410 Some(ConfigSize::from_mb(800))
2411 );
2412 }
2413
2414 #[test]
2415 fn resolved_datafusion_memory_falls_back_to_resources() {
2416 let config = RuntimeConfig {
2418 max_rss: None,
2419 resources: ResourceConfig {
2420 memory_max: Some(ConfigSize::from_mb(16_000)),
2421 ..Default::default()
2422 },
2423 ..Default::default()
2424 };
2425 assert_eq!(
2426 config.resolved_datafusion_memory(),
2427 Some(ConfigSize::from_mb(800))
2428 );
2429 }
2430
2431 #[test]
2432 fn ft_config() {
2433 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2434 #[serde(default)]
2435 struct Wrapper {
2436 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2437 config: FtConfig,
2438 }
2439
2440 for s in [
2443 "{}",
2444 r#"{"config": null}"#,
2445 r#"{"config": {"model": "none"}}"#,
2446 ] {
2447 let config: Wrapper = serde_json::from_str(s).unwrap();
2448 assert_eq!(config.config.model, None);
2449 assert_eq!(config.config.checkpoint_interval(), None);
2450 }
2451
2452 let s = serde_json::to_string(&Wrapper {
2454 config: FtConfig::default(),
2455 })
2456 .unwrap();
2457 assert!(s.contains("\"none\""));
2458
2459 for s in [
2462 r#"{}"#,
2463 r#"{"checkpoint_interval": "60s"}"#,
2464 r#"{"checkpoint_interval_secs": 60}"#,
2465 ] {
2466 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2467 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2468 assert_eq!(
2469 config.checkpoint_interval(),
2470 Some(Duration::from_secs(60)),
2471 "parsing {s}"
2472 );
2473 }
2474
2475 for s in [
2478 r#"{"checkpoint_interval": null}"#,
2479 r#"{"checkpoint_interval_secs": null}"#,
2480 ] {
2481 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2482 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2483 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2484 }
2485
2486 let error = serde_json::from_str::<FtConfig>(
2489 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2490 )
2491 .unwrap_err()
2492 .to_string();
2493 assert!(error.contains("duplicate field"), "{error}");
2494
2495 for (json, expected_secs) in [
2497 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2498 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2499 ] {
2500 assert_eq!(
2501 serde_json::from_str::<FtConfig>(json)
2502 .unwrap()
2503 .checkpoint_interval(),
2504 Some(Duration::from_secs(expected_secs)),
2505 "parsing {json}"
2506 );
2507 }
2508 }
2509
2510 #[test]
2514 fn legacy_duration_spelling_uses_the_older_keys() {
2515 let mut config = serde_json::json!({
2516 "workers": 2,
2517 "clock_resolution": "250ms",
2518 "max_buffering_delay": "3ms",
2519 "provisioning_timeout": "15m",
2520 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2521 "storage": {"backend": {"name": "file", "config": {
2522 "ioop_latency": "5ms",
2523 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2524 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2525 });
2526 super::to_legacy_duration_spelling(&mut config);
2527 assert_eq!(
2528 config,
2529 serde_json::json!({
2530 "workers": 2,
2531 "clock_resolution_usecs": 250_000,
2532 "max_buffering_delay_usecs": 3_000,
2533 "provisioning_timeout_secs": 900,
2534 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2535 "storage": {"backend": {"name": "file", "config": {
2536 "ioop_delay": 5,
2537 "sync": {"bucket": "b", "pull_interval": 10,
2538 "push_interval": 3_600, "retention_min_age": 30}}}},
2539 })
2540 );
2541 }
2542
2543 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2545 serde_json::json!({
2546 "name": "p",
2547 "clock_resolution": "250ms",
2548 "inputs": {
2549 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2550 "topic": "t", "group_join_timeout": "30s"}}},
2551 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2552 "path": "http://x", "pause_linger": "7s"}}},
2553 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2554 "connection_config": {"server_url": "nats://x",
2555 "connection_timeout": "5s", "request_timeout": "6s"},
2556 "stream_name": "s",
2557 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2558 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2559 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2560 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2561 },
2562 "outputs": {
2563 "v.kafka": {"stream": "v",
2564 "transport": {"name": "kafka_output", "config": {
2565 "topic": "v", "initialization_timeout": "40s"}},
2566 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2567 "registry_timeout": "8s"}},
2568 "enable_output_buffer": true,
2569 "max_output_buffer_time": "500ms"},
2570 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2571 "connection_config": {"server_url": "nats://x",
2572 "connection_timeout": "5s", "request_timeout": "6s"},
2573 "subject": "s", "publish_timeout": "9s"}}},
2574 },
2575 })
2576 }
2577
2578 #[test]
2582 fn legacy_duration_spelling_rewrites_every_connector() {
2583 let mut config = pipeline_with_every_duration_connector();
2584 super::to_legacy_duration_spelling(&mut config);
2585 let i = &config["inputs"];
2586 assert_eq!(
2587 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2588 30
2589 );
2590 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2591 let nats = &i["t.nats"]["transport"]["config"];
2592 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2593 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2594 assert_eq!(nats["inactivity_timeout_secs"], 90);
2595 assert_eq!(nats["retry_interval_secs"], 3);
2596 assert_eq!(
2597 nats["consumer_config"]["max_expires"],
2598 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2599 );
2600 let pubsub = &i["t.pubsub"]["transport"]["config"];
2601 assert_eq!(pubsub["timeout_seconds"], 20);
2602 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2603 let out = &config["outputs"]["v.kafka"];
2604 assert_eq!(
2605 out["transport"]["config"]["initialization_timeout_secs"],
2606 40
2607 );
2608 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2609 assert_eq!(out["max_output_buffer_time_millis"], 500);
2610 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2611 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2612 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2613 assert_eq!(nats["publish_timeout_secs"], 9);
2614
2615 let text = config.to_string();
2617 for new in [
2618 "\"group_join_timeout\"",
2619 "\"pause_linger\"",
2620 "\"connection_timeout\"",
2621 "\"request_timeout\"",
2622 "\"inactivity_timeout\"",
2623 "\"retry_interval\"",
2624 "\"max_expiry\"",
2625 "\"timeout\"",
2626 "\"connect_timeout\"",
2627 "\"initialization_timeout\"",
2628 "\"registry_timeout\"",
2629 "\"max_output_buffer_time\"",
2630 "\"publish_timeout\"",
2631 "\"clock_resolution\"",
2632 ] {
2633 assert!(!text.contains(new), "{new} survived in {text}");
2634 }
2635 }
2636
2637 #[test]
2639 fn legacy_duration_spelling_round_trips_connectors() {
2640 let original: PipelineConfig =
2641 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2642 let mut value = serde_json::to_value(&original).unwrap();
2643 super::to_legacy_duration_spelling(&mut value);
2644 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2645
2646 let registry = |config: &PipelineConfig| {
2649 let format = config.outputs["v.kafka"]
2650 .connector_config
2651 .format
2652 .clone()
2653 .unwrap();
2654 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2655 .unwrap()
2656 .registry_config
2657 .registry_timeout
2658 };
2659 assert_eq!(registry(&reread), registry(&original));
2660 let mut original = original;
2661 for config in [&mut reread, &mut original] {
2662 config
2663 .outputs
2664 .get_mut("v.kafka")
2665 .unwrap()
2666 .connector_config
2667 .format = None;
2668 }
2669 assert_eq!(reread, original);
2670 }
2671
2672 #[test]
2676 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2677 let mut config = serde_json::json!({
2678 "inputs": {
2679 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2680 "group_join_timeout": "100000000000s"}}},
2681 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2682 },
2683 "storage": {"backend": {"name": "file", "config": {
2684 "sync": {"min_retention": "100000000000d"}}}},
2685 });
2686 super::to_legacy_duration_spelling(&mut config);
2687 let i = &config["inputs"];
2688 assert_eq!(
2689 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2690 u64::from(u32::MAX)
2691 );
2692 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2693 assert_eq!(
2694 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2695 u64::from(u32::MAX)
2696 );
2697 }
2698
2699 #[test]
2703 fn legacy_duration_spelling_round_trips() {
2704 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2705 "clock_resolution": "250ms",
2706 "max_buffering_delay": "3ms",
2707 "provisioning_timeout": "15m",
2708 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2709 }))
2710 .unwrap();
2711 let mut value = serde_json::to_value(&original).unwrap();
2712 super::to_legacy_duration_spelling(&mut value);
2713 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2714 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2715 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2716 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2717 assert_eq!(
2718 reread.fault_tolerance.checkpoint_interval(),
2719 original.fault_tolerance.checkpoint_interval()
2720 );
2721 }
2722
2723 #[test]
2728 fn legacy_duration_spelling_edge_cases() {
2729 let mut config = serde_json::json!({
2730 "max_buffering_delay": null,
2731 "provisioning_timeout": "1.5s",
2732 "fault_tolerance": {"checkpoint_interval": null},
2733 "clock_resolution": "10sec",
2734 "storage": {"backend": {"name": "file", "config": {
2735 "ioop_latency": "400us",
2736 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2737 });
2738 super::to_legacy_duration_spelling(&mut config);
2739 assert_eq!(
2740 config,
2741 serde_json::json!({
2742 "provisioning_timeout_secs": 2,
2743 "fault_tolerance": {"checkpoint_interval_secs": null},
2744 "clock_resolution": "10sec",
2745 "storage": {"backend": {"name": "file", "config": {
2746 "ioop_delay": 1,
2747 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2748 })
2749 );
2750
2751 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2753 super::to_legacy_duration_spelling(&mut zero);
2754 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2755
2756 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2758 let mut again = legacy.clone();
2759 super::to_legacy_duration_spelling(&mut again);
2760 assert_eq!(again, legacy);
2761 }
2762
2763 #[test]
2767 fn legacy_size_spelling_uses_the_older_keys() {
2768 let mut config = serde_json::json!({
2769 "workers": 2,
2770 "max_rss": "16G",
2771 "datafusion_memory": "1.5G",
2772 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2773 "resources": {
2774 "memory_min": "4G", "memory_max": "16Gi",
2775 "storage_min": "100G", "storage_max": "400Gi",
2776 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2777 },
2778 "dev_tweaks": {
2779 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2780 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2781 },
2782 "inputs": {
2783 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2784 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2785 "t.cdc": {"stream": "t",
2786 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2787 },
2788 "outputs": {
2789 "v.ddb": {"stream": "v",
2790 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2791 "v.pg": {"stream": "v",
2792 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2793 },
2794 });
2795 super::to_legacy_size_spelling(&mut config);
2796 assert_eq!(
2797 config,
2798 serde_json::json!({
2799 "workers": 2,
2800 "max_rss_mb": 16_000,
2801 "datafusion_memory_mb": 1_500,
2802 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2803 "resources": {
2804 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2806 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2807 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2808 },
2809 "dev_tweaks": {
2810 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2811 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2812 },
2813 "inputs": {
2814 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2815 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2816 "t.cdc": {"stream": "t",
2817 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2818 },
2819 "outputs": {
2820 "v.ddb": {"stream": "v",
2821 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2822 "v.pg": {"stream": "v",
2823 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2824 },
2825 })
2826 );
2827 }
2828
2829 #[test]
2832 fn legacy_size_spelling_round_trips() {
2833 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2834 "name": "p",
2835 "max_rss": "16G",
2836 "datafusion_memory": "1G",
2839 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2840 "resources": {"memory_max": "16G", "storage_max": "400G"},
2841 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2842 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2843 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2844 "outputs": {},
2845 }))
2846 .unwrap();
2847 let mut value = serde_json::to_value(&config).unwrap();
2848 super::to_legacy_size_spelling(&mut value);
2849 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2850 assert_eq!(
2851 value["inputs"]["t.file"]["max_queued_bytes"],
2852 serde_json::json!(1024 * 1024)
2853 );
2854 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2855 assert_eq!(reread, config);
2856 }
2857
2858 #[test]
2861 fn legacy_spelling_applies_each_rename_separately() {
2862 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2863 let mut both = current.clone();
2864 super::LegacySpelling {
2865 durations: true,
2866 sizes: true,
2867 }
2868 .apply(&mut both);
2869 assert_eq!(
2870 both,
2871 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2872 );
2873 let mut sizes_only = current.clone();
2874 super::LegacySpelling {
2875 durations: false,
2876 sizes: true,
2877 }
2878 .apply(&mut sizes_only);
2879 assert_eq!(
2880 sizes_only,
2881 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2882 );
2883 let mut none = current.clone();
2884 super::LegacySpelling::NONE.apply(&mut none);
2885 assert_eq!(none, current);
2886 assert!(!super::LegacySpelling::NONE.any());
2887 }
2888
2889 #[test]
2890 fn legacy_size_spelling_edge_cases() {
2891 let mut config = serde_json::json!({
2894 "max_rss": "lots",
2895 "resources": {"memory_max": null, "memory_min": 4000}
2896 });
2897 super::to_legacy_size_spelling(&mut config);
2898 assert_eq!(
2899 config,
2900 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2901 );
2902
2903 let mut small = serde_json::json!({"max_rss": "1"});
2906 super::to_legacy_size_spelling(&mut small);
2907 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2908
2909 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2911 let mut again = legacy.clone();
2912 super::to_legacy_size_spelling(&mut again);
2913 assert_eq!(again, legacy);
2914 }
2915
2916 #[test]
2925 fn a_stored_default_matches_an_omitted_one() {
2926 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2927 "transport": {
2928 "name": "url_input",
2929 "config": {"path": "http://example.com/x", "pause_timeout": 60},
2930 }
2931 }))
2932 .unwrap();
2933 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2934 "transport": {
2935 "name": "url_input",
2936 "config": {"path": "http://example.com/x"},
2937 }
2938 }))
2939 .unwrap();
2940
2941 assert_ne!(stored, fresh);
2944 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2945
2946 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2948 "transport": {
2949 "name": "url_input",
2950 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2951 }
2952 }))
2953 .unwrap();
2954 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2955 }
2956
2957 #[test]
2965 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2966 let connector = |registry: serde_json::Value| -> ConnectorConfig {
2967 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2968 format
2969 .as_object_mut()
2970 .unwrap()
2971 .extend(registry.as_object().unwrap().clone());
2972 serde_json::from_value(serde_json::json!({
2973 "transport": {
2974 "name": "url_input",
2975 "config": {"path": "http://example.com/x"},
2976 },
2977 "format": {"name": "avro", "config": format},
2978 }))
2979 .unwrap()
2980 };
2981 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2982 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2983 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2984 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2985 let unset = connector(serde_json::json!({}));
2986
2987 assert!(stored.equal_modulo_paused(¤t));
2988 assert!(stored.equal_for_input_checkpoint_replay(¤t));
2989 assert!(current.equal_modulo_paused(&spelled_out));
2990 assert!(!stored.equal_modulo_paused(&changed));
2991 assert!(!stored.equal_modulo_paused(&unset));
2992 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2994 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2995 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2996 }))
2997 .unwrap();
2998 assert!(!json.equal_modulo_paused(&stored));
2999 }
3000
3001 #[test]
3007 fn the_largest_legacy_defaults_still_load() {
3008 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
3009 "enable_output_buffer": false,
3010 "max_output_buffer_time_millis": u64::MAX,
3011 "max_output_buffer_size_records": 10_000_000u64,
3012 }))
3013 .unwrap();
3014 assert_eq!(
3015 buffer.max_output_buffer_time,
3016 Some(ConfigDuration::from_millis(u64::MAX))
3017 );
3018
3019 let sync: SyncConfig =
3021 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
3022 assert_eq!(
3023 sync.min_retention(),
3024 ConfigDuration::from_days(4_000_000_000)
3025 );
3026 }
3027
3028 #[test]
3032 fn a_legacy_number_past_u64_seconds_saturates() {
3033 let sync: SyncConfig =
3034 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
3035 .unwrap();
3036 assert_eq!(
3037 sync.min_retention(),
3038 ConfigDuration::from(std::time::Duration::MAX)
3039 );
3040 }
3041
3042 #[test]
3046 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3047 fn connector(value: serde_json::Value) -> ConnectorConfig {
3048 serde_json::from_value(value).unwrap()
3049 }
3050 fn secs(duration: ConfigDuration) -> u64 {
3051 std::time::Duration::from(duration).as_secs()
3052 }
3053 let fresh_kafka = connector(serde_json::json!({
3054 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3055 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3056 unreachable!()
3057 };
3058 let stored_kafka = connector(serde_json::json!({
3059 "transport": {"name": "kafka_input", "config": {
3060 "topic": "t",
3061 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3062 assert_ne!(stored_kafka, fresh_kafka);
3063 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3064
3065 let base = serde_json::json!({
3066 "connection_config": {"server_url": "nats://x"},
3067 "stream_name": "s",
3068 "consumer_config": {"deliver_policy": "All"}});
3069 let fresh_nats = connector(serde_json::json!({
3070 "transport": {"name": "nats_input", "config": base.clone()}}));
3071 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3072 unreachable!()
3073 };
3074 let mut spelled_out = base;
3075 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3076 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3077 spelled_out["connection_config"]["connection_timeout_secs"] =
3078 secs(nats.connection_config.connection_timeout()).into();
3079 spelled_out["connection_config"]["request_timeout_secs"] =
3080 secs(nats.connection_config.request_timeout()).into();
3081 let stored_nats = connector(serde_json::json!({
3082 "transport": {"name": "nats_input", "config": spelled_out}}));
3083 assert_ne!(stored_nats, fresh_nats);
3084 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3085 }
3086
3087 #[test]
3093 fn superseded_keys_are_normalised_by_a_round_trip() {
3094 let stored = serde_json::json!({
3095 "workers": 4,
3096 "clock_resolution_usecs": 100_000,
3097 "max_buffering_delay_usecs": 0,
3098 "provisioning_timeout_secs": 300,
3099 });
3100
3101 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3102 let written = serde_json::to_value(&config).unwrap();
3103
3104 assert_eq!(written["clock_resolution"], "100ms");
3105 assert_eq!(written["max_buffering_delay"], "0s");
3106 assert_eq!(written["provisioning_timeout"], "5m");
3107 for superseded in [
3108 "clock_resolution_usecs",
3109 "max_buffering_delay_usecs",
3110 "provisioning_timeout_secs",
3111 ] {
3112 assert!(
3113 written.get(superseded).is_none(),
3114 "`{superseded}` survived the round trip: {written}"
3115 );
3116 }
3117
3118 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3121 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3122 }
3123
3124 #[test]
3129 fn ioop_latency_accepts_both_spellings() {
3130 for (json, expected) in [
3131 (r#"{"name": "file", "config": {}}"#, None),
3132 (
3133 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3134 Some(ConfigDuration::from_millis(5)),
3135 ),
3136 (
3137 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3138 Some(ConfigDuration::from_millis(5)),
3139 ),
3140 (
3141 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3142 Some(ConfigDuration::from_secs(1)),
3143 ),
3144 ] {
3145 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3146 let StorageBackendConfig::File(file) = backend else {
3147 panic!("expected the file backend, parsing {json}");
3148 };
3149 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3150 }
3151 }
3152
3153 #[test]
3157 fn clock_resolution_falls_back_to_the_deprecated_field() {
3158 for (json, expected) in [
3159 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3160 (
3161 r#"{"clock_resolution": "100ms"}"#,
3162 ConfigDuration::from_millis(100),
3163 ),
3164 (
3165 r#"{"clock_resolution_usecs": 100000}"#,
3166 ConfigDuration::from_millis(100),
3167 ),
3168 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3169 (
3170 r#"{"clock_resolution_usecs": null}"#,
3171 DEFAULT_CLOCK_RESOLUTION,
3172 ),
3173 ] {
3174 assert_eq!(
3175 serde_json::from_str::<RuntimeConfig>(json)
3176 .unwrap()
3177 .clock_resolution(),
3178 expected,
3179 "parsing {json}"
3180 );
3181 }
3182 }
3183
3184 #[test]
3187 fn deprecated_duration_fields_still_work() {
3188 let runtime: RuntimeConfig = serde_json::from_str(
3189 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3190 )
3191 .unwrap();
3192 assert_eq!(
3193 runtime.max_buffering_delay(),
3194 ConfigDuration::from_millis(5)
3195 );
3196 assert_eq!(
3197 runtime.provisioning_timeout,
3198 Some(ConfigDuration::from_secs(1200))
3199 );
3200
3201 let sync: SyncConfig = serde_json::from_str(
3202 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3203 )
3204 .unwrap();
3205 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3206 assert_eq!(
3207 sync.checkpoint_push_interval(),
3208 Some(ConfigDuration::from_secs(300))
3209 );
3210 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3211
3212 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3213 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3214
3215 let buffer: OutputBufferConfig =
3216 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3217 assert_eq!(
3218 buffer.max_output_buffer_time(),
3219 ConfigDuration::from_millis(250)
3220 );
3221 }
3222
3223 #[test]
3226 fn duration_fields_default_when_unset() {
3227 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3228 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3229 assert_eq!(sync.checkpoint_push_interval(), None);
3230 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3231
3232 let runtime = RuntimeConfig::default();
3233 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3234 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3235 assert_eq!(runtime.provisioning_timeout, None);
3236 }
3237
3238 #[test]
3242 fn storage_options_f64_roundtrip_through_pipeline_config() {
3243 let pc = PipelineConfig {
3244 global: RuntimeConfig {
3245 storage: Some(StorageOptions {
3246 bloom_false_positive_rate: Some(0.01),
3247 ..Default::default()
3248 }),
3249 ..Default::default()
3250 },
3251 multihost: None,
3252 name: Some("test-pipeline".into()),
3253 given_name: None,
3254 storage_config: None,
3255 secrets_dir: None,
3256 inputs: Default::default(),
3257 outputs: Default::default(),
3258 program_ir: None,
3259 };
3260
3261 let json = serde_json::to_string_pretty(&pc).unwrap();
3263 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3264 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3265 );
3266 assert_eq!(
3267 pc2.global.storage.unwrap().bloom_false_positive_rate,
3268 Some(0.01)
3269 );
3270
3271 let value = serde_json::to_value(&pc).unwrap();
3273 let pc3: PipelineConfig = serde_json::from_value(value)
3274 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3275 assert_eq!(
3276 pc3.global.storage.unwrap().bloom_false_positive_rate,
3277 Some(0.01)
3278 );
3279 }
3280}
3281
3282impl FtConfig {
3283 pub fn is_enabled(&self) -> bool {
3284 self.model.is_some()
3285 }
3286
3287 pub fn checkpoint_interval(&self) -> Option<Duration> {
3294 if !self.is_enabled() {
3295 return None;
3296 }
3297
3298 let interval = self
3299 .checkpoint_interval
3300 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3301
3302 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3303 }
3304}
3305
3306mod none_as_string {
3313 use std::marker::PhantomData;
3314
3315 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3316 use serde::ser::{Serialize, Serializer};
3317
3318 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3319 where
3320 S: Serializer,
3321 T: Serialize,
3322 {
3323 match value.as_ref() {
3324 Some(value) => value.serialize(serializer),
3325 None => "none".serialize(serializer),
3326 }
3327 }
3328
3329 struct NoneAsString<T>(PhantomData<fn() -> T>);
3330
3331 impl<'de, T> Visitor<'de> for NoneAsString<T>
3332 where
3333 T: Deserialize<'de>,
3334 {
3335 type Value = Option<T>;
3336
3337 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3338 formatter.write_str("string")
3339 }
3340
3341 fn visit_none<E>(self) -> Result<Self::Value, E>
3342 where
3343 E: serde::de::Error,
3344 {
3345 Ok(None)
3346 }
3347
3348 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3349 where
3350 E: serde::de::Error,
3351 {
3352 if &value.to_ascii_lowercase() == "none" {
3353 Ok(None)
3354 } else {
3355 Ok(Some(T::deserialize(value.into_deserializer())?))
3356 }
3357 }
3358 }
3359
3360 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3361 where
3362 D: Deserializer<'de>,
3363 T: Deserialize<'de>,
3364 {
3365 deserializer.deserialize_str(NoneAsString(PhantomData))
3366 }
3367}
3368
3369fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3372 Schema::OneOf(
3373 OneOfBuilder::new()
3374 .item(RefOr::Ref(Ref::new(format!(
3375 "#/components/schemas/{}",
3376 T::schema().0
3377 ))))
3378 .item(
3379 ObjectBuilder::new()
3380 .schema_type(SchemaType::String)
3381 .enum_values(Some(vec!["none"])),
3382 )
3383 .default(Some(
3384 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3385 ))
3386 .build(),
3387 )
3388}
3389
3390#[derive(
3395 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3396)]
3397#[serde(rename_all = "snake_case")]
3398pub enum FtModel {
3399 AtLeastOnce,
3402
3403 #[default]
3406 ExactlyOnce,
3407}
3408
3409impl FtModel {
3410 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3411 value.map_or("no", |model| model.as_str())
3412 }
3413
3414 pub fn as_str(&self) -> &'static str {
3415 match self {
3416 FtModel::AtLeastOnce => "at_least_once",
3417 FtModel::ExactlyOnce => "exactly_once",
3418 }
3419 }
3420}
3421
3422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3424pub struct FtModelUnknown;
3425
3426impl std::fmt::Display for FtModelUnknown {
3427 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3428 f.write_str("expected `exactly_once` or `at_least_once`")
3429 }
3430}
3431
3432impl std::error::Error for FtModelUnknown {}
3433
3434impl FromStr for FtModel {
3435 type Err = FtModelUnknown;
3436
3437 fn from_str(s: &str) -> Result<Self, Self::Err> {
3438 match s.to_ascii_lowercase().as_str() {
3439 "exactly_once" => Ok(Self::ExactlyOnce),
3440 "at_least_once" => Ok(Self::AtLeastOnce),
3441 _ => Err(FtModelUnknown),
3442 }
3443 }
3444}
3445
3446#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3448pub struct InputEndpointConfig {
3449 pub stream: Cow<'static, str>,
3452
3453 #[serde(flatten)]
3455 pub connector_config: ConnectorConfig,
3456}
3457
3458impl InputEndpointConfig {
3459 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3460 Self {
3461 stream: stream.into(),
3462 connector_config,
3463 }
3464 }
3465}
3466
3467fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3471where
3472 D: Deserializer<'de>,
3473{
3474 let value = Option::<JsonValue>::deserialize(deserializer)?;
3475 match value {
3476 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3477 Some(JsonValue::Array(arr)) => {
3478 let vec = arr
3479 .into_iter()
3480 .map(|item| {
3481 item.as_str()
3482 .map(|s| s.to_string())
3483 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3484 })
3485 .collect::<Result<Vec<String>, _>>()?;
3486 Ok(Some(vec))
3487 }
3488 Some(JsonValue::Null) | None => Ok(None),
3489 _ => Err(serde::de::Error::custom(
3490 "invalid 'start_after' property: expected a string, an array of strings, or null",
3491 )),
3492 }
3493}
3494
3495#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3496pub struct ConnectorConfig {
3497 #[serde(default)]
3510 pub send_snapshot: bool,
3511
3512 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3529 pub soft_delete: bool,
3530
3531 pub transport: TransportConfig,
3533
3534 #[serde(skip_serializing_if = "Option::is_none")]
3536 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3537
3538 pub format: Option<FormatConfig>,
3540
3541 #[serde(skip_serializing_if = "Option::is_none")]
3543 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3544
3545 pub index: Option<String>,
3560
3561 #[serde(flatten)]
3563 pub output_buffer_config: OutputBufferConfig,
3564
3565 #[serde(skip_serializing_if = "Option::is_none")]
3578 pub max_batch_size: Option<u64>,
3579
3580 #[serde(skip_serializing_if = "Option::is_none")]
3593 pub max_worker_batch_size: Option<u64>,
3594
3595 #[serde(default = "default_max_queued_records")]
3616 pub max_queued_records: u64,
3617
3618 #[serde(
3641 default,
3642 alias = "max_queued_bytes",
3643 deserialize_with = "size_max_queued_size",
3644 skip_serializing_if = "Option::is_none"
3645 )]
3646 #[schema(value_type = Option<String>)]
3647 pub max_queued_size: Option<ConfigSize>,
3648
3649 #[serde(default)]
3660 pub paused: bool,
3661
3662 #[serde(default)]
3667 pub labels: Vec<String>,
3668
3669 #[serde(deserialize_with = "deserialize_start_after")]
3675 #[serde(default)]
3676 pub start_after: Option<Vec<String>>,
3677
3678 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3690 pub distributed: bool,
3691}
3692
3693impl ConnectorConfig {
3694 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3695 Self {
3696 send_snapshot: false,
3697 soft_delete: false,
3698 transport,
3699 preprocessor: None,
3700 format,
3701 postprocessor: None,
3702 index: None,
3703 output_buffer_config: Default::default(),
3704 max_batch_size: None,
3705 max_worker_batch_size: None,
3706 max_queued_records: default_max_queued_records(),
3707 max_queued_size: None,
3708 paused: false,
3709 labels: Vec::new(),
3710 start_after: None,
3711 distributed: false,
3712 }
3713 }
3714
3715 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3716 self.max_batch_size = max_batch_size;
3717 self
3718 }
3719
3720 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3721 self.max_queued_records = max_queued_records;
3722 self
3723 }
3724
3725 pub fn validate_queue_limits(&self) -> Result<(), String> {
3730 if self.max_queued_records == 0 {
3731 return Err("'max_queued_records' must be greater than 0".to_string());
3732 }
3733 if self.max_queued_size.is_some() && self.max_queued_bytes() == 0 {
3734 return Err("'max_queued_size' must be greater than 0".to_string());
3735 }
3736 Ok(())
3737 }
3738
3739 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3744 let mut a = self.clone();
3745 let mut b = other.clone();
3746 a.paused = false;
3747 b.paused = false;
3748 a.normalize_durations();
3749 b.normalize_durations();
3750 a == b
3751 }
3752
3753 fn normalize_durations(&mut self) {
3764 self.transport.normalize_durations();
3765 self.output_buffer_config.max_output_buffer_time =
3766 Some(self.output_buffer_config.max_output_buffer_time());
3767 if let Some(format) = &mut self.format {
3768 format.normalize_durations();
3769 }
3770 }
3771
3772 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3775 let mut a = self.clone();
3776 let mut b = other.clone();
3777 a.normalize_for_input_checkpoint_replay();
3778 b.normalize_for_input_checkpoint_replay();
3779 a == b
3780 }
3781
3782 fn normalize_for_input_checkpoint_replay(&mut self) {
3783 self.paused = false;
3784 self.max_batch_size = None;
3785 self.max_worker_batch_size = None;
3786 self.max_queued_records = default_max_queued_records();
3787 self.max_queued_size = None;
3788 self.normalize_durations();
3789 }
3790
3791 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3794 self.max_batch_size = other.max_batch_size;
3795 self.max_worker_batch_size = other.max_worker_batch_size;
3796 self.max_queued_records = other.max_queued_records;
3797 self.max_queued_size = other.max_queued_size;
3798 }
3799
3800 pub fn max_queued_records(&self) -> u64 {
3802 self.max_queued_records
3803 }
3804
3805 pub fn max_queued_bytes(&self) -> u64 {
3808 self.max_queued_size
3809 .map(ConfigSize::as_bytes)
3810 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3811 }
3812}
3813
3814#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3815#[serde(default)]
3816pub struct OutputBufferConfig {
3817 pub enable_output_buffer: bool,
3840
3841 #[serde(
3850 default,
3851 alias = "max_output_buffer_time_millis",
3852 deserialize_with = "duration_max_output_buffer_time",
3853 skip_serializing_if = "Option::is_none"
3854 )]
3855 #[schema(value_type = Option<String>)]
3856 pub max_output_buffer_time: Option<ConfigDuration>,
3857
3858 pub max_output_buffer_size_records: usize,
3870}
3871
3872impl OutputBufferConfig {
3873 pub fn max_output_buffer_time(&self) -> ConfigDuration {
3875 self.max_output_buffer_time
3876 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3877 }
3878}
3879
3880impl Default for OutputBufferConfig {
3881 fn default() -> Self {
3882 Self {
3883 enable_output_buffer: false,
3884 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3885 max_output_buffer_time: None,
3886 }
3887 }
3888}
3889
3890#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3892pub struct OutputEndpointConfig {
3893 pub stream: Cow<'static, str>,
3896
3897 #[serde(flatten)]
3899 pub connector_config: ConnectorConfig,
3900}
3901
3902impl OutputEndpointConfig {
3903 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3904 Self {
3905 stream: stream.into(),
3906 connector_config,
3907 }
3908 }
3909}
3910
3911#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3915#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3916pub enum TransportConfig {
3917 FileInput(FileInputConfig),
3918 FileOutput(FileOutputConfig),
3919 NatsInput(Box<NatsInputConfig>),
3922 NatsOutput(NatsOutputConfig),
3923 KafkaInput(KafkaInputConfig),
3924 KafkaOutput(KafkaOutputConfig),
3925 PubSubInput(PubSubInputConfig),
3926 UrlInput(UrlInputConfig),
3927 S3Input(S3InputConfig),
3928 DeltaTableInput(DeltaTableReaderConfig),
3929 DeltaTableOutput(DeltaTableWriterConfig),
3930 #[serde(rename = "dynamodb_output")]
3933 DynamoDBOutput(DynamoDBWriterConfig),
3934 RedisOutput(RedisOutputConfig),
3935 IcebergInput(Box<IcebergReaderConfig>),
3937 PostgresInput(PostgresReaderConfig),
3938 PostgresCdcInput(PostgresCdcReaderConfig),
3939 PostgresOutput(PostgresWriterConfig),
3940 Datagen(DatagenInputConfig),
3941 Nexmark(NexmarkInputConfig),
3942 HttpInput(HttpInputConfig),
3944 HttpOutput(HttpOutputConfig),
3946 AdHocInput(AdHocInputConfig),
3948 ClockInput(ClockConfig),
3949 S2Input(S2InputConfig),
3950 S2Output(S2OutputConfig),
3951 NullOutput,
3953 EmptyInput,
3955}
3956
3957pub const REFUSE_LOCAL_FILE_URIS_ENV: &str = "FELDERA_REFUSE_LOCAL_FILE_URIS";
3960
3961fn is_local_file_uri(location: &str) -> bool {
3963 let Some((scheme, _)) = location.split_once(':') else {
3964 return true;
3965 };
3966 let valid_scheme = scheme.len() > 1
3967 && scheme.starts_with(|c: char| c.is_ascii_alphabetic())
3968 && scheme
3969 .chars()
3970 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
3971 !valid_scheme || scheme.eq_ignore_ascii_case("file")
3972}
3973
3974impl TransportConfig {
3975 pub fn local_file_uris(&self, resolved: bool) -> Vec<(&'static str, &str)> {
3979 let locations = match self {
3980 TransportConfig::DeltaTableInput(config) => vec![("uri", Some(&*config.uri))],
3981 TransportConfig::DeltaTableOutput(config) => vec![("uri", Some(&*config.uri))],
3982 TransportConfig::IcebergInput(config) => vec![
3983 ("metadata_location", config.metadata_location.as_deref()),
3984 (
3985 "glue.warehouse",
3986 config.glue_catalog_config.warehouse.as_deref(),
3987 ),
3988 ],
3989 _ => Vec::new(),
3990 };
3991 locations
3992 .into_iter()
3993 .filter_map(|(property, location)| Some((property, location?)))
3994 .filter(|(_, location)| {
3995 (resolved
3996 || matches!(
3997 MaybeSecretRef::new(location.to_string()),
3998 Ok(MaybeSecretRef::String(_))
3999 ))
4000 && is_local_file_uri(location)
4001 })
4002 .collect()
4003 }
4004
4005 pub fn normalize_durations(&mut self) {
4008 match self {
4009 TransportConfig::UrlInput(config) => {
4010 config.pause_linger = Some(config.pause_linger());
4011 }
4012 TransportConfig::KafkaInput(config) => {
4013 config.group_join_timeout = Some(config.group_join_timeout());
4014 }
4015 TransportConfig::KafkaOutput(config) => {
4016 config.initialization_timeout = Some(config.initialization_timeout());
4017 }
4018 TransportConfig::NatsInput(config) => {
4019 config.connection_config.connection_timeout =
4020 Some(config.connection_config.connection_timeout());
4021 config.connection_config.request_timeout =
4022 Some(config.connection_config.request_timeout());
4023 config.inactivity_timeout = Some(config.inactivity_timeout());
4024 config.retry_interval = Some(config.retry_interval());
4025 }
4026 TransportConfig::NatsOutput(config) => {
4027 config.connection_config.connection_timeout =
4028 Some(config.connection_config.connection_timeout());
4029 config.connection_config.request_timeout =
4030 Some(config.connection_config.request_timeout());
4031 config.publish_timeout = Some(config.publish_timeout());
4032 }
4033 _ => {}
4034 }
4035 }
4036
4037 pub fn name(&self) -> String {
4038 match self {
4039 TransportConfig::FileInput(_) => "file_input".to_string(),
4040 TransportConfig::FileOutput(_) => "file_output".to_string(),
4041 TransportConfig::NatsInput(_) => "nats_input".to_string(),
4042 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
4043 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
4044 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
4045 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
4046 TransportConfig::UrlInput(_) => "url_input".to_string(),
4047 TransportConfig::S3Input(_) => "s3_input".to_string(),
4048 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
4049 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
4050 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
4051 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
4052 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
4053 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
4054 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
4055 TransportConfig::Datagen(_) => "datagen".to_string(),
4056 TransportConfig::Nexmark(_) => "nexmark".to_string(),
4057 TransportConfig::HttpInput(_) => "http_input".to_string(),
4058 TransportConfig::HttpOutput(_) => "http_output".to_string(),
4059 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
4060 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
4061 TransportConfig::ClockInput(_) => "clock".to_string(),
4062 TransportConfig::S2Input(_) => "s2_input".to_string(),
4063 TransportConfig::S2Output(_) => "s2_output".to_string(),
4064 TransportConfig::NullOutput => "null_output".to_string(),
4065 TransportConfig::EmptyInput => "empty_input".to_string(),
4066 }
4067 }
4068
4069 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
4074 match self {
4075 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
4076 _ => None,
4077 }
4078 }
4079
4080 pub fn is_transient(&self) -> bool {
4083 matches!(
4084 self,
4085 TransportConfig::AdHocInput(_)
4086 | TransportConfig::HttpInput(_)
4087 | TransportConfig::HttpOutput(_)
4088 | TransportConfig::ClockInput(_)
4089 )
4090 }
4091
4092 pub fn is_http_input(&self) -> bool {
4093 matches!(self, TransportConfig::HttpInput(_))
4094 }
4095
4096 pub fn supports_distribution(&self) -> bool {
4100 matches!(
4101 self,
4102 TransportConfig::KafkaInput(_)
4103 | TransportConfig::DeltaTableInput(_)
4104 | TransportConfig::IcebergInput(_)
4105 )
4106 }
4107
4108 pub fn needs_input_choice(&self) -> bool {
4120 matches!(
4121 self,
4122 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4123 )
4124 }
4125
4126 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4129 use crate::adapter_stats::FrontierMerge;
4130 match self {
4131 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4132 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4133 FrontierMerge::Shared
4134 }
4135 _ => FrontierMerge::Opaque,
4136 }
4137 }
4138}
4139
4140#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4143pub struct FormatConfig {
4144 pub name: Cow<'static, str>,
4146
4147 #[serde(default)]
4149 #[schema(value_type = Object)]
4150 pub config: JsonValue,
4151}
4152
4153impl FormatConfig {
4154 pub fn normalize_durations(&mut self) {
4161 if self.name != "avro" {
4162 return;
4163 }
4164 let has_timeout = self.config.as_object().is_some_and(|object| {
4165 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4166 });
4167 if !has_timeout {
4168 return;
4169 }
4170 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4171 self.config.clone(),
4172 ) else {
4173 return;
4174 };
4175 let object = self.config.as_object_mut().unwrap();
4176 object.remove("registry_timeout_secs");
4177 match registry.registry_timeout {
4178 Some(timeout) => object.insert(
4179 "registry_timeout".to_string(),
4180 JsonValue::String(timeout.to_string()),
4181 ),
4182 None => object.remove("registry_timeout"),
4183 };
4184 }
4185}
4186
4187#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4189#[serde(deny_unknown_fields)]
4190pub struct DynamicConfig {
4191 #[serde(default)]
4192 pub resources: DynamicResources,
4193}
4194
4195#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4198#[serde(deny_unknown_fields)]
4199pub struct DynamicResources {
4200 pub cpu_cores_min: Option<f64>,
4201 pub cpu_cores_max: Option<f64>,
4202 #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4205 #[schema(value_type = Option<String>)]
4206 pub memory_min: Option<ConfigSize>,
4207 #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4210 #[schema(value_type = Option<String>)]
4211 pub memory_max: Option<ConfigSize>,
4212 #[serde(
4217 default,
4218 alias = "storage_mb_min",
4219 deserialize_with = "size_storage_min",
4220 skip_serializing_if = "Option::is_none"
4221 )]
4222 #[schema(value_type = Option<String>)]
4223 pub storage_min: Option<ConfigSize>,
4224 #[serde(
4227 default,
4228 alias = "storage_mb_max",
4229 deserialize_with = "size_storage_max",
4230 skip_serializing_if = "Option::is_none"
4231 )]
4232 #[schema(value_type = Option<String>)]
4233 pub storage_max: Option<ConfigSize>,
4234 #[serde(default, skip_serializing_if = "Option::is_none")]
4237 pub volume_attributes_class: Option<String>,
4238}
4239
4240#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4241#[serde(default)]
4242pub struct ResourceConfig {
4243 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4246 pub cpu_cores_min: Option<f64>,
4247
4248 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4251 pub cpu_cores_max: Option<f64>,
4252
4253 #[serde(
4259 alias = "memory_mb_min",
4260 deserialize_with = "size_memory_min",
4261 skip_serializing_if = "Option::is_none"
4262 )]
4263 #[schema(value_type = Option<String>)]
4264 pub memory_min: Option<ConfigSize>,
4265
4266 #[serde(
4272 alias = "memory_mb_max",
4273 deserialize_with = "size_memory_max",
4274 skip_serializing_if = "Option::is_none"
4275 )]
4276 #[schema(value_type = Option<String>)]
4277 pub memory_max: Option<ConfigSize>,
4278
4279 #[serde(
4286 alias = "storage_mb_min",
4287 deserialize_with = "size_storage_min",
4288 skip_serializing_if = "Option::is_none"
4289 )]
4290 #[schema(value_type = Option<String>)]
4291 pub storage_min: Option<ConfigSize>,
4292
4293 #[serde(
4304 alias = "storage_mb_max",
4305 deserialize_with = "size_storage_max",
4306 skip_serializing_if = "Option::is_none"
4307 )]
4308 #[schema(value_type = Option<String>)]
4309 pub storage_max: Option<ConfigSize>,
4310
4311 #[serde(skip_serializing_if = "Option::is_none")]
4313 pub autoscaling: Option<AutoscalingConfig>,
4314
4315 pub storage_class: Option<String>,
4318
4319 #[serde(skip_serializing_if = "Option::is_none")]
4326 pub volume_attributes_class: Option<String>,
4327
4328 pub service_account_name: Option<String>,
4331
4332 pub namespace: Option<String>,
4340}
4341
4342#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4344#[serde(default)]
4345pub struct AutoscalingConfig {
4346 #[serde(skip_serializing_if = "Option::is_none")]
4348 pub storage: Option<StorageAutoscalingConfig>,
4349}
4350
4351#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4354#[serde(default)]
4355pub struct StorageAutoscalingConfig {
4356 #[serde(
4358 deserialize_with = "crate::serde_via_value::deserialize",
4359 skip_serializing_if = "Option::is_none"
4360 )]
4361 pub scale_threshold: Option<f64>,
4362
4363 #[serde(
4370 alias = "scale_threshold_available_mb",
4371 deserialize_with = "size_scale_threshold_available",
4372 skip_serializing_if = "Option::is_none"
4373 )]
4374 #[schema(value_type = Option<String>)]
4375 pub scale_threshold_available: Option<ConfigSize>,
4376
4377 #[serde(
4379 deserialize_with = "crate::serde_via_value::deserialize",
4380 skip_serializing_if = "Option::is_none"
4381 )]
4382 pub scale_factor: Option<f64>,
4383}
4384
4385#[cfg(test)]
4386mod resource_config_tests {
4387 use super::{
4388 AutoscalingConfig, DynamicConfig, DynamicResources, ResourceConfig,
4389 StorageAutoscalingConfig,
4390 };
4391 use crate::size::ConfigSize;
4392 use serde_json::json;
4393
4394 #[test]
4397 fn dynamic_config_leaves_out_unset_storage() {
4398 let update = DynamicConfig {
4399 resources: DynamicResources {
4400 memory_max: Some(ConfigSize::from_mb(1000)),
4401 ..Default::default()
4402 },
4403 };
4404 assert_eq!(
4405 serde_json::to_value(&update).unwrap(),
4406 json!({"resources": {
4407 "cpu_cores_min": null, "cpu_cores_max": null,
4408 "memory_min": null, "memory_max": "1G",
4409 }})
4410 );
4411 let resize = json!({"resources": {"storage_mb_min": 1000, "storage_max": "8G"}});
4412 let resize: DynamicConfig = serde_json::from_value(resize).unwrap();
4413 assert_eq!(
4414 resize.resources.storage_min,
4415 Some(ConfigSize::from_mb(1000))
4416 );
4417 assert_eq!(
4418 resize.resources.storage_max,
4419 Some(ConfigSize::from_mb(8000))
4420 );
4421 }
4422
4423 #[test]
4424 fn storage_autoscaling_round_trips_through_json() {
4425 let input = json!({
4426 "storage_min": "1G",
4427 "storage_max": "8G",
4428 "autoscaling": {
4429 "storage": {
4430 "scale_threshold": 0.8,
4431 "scale_threshold_available": "10G",
4432 "scale_factor": 2.0
4433 }
4434 }
4435 });
4436 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4437 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4438 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4439 assert_eq!(
4440 config.autoscaling,
4441 Some(AutoscalingConfig {
4442 storage: Some(StorageAutoscalingConfig {
4443 scale_threshold: Some(0.8),
4444 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4445 scale_factor: Some(2.0),
4446 }),
4447 })
4448 );
4449 let output = serde_json::to_value(&config).unwrap();
4450 assert_eq!(output["storage_min"], json!("1G"));
4451 assert_eq!(
4452 output["autoscaling"]["storage"]["scale_threshold"],
4453 json!(0.8)
4454 );
4455 assert_eq!(
4456 output["autoscaling"]["storage"]["scale_threshold_available"],
4457 json!("10G")
4458 );
4459 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4460 }
4461
4462 #[test]
4463 fn autoscaling_fields_default_to_none() {
4464 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4465 assert_eq!(config.storage_min, None);
4466 assert_eq!(config.autoscaling, None);
4467
4468 let output = serde_json::to_value(&config).unwrap();
4471 assert!(output.get("storage_min").is_none());
4472 assert!(output.get("autoscaling").is_none());
4473 assert!(output.get("storage_max").is_none());
4474
4475 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4477 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4478 let output = serde_json::to_value(&config).unwrap();
4479 assert_eq!(output["autoscaling"], input["autoscaling"]);
4480
4481 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4483 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4484 }
4485
4486 #[test]
4487 fn autoscaling_rejects_non_numeric_values() {
4488 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4489 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4490 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4491 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4492 let input = json!({ "storage_mb_min": -1 });
4493 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4494 }
4495}
4496
4497#[cfg(test)]
4498mod sync_config_tests {
4499 use super::SyncConfig;
4500
4501 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4502 SyncConfig {
4503 bucket: bucket.to_owned(),
4504 read_bucket: read_bucket.map(str::to_owned),
4505 ..Default::default()
4506 }
4507 }
4508
4509 #[test]
4510 fn read_bucket_must_differ_from_bucket() {
4511 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4512 assert!(err.contains("different locations"), "{err}");
4513 }
4514
4515 #[test]
4516 fn read_bucket_must_use_the_same_object_store() {
4517 let err = config("gs://ckpts/a", Some("ckpts/b"))
4518 .validate()
4519 .unwrap_err();
4520 assert!(err.contains("same object store"), "{err}");
4521 let err = config("ckpts/a", Some("gs://ckpts/b"))
4522 .validate()
4523 .unwrap_err();
4524 assert!(err.contains("same object store"), "{err}");
4525 }
4526
4527 #[test]
4528 fn matching_object_stores_are_accepted() {
4529 config("gs://ckpts/a", Some("gs://ckpts/b"))
4530 .validate()
4531 .unwrap();
4532 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4533 config("gs://ckpts/a", None).validate().unwrap();
4534 }
4535
4536 #[test]
4537 fn take_bucket_ownership_defaults_to_false() {
4538 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4539 assert!(!sync.take_bucket_ownership);
4540
4541 let sync: SyncConfig =
4542 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4543 .unwrap();
4544 assert!(sync.take_bucket_ownership);
4545 }
4546}
4547
4548#[cfg(test)]
4549mod queue_limit_tests {
4550 use super::ConnectorConfig;
4551 use serde_json::json;
4552
4553 fn connector(extra: serde_json::Value) -> ConnectorConfig {
4554 let mut value = json!({"transport": {"name": "datagen", "config": {}}});
4555 value
4556 .as_object_mut()
4557 .unwrap()
4558 .extend(extra.as_object().unwrap().clone());
4559 serde_json::from_value(value).unwrap()
4560 }
4561
4562 #[test]
4563 fn zero_queue_limits_are_rejected() {
4564 let err = connector(json!({"max_queued_records": 0}))
4565 .validate_queue_limits()
4566 .unwrap_err();
4567 assert!(err.contains("max_queued_records"), "{err}");
4568
4569 for size in [json!(0), json!("0"), json!("0Mi")] {
4570 let err = connector(json!({"max_queued_size": size}))
4571 .validate_queue_limits()
4572 .unwrap_err();
4573 assert!(err.contains("max_queued_size"), "{err}");
4574 }
4575 let err = connector(json!({"max_queued_bytes": 0}))
4576 .validate_queue_limits()
4577 .unwrap_err();
4578 assert!(err.contains("max_queued_size"), "{err}");
4579 }
4580
4581 #[test]
4582 fn nonzero_queue_limits_are_accepted() {
4583 connector(json!({})).validate_queue_limits().unwrap();
4584 connector(json!({"max_queued_records": 1, "max_queued_size": 1}))
4585 .validate_queue_limits()
4586 .unwrap();
4587 }
4588}
4589
4590#[cfg(test)]
4591mod transport_metadata_tests {
4592 use super::TransportConfig;
4593 use serde_json::json;
4594
4595 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4596 serde_json::from_value(json!({
4597 "name": "nats_input",
4598 "config": {
4599 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4600 "stream_name": "orders",
4601 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4602 },
4603 }))
4604 .unwrap()
4605 }
4606
4607 #[test]
4608 fn nats_input_exposes_consumer_metadata() {
4609 let mut transport = nats_input(json!({ "team": "ingest" }));
4610 let metadata = transport.transport_metadata_mut().unwrap();
4611 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4612
4613 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4614 let TransportConfig::NatsInput(config) = &transport else {
4615 unreachable!()
4616 };
4617 assert_eq!(
4618 config
4619 .consumer_config
4620 .metadata
4621 .get("pipeline")
4622 .map(String::as_str),
4623 Some("orders_pipeline"),
4624 "writes through the returned map must reach the consumer config"
4625 );
4626 }
4627
4628 #[test]
4629 fn transports_without_metadata_return_none() {
4630 let mut transport: TransportConfig = serde_json::from_value(json!({
4631 "name": "file_input",
4632 "config": { "path": "/tmp/input.csv" },
4633 }))
4634 .unwrap();
4635 assert!(transport.transport_metadata_mut().is_none());
4636 }
4637}
4638
4639#[cfg(test)]
4640mod local_file_uri_tests {
4641 use super::TransportConfig;
4642 use serde_json::json;
4643
4644 #[test]
4645 fn local_file_uris() {
4646 let delta = |uri: &str| -> TransportConfig {
4647 serde_json::from_value(
4648 json!({"name": "delta_table_input", "config": {"uri": uri, "mode": "snapshot"}}),
4649 )
4650 .unwrap()
4651 };
4652 for uri in [
4653 "file:///etc",
4654 "FILE:/etc",
4655 "/etc",
4656 "./t",
4657 "",
4658 "c:/t",
4659 " file:///etc",
4660 ] {
4661 assert_eq!(delta(uri).local_file_uris(false), vec![("uri", uri)]);
4662 }
4663 for uri in [
4664 "s3://b/t",
4665 "gs://b/t",
4666 "az://c/t",
4667 "abfss://c@a/t",
4668 "uc://c.s.t",
4669 ] {
4670 assert!(delta(uri).local_file_uris(false).is_empty(), "{uri}");
4671 }
4672 assert!(delta("${env:X}").local_file_uris(false).is_empty());
4674 assert_eq!(
4675 delta("${env:X}").local_file_uris(true),
4676 vec![("uri", "${env:X}")]
4677 );
4678
4679 let iceberg: TransportConfig = serde_json::from_value(json!({"name": "iceberg_input",
4680 "config": {"mode": "snapshot", "metadata_location": "file:///t/m.json"}}))
4681 .unwrap();
4682 assert_eq!(
4683 iceberg.local_file_uris(false),
4684 vec![("metadata_location", "file:///t/m.json")]
4685 );
4686 }
4687}