1use crate::duration::ConfigDuration;
9use crate::postprocess::PostprocessorConfig;
10use crate::preprocess::PreprocessorConfig;
11use crate::secret_resolver::default_secrets_directory;
12use crate::size::{ConfigSize, LegacySizeUnit};
13use crate::transport::adhoc::AdHocInputConfig;
14use crate::transport::clock::{ClockConfig, ClockTimezoneOffset};
15use crate::transport::datagen::DatagenInputConfig;
16use crate::transport::delta_table::{DeltaTableReaderConfig, DeltaTableWriterConfig};
17use crate::transport::dynamodb::DynamoDBWriterConfig;
18use crate::transport::file::{FileInputConfig, FileOutputConfig};
19use crate::transport::http::{HttpInputConfig, HttpOutputConfig};
20use crate::transport::iceberg::IcebergReaderConfig;
21use crate::transport::kafka::{KafkaInputConfig, KafkaOutputConfig};
22use crate::transport::nats::{NatsInputConfig, NatsOutputConfig};
23use crate::transport::nexmark::NexmarkInputConfig;
24use crate::transport::postgres::{
25 PostgresCdcReaderConfig, PostgresReaderConfig, PostgresWriterConfig,
26};
27use crate::transport::pubsub::PubSubInputConfig;
28use crate::transport::redis::RedisOutputConfig;
29use crate::transport::s2::{S2InputConfig, S2OutputConfig};
30use crate::transport::s3::S3InputConfig;
31use crate::transport::url::UrlInputConfig;
32use crate::{duration::LegacyUnit, duration_setting, nullable_duration_setting, size_setting};
33use core::fmt;
34use feldera_ir::{MirNode, MirNodeId};
35use serde::de::{self, MapAccess, Visitor};
36use serde::{Deserialize, Deserializer, Serialize};
37use serde_json::Value as JsonValue;
38use std::collections::HashMap;
39use std::fmt::Display;
40use std::path::Path;
41use std::str::FromStr;
42use std::time::Duration;
43use std::{borrow::Cow, cmp::max, collections::BTreeMap};
44use utoipa::ToSchema;
45use utoipa::openapi::{ObjectBuilder, OneOfBuilder, Ref, RefOr, Schema, SchemaType};
46
47pub mod dev_tweaks;
48pub use dev_tweaks::DevTweaks;
49
50const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
51
52const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
54
55pub const fn default_max_queued_records() -> u64 {
57 1_000_000
58}
59
60pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
61
62pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
64
65pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
67
68pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
70
71pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
73
74fn default_clock_resolution() -> String {
77 DEFAULT_CLOCK_RESOLUTION.to_string()
78}
79fn default_checkpoint_interval() -> String {
80 DEFAULT_CHECKPOINT_INTERVAL.to_string()
81}
82fn default_pull_interval() -> String {
83 DEFAULT_PULL_INTERVAL.to_string()
84}
85fn default_retention_min_age() -> String {
86 DEFAULT_RETENTION_MIN_AGE.to_string()
87}
88
89duration_setting!(
90 duration_standby_pull_interval,
91 "standby_pull_interval",
92 LegacyUnit::Secs
93);
94duration_setting!(
95 duration_checkpoint_push_interval,
96 "checkpoint_push_interval",
97 LegacyUnit::Secs
98);
99duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
100duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
101duration_setting!(
102 duration_max_buffering_delay,
103 "max_buffering_delay",
104 LegacyUnit::Micros
105);
106duration_setting!(
107 duration_clock_resolution,
108 "clock_resolution",
109 LegacyUnit::Micros
110);
111duration_setting!(
112 duration_provisioning_timeout,
113 "provisioning_timeout",
114 LegacyUnit::Secs
115);
116nullable_duration_setting!(
117 duration_checkpoint_interval,
118 "checkpoint_interval",
119 LegacyUnit::Secs
120);
121duration_setting!(
122 duration_max_output_buffer_time,
123 "max_output_buffer_time",
124 LegacyUnit::Millis
125);
126size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
127size_setting!(
128 size_datafusion_memory,
129 "datafusion_memory",
130 LegacySizeUnit::Megabytes
131);
132size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
133size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
134size_setting!(
135 size_min_step_spill_size,
136 "min_step_spill_size",
137 LegacySizeUnit::Bytes
138);
139size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
140size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
141size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
142size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
143size_setting!(
144 size_scale_threshold_available,
145 "scale_threshold_available",
146 LegacySizeUnit::Megabytes
147);
148size_setting!(
149 size_max_queued_size,
150 "max_queued_size",
151 LegacySizeUnit::Bytes
152);
153
154#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
156pub struct ProgramIr {
157 pub mir: HashMap<MirNodeId, MirNode>,
159 pub program_schema: serde_json::Value,
161 #[serde(default)]
165 pub circuit_ir: Option<serde_json::Value>,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub udf_library: Option<UdfLibrary>,
171}
172
173#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
175pub struct UdfLibrary {
176 pub source_checksum: String,
178 pub integrity_checksum: String,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185pub struct PipelineIdentity {
186 pub name: String,
188 pub given_name: Option<String>,
190}
191
192impl Display for PipelineIdentity {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 match &self.given_name {
195 Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
196 None => write!(f, "{}", self.name),
197 }
198 }
199}
200
201#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
207pub struct PipelineConfig {
208 #[serde(flatten)]
210 #[schema(inline)]
211 pub global: RuntimeConfig,
212
213 pub multihost: Option<MultihostConfig>,
221
222 pub name: Option<String>,
228
229 pub given_name: Option<String>,
234
235 #[serde(default)]
241 pub storage_config: Option<StorageConfig>,
242
243 pub secrets_dir: Option<String>,
247
248 #[serde(default)]
250 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
251
252 #[serde(default)]
254 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
255
256 #[serde(default)]
258 pub program_ir: Option<ProgramIr>,
259}
260
261impl PipelineConfig {
262 pub fn max_parallel_connector_init(&self) -> u64 {
263 max(
264 self.global
265 .max_parallel_connector_init
266 .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
267 1,
268 )
269 }
270
271 pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
274 PipelineConfigProgramInfo {
275 inputs: self.inputs.clone(),
276 outputs: self.outputs.clone(),
277 program_ir: self.program_ir.clone(),
278 }
279 }
280
281 pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
282 let (storage_config, storage_options) = storage.unzip();
283 Self {
284 global: RuntimeConfig {
285 storage: storage_options,
286 ..self.global
287 },
288 storage_config,
289 ..self
290 }
291 }
292
293 pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
294 let storage_options = self.global.storage.as_ref();
295 let storage_config = self.storage_config.as_ref();
296 storage_config.zip(storage_options)
297 }
298
299 pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
304 self.name.as_ref().map(|name| PipelineIdentity {
305 name: name.clone(),
306 given_name: self.given_name.clone(),
307 })
308 }
309
310 pub fn secrets_dir(&self) -> &Path {
313 match &self.secrets_dir {
314 Some(dir) => Path::new(dir.as_str()),
315 None => default_secrets_directory(),
316 }
317 }
318
319 pub fn display_summary(&self) -> String {
321 let summary = serde_json::json!({
323 "name": self.name,
324 "given_name": self.given_name,
325 "global": self.global,
326 "storage_config": self.storage_config,
327 "secrets_dir": self.secrets_dir,
328 "inputs": self.inputs,
329 "outputs": self.outputs
330 });
331
332 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
333 }
334}
335
336#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
344pub struct PipelineConfigProgramInfo {
345 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
347
348 #[serde(default)]
350 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
351
352 #[serde(default)]
354 pub program_ir: Option<ProgramIr>,
355}
356
357#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
361pub struct MultihostConfig {
362 pub hosts: usize,
368}
369
370impl Default for MultihostConfig {
371 fn default() -> Self {
372 Self { hosts: 1 }
373 }
374}
375
376#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
378pub struct StorageConfig {
379 pub path: String,
388
389 #[serde(default)]
391 pub cache: StorageCacheConfig,
392}
393
394impl StorageConfig {
395 pub fn path(&self) -> &Path {
396 Path::new(&self.path)
397 }
398}
399
400#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
402#[serde(rename_all = "snake_case")]
403pub enum StorageCacheConfig {
404 #[default]
409 PageCache,
410
411 FelderaCache,
416}
417
418impl StorageCacheConfig {
419 #[cfg(unix)]
420 pub fn to_custom_open_flags(&self) -> i32 {
421 match self {
422 StorageCacheConfig::PageCache => (),
423 StorageCacheConfig::FelderaCache => {
424 #[cfg(target_os = "linux")]
425 return libc::O_DIRECT;
426 }
427 }
428 0
429 }
430}
431
432#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
434#[serde(default)]
435pub struct StorageOptions {
436 pub backend: StorageBackendConfig,
438
439 #[serde(
453 alias = "min_storage_bytes",
454 deserialize_with = "size_min_spill_size",
455 skip_serializing_if = "Option::is_none"
456 )]
457 #[schema(value_type = Option<String>)]
458 pub min_spill_size: Option<ConfigSize>,
459
460 #[serde(
474 alias = "min_step_storage_bytes",
475 deserialize_with = "size_min_step_spill_size",
476 skip_serializing_if = "Option::is_none"
477 )]
478 #[schema(value_type = Option<String>)]
479 pub min_step_spill_size: Option<ConfigSize>,
480
481 pub compression: StorageCompression,
487
488 pub compression_level: Option<i32>,
499
500 #[serde(
509 alias = "cache_mib",
510 deserialize_with = "size_cache_size",
511 skip_serializing_if = "Option::is_none"
512 )]
513 #[schema(value_type = Option<String>)]
514 pub cache_size: Option<ConfigSize>,
515
516 #[serde(skip_serializing_if = "Option::is_none")]
531 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
532 pub bloom_false_positive_rate: Option<f64>,
533}
534
535impl Eq for StorageOptions {}
538
539#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
541#[serde(tag = "name", content = "config", rename_all = "snake_case")]
542pub enum StorageBackendConfig {
543 #[default]
547 Default,
548
549 File(Box<FileBackendConfig>),
553
554 Object(ObjectStorageConfig),
556}
557
558impl Display for StorageBackendConfig {
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560 match self {
561 StorageBackendConfig::Default => write!(f, "default"),
562 StorageBackendConfig::File(_) => write!(f, "file"),
563 StorageBackendConfig::Object(_) => write!(f, "object"),
564 }
565 }
566}
567
568#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
570#[serde(rename_all = "snake_case")]
571pub enum StorageCompression {
572 #[default]
577 Default,
578
579 None,
581
582 Snappy,
584
585 Lz4,
590
591 Zstd,
597}
598
599#[derive(Debug, Clone, Eq, PartialEq)]
600pub enum StartFromCheckpoint {
601 Latest,
602 Uuid(uuid::Uuid),
603}
604
605impl ToSchema<'_> for StartFromCheckpoint {
606 fn schema() -> (
607 &'static str,
608 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
609 ) {
610 (
611 "StartFromCheckpoint",
612 utoipa::openapi::RefOr::T(Schema::OneOf(
613 OneOfBuilder::new()
614 .item(
615 ObjectBuilder::new()
616 .schema_type(SchemaType::String)
617 .enum_values(Some(["latest"].into_iter()))
618 .build(),
619 )
620 .item(
621 ObjectBuilder::new()
622 .schema_type(SchemaType::String)
623 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
624 utoipa::openapi::KnownFormat::Uuid,
625 )))
626 .build(),
627 )
628 .nullable(true)
629 .build(),
630 )),
631 )
632 }
633}
634
635impl<'de> Deserialize<'de> for StartFromCheckpoint {
636 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
637 where
638 D: Deserializer<'de>,
639 {
640 struct StartFromCheckpointVisitor;
641
642 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
643 type Value = StartFromCheckpoint;
644
645 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
646 formatter.write_str("a UUID string or the string \"latest\"")
647 }
648
649 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
650 where
651 E: de::Error,
652 {
653 if value == "latest" {
654 Ok(StartFromCheckpoint::Latest)
655 } else {
656 uuid::Uuid::parse_str(value)
657 .map(StartFromCheckpoint::Uuid)
658 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
659 }
660 }
661 }
662
663 deserializer.deserialize_str(StartFromCheckpointVisitor)
664 }
665}
666
667impl Serialize for StartFromCheckpoint {
668 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
669 where
670 S: serde::Serializer,
671 {
672 match self {
673 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
674 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
675 }
676 }
677}
678
679#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
680pub struct SyncConfig {
681 pub endpoint: Option<String>,
691
692 pub bucket: String,
701
702 pub region: Option<String>,
706
707 pub provider: Option<String>,
714
715 pub access_key: Option<String>,
721
722 pub secret_key: Option<String>,
728
729 pub start_from_checkpoint: Option<StartFromCheckpoint>,
734
735 #[schema(default = std::primitive::bool::default)]
741 #[serde(default)]
742 pub fail_if_no_checkpoint: bool,
743
744 pub transfers: Option<u8>,
747
748 pub checkers: Option<u8>,
751
752 pub ignore_checksum: Option<bool>,
756
757 pub multi_thread_streams: Option<u8>,
760
761 pub multi_thread_cutoff: Option<String>,
766
767 #[schema(default = default_optimize_download_resources)]
778 #[serde(default = "default_optimize_download_resources")]
779 pub optimize_download_resources: bool,
780
781 pub upload_concurrency: Option<u8>,
784
785 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
787 #[schema(default = std::primitive::bool::default)]
788 #[serde(default)]
789 pub standby: bool,
790
791 #[serde(
797 default,
798 alias = "pull_interval",
799 deserialize_with = "duration_standby_pull_interval",
800 skip_serializing_if = "Option::is_none"
801 )]
802 #[schema(value_type = Option<String>, default = default_pull_interval)]
803 pub standby_pull_interval: Option<ConfigDuration>,
804
805 #[serde(
811 default,
812 alias = "push_interval",
813 deserialize_with = "duration_checkpoint_push_interval",
814 skip_serializing_if = "Option::is_none"
815 )]
816 #[schema(value_type = Option<String>)]
817 pub checkpoint_push_interval: Option<ConfigDuration>,
818
819 pub flags: Option<Vec<String>>,
828
829 #[schema(default = default_retention_min_count)]
834 #[serde(default = "default_retention_min_count")]
835 pub retention_min_count: u32,
836
837 #[serde(
841 default,
842 alias = "retention_min_age",
843 deserialize_with = "duration_min_retention",
844 skip_serializing_if = "Option::is_none"
845 )]
846 #[schema(value_type = Option<String>, default = default_retention_min_age)]
847 pub min_retention: Option<ConfigDuration>,
848
849 #[serde(default)]
862 pub read_bucket: Option<String>,
863
864 #[schema(default = std::primitive::bool::default)]
890 #[serde(default)]
891 pub take_bucket_ownership: bool,
892}
893
894fn default_retention_min_count() -> u32 {
895 10
896}
897
898fn default_optimize_download_resources() -> bool {
899 true
900}
901
902impl SyncConfig {
903 pub fn standby_pull_interval(&self) -> ConfigDuration {
910 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
911 }
912
913 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
915 self.checkpoint_push_interval
916 }
917
918 pub fn min_retention(&self) -> ConfigDuration {
921 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
922 }
923
924 pub fn validate(&self) -> Result<(), String> {
925 #[allow(deprecated)]
926 if self.standby {
927 return Err(
928 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
929 );
930 }
931
932 if let Some(ref rb) = self.read_bucket {
933 if rb == &self.bucket {
934 return Err(
935 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
936 .to_owned(),
937 );
938 }
939 if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
942 return Err(format!(
943 "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",
944 self.bucket, rb
945 ));
946 }
947 }
948
949 Ok(())
950 }
951}
952
953fn is_gcs_bucket(bucket: &str) -> bool {
955 bucket.starts_with("gs://")
956}
957
958#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
985pub struct PipelineTemplateConfig {
986 pub name: String,
988 #[schema(default = default_pipeline_template_key)]
992 #[serde(default = "default_pipeline_template_key")]
993 pub key: String,
994}
995
996fn default_pipeline_template_key() -> String {
997 "pipelineTemplate".to_string()
998}
999
1000#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1001pub struct ObjectStorageConfig {
1002 pub url: String,
1031
1032 #[serde(flatten)]
1065 pub other_options: BTreeMap<String, String>,
1066}
1067
1068#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1070#[serde(default)]
1071pub struct FileBackendConfig {
1072 pub async_threads: Option<bool>,
1078
1079 #[serde(
1084 default,
1085 alias = "ioop_delay",
1086 deserialize_with = "duration_ioop_latency",
1087 skip_serializing_if = "Option::is_none"
1088 )]
1089 #[schema(value_type = Option<String>)]
1090 pub ioop_latency: Option<ConfigDuration>,
1091
1092 pub sync: Option<SyncConfig>,
1094
1095 pub sync_mode: Option<StorageSyncMode>,
1100}
1101
1102#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1108#[serde(rename_all = "snake_case")]
1109pub enum StorageSyncMode {
1110 #[default]
1113 Auto,
1114
1115 Syncfs,
1125
1126 PerFile,
1131}
1132
1133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1136#[serde(default)]
1137pub struct RuntimeConfig {
1138 pub workers: u16,
1148
1149 #[serde(
1177 default,
1178 alias = "max_rss_mb",
1179 deserialize_with = "size_max_rss",
1180 skip_serializing_if = "Option::is_none"
1181 )]
1182 #[schema(value_type = Option<String>)]
1183 pub max_rss: Option<ConfigSize>,
1184
1185 #[serde(
1208 default,
1209 alias = "datafusion_memory_mb",
1210 deserialize_with = "size_datafusion_memory",
1211 skip_serializing_if = "Option::is_none"
1212 )]
1213 #[schema(value_type = Option<String>)]
1214 pub datafusion_memory: Option<ConfigSize>,
1215
1216 pub hosts: usize,
1223
1224 #[serde(deserialize_with = "deserialize_storage_options")]
1236 pub storage: Option<StorageOptions>,
1237
1238 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1240 pub fault_tolerance: FtConfig,
1241
1242 pub cpu_profiler: bool,
1246
1247 pub tracing: bool,
1249
1250 pub tracing_endpoint_jaeger: String,
1252
1253 pub min_batch_size_records: u64,
1261
1262 #[serde(
1265 default,
1266 alias = "max_buffering_delay_usecs",
1267 deserialize_with = "duration_max_buffering_delay",
1268 skip_serializing_if = "Option::is_none"
1269 )]
1270 #[schema(value_type = Option<String>)]
1271 pub max_buffering_delay: Option<ConfigDuration>,
1272
1273 pub resources: ResourceConfig,
1276
1277 #[serde(
1287 default,
1288 alias = "clock_resolution_usecs",
1289 deserialize_with = "duration_clock_resolution",
1290 skip_serializing_if = "Option::is_none"
1291 )]
1292 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1293 pub clock_resolution: Option<ConfigDuration>,
1294
1295 #[schema(value_type = Option<String>, example = "+05:30")]
1306 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1307
1308 pub pin_cpus: Vec<usize>,
1317
1318 #[serde(
1321 default,
1322 alias = "provisioning_timeout_secs",
1323 deserialize_with = "duration_provisioning_timeout",
1324 skip_serializing_if = "Option::is_none"
1325 )]
1326 #[schema(value_type = Option<String>)]
1327 pub provisioning_timeout: Option<ConfigDuration>,
1328
1329 pub max_parallel_connector_init: Option<u64>,
1340
1341 pub init_containers: Option<serde_json::Value>,
1343
1344 pub checkpoint_during_suspend: bool,
1346
1347 pub http_workers: Option<u64>,
1355
1356 pub io_workers: Option<u64>,
1367
1368 #[serde(default)]
1375 pub env: BTreeMap<String, String>,
1376
1377 pub dev_tweaks: DevTweaks,
1379
1380 pub logging: Option<String>,
1389
1390 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1398}
1399
1400fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1402where
1403 D: Deserializer<'de>,
1404{
1405 struct BoolOrStruct;
1406
1407 impl<'de> Visitor<'de> for BoolOrStruct {
1408 type Value = Option<StorageOptions>;
1409
1410 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1411 formatter.write_str("boolean or StorageOptions")
1412 }
1413
1414 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1415 where
1416 E: de::Error,
1417 {
1418 match v {
1419 false => Ok(None),
1420 true => Ok(Some(StorageOptions::default())),
1421 }
1422 }
1423
1424 fn visit_unit<E>(self) -> Result<Self::Value, E>
1425 where
1426 E: de::Error,
1427 {
1428 Ok(None)
1429 }
1430
1431 fn visit_none<E>(self) -> Result<Self::Value, E>
1432 where
1433 E: de::Error,
1434 {
1435 Ok(None)
1436 }
1437
1438 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1439 where
1440 M: MapAccess<'de>,
1441 {
1442 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1443 }
1444 }
1445
1446 deserializer.deserialize_any(BoolOrStruct)
1447}
1448
1449fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1457where
1458 D: Deserializer<'de>,
1459{
1460 struct StringOrStruct;
1461
1462 impl<'de> Visitor<'de> for StringOrStruct {
1463 type Value = FtConfig;
1464
1465 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1466 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1467 }
1468
1469 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1470 where
1471 E: de::Error,
1472 {
1473 match v {
1474 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1475 model: Some(FtModel::default()),
1476 ..FtConfig::default()
1477 }),
1478 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1479 }
1480 }
1481
1482 fn visit_unit<E>(self) -> Result<Self::Value, E>
1483 where
1484 E: de::Error,
1485 {
1486 Ok(FtConfig::default())
1487 }
1488
1489 fn visit_none<E>(self) -> Result<Self::Value, E>
1490 where
1491 E: de::Error,
1492 {
1493 Ok(FtConfig::default())
1494 }
1495
1496 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1497 where
1498 M: MapAccess<'de>,
1499 {
1500 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1501 }
1502 }
1503
1504 deserializer.deserialize_any(StringOrStruct)
1505}
1506
1507impl Default for RuntimeConfig {
1508 fn default() -> Self {
1509 Self {
1510 workers: 8,
1511 max_rss: None,
1512 datafusion_memory: None,
1513 hosts: 1,
1514 storage: Some(StorageOptions::default()),
1515 fault_tolerance: FtConfig::default(),
1516 cpu_profiler: true,
1517 tracing: {
1518 false
1521 },
1522 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1523 min_batch_size_records: 0,
1524 max_buffering_delay: None,
1525 resources: ResourceConfig::default(),
1526 clock_resolution: None,
1527 clock_timezone_offset: None,
1528 pin_cpus: Vec::new(),
1529 provisioning_timeout: None,
1530 max_parallel_connector_init: None,
1531 init_containers: None,
1532 checkpoint_during_suspend: true,
1533 io_workers: None,
1534 http_workers: None,
1535 env: BTreeMap::default(),
1536 dev_tweaks: DevTweaks::default(),
1537 logging: None,
1538 pipeline_template_configmap: None,
1539 }
1540 }
1541}
1542
1543pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1547
1548pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1551
1552impl RuntimeConfig {
1553 pub fn max_buffering_delay(&self) -> ConfigDuration {
1555 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1556 }
1557
1558 pub fn clock_resolution(&self) -> ConfigDuration {
1560 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1561 }
1562
1563 pub fn effective_memory(&self) -> Option<ConfigSize> {
1566 self.max_rss.or(self.resources.memory_max)
1567 }
1568
1569 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1574 if let Some(explicit) = self.datafusion_memory {
1575 return Some(explicit);
1576 }
1577 let effective = self.effective_memory()?.as_bytes();
1578 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1580 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1581 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1582 }
1583}
1584
1585#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1596#[serde(rename_all = "snake_case")]
1597pub struct FtConfig {
1598 #[serde(with = "none_as_string")]
1600 #[serde(default = "default_model")]
1601 #[schema(
1602 schema_with = none_as_string_schema::<FtModel>,
1603 )]
1604 pub model: Option<FtModel>,
1605
1606 #[serde(
1613 default,
1614 alias = "checkpoint_interval_secs",
1615 deserialize_with = "duration_checkpoint_interval",
1616 skip_serializing_if = "Option::is_none"
1617 )]
1618 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1619 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1620}
1621
1622fn default_model() -> Option<FtModel> {
1623 Some(FtModel::default())
1624}
1625
1626pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1646 use crate::duration::LegacyUnit;
1647 use serde_json::{Map, Value};
1648
1649 struct Rule {
1651 new: &'static str,
1652 old: &'static str,
1653 unit: LegacyUnit,
1654 max: u64,
1656 null_allowed: bool,
1659 }
1660 const fn rule(
1661 new: &'static str,
1662 old: &'static str,
1663 unit: LegacyUnit,
1664 max: u64,
1665 null_allowed: bool,
1666 ) -> Rule {
1667 Rule {
1668 new,
1669 old,
1670 unit,
1671 max,
1672 null_allowed,
1673 }
1674 }
1675 const U32: u64 = u32::MAX as u64;
1676 const U64: u64 = u64::MAX;
1677 use LegacyUnit::{Days, Micros, Millis, Secs};
1678
1679 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1680 for rule in rules {
1681 let Some(value) = object.remove(rule.new) else {
1682 continue;
1683 };
1684 let legacy = match &value {
1685 Value::String(text) => match text.parse::<ConfigDuration>() {
1686 Ok(duration) => {
1687 let nanos = std::time::Duration::from(duration).as_nanos();
1688 let unit_nanos = u128::from(rule.unit.nanos());
1689 let whole = nanos.div_ceil(unit_nanos);
1690 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1691 }
1692 Err(_) => {
1693 object.insert(rule.new.to_string(), value);
1694 continue;
1695 }
1696 },
1697 Value::Null if !rule.null_allowed => continue,
1698 other => other.clone(),
1700 };
1701 object.insert(rule.old.to_string(), legacy);
1702 }
1703 }
1704 fn child<'a>(
1705 object: &'a mut Map<String, Value>,
1706 key: &str,
1707 ) -> Option<&'a mut Map<String, Value>> {
1708 object.get_mut(key).and_then(Value::as_object_mut)
1709 }
1710 fn max_expiry(consumer: &mut Map<String, Value>) {
1713 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1714 return;
1715 };
1716 let Ok(duration) = text.parse::<ConfigDuration>() else {
1717 return;
1718 };
1719 let duration = std::time::Duration::from(duration);
1720 consumer.remove("max_expiry");
1721 consumer.insert(
1722 "max_expires".to_string(),
1723 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1724 );
1725 }
1726 fn nats_connection(transport: &mut Map<String, Value>) {
1728 if let Some(connection) = child(transport, "connection_config") {
1729 apply(
1730 connection,
1731 &[
1732 rule(
1733 "connection_timeout",
1734 "connection_timeout_secs",
1735 Secs,
1736 U64,
1737 false,
1738 ),
1739 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1740 ],
1741 );
1742 }
1743 }
1744 fn connector(endpoint: &mut Map<String, Value>) {
1746 apply(
1747 endpoint,
1748 &[rule(
1749 "max_output_buffer_time",
1750 "max_output_buffer_time_millis",
1751 Millis,
1752 U64,
1753 false,
1754 )],
1755 );
1756 let name = endpoint
1757 .get("transport")
1758 .and_then(|transport| transport.get("name"))
1759 .and_then(Value::as_str)
1760 .map(str::to_string);
1761 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1762 match name.as_deref() {
1763 Some("url_input") => apply(
1764 transport,
1765 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1766 ),
1767 Some("kafka_input") => apply(
1768 transport,
1769 &[rule(
1770 "group_join_timeout",
1771 "group_join_timeout_secs",
1772 Secs,
1773 U32,
1774 false,
1775 )],
1776 ),
1777 Some("kafka_output") => apply(
1778 transport,
1779 &[rule(
1780 "initialization_timeout",
1781 "initialization_timeout_secs",
1782 Secs,
1783 U32,
1784 false,
1785 )],
1786 ),
1787 Some("clock_input") => apply(
1788 transport,
1789 &[rule(
1790 "clock_resolution",
1791 "clock_resolution_usecs",
1792 Micros,
1793 U64,
1794 false,
1795 )],
1796 ),
1797 Some("pub_sub_input") => apply(
1798 transport,
1799 &[
1800 rule("timeout", "timeout_seconds", Secs, U32, true),
1801 rule(
1802 "connect_timeout",
1803 "connect_timeout_seconds",
1804 Secs,
1805 U32,
1806 true,
1807 ),
1808 ],
1809 ),
1810 Some("nats_input") => {
1811 apply(
1812 transport,
1813 &[
1814 rule(
1815 "inactivity_timeout",
1816 "inactivity_timeout_secs",
1817 Secs,
1818 U64,
1819 false,
1820 ),
1821 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1822 ],
1823 );
1824 nats_connection(transport);
1825 if let Some(consumer) = child(transport, "consumer_config") {
1826 max_expiry(consumer);
1827 }
1828 }
1829 Some("nats_output") => {
1830 apply(
1831 transport,
1832 &[rule(
1833 "publish_timeout",
1834 "publish_timeout_secs",
1835 Secs,
1836 U64,
1837 false,
1838 )],
1839 );
1840 nats_connection(transport);
1841 }
1842 _ => {}
1843 }
1844 }
1845 let is_avro = endpoint
1846 .get("format")
1847 .and_then(|format| format.get("name"))
1848 .and_then(Value::as_str)
1849 == Some("avro");
1850 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1851 {
1852 apply(
1853 format,
1854 &[rule(
1855 "registry_timeout",
1856 "registry_timeout_secs",
1857 Secs,
1858 U64,
1859 true,
1860 )],
1861 );
1862 }
1863 }
1864
1865 let Some(global) = config.as_object_mut() else {
1866 return;
1867 };
1868 apply(
1869 global,
1870 &[
1871 rule(
1872 "clock_resolution",
1873 "clock_resolution_usecs",
1874 Micros,
1875 U64,
1876 true,
1877 ),
1878 rule(
1879 "max_buffering_delay",
1880 "max_buffering_delay_usecs",
1881 Micros,
1882 U64,
1883 false,
1884 ),
1885 rule(
1886 "provisioning_timeout",
1887 "provisioning_timeout_secs",
1888 Secs,
1889 U64,
1890 true,
1891 ),
1892 ],
1893 );
1894 if let Some(ft) = child(global, "fault_tolerance") {
1895 apply(
1897 ft,
1898 &[rule(
1899 "checkpoint_interval",
1900 "checkpoint_interval_secs",
1901 Secs,
1902 U64,
1903 true,
1904 )],
1905 );
1906 }
1907 let backend = child(global, "storage")
1908 .and_then(|storage| child(storage, "backend"))
1909 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1910 .and_then(|backend| child(backend, "config"));
1911 if let Some(file) = backend {
1912 apply(
1913 file,
1914 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1915 );
1916 if let Some(sync) = child(file, "sync") {
1917 apply(
1918 sync,
1919 &[
1920 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1921 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1922 rule("min_retention", "retention_min_age", Days, U32, false),
1923 ],
1924 );
1925 }
1926 }
1927 for endpoints in ["inputs", "outputs"] {
1928 if let Some(endpoints) = child(global, endpoints) {
1929 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1930 connector(endpoint);
1931 }
1932 }
1933 }
1934}
1935
1936#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1942pub struct LegacySpelling {
1943 pub durations: bool,
1945 pub sizes: bool,
1947}
1948
1949impl LegacySpelling {
1950 pub const NONE: LegacySpelling = LegacySpelling {
1952 durations: false,
1953 sizes: false,
1954 };
1955
1956 pub fn any(self) -> bool {
1958 self.durations || self.sizes
1959 }
1960
1961 pub fn apply(self, config: &mut serde_json::Value) {
1964 if self.durations {
1965 to_legacy_duration_spelling(config);
1966 }
1967 if self.sizes {
1968 to_legacy_size_spelling(config);
1969 }
1970 }
1971}
1972
1973pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
1984 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
1985 use serde_json::{Map, Value};
1986
1987 struct Rule {
1989 new: &'static str,
1990 old: &'static str,
1991 unit: LegacySizeUnit,
1992 }
1993 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
1994 Rule { new, old, unit }
1995 }
1996
1997 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1998 for rule in rules {
1999 let Some(value) = object.remove(rule.new) else {
2000 continue;
2001 };
2002 let legacy = match &value {
2003 Value::String(text) => match text.parse::<ConfigSize>() {
2004 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2005 Err(_) => {
2006 object.insert(rule.new.to_string(), value);
2007 continue;
2008 }
2009 },
2010 Value::Null => continue,
2012 other => other.clone(),
2014 };
2015 object.insert(rule.old.to_string(), legacy);
2016 }
2017 }
2018 fn child<'a>(
2019 object: &'a mut Map<String, Value>,
2020 key: &str,
2021 ) -> Option<&'a mut Map<String, Value>> {
2022 object.get_mut(key).and_then(Value::as_object_mut)
2023 }
2024 fn connector(endpoint: &mut Map<String, Value>) {
2026 apply(
2027 endpoint,
2028 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2029 );
2030 let name = endpoint
2031 .get("transport")
2032 .and_then(|transport| transport.get("name"))
2033 .and_then(Value::as_str)
2034 .map(str::to_string);
2035 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2036 match name.as_deref() {
2037 Some("file_input") => apply(
2038 transport,
2039 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2040 ),
2041 Some("dynamodb_output" | "postgres_output") => apply(
2042 transport,
2043 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2044 ),
2045 Some("postgres_cdc_input") => {
2046 if let Some(batch) = child(transport, "batch") {
2047 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2048 }
2049 }
2050 _ => {}
2051 }
2052 }
2053 }
2054
2055 let Some(global) = config.as_object_mut() else {
2056 return;
2057 };
2058 apply(
2059 global,
2060 &[
2061 rule("max_rss", "max_rss_mb", Megabytes),
2062 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2063 ],
2064 );
2065 if let Some(storage) = child(global, "storage") {
2066 apply(
2067 storage,
2068 &[
2069 rule("cache_size", "cache_mib", Mebibytes),
2070 rule("min_spill_size", "min_storage_bytes", Bytes),
2071 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2072 ],
2073 );
2074 }
2075 if let Some(resources) = child(global, "resources") {
2076 apply(
2077 resources,
2078 &[
2079 rule("memory_min", "memory_mb_min", Megabytes),
2080 rule("memory_max", "memory_mb_max", Megabytes),
2081 rule("storage_min", "storage_mb_min", Megabytes),
2082 rule("storage_max", "storage_mb_max", Megabytes),
2083 ],
2084 );
2085 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2086 apply(
2087 storage,
2088 &[rule(
2089 "scale_threshold_available",
2090 "scale_threshold_available_mb",
2091 Megabytes,
2092 )],
2093 );
2094 }
2095 }
2096 if let Some(tweaks) = child(global, "dev_tweaks") {
2097 apply(
2098 tweaks,
2099 &[
2100 rule("storage_max", "storage_mb_max", Mebibytes),
2101 rule(
2102 "fbuf_slab_size_per_class",
2103 "fbuf_slab_bytes_per_class",
2104 Bytes,
2105 ),
2106 rule(
2107 "lazy_input_map_key_block_size",
2108 "lazy_input_map_key_block_bytes",
2109 Bytes,
2110 ),
2111 rule(
2112 "exchange_channel_capacity",
2113 "exchange_channel_capacity_bytes",
2114 Bytes,
2115 ),
2116 ],
2117 );
2118 }
2119 for endpoints in ["inputs", "outputs"] {
2120 if let Some(endpoints) = child(global, endpoints) {
2121 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2122 connector(endpoint);
2123 }
2124 }
2125 }
2126}
2127
2128#[cfg(test)]
2129mod test {
2130 use super::deserialize_fault_tolerance;
2131 use crate::config::{
2132 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2133 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2134 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2135 StorageOptions, SyncConfig, TransportConfig,
2136 };
2137 use crate::duration::ConfigDuration;
2138 use crate::size::ConfigSize;
2139 use serde::{Deserialize, Serialize};
2140 use serde_json::json;
2141 use std::time::Duration;
2142
2143 fn assert_reloads<T>(value: serde_json::Value)
2146 where
2147 T: Serialize + for<'de> Deserialize<'de>,
2148 {
2149 let first: T = serde_json::from_value(value.clone())
2150 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2151 let written = serde_json::to_value(&first).unwrap();
2152 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2153 panic!("{value} is written as {written}, which does not load: {e}")
2154 });
2155 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2156 }
2157
2158 #[test]
2163 fn size_settings_reload_from_what_is_written() {
2164 use crate::transport::dynamodb::DynamoDBWriterConfig;
2165 use crate::transport::file::FileInputConfig;
2166 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2167
2168 for number in [0u64, 1, 1_100, u64::MAX] {
2171 assert_reloads::<RuntimeConfig>(json!({
2172 "max_rss_mb": number,
2173 "datafusion_memory_mb": number,
2174 "storage": {"cache_mib": number, "min_storage_bytes": number},
2175 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2176 "dev_tweaks": {"storage_mb_max": number},
2177 }));
2178 }
2179
2180 let max = format!("{}B", u64::MAX);
2181 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2182 assert_reloads::<RuntimeConfig>(json!({
2183 "max_rss": size,
2184 "datafusion_memory": size,
2185 "storage": {
2186 "cache_size": size,
2187 "min_spill_size": size,
2188 "min_step_spill_size": size,
2189 },
2190 "resources": {
2191 "memory_min": size,
2192 "memory_max": size,
2193 "storage_min": size,
2194 "storage_max": size,
2195 "autoscaling": {"storage": {"scale_threshold_available": size}},
2196 },
2197 "dev_tweaks": {
2198 "storage_max": size,
2199 "fbuf_slab_size_per_class": size,
2200 "exchange_channel_capacity": size,
2201 },
2202 }));
2203 assert_reloads::<ConnectorConfig>(json!({
2204 "transport": {
2205 "name": "file_input",
2206 "config": {"path": "input.csv", "buffer_size": size},
2207 },
2208 "max_queued_size": size,
2209 }));
2210 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2211 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2212 assert_reloads::<PostgresWriterConfig>(json!({
2213 "uri": "postgres://localhost/db",
2214 "table": "t",
2215 "max_buffer_size": size,
2216 }));
2217 assert_reloads::<DynamoDBWriterConfig>(json!({
2218 "table": "t",
2219 "region": "us-east-1",
2220 "max_buffer_size": size,
2221 }));
2222 }
2223 }
2224
2225 #[test]
2230 fn soft_delete_is_backward_compatible() {
2231 let config: ConnectorConfig = serde_json::from_value(json!({
2232 "transport": {"name": "empty_input"}
2233 }))
2234 .unwrap();
2235 assert!(!config.soft_delete);
2236
2237 let serialized = serde_json::to_value(&config).unwrap();
2238 assert_eq!(serialized.get("soft_delete"), None);
2239
2240 let config: ConnectorConfig = serde_json::from_value(json!({
2241 "transport": {"name": "empty_input"},
2242 "soft_delete": true
2243 }))
2244 .unwrap();
2245 assert!(config.soft_delete);
2246 assert_eq!(
2247 serde_json::to_value(&config).unwrap().get("soft_delete"),
2248 Some(&json!(true))
2249 );
2250 }
2251
2252 #[test]
2255 fn soft_delete_invalidates_checkpointed_connector_state() {
2256 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2257 let mut soft_delete = config.clone();
2258 soft_delete.soft_delete = true;
2259
2260 assert!(config.equal_for_input_checkpoint_replay(&config));
2261 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2262 }
2263
2264 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2265 PipelineConfig {
2266 global: RuntimeConfig::default(),
2267 multihost: None,
2268 name: name.map(str::to_string),
2269 given_name: None,
2270 storage_config: None,
2271 secrets_dir: None,
2272 inputs: Default::default(),
2273 outputs: Default::default(),
2274 program_ir: None,
2275 }
2276 }
2277
2278 #[test]
2279 fn pipeline_identity_uses_system_and_given_names() {
2280 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2281 config.given_name = Some("my-pipeline".to_string());
2282
2283 let metadata = config.pipeline_identity().unwrap();
2284 assert_eq!(
2285 metadata.name,
2286 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2287 );
2288 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2289 }
2290
2291 #[test]
2292 fn pipeline_identity_is_none_without_system_name() {
2293 assert_eq!(config_with_name(None).pipeline_identity(), None);
2294 }
2295
2296 #[test]
2297 fn resolved_datafusion_memory_explicit_passes_through() {
2298 let config = RuntimeConfig {
2299 max_rss: Some(ConfigSize::from_mb(8_000)),
2300 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2301 ..Default::default()
2302 };
2303 assert_eq!(
2304 config.resolved_datafusion_memory(),
2305 Some(ConfigSize::from_mb(1_500))
2306 );
2307 }
2308
2309 #[test]
2310 fn resolved_datafusion_memory_unconfigured_returns_none() {
2311 let config = RuntimeConfig::default();
2312 assert!(config.max_rss.is_none());
2313 assert!(config.resources.memory_max.is_none());
2314 assert_eq!(config.resolved_datafusion_memory(), None);
2315 }
2316
2317 #[test]
2318 fn resolved_datafusion_memory_small_budget_scales_down() {
2319 let config = RuntimeConfig {
2321 max_rss: Some(ConfigSize::from_mb(256)),
2322 ..Default::default()
2323 };
2324 assert_eq!(
2325 config.resolved_datafusion_memory(),
2326 Some(ConfigSize::from_bytes(12_800_000))
2327 );
2328
2329 let config = RuntimeConfig {
2330 max_rss: Some(ConfigSize::from_mb(512)),
2331 ..Default::default()
2332 };
2333 assert_eq!(
2334 config.resolved_datafusion_memory(),
2335 Some(ConfigSize::from_bytes(25_600_000))
2336 );
2337 }
2338
2339 #[test]
2340 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2341 let config = RuntimeConfig {
2343 max_rss: Some(ConfigSize::from_mb(64_000)),
2344 ..Default::default()
2345 };
2346 assert_eq!(
2347 config.resolved_datafusion_memory(),
2348 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2349 );
2350 }
2351
2352 #[test]
2353 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2354 let config = RuntimeConfig {
2356 max_rss: Some(ConfigSize::from_mb(16_000)),
2357 ..Default::default()
2358 };
2359 assert_eq!(
2360 config.resolved_datafusion_memory(),
2361 Some(ConfigSize::from_mb(800))
2362 );
2363 }
2364
2365 #[test]
2366 fn resolved_datafusion_memory_falls_back_to_resources() {
2367 let config = RuntimeConfig {
2369 max_rss: None,
2370 resources: ResourceConfig {
2371 memory_max: Some(ConfigSize::from_mb(16_000)),
2372 ..Default::default()
2373 },
2374 ..Default::default()
2375 };
2376 assert_eq!(
2377 config.resolved_datafusion_memory(),
2378 Some(ConfigSize::from_mb(800))
2379 );
2380 }
2381
2382 #[test]
2383 fn ft_config() {
2384 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2385 #[serde(default)]
2386 struct Wrapper {
2387 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2388 config: FtConfig,
2389 }
2390
2391 for s in [
2394 "{}",
2395 r#"{"config": null}"#,
2396 r#"{"config": {"model": "none"}}"#,
2397 ] {
2398 let config: Wrapper = serde_json::from_str(s).unwrap();
2399 assert_eq!(config.config.model, None);
2400 assert_eq!(config.config.checkpoint_interval(), None);
2401 }
2402
2403 let s = serde_json::to_string(&Wrapper {
2405 config: FtConfig::default(),
2406 })
2407 .unwrap();
2408 assert!(s.contains("\"none\""));
2409
2410 for s in [
2413 r#"{}"#,
2414 r#"{"checkpoint_interval": "60s"}"#,
2415 r#"{"checkpoint_interval_secs": 60}"#,
2416 ] {
2417 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2418 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2419 assert_eq!(
2420 config.checkpoint_interval(),
2421 Some(Duration::from_secs(60)),
2422 "parsing {s}"
2423 );
2424 }
2425
2426 for s in [
2429 r#"{"checkpoint_interval": null}"#,
2430 r#"{"checkpoint_interval_secs": null}"#,
2431 ] {
2432 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2433 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2434 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2435 }
2436
2437 let error = serde_json::from_str::<FtConfig>(
2440 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2441 )
2442 .unwrap_err()
2443 .to_string();
2444 assert!(error.contains("duplicate field"), "{error}");
2445
2446 for (json, expected_secs) in [
2448 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2449 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2450 ] {
2451 assert_eq!(
2452 serde_json::from_str::<FtConfig>(json)
2453 .unwrap()
2454 .checkpoint_interval(),
2455 Some(Duration::from_secs(expected_secs)),
2456 "parsing {json}"
2457 );
2458 }
2459 }
2460
2461 #[test]
2465 fn legacy_duration_spelling_uses_the_older_keys() {
2466 let mut config = serde_json::json!({
2467 "workers": 2,
2468 "clock_resolution": "250ms",
2469 "max_buffering_delay": "3ms",
2470 "provisioning_timeout": "15m",
2471 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2472 "storage": {"backend": {"name": "file", "config": {
2473 "ioop_latency": "5ms",
2474 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2475 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2476 });
2477 super::to_legacy_duration_spelling(&mut config);
2478 assert_eq!(
2479 config,
2480 serde_json::json!({
2481 "workers": 2,
2482 "clock_resolution_usecs": 250_000,
2483 "max_buffering_delay_usecs": 3_000,
2484 "provisioning_timeout_secs": 900,
2485 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2486 "storage": {"backend": {"name": "file", "config": {
2487 "ioop_delay": 5,
2488 "sync": {"bucket": "b", "pull_interval": 10,
2489 "push_interval": 3_600, "retention_min_age": 30}}}},
2490 })
2491 );
2492 }
2493
2494 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2496 serde_json::json!({
2497 "name": "p",
2498 "clock_resolution": "250ms",
2499 "inputs": {
2500 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2501 "topic": "t", "group_join_timeout": "30s"}}},
2502 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2503 "path": "http://x", "pause_linger": "7s"}}},
2504 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2505 "connection_config": {"server_url": "nats://x",
2506 "connection_timeout": "5s", "request_timeout": "6s"},
2507 "stream_name": "s",
2508 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2509 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2510 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2511 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2512 },
2513 "outputs": {
2514 "v.kafka": {"stream": "v",
2515 "transport": {"name": "kafka_output", "config": {
2516 "topic": "v", "initialization_timeout": "40s"}},
2517 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2518 "registry_timeout": "8s"}},
2519 "enable_output_buffer": true,
2520 "max_output_buffer_time": "500ms"},
2521 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2522 "connection_config": {"server_url": "nats://x",
2523 "connection_timeout": "5s", "request_timeout": "6s"},
2524 "subject": "s", "publish_timeout": "9s"}}},
2525 },
2526 })
2527 }
2528
2529 #[test]
2533 fn legacy_duration_spelling_rewrites_every_connector() {
2534 let mut config = pipeline_with_every_duration_connector();
2535 super::to_legacy_duration_spelling(&mut config);
2536 let i = &config["inputs"];
2537 assert_eq!(
2538 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2539 30
2540 );
2541 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2542 let nats = &i["t.nats"]["transport"]["config"];
2543 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2544 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2545 assert_eq!(nats["inactivity_timeout_secs"], 90);
2546 assert_eq!(nats["retry_interval_secs"], 3);
2547 assert_eq!(
2548 nats["consumer_config"]["max_expires"],
2549 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2550 );
2551 let pubsub = &i["t.pubsub"]["transport"]["config"];
2552 assert_eq!(pubsub["timeout_seconds"], 20);
2553 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2554 let out = &config["outputs"]["v.kafka"];
2555 assert_eq!(
2556 out["transport"]["config"]["initialization_timeout_secs"],
2557 40
2558 );
2559 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2560 assert_eq!(out["max_output_buffer_time_millis"], 500);
2561 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2562 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2563 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2564 assert_eq!(nats["publish_timeout_secs"], 9);
2565
2566 let text = config.to_string();
2568 for new in [
2569 "\"group_join_timeout\"",
2570 "\"pause_linger\"",
2571 "\"connection_timeout\"",
2572 "\"request_timeout\"",
2573 "\"inactivity_timeout\"",
2574 "\"retry_interval\"",
2575 "\"max_expiry\"",
2576 "\"timeout\"",
2577 "\"connect_timeout\"",
2578 "\"initialization_timeout\"",
2579 "\"registry_timeout\"",
2580 "\"max_output_buffer_time\"",
2581 "\"publish_timeout\"",
2582 "\"clock_resolution\"",
2583 ] {
2584 assert!(!text.contains(new), "{new} survived in {text}");
2585 }
2586 }
2587
2588 #[test]
2590 fn legacy_duration_spelling_round_trips_connectors() {
2591 let original: PipelineConfig =
2592 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2593 let mut value = serde_json::to_value(&original).unwrap();
2594 super::to_legacy_duration_spelling(&mut value);
2595 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2596
2597 let registry = |config: &PipelineConfig| {
2600 let format = config.outputs["v.kafka"]
2601 .connector_config
2602 .format
2603 .clone()
2604 .unwrap();
2605 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2606 .unwrap()
2607 .registry_config
2608 .registry_timeout
2609 };
2610 assert_eq!(registry(&reread), registry(&original));
2611 let mut original = original;
2612 for config in [&mut reread, &mut original] {
2613 config
2614 .outputs
2615 .get_mut("v.kafka")
2616 .unwrap()
2617 .connector_config
2618 .format = None;
2619 }
2620 assert_eq!(reread, original);
2621 }
2622
2623 #[test]
2627 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2628 let mut config = serde_json::json!({
2629 "inputs": {
2630 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2631 "group_join_timeout": "100000000000s"}}},
2632 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2633 },
2634 "storage": {"backend": {"name": "file", "config": {
2635 "sync": {"min_retention": "100000000000d"}}}},
2636 });
2637 super::to_legacy_duration_spelling(&mut config);
2638 let i = &config["inputs"];
2639 assert_eq!(
2640 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2641 u64::from(u32::MAX)
2642 );
2643 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2644 assert_eq!(
2645 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2646 u64::from(u32::MAX)
2647 );
2648 }
2649
2650 #[test]
2654 fn legacy_duration_spelling_round_trips() {
2655 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2656 "clock_resolution": "250ms",
2657 "max_buffering_delay": "3ms",
2658 "provisioning_timeout": "15m",
2659 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2660 }))
2661 .unwrap();
2662 let mut value = serde_json::to_value(&original).unwrap();
2663 super::to_legacy_duration_spelling(&mut value);
2664 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2665 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2666 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2667 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2668 assert_eq!(
2669 reread.fault_tolerance.checkpoint_interval(),
2670 original.fault_tolerance.checkpoint_interval()
2671 );
2672 }
2673
2674 #[test]
2679 fn legacy_duration_spelling_edge_cases() {
2680 let mut config = serde_json::json!({
2681 "max_buffering_delay": null,
2682 "provisioning_timeout": "1.5s",
2683 "fault_tolerance": {"checkpoint_interval": null},
2684 "clock_resolution": "10sec",
2685 "storage": {"backend": {"name": "file", "config": {
2686 "ioop_latency": "400us",
2687 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2688 });
2689 super::to_legacy_duration_spelling(&mut config);
2690 assert_eq!(
2691 config,
2692 serde_json::json!({
2693 "provisioning_timeout_secs": 2,
2694 "fault_tolerance": {"checkpoint_interval_secs": null},
2695 "clock_resolution": "10sec",
2696 "storage": {"backend": {"name": "file", "config": {
2697 "ioop_delay": 1,
2698 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2699 })
2700 );
2701
2702 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2704 super::to_legacy_duration_spelling(&mut zero);
2705 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2706
2707 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2709 let mut again = legacy.clone();
2710 super::to_legacy_duration_spelling(&mut again);
2711 assert_eq!(again, legacy);
2712 }
2713
2714 #[test]
2718 fn legacy_size_spelling_uses_the_older_keys() {
2719 let mut config = serde_json::json!({
2720 "workers": 2,
2721 "max_rss": "16G",
2722 "datafusion_memory": "1.5G",
2723 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2724 "resources": {
2725 "memory_min": "4G", "memory_max": "16Gi",
2726 "storage_min": "100G", "storage_max": "400Gi",
2727 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2728 },
2729 "dev_tweaks": {
2730 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2731 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2732 },
2733 "inputs": {
2734 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2735 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2736 "t.cdc": {"stream": "t",
2737 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2738 },
2739 "outputs": {
2740 "v.ddb": {"stream": "v",
2741 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2742 "v.pg": {"stream": "v",
2743 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2744 },
2745 });
2746 super::to_legacy_size_spelling(&mut config);
2747 assert_eq!(
2748 config,
2749 serde_json::json!({
2750 "workers": 2,
2751 "max_rss_mb": 16_000,
2752 "datafusion_memory_mb": 1_500,
2753 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2754 "resources": {
2755 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2757 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2758 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2759 },
2760 "dev_tweaks": {
2761 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2762 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2763 },
2764 "inputs": {
2765 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2766 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2767 "t.cdc": {"stream": "t",
2768 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2769 },
2770 "outputs": {
2771 "v.ddb": {"stream": "v",
2772 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2773 "v.pg": {"stream": "v",
2774 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2775 },
2776 })
2777 );
2778 }
2779
2780 #[test]
2783 fn legacy_size_spelling_round_trips() {
2784 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2785 "name": "p",
2786 "max_rss": "16G",
2787 "datafusion_memory": "1G",
2790 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2791 "resources": {"memory_max": "16G", "storage_max": "400G"},
2792 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2793 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2794 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2795 "outputs": {},
2796 }))
2797 .unwrap();
2798 let mut value = serde_json::to_value(&config).unwrap();
2799 super::to_legacy_size_spelling(&mut value);
2800 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2801 assert_eq!(
2802 value["inputs"]["t.file"]["max_queued_bytes"],
2803 serde_json::json!(1024 * 1024)
2804 );
2805 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2806 assert_eq!(reread, config);
2807 }
2808
2809 #[test]
2812 fn legacy_spelling_applies_each_rename_separately() {
2813 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2814 let mut both = current.clone();
2815 super::LegacySpelling {
2816 durations: true,
2817 sizes: true,
2818 }
2819 .apply(&mut both);
2820 assert_eq!(
2821 both,
2822 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2823 );
2824 let mut sizes_only = current.clone();
2825 super::LegacySpelling {
2826 durations: false,
2827 sizes: true,
2828 }
2829 .apply(&mut sizes_only);
2830 assert_eq!(
2831 sizes_only,
2832 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2833 );
2834 let mut none = current.clone();
2835 super::LegacySpelling::NONE.apply(&mut none);
2836 assert_eq!(none, current);
2837 assert!(!super::LegacySpelling::NONE.any());
2838 }
2839
2840 #[test]
2841 fn legacy_size_spelling_edge_cases() {
2842 let mut config = serde_json::json!({
2845 "max_rss": "lots",
2846 "resources": {"memory_max": null, "memory_min": 4000}
2847 });
2848 super::to_legacy_size_spelling(&mut config);
2849 assert_eq!(
2850 config,
2851 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2852 );
2853
2854 let mut small = serde_json::json!({"max_rss": "1"});
2857 super::to_legacy_size_spelling(&mut small);
2858 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2859
2860 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2862 let mut again = legacy.clone();
2863 super::to_legacy_size_spelling(&mut again);
2864 assert_eq!(again, legacy);
2865 }
2866
2867 #[test]
2876 fn a_stored_default_matches_an_omitted_one() {
2877 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2878 "transport": {
2879 "name": "url_input",
2880 "config": {"path": "http://example.com/x", "pause_timeout": 60},
2881 }
2882 }))
2883 .unwrap();
2884 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2885 "transport": {
2886 "name": "url_input",
2887 "config": {"path": "http://example.com/x"},
2888 }
2889 }))
2890 .unwrap();
2891
2892 assert_ne!(stored, fresh);
2895 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2896
2897 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2899 "transport": {
2900 "name": "url_input",
2901 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2902 }
2903 }))
2904 .unwrap();
2905 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2906 }
2907
2908 #[test]
2916 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2917 let connector = |registry: serde_json::Value| -> ConnectorConfig {
2918 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2919 format
2920 .as_object_mut()
2921 .unwrap()
2922 .extend(registry.as_object().unwrap().clone());
2923 serde_json::from_value(serde_json::json!({
2924 "transport": {
2925 "name": "url_input",
2926 "config": {"path": "http://example.com/x"},
2927 },
2928 "format": {"name": "avro", "config": format},
2929 }))
2930 .unwrap()
2931 };
2932 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2933 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2934 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2935 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2936 let unset = connector(serde_json::json!({}));
2937
2938 assert!(stored.equal_modulo_paused(¤t));
2939 assert!(stored.equal_for_input_checkpoint_replay(¤t));
2940 assert!(current.equal_modulo_paused(&spelled_out));
2941 assert!(!stored.equal_modulo_paused(&changed));
2942 assert!(!stored.equal_modulo_paused(&unset));
2943 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2945 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2946 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2947 }))
2948 .unwrap();
2949 assert!(!json.equal_modulo_paused(&stored));
2950 }
2951
2952 #[test]
2958 fn the_largest_legacy_defaults_still_load() {
2959 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
2960 "enable_output_buffer": false,
2961 "max_output_buffer_time_millis": u64::MAX,
2962 "max_output_buffer_size_records": 10_000_000u64,
2963 }))
2964 .unwrap();
2965 assert_eq!(
2966 buffer.max_output_buffer_time,
2967 Some(ConfigDuration::from_millis(u64::MAX))
2968 );
2969
2970 let sync: SyncConfig =
2972 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
2973 assert_eq!(
2974 sync.min_retention(),
2975 ConfigDuration::from_days(4_000_000_000)
2976 );
2977 }
2978
2979 #[test]
2983 fn a_legacy_number_past_u64_seconds_saturates() {
2984 let sync: SyncConfig =
2985 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
2986 .unwrap();
2987 assert_eq!(
2988 sync.min_retention(),
2989 ConfigDuration::from(std::time::Duration::MAX)
2990 );
2991 }
2992
2993 #[test]
2997 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
2998 fn connector(value: serde_json::Value) -> ConnectorConfig {
2999 serde_json::from_value(value).unwrap()
3000 }
3001 fn secs(duration: ConfigDuration) -> u64 {
3002 std::time::Duration::from(duration).as_secs()
3003 }
3004 let fresh_kafka = connector(serde_json::json!({
3005 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3006 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3007 unreachable!()
3008 };
3009 let stored_kafka = connector(serde_json::json!({
3010 "transport": {"name": "kafka_input", "config": {
3011 "topic": "t",
3012 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3013 assert_ne!(stored_kafka, fresh_kafka);
3014 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3015
3016 let base = serde_json::json!({
3017 "connection_config": {"server_url": "nats://x"},
3018 "stream_name": "s",
3019 "consumer_config": {"deliver_policy": "All"}});
3020 let fresh_nats = connector(serde_json::json!({
3021 "transport": {"name": "nats_input", "config": base.clone()}}));
3022 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3023 unreachable!()
3024 };
3025 let mut spelled_out = base;
3026 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3027 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3028 spelled_out["connection_config"]["connection_timeout_secs"] =
3029 secs(nats.connection_config.connection_timeout()).into();
3030 spelled_out["connection_config"]["request_timeout_secs"] =
3031 secs(nats.connection_config.request_timeout()).into();
3032 let stored_nats = connector(serde_json::json!({
3033 "transport": {"name": "nats_input", "config": spelled_out}}));
3034 assert_ne!(stored_nats, fresh_nats);
3035 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3036 }
3037
3038 #[test]
3044 fn superseded_keys_are_normalised_by_a_round_trip() {
3045 let stored = serde_json::json!({
3046 "workers": 4,
3047 "clock_resolution_usecs": 100_000,
3048 "max_buffering_delay_usecs": 0,
3049 "provisioning_timeout_secs": 300,
3050 });
3051
3052 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3053 let written = serde_json::to_value(&config).unwrap();
3054
3055 assert_eq!(written["clock_resolution"], "100ms");
3056 assert_eq!(written["max_buffering_delay"], "0s");
3057 assert_eq!(written["provisioning_timeout"], "5m");
3058 for superseded in [
3059 "clock_resolution_usecs",
3060 "max_buffering_delay_usecs",
3061 "provisioning_timeout_secs",
3062 ] {
3063 assert!(
3064 written.get(superseded).is_none(),
3065 "`{superseded}` survived the round trip: {written}"
3066 );
3067 }
3068
3069 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3072 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3073 }
3074
3075 #[test]
3080 fn ioop_latency_accepts_both_spellings() {
3081 for (json, expected) in [
3082 (r#"{"name": "file", "config": {}}"#, None),
3083 (
3084 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3085 Some(ConfigDuration::from_millis(5)),
3086 ),
3087 (
3088 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3089 Some(ConfigDuration::from_millis(5)),
3090 ),
3091 (
3092 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3093 Some(ConfigDuration::from_secs(1)),
3094 ),
3095 ] {
3096 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3097 let StorageBackendConfig::File(file) = backend else {
3098 panic!("expected the file backend, parsing {json}");
3099 };
3100 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3101 }
3102 }
3103
3104 #[test]
3108 fn clock_resolution_falls_back_to_the_deprecated_field() {
3109 for (json, expected) in [
3110 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3111 (
3112 r#"{"clock_resolution": "100ms"}"#,
3113 ConfigDuration::from_millis(100),
3114 ),
3115 (
3116 r#"{"clock_resolution_usecs": 100000}"#,
3117 ConfigDuration::from_millis(100),
3118 ),
3119 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3120 (
3121 r#"{"clock_resolution_usecs": null}"#,
3122 DEFAULT_CLOCK_RESOLUTION,
3123 ),
3124 ] {
3125 assert_eq!(
3126 serde_json::from_str::<RuntimeConfig>(json)
3127 .unwrap()
3128 .clock_resolution(),
3129 expected,
3130 "parsing {json}"
3131 );
3132 }
3133 }
3134
3135 #[test]
3138 fn deprecated_duration_fields_still_work() {
3139 let runtime: RuntimeConfig = serde_json::from_str(
3140 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3141 )
3142 .unwrap();
3143 assert_eq!(
3144 runtime.max_buffering_delay(),
3145 ConfigDuration::from_millis(5)
3146 );
3147 assert_eq!(
3148 runtime.provisioning_timeout,
3149 Some(ConfigDuration::from_secs(1200))
3150 );
3151
3152 let sync: SyncConfig = serde_json::from_str(
3153 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3154 )
3155 .unwrap();
3156 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3157 assert_eq!(
3158 sync.checkpoint_push_interval(),
3159 Some(ConfigDuration::from_secs(300))
3160 );
3161 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3162
3163 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3164 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3165
3166 let buffer: OutputBufferConfig =
3167 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3168 assert_eq!(
3169 buffer.max_output_buffer_time(),
3170 ConfigDuration::from_millis(250)
3171 );
3172 }
3173
3174 #[test]
3177 fn duration_fields_default_when_unset() {
3178 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3179 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3180 assert_eq!(sync.checkpoint_push_interval(), None);
3181 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3182
3183 let runtime = RuntimeConfig::default();
3184 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3185 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3186 assert_eq!(runtime.provisioning_timeout, None);
3187 }
3188
3189 #[test]
3193 fn storage_options_f64_roundtrip_through_pipeline_config() {
3194 let pc = PipelineConfig {
3195 global: RuntimeConfig {
3196 storage: Some(StorageOptions {
3197 bloom_false_positive_rate: Some(0.01),
3198 ..Default::default()
3199 }),
3200 ..Default::default()
3201 },
3202 multihost: None,
3203 name: Some("test-pipeline".into()),
3204 given_name: None,
3205 storage_config: None,
3206 secrets_dir: None,
3207 inputs: Default::default(),
3208 outputs: Default::default(),
3209 program_ir: None,
3210 };
3211
3212 let json = serde_json::to_string_pretty(&pc).unwrap();
3214 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3215 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3216 );
3217 assert_eq!(
3218 pc2.global.storage.unwrap().bloom_false_positive_rate,
3219 Some(0.01)
3220 );
3221
3222 let value = serde_json::to_value(&pc).unwrap();
3224 let pc3: PipelineConfig = serde_json::from_value(value)
3225 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3226 assert_eq!(
3227 pc3.global.storage.unwrap().bloom_false_positive_rate,
3228 Some(0.01)
3229 );
3230 }
3231}
3232
3233impl FtConfig {
3234 pub fn is_enabled(&self) -> bool {
3235 self.model.is_some()
3236 }
3237
3238 pub fn checkpoint_interval(&self) -> Option<Duration> {
3245 if !self.is_enabled() {
3246 return None;
3247 }
3248
3249 let interval = self
3250 .checkpoint_interval
3251 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3252
3253 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3254 }
3255}
3256
3257mod none_as_string {
3264 use std::marker::PhantomData;
3265
3266 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3267 use serde::ser::{Serialize, Serializer};
3268
3269 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3270 where
3271 S: Serializer,
3272 T: Serialize,
3273 {
3274 match value.as_ref() {
3275 Some(value) => value.serialize(serializer),
3276 None => "none".serialize(serializer),
3277 }
3278 }
3279
3280 struct NoneAsString<T>(PhantomData<fn() -> T>);
3281
3282 impl<'de, T> Visitor<'de> for NoneAsString<T>
3283 where
3284 T: Deserialize<'de>,
3285 {
3286 type Value = Option<T>;
3287
3288 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3289 formatter.write_str("string")
3290 }
3291
3292 fn visit_none<E>(self) -> Result<Self::Value, E>
3293 where
3294 E: serde::de::Error,
3295 {
3296 Ok(None)
3297 }
3298
3299 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3300 where
3301 E: serde::de::Error,
3302 {
3303 if &value.to_ascii_lowercase() == "none" {
3304 Ok(None)
3305 } else {
3306 Ok(Some(T::deserialize(value.into_deserializer())?))
3307 }
3308 }
3309 }
3310
3311 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3312 where
3313 D: Deserializer<'de>,
3314 T: Deserialize<'de>,
3315 {
3316 deserializer.deserialize_str(NoneAsString(PhantomData))
3317 }
3318}
3319
3320fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3323 Schema::OneOf(
3324 OneOfBuilder::new()
3325 .item(RefOr::Ref(Ref::new(format!(
3326 "#/components/schemas/{}",
3327 T::schema().0
3328 ))))
3329 .item(
3330 ObjectBuilder::new()
3331 .schema_type(SchemaType::String)
3332 .enum_values(Some(vec!["none"])),
3333 )
3334 .default(Some(
3335 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3336 ))
3337 .build(),
3338 )
3339}
3340
3341#[derive(
3346 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3347)]
3348#[serde(rename_all = "snake_case")]
3349pub enum FtModel {
3350 AtLeastOnce,
3353
3354 #[default]
3357 ExactlyOnce,
3358}
3359
3360impl FtModel {
3361 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3362 value.map_or("no", |model| model.as_str())
3363 }
3364
3365 pub fn as_str(&self) -> &'static str {
3366 match self {
3367 FtModel::AtLeastOnce => "at_least_once",
3368 FtModel::ExactlyOnce => "exactly_once",
3369 }
3370 }
3371}
3372
3373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3375pub struct FtModelUnknown;
3376
3377impl std::fmt::Display for FtModelUnknown {
3378 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3379 f.write_str("expected `exactly_once` or `at_least_once`")
3380 }
3381}
3382
3383impl std::error::Error for FtModelUnknown {}
3384
3385impl FromStr for FtModel {
3386 type Err = FtModelUnknown;
3387
3388 fn from_str(s: &str) -> Result<Self, Self::Err> {
3389 match s.to_ascii_lowercase().as_str() {
3390 "exactly_once" => Ok(Self::ExactlyOnce),
3391 "at_least_once" => Ok(Self::AtLeastOnce),
3392 _ => Err(FtModelUnknown),
3393 }
3394 }
3395}
3396
3397#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3399pub struct InputEndpointConfig {
3400 pub stream: Cow<'static, str>,
3403
3404 #[serde(flatten)]
3406 pub connector_config: ConnectorConfig,
3407}
3408
3409impl InputEndpointConfig {
3410 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3411 Self {
3412 stream: stream.into(),
3413 connector_config,
3414 }
3415 }
3416}
3417
3418fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3422where
3423 D: Deserializer<'de>,
3424{
3425 let value = Option::<JsonValue>::deserialize(deserializer)?;
3426 match value {
3427 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3428 Some(JsonValue::Array(arr)) => {
3429 let vec = arr
3430 .into_iter()
3431 .map(|item| {
3432 item.as_str()
3433 .map(|s| s.to_string())
3434 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3435 })
3436 .collect::<Result<Vec<String>, _>>()?;
3437 Ok(Some(vec))
3438 }
3439 Some(JsonValue::Null) | None => Ok(None),
3440 _ => Err(serde::de::Error::custom(
3441 "invalid 'start_after' property: expected a string, an array of strings, or null",
3442 )),
3443 }
3444}
3445
3446#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3447pub struct ConnectorConfig {
3448 #[serde(default)]
3461 pub send_snapshot: bool,
3462
3463 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3480 pub soft_delete: bool,
3481
3482 pub transport: TransportConfig,
3484
3485 #[serde(skip_serializing_if = "Option::is_none")]
3487 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3488
3489 pub format: Option<FormatConfig>,
3491
3492 #[serde(skip_serializing_if = "Option::is_none")]
3494 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3495
3496 pub index: Option<String>,
3511
3512 #[serde(flatten)]
3514 pub output_buffer_config: OutputBufferConfig,
3515
3516 #[serde(skip_serializing_if = "Option::is_none")]
3529 pub max_batch_size: Option<u64>,
3530
3531 #[serde(skip_serializing_if = "Option::is_none")]
3544 pub max_worker_batch_size: Option<u64>,
3545
3546 #[serde(default = "default_max_queued_records")]
3565 pub max_queued_records: u64,
3566
3567 #[serde(
3589 default,
3590 alias = "max_queued_bytes",
3591 deserialize_with = "size_max_queued_size",
3592 skip_serializing_if = "Option::is_none"
3593 )]
3594 #[schema(value_type = Option<String>)]
3595 pub max_queued_size: Option<ConfigSize>,
3596
3597 #[serde(default)]
3608 pub paused: bool,
3609
3610 #[serde(default)]
3615 pub labels: Vec<String>,
3616
3617 #[serde(deserialize_with = "deserialize_start_after")]
3623 #[serde(default)]
3624 pub start_after: Option<Vec<String>>,
3625
3626 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3638 pub distributed: bool,
3639}
3640
3641impl ConnectorConfig {
3642 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3643 Self {
3644 send_snapshot: false,
3645 soft_delete: false,
3646 transport,
3647 preprocessor: None,
3648 format,
3649 postprocessor: None,
3650 index: None,
3651 output_buffer_config: Default::default(),
3652 max_batch_size: None,
3653 max_worker_batch_size: None,
3654 max_queued_records: default_max_queued_records(),
3655 max_queued_size: None,
3656 paused: false,
3657 labels: Vec::new(),
3658 start_after: None,
3659 distributed: false,
3660 }
3661 }
3662
3663 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3664 self.max_batch_size = max_batch_size;
3665 self
3666 }
3667
3668 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3669 self.max_queued_records = max_queued_records;
3670 self
3671 }
3672
3673 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3678 let mut a = self.clone();
3679 let mut b = other.clone();
3680 a.paused = false;
3681 b.paused = false;
3682 a.normalize_durations();
3683 b.normalize_durations();
3684 a == b
3685 }
3686
3687 fn normalize_durations(&mut self) {
3698 self.transport.normalize_durations();
3699 self.output_buffer_config.max_output_buffer_time =
3700 Some(self.output_buffer_config.max_output_buffer_time());
3701 if let Some(format) = &mut self.format {
3702 format.normalize_durations();
3703 }
3704 }
3705
3706 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3709 let mut a = self.clone();
3710 let mut b = other.clone();
3711 a.normalize_for_input_checkpoint_replay();
3712 b.normalize_for_input_checkpoint_replay();
3713 a == b
3714 }
3715
3716 fn normalize_for_input_checkpoint_replay(&mut self) {
3717 self.paused = false;
3718 self.max_batch_size = None;
3719 self.max_worker_batch_size = None;
3720 self.max_queued_records = default_max_queued_records();
3721 self.max_queued_size = None;
3722 self.normalize_durations();
3723 }
3724
3725 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3728 self.max_batch_size = other.max_batch_size;
3729 self.max_worker_batch_size = other.max_worker_batch_size;
3730 self.max_queued_records = other.max_queued_records;
3731 self.max_queued_size = other.max_queued_size;
3732 }
3733
3734 pub fn max_queued_records(&self) -> u64 {
3736 self.max_queued_records
3737 }
3738
3739 pub fn max_queued_bytes(&self) -> u64 {
3742 self.max_queued_size
3743 .map(ConfigSize::as_bytes)
3744 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3745 }
3746}
3747
3748#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3749#[serde(default)]
3750pub struct OutputBufferConfig {
3751 pub enable_output_buffer: bool,
3774
3775 #[serde(
3784 default,
3785 alias = "max_output_buffer_time_millis",
3786 deserialize_with = "duration_max_output_buffer_time",
3787 skip_serializing_if = "Option::is_none"
3788 )]
3789 #[schema(value_type = Option<String>)]
3790 pub max_output_buffer_time: Option<ConfigDuration>,
3791
3792 pub max_output_buffer_size_records: usize,
3804}
3805
3806impl OutputBufferConfig {
3807 pub fn max_output_buffer_time(&self) -> ConfigDuration {
3809 self.max_output_buffer_time
3810 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3811 }
3812}
3813
3814impl Default for OutputBufferConfig {
3815 fn default() -> Self {
3816 Self {
3817 enable_output_buffer: false,
3818 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3819 max_output_buffer_time: None,
3820 }
3821 }
3822}
3823
3824#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3826pub struct OutputEndpointConfig {
3827 pub stream: Cow<'static, str>,
3830
3831 #[serde(flatten)]
3833 pub connector_config: ConnectorConfig,
3834}
3835
3836impl OutputEndpointConfig {
3837 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3838 Self {
3839 stream: stream.into(),
3840 connector_config,
3841 }
3842 }
3843}
3844
3845#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3849#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3850pub enum TransportConfig {
3851 FileInput(FileInputConfig),
3852 FileOutput(FileOutputConfig),
3853 NatsInput(Box<NatsInputConfig>),
3856 NatsOutput(NatsOutputConfig),
3857 KafkaInput(KafkaInputConfig),
3858 KafkaOutput(KafkaOutputConfig),
3859 PubSubInput(PubSubInputConfig),
3860 UrlInput(UrlInputConfig),
3861 S3Input(S3InputConfig),
3862 DeltaTableInput(DeltaTableReaderConfig),
3863 DeltaTableOutput(DeltaTableWriterConfig),
3864 #[serde(rename = "dynamodb_output")]
3867 DynamoDBOutput(DynamoDBWriterConfig),
3868 RedisOutput(RedisOutputConfig),
3869 IcebergInput(Box<IcebergReaderConfig>),
3871 PostgresInput(PostgresReaderConfig),
3872 PostgresCdcInput(PostgresCdcReaderConfig),
3873 PostgresOutput(PostgresWriterConfig),
3874 Datagen(DatagenInputConfig),
3875 Nexmark(NexmarkInputConfig),
3876 HttpInput(HttpInputConfig),
3878 HttpOutput(HttpOutputConfig),
3880 AdHocInput(AdHocInputConfig),
3882 ClockInput(ClockConfig),
3883 S2Input(S2InputConfig),
3884 S2Output(S2OutputConfig),
3885 NullOutput,
3887 EmptyInput,
3889}
3890
3891impl TransportConfig {
3892 pub fn normalize_durations(&mut self) {
3895 match self {
3896 TransportConfig::UrlInput(config) => {
3897 config.pause_linger = Some(config.pause_linger());
3898 }
3899 TransportConfig::KafkaInput(config) => {
3900 config.group_join_timeout = Some(config.group_join_timeout());
3901 }
3902 TransportConfig::KafkaOutput(config) => {
3903 config.initialization_timeout = Some(config.initialization_timeout());
3904 }
3905 TransportConfig::NatsInput(config) => {
3906 config.connection_config.connection_timeout =
3907 Some(config.connection_config.connection_timeout());
3908 config.connection_config.request_timeout =
3909 Some(config.connection_config.request_timeout());
3910 config.inactivity_timeout = Some(config.inactivity_timeout());
3911 config.retry_interval = Some(config.retry_interval());
3912 }
3913 TransportConfig::NatsOutput(config) => {
3914 config.connection_config.connection_timeout =
3915 Some(config.connection_config.connection_timeout());
3916 config.connection_config.request_timeout =
3917 Some(config.connection_config.request_timeout());
3918 config.publish_timeout = Some(config.publish_timeout());
3919 }
3920 _ => {}
3921 }
3922 }
3923
3924 pub fn name(&self) -> String {
3925 match self {
3926 TransportConfig::FileInput(_) => "file_input".to_string(),
3927 TransportConfig::FileOutput(_) => "file_output".to_string(),
3928 TransportConfig::NatsInput(_) => "nats_input".to_string(),
3929 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
3930 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
3931 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
3932 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
3933 TransportConfig::UrlInput(_) => "url_input".to_string(),
3934 TransportConfig::S3Input(_) => "s3_input".to_string(),
3935 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
3936 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
3937 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
3938 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
3939 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
3940 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
3941 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
3942 TransportConfig::Datagen(_) => "datagen".to_string(),
3943 TransportConfig::Nexmark(_) => "nexmark".to_string(),
3944 TransportConfig::HttpInput(_) => "http_input".to_string(),
3945 TransportConfig::HttpOutput(_) => "http_output".to_string(),
3946 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
3947 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
3948 TransportConfig::ClockInput(_) => "clock".to_string(),
3949 TransportConfig::S2Input(_) => "s2_input".to_string(),
3950 TransportConfig::S2Output(_) => "s2_output".to_string(),
3951 TransportConfig::NullOutput => "null_output".to_string(),
3952 TransportConfig::EmptyInput => "empty_input".to_string(),
3953 }
3954 }
3955
3956 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
3961 match self {
3962 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
3963 _ => None,
3964 }
3965 }
3966
3967 pub fn is_transient(&self) -> bool {
3970 matches!(
3971 self,
3972 TransportConfig::AdHocInput(_)
3973 | TransportConfig::HttpInput(_)
3974 | TransportConfig::HttpOutput(_)
3975 | TransportConfig::ClockInput(_)
3976 )
3977 }
3978
3979 pub fn is_http_input(&self) -> bool {
3980 matches!(self, TransportConfig::HttpInput(_))
3981 }
3982
3983 pub fn supports_distribution(&self) -> bool {
3987 matches!(
3988 self,
3989 TransportConfig::KafkaInput(_)
3990 | TransportConfig::DeltaTableInput(_)
3991 | TransportConfig::IcebergInput(_)
3992 )
3993 }
3994
3995 pub fn needs_input_choice(&self) -> bool {
4007 matches!(
4008 self,
4009 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4010 )
4011 }
4012
4013 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4016 use crate::adapter_stats::FrontierMerge;
4017 match self {
4018 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4019 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4020 FrontierMerge::Shared
4021 }
4022 _ => FrontierMerge::Opaque,
4023 }
4024 }
4025}
4026
4027#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4030pub struct FormatConfig {
4031 pub name: Cow<'static, str>,
4033
4034 #[serde(default)]
4036 #[schema(value_type = Object)]
4037 pub config: JsonValue,
4038}
4039
4040impl FormatConfig {
4041 pub fn normalize_durations(&mut self) {
4048 if self.name != "avro" {
4049 return;
4050 }
4051 let has_timeout = self.config.as_object().is_some_and(|object| {
4052 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4053 });
4054 if !has_timeout {
4055 return;
4056 }
4057 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4058 self.config.clone(),
4059 ) else {
4060 return;
4061 };
4062 let object = self.config.as_object_mut().unwrap();
4063 object.remove("registry_timeout_secs");
4064 match registry.registry_timeout {
4065 Some(timeout) => object.insert(
4066 "registry_timeout".to_string(),
4067 JsonValue::String(timeout.to_string()),
4068 ),
4069 None => object.remove("registry_timeout"),
4070 };
4071 }
4072}
4073
4074#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4075#[serde(default)]
4076pub struct ResourceConfig {
4077 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4080 pub cpu_cores_min: Option<f64>,
4081
4082 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4085 pub cpu_cores_max: Option<f64>,
4086
4087 #[serde(
4093 alias = "memory_mb_min",
4094 deserialize_with = "size_memory_min",
4095 skip_serializing_if = "Option::is_none"
4096 )]
4097 #[schema(value_type = Option<String>)]
4098 pub memory_min: Option<ConfigSize>,
4099
4100 #[serde(
4106 alias = "memory_mb_max",
4107 deserialize_with = "size_memory_max",
4108 skip_serializing_if = "Option::is_none"
4109 )]
4110 #[schema(value_type = Option<String>)]
4111 pub memory_max: Option<ConfigSize>,
4112
4113 #[serde(
4120 alias = "storage_mb_min",
4121 deserialize_with = "size_storage_min",
4122 skip_serializing_if = "Option::is_none"
4123 )]
4124 #[schema(value_type = Option<String>)]
4125 pub storage_min: Option<ConfigSize>,
4126
4127 #[serde(
4138 alias = "storage_mb_max",
4139 deserialize_with = "size_storage_max",
4140 skip_serializing_if = "Option::is_none"
4141 )]
4142 #[schema(value_type = Option<String>)]
4143 pub storage_max: Option<ConfigSize>,
4144
4145 #[serde(skip_serializing_if = "Option::is_none")]
4147 pub autoscaling: Option<AutoscalingConfig>,
4148
4149 pub storage_class: Option<String>,
4152
4153 #[serde(skip_serializing_if = "Option::is_none")]
4159 pub volume_attributes_class: Option<String>,
4160
4161 pub service_account_name: Option<String>,
4164
4165 pub namespace: Option<String>,
4173}
4174
4175#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4177#[serde(default)]
4178pub struct AutoscalingConfig {
4179 #[serde(skip_serializing_if = "Option::is_none")]
4181 pub storage: Option<StorageAutoscalingConfig>,
4182}
4183
4184#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4187#[serde(default)]
4188pub struct StorageAutoscalingConfig {
4189 #[serde(
4191 deserialize_with = "crate::serde_via_value::deserialize",
4192 skip_serializing_if = "Option::is_none"
4193 )]
4194 pub scale_threshold: Option<f64>,
4195
4196 #[serde(
4203 alias = "scale_threshold_available_mb",
4204 deserialize_with = "size_scale_threshold_available",
4205 skip_serializing_if = "Option::is_none"
4206 )]
4207 #[schema(value_type = Option<String>)]
4208 pub scale_threshold_available: Option<ConfigSize>,
4209
4210 #[serde(
4212 deserialize_with = "crate::serde_via_value::deserialize",
4213 skip_serializing_if = "Option::is_none"
4214 )]
4215 pub scale_factor: Option<f64>,
4216}
4217
4218#[cfg(test)]
4219mod resource_config_tests {
4220 use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
4221 use crate::size::ConfigSize;
4222 use serde_json::json;
4223
4224 #[test]
4225 fn storage_autoscaling_round_trips_through_json() {
4226 let input = json!({
4227 "storage_min": "1G",
4228 "storage_max": "8G",
4229 "autoscaling": {
4230 "storage": {
4231 "scale_threshold": 0.8,
4232 "scale_threshold_available": "10G",
4233 "scale_factor": 2.0
4234 }
4235 }
4236 });
4237 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4238 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4239 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4240 assert_eq!(
4241 config.autoscaling,
4242 Some(AutoscalingConfig {
4243 storage: Some(StorageAutoscalingConfig {
4244 scale_threshold: Some(0.8),
4245 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4246 scale_factor: Some(2.0),
4247 }),
4248 })
4249 );
4250 let output = serde_json::to_value(&config).unwrap();
4251 assert_eq!(output["storage_min"], json!("1G"));
4252 assert_eq!(
4253 output["autoscaling"]["storage"]["scale_threshold"],
4254 json!(0.8)
4255 );
4256 assert_eq!(
4257 output["autoscaling"]["storage"]["scale_threshold_available"],
4258 json!("10G")
4259 );
4260 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4261 }
4262
4263 #[test]
4264 fn autoscaling_fields_default_to_none() {
4265 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4266 assert_eq!(config.storage_min, None);
4267 assert_eq!(config.autoscaling, None);
4268
4269 let output = serde_json::to_value(&config).unwrap();
4272 assert!(output.get("storage_min").is_none());
4273 assert!(output.get("autoscaling").is_none());
4274 assert!(output.get("storage_max").is_none());
4275
4276 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4278 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4279 let output = serde_json::to_value(&config).unwrap();
4280 assert_eq!(output["autoscaling"], input["autoscaling"]);
4281
4282 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4284 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4285 }
4286
4287 #[test]
4288 fn autoscaling_rejects_non_numeric_values() {
4289 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4290 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4291 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4292 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4293 let input = json!({ "storage_mb_min": -1 });
4294 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4295 }
4296}
4297
4298#[cfg(test)]
4299mod sync_config_tests {
4300 use super::SyncConfig;
4301
4302 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4303 SyncConfig {
4304 bucket: bucket.to_owned(),
4305 read_bucket: read_bucket.map(str::to_owned),
4306 ..Default::default()
4307 }
4308 }
4309
4310 #[test]
4311 fn read_bucket_must_differ_from_bucket() {
4312 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4313 assert!(err.contains("different locations"), "{err}");
4314 }
4315
4316 #[test]
4317 fn read_bucket_must_use_the_same_object_store() {
4318 let err = config("gs://ckpts/a", Some("ckpts/b"))
4319 .validate()
4320 .unwrap_err();
4321 assert!(err.contains("same object store"), "{err}");
4322 let err = config("ckpts/a", Some("gs://ckpts/b"))
4323 .validate()
4324 .unwrap_err();
4325 assert!(err.contains("same object store"), "{err}");
4326 }
4327
4328 #[test]
4329 fn matching_object_stores_are_accepted() {
4330 config("gs://ckpts/a", Some("gs://ckpts/b"))
4331 .validate()
4332 .unwrap();
4333 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4334 config("gs://ckpts/a", None).validate().unwrap();
4335 }
4336
4337 #[test]
4338 fn take_bucket_ownership_defaults_to_false() {
4339 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4340 assert!(!sync.take_bucket_ownership);
4341
4342 let sync: SyncConfig =
4343 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4344 .unwrap();
4345 assert!(sync.take_bucket_ownership);
4346 }
4347}
4348
4349#[cfg(test)]
4350mod transport_metadata_tests {
4351 use super::TransportConfig;
4352 use serde_json::json;
4353
4354 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4355 serde_json::from_value(json!({
4356 "name": "nats_input",
4357 "config": {
4358 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4359 "stream_name": "orders",
4360 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4361 },
4362 }))
4363 .unwrap()
4364 }
4365
4366 #[test]
4367 fn nats_input_exposes_consumer_metadata() {
4368 let mut transport = nats_input(json!({ "team": "ingest" }));
4369 let metadata = transport.transport_metadata_mut().unwrap();
4370 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4371
4372 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4373 let TransportConfig::NatsInput(config) = &transport else {
4374 unreachable!()
4375 };
4376 assert_eq!(
4377 config
4378 .consumer_config
4379 .metadata
4380 .get("pipeline")
4381 .map(String::as_str),
4382 Some("orders_pipeline"),
4383 "writes through the returned map must reach the consumer config"
4384 );
4385 }
4386
4387 #[test]
4388 fn transports_without_metadata_return_none() {
4389 let mut transport: TransportConfig = serde_json::from_value(json!({
4390 "name": "file_input",
4391 "config": { "path": "/tmp/input.csv" },
4392 }))
4393 .unwrap();
4394 assert!(transport.transport_metadata_mut().is_none());
4395 }
4396}