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)]
994pub struct PipelineTemplateConfig {
995 pub name: String,
997 #[schema(default = default_pipeline_template_key)]
1001 #[serde(default = "default_pipeline_template_key")]
1002 pub key: String,
1003}
1004
1005fn default_pipeline_template_key() -> String {
1006 "pipelineTemplate".to_string()
1007}
1008
1009#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1010pub struct ObjectStorageConfig {
1011 pub url: String,
1040
1041 #[serde(flatten)]
1074 pub other_options: BTreeMap<String, String>,
1075}
1076
1077#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1079#[serde(default)]
1080pub struct FileBackendConfig {
1081 pub async_threads: Option<bool>,
1087
1088 #[serde(
1093 default,
1094 alias = "ioop_delay",
1095 deserialize_with = "duration_ioop_latency",
1096 skip_serializing_if = "Option::is_none"
1097 )]
1098 #[schema(value_type = Option<String>)]
1099 pub ioop_latency: Option<ConfigDuration>,
1100
1101 pub sync: Option<SyncConfig>,
1103
1104 pub sync_mode: Option<StorageSyncMode>,
1109}
1110
1111#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1117#[serde(rename_all = "snake_case")]
1118pub enum StorageSyncMode {
1119 #[default]
1122 Auto,
1123
1124 Syncfs,
1134
1135 PerFile,
1140}
1141
1142#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1145#[serde(default)]
1146pub struct RuntimeConfig {
1147 pub workers: u16,
1157
1158 #[serde(
1186 default,
1187 alias = "max_rss_mb",
1188 deserialize_with = "size_max_rss",
1189 skip_serializing_if = "Option::is_none"
1190 )]
1191 #[schema(value_type = Option<String>)]
1192 pub max_rss: Option<ConfigSize>,
1193
1194 #[serde(
1217 default,
1218 alias = "datafusion_memory_mb",
1219 deserialize_with = "size_datafusion_memory",
1220 skip_serializing_if = "Option::is_none"
1221 )]
1222 #[schema(value_type = Option<String>)]
1223 pub datafusion_memory: Option<ConfigSize>,
1224
1225 pub hosts: usize,
1232
1233 #[serde(deserialize_with = "deserialize_storage_options")]
1245 pub storage: Option<StorageOptions>,
1246
1247 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1249 pub fault_tolerance: FtConfig,
1250
1251 pub cpu_profiler: bool,
1255
1256 pub tracing: bool,
1258
1259 pub tracing_endpoint_jaeger: String,
1261
1262 pub min_batch_size_records: u64,
1270
1271 #[serde(
1274 default,
1275 alias = "max_buffering_delay_usecs",
1276 deserialize_with = "duration_max_buffering_delay",
1277 skip_serializing_if = "Option::is_none"
1278 )]
1279 #[schema(value_type = Option<String>)]
1280 pub max_buffering_delay: Option<ConfigDuration>,
1281
1282 pub resources: ResourceConfig,
1285
1286 #[serde(
1296 default,
1297 alias = "clock_resolution_usecs",
1298 deserialize_with = "duration_clock_resolution",
1299 skip_serializing_if = "Option::is_none"
1300 )]
1301 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1302 pub clock_resolution: Option<ConfigDuration>,
1303
1304 #[schema(value_type = Option<String>, example = "+05:30")]
1315 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1316
1317 pub pin_cpus: Vec<usize>,
1326
1327 #[serde(
1330 default,
1331 alias = "provisioning_timeout_secs",
1332 deserialize_with = "duration_provisioning_timeout",
1333 skip_serializing_if = "Option::is_none"
1334 )]
1335 #[schema(value_type = Option<String>)]
1336 pub provisioning_timeout: Option<ConfigDuration>,
1337
1338 pub max_parallel_connector_init: Option<u64>,
1349
1350 pub init_containers: Option<serde_json::Value>,
1352
1353 pub checkpoint_during_suspend: bool,
1355
1356 pub http_workers: Option<u64>,
1364
1365 pub io_workers: Option<u64>,
1376
1377 #[serde(default)]
1384 pub env: BTreeMap<String, String>,
1385
1386 pub dev_tweaks: DevTweaks,
1388
1389 pub logging: Option<String>,
1398
1399 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1407}
1408
1409fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1411where
1412 D: Deserializer<'de>,
1413{
1414 struct BoolOrStruct;
1415
1416 impl<'de> Visitor<'de> for BoolOrStruct {
1417 type Value = Option<StorageOptions>;
1418
1419 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1420 formatter.write_str("boolean or StorageOptions")
1421 }
1422
1423 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1424 where
1425 E: de::Error,
1426 {
1427 match v {
1428 false => Ok(None),
1429 true => Ok(Some(StorageOptions::default())),
1430 }
1431 }
1432
1433 fn visit_unit<E>(self) -> Result<Self::Value, E>
1434 where
1435 E: de::Error,
1436 {
1437 Ok(None)
1438 }
1439
1440 fn visit_none<E>(self) -> Result<Self::Value, E>
1441 where
1442 E: de::Error,
1443 {
1444 Ok(None)
1445 }
1446
1447 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1448 where
1449 M: MapAccess<'de>,
1450 {
1451 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1452 }
1453 }
1454
1455 deserializer.deserialize_any(BoolOrStruct)
1456}
1457
1458fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1466where
1467 D: Deserializer<'de>,
1468{
1469 struct StringOrStruct;
1470
1471 impl<'de> Visitor<'de> for StringOrStruct {
1472 type Value = FtConfig;
1473
1474 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1475 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1476 }
1477
1478 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1479 where
1480 E: de::Error,
1481 {
1482 match v {
1483 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1484 model: Some(FtModel::default()),
1485 ..FtConfig::default()
1486 }),
1487 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1488 }
1489 }
1490
1491 fn visit_unit<E>(self) -> Result<Self::Value, E>
1492 where
1493 E: de::Error,
1494 {
1495 Ok(FtConfig::default())
1496 }
1497
1498 fn visit_none<E>(self) -> Result<Self::Value, E>
1499 where
1500 E: de::Error,
1501 {
1502 Ok(FtConfig::default())
1503 }
1504
1505 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1506 where
1507 M: MapAccess<'de>,
1508 {
1509 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1510 }
1511 }
1512
1513 deserializer.deserialize_any(StringOrStruct)
1514}
1515
1516impl Default for RuntimeConfig {
1517 fn default() -> Self {
1518 Self {
1519 workers: 8,
1520 max_rss: None,
1521 datafusion_memory: None,
1522 hosts: 1,
1523 storage: Some(StorageOptions::default()),
1524 fault_tolerance: FtConfig::default(),
1525 cpu_profiler: true,
1526 tracing: {
1527 false
1530 },
1531 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1532 min_batch_size_records: 0,
1533 max_buffering_delay: None,
1534 resources: ResourceConfig::default(),
1535 clock_resolution: None,
1536 clock_timezone_offset: None,
1537 pin_cpus: Vec::new(),
1538 provisioning_timeout: None,
1539 max_parallel_connector_init: None,
1540 init_containers: None,
1541 checkpoint_during_suspend: true,
1542 io_workers: None,
1543 http_workers: None,
1544 env: BTreeMap::default(),
1545 dev_tweaks: DevTweaks::default(),
1546 logging: None,
1547 pipeline_template_configmap: None,
1548 }
1549 }
1550}
1551
1552pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1556
1557pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1560
1561impl RuntimeConfig {
1562 pub fn max_buffering_delay(&self) -> ConfigDuration {
1564 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1565 }
1566
1567 pub fn clock_resolution(&self) -> ConfigDuration {
1569 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1570 }
1571
1572 pub fn effective_memory(&self) -> Option<ConfigSize> {
1575 self.max_rss.or(self.resources.memory_max)
1576 }
1577
1578 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1583 if let Some(explicit) = self.datafusion_memory {
1584 return Some(explicit);
1585 }
1586 let effective = self.effective_memory()?.as_bytes();
1587 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1589 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1590 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1591 }
1592}
1593
1594#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1605#[serde(rename_all = "snake_case")]
1606pub struct FtConfig {
1607 #[serde(with = "none_as_string")]
1609 #[serde(default = "default_model")]
1610 #[schema(
1611 schema_with = none_as_string_schema::<FtModel>,
1612 )]
1613 pub model: Option<FtModel>,
1614
1615 #[serde(
1622 default,
1623 alias = "checkpoint_interval_secs",
1624 deserialize_with = "duration_checkpoint_interval",
1625 skip_serializing_if = "Option::is_none"
1626 )]
1627 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1628 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1629}
1630
1631fn default_model() -> Option<FtModel> {
1632 Some(FtModel::default())
1633}
1634
1635pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1655 use crate::duration::LegacyUnit;
1656 use serde_json::{Map, Value};
1657
1658 struct Rule {
1660 new: &'static str,
1661 old: &'static str,
1662 unit: LegacyUnit,
1663 max: u64,
1665 null_allowed: bool,
1668 }
1669 const fn rule(
1670 new: &'static str,
1671 old: &'static str,
1672 unit: LegacyUnit,
1673 max: u64,
1674 null_allowed: bool,
1675 ) -> Rule {
1676 Rule {
1677 new,
1678 old,
1679 unit,
1680 max,
1681 null_allowed,
1682 }
1683 }
1684 const U32: u64 = u32::MAX as u64;
1685 const U64: u64 = u64::MAX;
1686 use LegacyUnit::{Days, Micros, Millis, Secs};
1687
1688 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1689 for rule in rules {
1690 let Some(value) = object.remove(rule.new) else {
1691 continue;
1692 };
1693 let legacy = match &value {
1694 Value::String(text) => match text.parse::<ConfigDuration>() {
1695 Ok(duration) => {
1696 let nanos = std::time::Duration::from(duration).as_nanos();
1697 let unit_nanos = u128::from(rule.unit.nanos());
1698 let whole = nanos.div_ceil(unit_nanos);
1699 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1700 }
1701 Err(_) => {
1702 object.insert(rule.new.to_string(), value);
1703 continue;
1704 }
1705 },
1706 Value::Null if !rule.null_allowed => continue,
1707 other => other.clone(),
1709 };
1710 object.insert(rule.old.to_string(), legacy);
1711 }
1712 }
1713 fn child<'a>(
1714 object: &'a mut Map<String, Value>,
1715 key: &str,
1716 ) -> Option<&'a mut Map<String, Value>> {
1717 object.get_mut(key).and_then(Value::as_object_mut)
1718 }
1719 fn max_expiry(consumer: &mut Map<String, Value>) {
1722 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1723 return;
1724 };
1725 let Ok(duration) = text.parse::<ConfigDuration>() else {
1726 return;
1727 };
1728 let duration = std::time::Duration::from(duration);
1729 consumer.remove("max_expiry");
1730 consumer.insert(
1731 "max_expires".to_string(),
1732 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1733 );
1734 }
1735 fn nats_connection(transport: &mut Map<String, Value>) {
1737 if let Some(connection) = child(transport, "connection_config") {
1738 apply(
1739 connection,
1740 &[
1741 rule(
1742 "connection_timeout",
1743 "connection_timeout_secs",
1744 Secs,
1745 U64,
1746 false,
1747 ),
1748 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1749 ],
1750 );
1751 }
1752 }
1753 fn connector(endpoint: &mut Map<String, Value>) {
1755 apply(
1756 endpoint,
1757 &[rule(
1758 "max_output_buffer_time",
1759 "max_output_buffer_time_millis",
1760 Millis,
1761 U64,
1762 false,
1763 )],
1764 );
1765 let name = endpoint
1766 .get("transport")
1767 .and_then(|transport| transport.get("name"))
1768 .and_then(Value::as_str)
1769 .map(str::to_string);
1770 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1771 match name.as_deref() {
1772 Some("url_input") => apply(
1773 transport,
1774 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1775 ),
1776 Some("kafka_input") => apply(
1777 transport,
1778 &[rule(
1779 "group_join_timeout",
1780 "group_join_timeout_secs",
1781 Secs,
1782 U32,
1783 false,
1784 )],
1785 ),
1786 Some("kafka_output") => apply(
1787 transport,
1788 &[rule(
1789 "initialization_timeout",
1790 "initialization_timeout_secs",
1791 Secs,
1792 U32,
1793 false,
1794 )],
1795 ),
1796 Some("clock_input") => apply(
1797 transport,
1798 &[rule(
1799 "clock_resolution",
1800 "clock_resolution_usecs",
1801 Micros,
1802 U64,
1803 false,
1804 )],
1805 ),
1806 Some("pub_sub_input") => apply(
1807 transport,
1808 &[
1809 rule("timeout", "timeout_seconds", Secs, U32, true),
1810 rule(
1811 "connect_timeout",
1812 "connect_timeout_seconds",
1813 Secs,
1814 U32,
1815 true,
1816 ),
1817 ],
1818 ),
1819 Some("nats_input") => {
1820 apply(
1821 transport,
1822 &[
1823 rule(
1824 "inactivity_timeout",
1825 "inactivity_timeout_secs",
1826 Secs,
1827 U64,
1828 false,
1829 ),
1830 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1831 ],
1832 );
1833 nats_connection(transport);
1834 if let Some(consumer) = child(transport, "consumer_config") {
1835 max_expiry(consumer);
1836 }
1837 }
1838 Some("nats_output") => {
1839 apply(
1840 transport,
1841 &[rule(
1842 "publish_timeout",
1843 "publish_timeout_secs",
1844 Secs,
1845 U64,
1846 false,
1847 )],
1848 );
1849 nats_connection(transport);
1850 }
1851 _ => {}
1852 }
1853 }
1854 let is_avro = endpoint
1855 .get("format")
1856 .and_then(|format| format.get("name"))
1857 .and_then(Value::as_str)
1858 == Some("avro");
1859 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1860 {
1861 apply(
1862 format,
1863 &[rule(
1864 "registry_timeout",
1865 "registry_timeout_secs",
1866 Secs,
1867 U64,
1868 true,
1869 )],
1870 );
1871 }
1872 }
1873
1874 let Some(global) = config.as_object_mut() else {
1875 return;
1876 };
1877 apply(
1878 global,
1879 &[
1880 rule(
1881 "clock_resolution",
1882 "clock_resolution_usecs",
1883 Micros,
1884 U64,
1885 true,
1886 ),
1887 rule(
1888 "max_buffering_delay",
1889 "max_buffering_delay_usecs",
1890 Micros,
1891 U64,
1892 false,
1893 ),
1894 rule(
1895 "provisioning_timeout",
1896 "provisioning_timeout_secs",
1897 Secs,
1898 U64,
1899 true,
1900 ),
1901 ],
1902 );
1903 if let Some(ft) = child(global, "fault_tolerance") {
1904 apply(
1906 ft,
1907 &[rule(
1908 "checkpoint_interval",
1909 "checkpoint_interval_secs",
1910 Secs,
1911 U64,
1912 true,
1913 )],
1914 );
1915 }
1916 let backend = child(global, "storage")
1917 .and_then(|storage| child(storage, "backend"))
1918 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1919 .and_then(|backend| child(backend, "config"));
1920 if let Some(file) = backend {
1921 apply(
1922 file,
1923 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1924 );
1925 if let Some(sync) = child(file, "sync") {
1926 apply(
1927 sync,
1928 &[
1929 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1930 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1931 rule("min_retention", "retention_min_age", Days, U32, false),
1932 ],
1933 );
1934 }
1935 }
1936 for endpoints in ["inputs", "outputs"] {
1937 if let Some(endpoints) = child(global, endpoints) {
1938 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1939 connector(endpoint);
1940 }
1941 }
1942 }
1943}
1944
1945#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1951pub struct LegacySpelling {
1952 pub durations: bool,
1954 pub sizes: bool,
1956}
1957
1958impl LegacySpelling {
1959 pub const NONE: LegacySpelling = LegacySpelling {
1961 durations: false,
1962 sizes: false,
1963 };
1964
1965 pub fn any(self) -> bool {
1967 self.durations || self.sizes
1968 }
1969
1970 pub fn apply(self, config: &mut serde_json::Value) {
1973 if self.durations {
1974 to_legacy_duration_spelling(config);
1975 }
1976 if self.sizes {
1977 to_legacy_size_spelling(config);
1978 }
1979 }
1980}
1981
1982pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
1993 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
1994 use serde_json::{Map, Value};
1995
1996 struct Rule {
1998 new: &'static str,
1999 old: &'static str,
2000 unit: LegacySizeUnit,
2001 }
2002 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2003 Rule { new, old, unit }
2004 }
2005
2006 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2007 for rule in rules {
2008 let Some(value) = object.remove(rule.new) else {
2009 continue;
2010 };
2011 let legacy = match &value {
2012 Value::String(text) => match text.parse::<ConfigSize>() {
2013 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2014 Err(_) => {
2015 object.insert(rule.new.to_string(), value);
2016 continue;
2017 }
2018 },
2019 Value::Null => continue,
2021 other => other.clone(),
2023 };
2024 object.insert(rule.old.to_string(), legacy);
2025 }
2026 }
2027 fn child<'a>(
2028 object: &'a mut Map<String, Value>,
2029 key: &str,
2030 ) -> Option<&'a mut Map<String, Value>> {
2031 object.get_mut(key).and_then(Value::as_object_mut)
2032 }
2033 fn connector(endpoint: &mut Map<String, Value>) {
2035 apply(
2036 endpoint,
2037 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2038 );
2039 let name = endpoint
2040 .get("transport")
2041 .and_then(|transport| transport.get("name"))
2042 .and_then(Value::as_str)
2043 .map(str::to_string);
2044 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2045 match name.as_deref() {
2046 Some("file_input") => apply(
2047 transport,
2048 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2049 ),
2050 Some("dynamodb_output" | "postgres_output") => apply(
2051 transport,
2052 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2053 ),
2054 Some("postgres_cdc_input") => {
2055 if let Some(batch) = child(transport, "batch") {
2056 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2057 }
2058 }
2059 _ => {}
2060 }
2061 }
2062 }
2063
2064 let Some(global) = config.as_object_mut() else {
2065 return;
2066 };
2067 apply(
2068 global,
2069 &[
2070 rule("max_rss", "max_rss_mb", Megabytes),
2071 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2072 ],
2073 );
2074 if let Some(storage) = child(global, "storage") {
2075 apply(
2076 storage,
2077 &[
2078 rule("cache_size", "cache_mib", Mebibytes),
2079 rule("min_spill_size", "min_storage_bytes", Bytes),
2080 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2081 ],
2082 );
2083 }
2084 if let Some(resources) = child(global, "resources") {
2085 apply(
2086 resources,
2087 &[
2088 rule("memory_min", "memory_mb_min", Megabytes),
2089 rule("memory_max", "memory_mb_max", Megabytes),
2090 rule("storage_min", "storage_mb_min", Megabytes),
2091 rule("storage_max", "storage_mb_max", Megabytes),
2092 ],
2093 );
2094 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2095 apply(
2096 storage,
2097 &[rule(
2098 "scale_threshold_available",
2099 "scale_threshold_available_mb",
2100 Megabytes,
2101 )],
2102 );
2103 }
2104 }
2105 if let Some(tweaks) = child(global, "dev_tweaks") {
2106 apply(
2107 tweaks,
2108 &[
2109 rule("storage_max", "storage_mb_max", Mebibytes),
2110 rule(
2111 "fbuf_slab_size_per_class",
2112 "fbuf_slab_bytes_per_class",
2113 Bytes,
2114 ),
2115 rule(
2116 "lazy_input_map_key_block_size",
2117 "lazy_input_map_key_block_bytes",
2118 Bytes,
2119 ),
2120 rule(
2121 "exchange_channel_capacity",
2122 "exchange_channel_capacity_bytes",
2123 Bytes,
2124 ),
2125 ],
2126 );
2127 }
2128 for endpoints in ["inputs", "outputs"] {
2129 if let Some(endpoints) = child(global, endpoints) {
2130 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2131 connector(endpoint);
2132 }
2133 }
2134 }
2135}
2136
2137#[cfg(test)]
2138mod test {
2139 use super::deserialize_fault_tolerance;
2140 use crate::config::{
2141 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2142 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2143 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2144 StorageOptions, SyncConfig, TransportConfig,
2145 };
2146 use crate::duration::ConfigDuration;
2147 use crate::size::ConfigSize;
2148 use serde::{Deserialize, Serialize};
2149 use serde_json::json;
2150 use std::time::Duration;
2151
2152 fn assert_reloads<T>(value: serde_json::Value)
2155 where
2156 T: Serialize + for<'de> Deserialize<'de>,
2157 {
2158 let first: T = serde_json::from_value(value.clone())
2159 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2160 let written = serde_json::to_value(&first).unwrap();
2161 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2162 panic!("{value} is written as {written}, which does not load: {e}")
2163 });
2164 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2165 }
2166
2167 #[test]
2172 fn size_settings_reload_from_what_is_written() {
2173 use crate::transport::dynamodb::DynamoDBWriterConfig;
2174 use crate::transport::file::FileInputConfig;
2175 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2176
2177 for number in [0u64, 1, 1_100, u64::MAX] {
2180 assert_reloads::<RuntimeConfig>(json!({
2181 "max_rss_mb": number,
2182 "datafusion_memory_mb": number,
2183 "storage": {"cache_mib": number, "min_storage_bytes": number},
2184 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2185 "dev_tweaks": {"storage_mb_max": number},
2186 }));
2187 }
2188
2189 let max = format!("{}B", u64::MAX);
2190 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2191 assert_reloads::<RuntimeConfig>(json!({
2192 "max_rss": size,
2193 "datafusion_memory": size,
2194 "storage": {
2195 "cache_size": size,
2196 "min_spill_size": size,
2197 "min_step_spill_size": size,
2198 },
2199 "resources": {
2200 "memory_min": size,
2201 "memory_max": size,
2202 "storage_min": size,
2203 "storage_max": size,
2204 "autoscaling": {"storage": {"scale_threshold_available": size}},
2205 },
2206 "dev_tweaks": {
2207 "storage_max": size,
2208 "fbuf_slab_size_per_class": size,
2209 "exchange_channel_capacity": size,
2210 },
2211 }));
2212 assert_reloads::<ConnectorConfig>(json!({
2213 "transport": {
2214 "name": "file_input",
2215 "config": {"path": "input.csv", "buffer_size": size},
2216 },
2217 "max_queued_size": size,
2218 }));
2219 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2220 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2221 assert_reloads::<PostgresWriterConfig>(json!({
2222 "uri": "postgres://localhost/db",
2223 "table": "t",
2224 "max_buffer_size": size,
2225 }));
2226 assert_reloads::<DynamoDBWriterConfig>(json!({
2227 "table": "t",
2228 "region": "us-east-1",
2229 "max_buffer_size": size,
2230 }));
2231 }
2232 }
2233
2234 #[test]
2239 fn soft_delete_is_backward_compatible() {
2240 let config: ConnectorConfig = serde_json::from_value(json!({
2241 "transport": {"name": "empty_input"}
2242 }))
2243 .unwrap();
2244 assert!(!config.soft_delete);
2245
2246 let serialized = serde_json::to_value(&config).unwrap();
2247 assert_eq!(serialized.get("soft_delete"), None);
2248
2249 let config: ConnectorConfig = serde_json::from_value(json!({
2250 "transport": {"name": "empty_input"},
2251 "soft_delete": true
2252 }))
2253 .unwrap();
2254 assert!(config.soft_delete);
2255 assert_eq!(
2256 serde_json::to_value(&config).unwrap().get("soft_delete"),
2257 Some(&json!(true))
2258 );
2259 }
2260
2261 #[test]
2264 fn soft_delete_invalidates_checkpointed_connector_state() {
2265 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2266 let mut soft_delete = config.clone();
2267 soft_delete.soft_delete = true;
2268
2269 assert!(config.equal_for_input_checkpoint_replay(&config));
2270 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2271 }
2272
2273 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2274 PipelineConfig {
2275 global: RuntimeConfig::default(),
2276 multihost: None,
2277 name: name.map(str::to_string),
2278 given_name: None,
2279 storage_config: None,
2280 secrets_dir: None,
2281 inputs: Default::default(),
2282 outputs: Default::default(),
2283 program_ir: None,
2284 }
2285 }
2286
2287 #[test]
2288 fn pipeline_identity_uses_system_and_given_names() {
2289 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2290 config.given_name = Some("my-pipeline".to_string());
2291
2292 let metadata = config.pipeline_identity().unwrap();
2293 assert_eq!(
2294 metadata.name,
2295 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2296 );
2297 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2298 }
2299
2300 #[test]
2301 fn pipeline_identity_is_none_without_system_name() {
2302 assert_eq!(config_with_name(None).pipeline_identity(), None);
2303 }
2304
2305 #[test]
2306 fn resolved_datafusion_memory_explicit_passes_through() {
2307 let config = RuntimeConfig {
2308 max_rss: Some(ConfigSize::from_mb(8_000)),
2309 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2310 ..Default::default()
2311 };
2312 assert_eq!(
2313 config.resolved_datafusion_memory(),
2314 Some(ConfigSize::from_mb(1_500))
2315 );
2316 }
2317
2318 #[test]
2319 fn resolved_datafusion_memory_unconfigured_returns_none() {
2320 let config = RuntimeConfig::default();
2321 assert!(config.max_rss.is_none());
2322 assert!(config.resources.memory_max.is_none());
2323 assert_eq!(config.resolved_datafusion_memory(), None);
2324 }
2325
2326 #[test]
2327 fn resolved_datafusion_memory_small_budget_scales_down() {
2328 let config = RuntimeConfig {
2330 max_rss: Some(ConfigSize::from_mb(256)),
2331 ..Default::default()
2332 };
2333 assert_eq!(
2334 config.resolved_datafusion_memory(),
2335 Some(ConfigSize::from_bytes(12_800_000))
2336 );
2337
2338 let config = RuntimeConfig {
2339 max_rss: Some(ConfigSize::from_mb(512)),
2340 ..Default::default()
2341 };
2342 assert_eq!(
2343 config.resolved_datafusion_memory(),
2344 Some(ConfigSize::from_bytes(25_600_000))
2345 );
2346 }
2347
2348 #[test]
2349 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2350 let config = RuntimeConfig {
2352 max_rss: Some(ConfigSize::from_mb(64_000)),
2353 ..Default::default()
2354 };
2355 assert_eq!(
2356 config.resolved_datafusion_memory(),
2357 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2358 );
2359 }
2360
2361 #[test]
2362 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2363 let config = RuntimeConfig {
2365 max_rss: Some(ConfigSize::from_mb(16_000)),
2366 ..Default::default()
2367 };
2368 assert_eq!(
2369 config.resolved_datafusion_memory(),
2370 Some(ConfigSize::from_mb(800))
2371 );
2372 }
2373
2374 #[test]
2375 fn resolved_datafusion_memory_falls_back_to_resources() {
2376 let config = RuntimeConfig {
2378 max_rss: None,
2379 resources: ResourceConfig {
2380 memory_max: Some(ConfigSize::from_mb(16_000)),
2381 ..Default::default()
2382 },
2383 ..Default::default()
2384 };
2385 assert_eq!(
2386 config.resolved_datafusion_memory(),
2387 Some(ConfigSize::from_mb(800))
2388 );
2389 }
2390
2391 #[test]
2392 fn ft_config() {
2393 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2394 #[serde(default)]
2395 struct Wrapper {
2396 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2397 config: FtConfig,
2398 }
2399
2400 for s in [
2403 "{}",
2404 r#"{"config": null}"#,
2405 r#"{"config": {"model": "none"}}"#,
2406 ] {
2407 let config: Wrapper = serde_json::from_str(s).unwrap();
2408 assert_eq!(config.config.model, None);
2409 assert_eq!(config.config.checkpoint_interval(), None);
2410 }
2411
2412 let s = serde_json::to_string(&Wrapper {
2414 config: FtConfig::default(),
2415 })
2416 .unwrap();
2417 assert!(s.contains("\"none\""));
2418
2419 for s in [
2422 r#"{}"#,
2423 r#"{"checkpoint_interval": "60s"}"#,
2424 r#"{"checkpoint_interval_secs": 60}"#,
2425 ] {
2426 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2427 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2428 assert_eq!(
2429 config.checkpoint_interval(),
2430 Some(Duration::from_secs(60)),
2431 "parsing {s}"
2432 );
2433 }
2434
2435 for s in [
2438 r#"{"checkpoint_interval": null}"#,
2439 r#"{"checkpoint_interval_secs": null}"#,
2440 ] {
2441 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2442 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2443 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2444 }
2445
2446 let error = serde_json::from_str::<FtConfig>(
2449 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2450 )
2451 .unwrap_err()
2452 .to_string();
2453 assert!(error.contains("duplicate field"), "{error}");
2454
2455 for (json, expected_secs) in [
2457 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2458 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2459 ] {
2460 assert_eq!(
2461 serde_json::from_str::<FtConfig>(json)
2462 .unwrap()
2463 .checkpoint_interval(),
2464 Some(Duration::from_secs(expected_secs)),
2465 "parsing {json}"
2466 );
2467 }
2468 }
2469
2470 #[test]
2474 fn legacy_duration_spelling_uses_the_older_keys() {
2475 let mut config = serde_json::json!({
2476 "workers": 2,
2477 "clock_resolution": "250ms",
2478 "max_buffering_delay": "3ms",
2479 "provisioning_timeout": "15m",
2480 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2481 "storage": {"backend": {"name": "file", "config": {
2482 "ioop_latency": "5ms",
2483 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2484 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2485 });
2486 super::to_legacy_duration_spelling(&mut config);
2487 assert_eq!(
2488 config,
2489 serde_json::json!({
2490 "workers": 2,
2491 "clock_resolution_usecs": 250_000,
2492 "max_buffering_delay_usecs": 3_000,
2493 "provisioning_timeout_secs": 900,
2494 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2495 "storage": {"backend": {"name": "file", "config": {
2496 "ioop_delay": 5,
2497 "sync": {"bucket": "b", "pull_interval": 10,
2498 "push_interval": 3_600, "retention_min_age": 30}}}},
2499 })
2500 );
2501 }
2502
2503 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2505 serde_json::json!({
2506 "name": "p",
2507 "clock_resolution": "250ms",
2508 "inputs": {
2509 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2510 "topic": "t", "group_join_timeout": "30s"}}},
2511 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2512 "path": "http://x", "pause_linger": "7s"}}},
2513 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2514 "connection_config": {"server_url": "nats://x",
2515 "connection_timeout": "5s", "request_timeout": "6s"},
2516 "stream_name": "s",
2517 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2518 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2519 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2520 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2521 },
2522 "outputs": {
2523 "v.kafka": {"stream": "v",
2524 "transport": {"name": "kafka_output", "config": {
2525 "topic": "v", "initialization_timeout": "40s"}},
2526 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2527 "registry_timeout": "8s"}},
2528 "enable_output_buffer": true,
2529 "max_output_buffer_time": "500ms"},
2530 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2531 "connection_config": {"server_url": "nats://x",
2532 "connection_timeout": "5s", "request_timeout": "6s"},
2533 "subject": "s", "publish_timeout": "9s"}}},
2534 },
2535 })
2536 }
2537
2538 #[test]
2542 fn legacy_duration_spelling_rewrites_every_connector() {
2543 let mut config = pipeline_with_every_duration_connector();
2544 super::to_legacy_duration_spelling(&mut config);
2545 let i = &config["inputs"];
2546 assert_eq!(
2547 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2548 30
2549 );
2550 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2551 let nats = &i["t.nats"]["transport"]["config"];
2552 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2553 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2554 assert_eq!(nats["inactivity_timeout_secs"], 90);
2555 assert_eq!(nats["retry_interval_secs"], 3);
2556 assert_eq!(
2557 nats["consumer_config"]["max_expires"],
2558 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2559 );
2560 let pubsub = &i["t.pubsub"]["transport"]["config"];
2561 assert_eq!(pubsub["timeout_seconds"], 20);
2562 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2563 let out = &config["outputs"]["v.kafka"];
2564 assert_eq!(
2565 out["transport"]["config"]["initialization_timeout_secs"],
2566 40
2567 );
2568 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2569 assert_eq!(out["max_output_buffer_time_millis"], 500);
2570 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2571 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2572 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2573 assert_eq!(nats["publish_timeout_secs"], 9);
2574
2575 let text = config.to_string();
2577 for new in [
2578 "\"group_join_timeout\"",
2579 "\"pause_linger\"",
2580 "\"connection_timeout\"",
2581 "\"request_timeout\"",
2582 "\"inactivity_timeout\"",
2583 "\"retry_interval\"",
2584 "\"max_expiry\"",
2585 "\"timeout\"",
2586 "\"connect_timeout\"",
2587 "\"initialization_timeout\"",
2588 "\"registry_timeout\"",
2589 "\"max_output_buffer_time\"",
2590 "\"publish_timeout\"",
2591 "\"clock_resolution\"",
2592 ] {
2593 assert!(!text.contains(new), "{new} survived in {text}");
2594 }
2595 }
2596
2597 #[test]
2599 fn legacy_duration_spelling_round_trips_connectors() {
2600 let original: PipelineConfig =
2601 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2602 let mut value = serde_json::to_value(&original).unwrap();
2603 super::to_legacy_duration_spelling(&mut value);
2604 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2605
2606 let registry = |config: &PipelineConfig| {
2609 let format = config.outputs["v.kafka"]
2610 .connector_config
2611 .format
2612 .clone()
2613 .unwrap();
2614 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2615 .unwrap()
2616 .registry_config
2617 .registry_timeout
2618 };
2619 assert_eq!(registry(&reread), registry(&original));
2620 let mut original = original;
2621 for config in [&mut reread, &mut original] {
2622 config
2623 .outputs
2624 .get_mut("v.kafka")
2625 .unwrap()
2626 .connector_config
2627 .format = None;
2628 }
2629 assert_eq!(reread, original);
2630 }
2631
2632 #[test]
2636 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2637 let mut config = serde_json::json!({
2638 "inputs": {
2639 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2640 "group_join_timeout": "100000000000s"}}},
2641 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2642 },
2643 "storage": {"backend": {"name": "file", "config": {
2644 "sync": {"min_retention": "100000000000d"}}}},
2645 });
2646 super::to_legacy_duration_spelling(&mut config);
2647 let i = &config["inputs"];
2648 assert_eq!(
2649 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2650 u64::from(u32::MAX)
2651 );
2652 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2653 assert_eq!(
2654 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2655 u64::from(u32::MAX)
2656 );
2657 }
2658
2659 #[test]
2663 fn legacy_duration_spelling_round_trips() {
2664 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2665 "clock_resolution": "250ms",
2666 "max_buffering_delay": "3ms",
2667 "provisioning_timeout": "15m",
2668 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2669 }))
2670 .unwrap();
2671 let mut value = serde_json::to_value(&original).unwrap();
2672 super::to_legacy_duration_spelling(&mut value);
2673 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2674 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2675 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2676 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2677 assert_eq!(
2678 reread.fault_tolerance.checkpoint_interval(),
2679 original.fault_tolerance.checkpoint_interval()
2680 );
2681 }
2682
2683 #[test]
2688 fn legacy_duration_spelling_edge_cases() {
2689 let mut config = serde_json::json!({
2690 "max_buffering_delay": null,
2691 "provisioning_timeout": "1.5s",
2692 "fault_tolerance": {"checkpoint_interval": null},
2693 "clock_resolution": "10sec",
2694 "storage": {"backend": {"name": "file", "config": {
2695 "ioop_latency": "400us",
2696 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2697 });
2698 super::to_legacy_duration_spelling(&mut config);
2699 assert_eq!(
2700 config,
2701 serde_json::json!({
2702 "provisioning_timeout_secs": 2,
2703 "fault_tolerance": {"checkpoint_interval_secs": null},
2704 "clock_resolution": "10sec",
2705 "storage": {"backend": {"name": "file", "config": {
2706 "ioop_delay": 1,
2707 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2708 })
2709 );
2710
2711 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2713 super::to_legacy_duration_spelling(&mut zero);
2714 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2715
2716 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2718 let mut again = legacy.clone();
2719 super::to_legacy_duration_spelling(&mut again);
2720 assert_eq!(again, legacy);
2721 }
2722
2723 #[test]
2727 fn legacy_size_spelling_uses_the_older_keys() {
2728 let mut config = serde_json::json!({
2729 "workers": 2,
2730 "max_rss": "16G",
2731 "datafusion_memory": "1.5G",
2732 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2733 "resources": {
2734 "memory_min": "4G", "memory_max": "16Gi",
2735 "storage_min": "100G", "storage_max": "400Gi",
2736 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2737 },
2738 "dev_tweaks": {
2739 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2740 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2741 },
2742 "inputs": {
2743 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2744 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2745 "t.cdc": {"stream": "t",
2746 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2747 },
2748 "outputs": {
2749 "v.ddb": {"stream": "v",
2750 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2751 "v.pg": {"stream": "v",
2752 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2753 },
2754 });
2755 super::to_legacy_size_spelling(&mut config);
2756 assert_eq!(
2757 config,
2758 serde_json::json!({
2759 "workers": 2,
2760 "max_rss_mb": 16_000,
2761 "datafusion_memory_mb": 1_500,
2762 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2763 "resources": {
2764 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2766 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2767 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2768 },
2769 "dev_tweaks": {
2770 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2771 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2772 },
2773 "inputs": {
2774 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2775 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2776 "t.cdc": {"stream": "t",
2777 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2778 },
2779 "outputs": {
2780 "v.ddb": {"stream": "v",
2781 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2782 "v.pg": {"stream": "v",
2783 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2784 },
2785 })
2786 );
2787 }
2788
2789 #[test]
2792 fn legacy_size_spelling_round_trips() {
2793 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2794 "name": "p",
2795 "max_rss": "16G",
2796 "datafusion_memory": "1G",
2799 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2800 "resources": {"memory_max": "16G", "storage_max": "400G"},
2801 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2802 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2803 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2804 "outputs": {},
2805 }))
2806 .unwrap();
2807 let mut value = serde_json::to_value(&config).unwrap();
2808 super::to_legacy_size_spelling(&mut value);
2809 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2810 assert_eq!(
2811 value["inputs"]["t.file"]["max_queued_bytes"],
2812 serde_json::json!(1024 * 1024)
2813 );
2814 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2815 assert_eq!(reread, config);
2816 }
2817
2818 #[test]
2821 fn legacy_spelling_applies_each_rename_separately() {
2822 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2823 let mut both = current.clone();
2824 super::LegacySpelling {
2825 durations: true,
2826 sizes: true,
2827 }
2828 .apply(&mut both);
2829 assert_eq!(
2830 both,
2831 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2832 );
2833 let mut sizes_only = current.clone();
2834 super::LegacySpelling {
2835 durations: false,
2836 sizes: true,
2837 }
2838 .apply(&mut sizes_only);
2839 assert_eq!(
2840 sizes_only,
2841 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2842 );
2843 let mut none = current.clone();
2844 super::LegacySpelling::NONE.apply(&mut none);
2845 assert_eq!(none, current);
2846 assert!(!super::LegacySpelling::NONE.any());
2847 }
2848
2849 #[test]
2850 fn legacy_size_spelling_edge_cases() {
2851 let mut config = serde_json::json!({
2854 "max_rss": "lots",
2855 "resources": {"memory_max": null, "memory_min": 4000}
2856 });
2857 super::to_legacy_size_spelling(&mut config);
2858 assert_eq!(
2859 config,
2860 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2861 );
2862
2863 let mut small = serde_json::json!({"max_rss": "1"});
2866 super::to_legacy_size_spelling(&mut small);
2867 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2868
2869 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2871 let mut again = legacy.clone();
2872 super::to_legacy_size_spelling(&mut again);
2873 assert_eq!(again, legacy);
2874 }
2875
2876 #[test]
2885 fn a_stored_default_matches_an_omitted_one() {
2886 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2887 "transport": {
2888 "name": "url_input",
2889 "config": {"path": "http://example.com/x", "pause_timeout": 60},
2890 }
2891 }))
2892 .unwrap();
2893 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2894 "transport": {
2895 "name": "url_input",
2896 "config": {"path": "http://example.com/x"},
2897 }
2898 }))
2899 .unwrap();
2900
2901 assert_ne!(stored, fresh);
2904 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2905
2906 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2908 "transport": {
2909 "name": "url_input",
2910 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2911 }
2912 }))
2913 .unwrap();
2914 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2915 }
2916
2917 #[test]
2925 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2926 let connector = |registry: serde_json::Value| -> ConnectorConfig {
2927 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2928 format
2929 .as_object_mut()
2930 .unwrap()
2931 .extend(registry.as_object().unwrap().clone());
2932 serde_json::from_value(serde_json::json!({
2933 "transport": {
2934 "name": "url_input",
2935 "config": {"path": "http://example.com/x"},
2936 },
2937 "format": {"name": "avro", "config": format},
2938 }))
2939 .unwrap()
2940 };
2941 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2942 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2943 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2944 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2945 let unset = connector(serde_json::json!({}));
2946
2947 assert!(stored.equal_modulo_paused(¤t));
2948 assert!(stored.equal_for_input_checkpoint_replay(¤t));
2949 assert!(current.equal_modulo_paused(&spelled_out));
2950 assert!(!stored.equal_modulo_paused(&changed));
2951 assert!(!stored.equal_modulo_paused(&unset));
2952 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2954 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2955 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2956 }))
2957 .unwrap();
2958 assert!(!json.equal_modulo_paused(&stored));
2959 }
2960
2961 #[test]
2967 fn the_largest_legacy_defaults_still_load() {
2968 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
2969 "enable_output_buffer": false,
2970 "max_output_buffer_time_millis": u64::MAX,
2971 "max_output_buffer_size_records": 10_000_000u64,
2972 }))
2973 .unwrap();
2974 assert_eq!(
2975 buffer.max_output_buffer_time,
2976 Some(ConfigDuration::from_millis(u64::MAX))
2977 );
2978
2979 let sync: SyncConfig =
2981 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
2982 assert_eq!(
2983 sync.min_retention(),
2984 ConfigDuration::from_days(4_000_000_000)
2985 );
2986 }
2987
2988 #[test]
2992 fn a_legacy_number_past_u64_seconds_saturates() {
2993 let sync: SyncConfig =
2994 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
2995 .unwrap();
2996 assert_eq!(
2997 sync.min_retention(),
2998 ConfigDuration::from(std::time::Duration::MAX)
2999 );
3000 }
3001
3002 #[test]
3006 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3007 fn connector(value: serde_json::Value) -> ConnectorConfig {
3008 serde_json::from_value(value).unwrap()
3009 }
3010 fn secs(duration: ConfigDuration) -> u64 {
3011 std::time::Duration::from(duration).as_secs()
3012 }
3013 let fresh_kafka = connector(serde_json::json!({
3014 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3015 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3016 unreachable!()
3017 };
3018 let stored_kafka = connector(serde_json::json!({
3019 "transport": {"name": "kafka_input", "config": {
3020 "topic": "t",
3021 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3022 assert_ne!(stored_kafka, fresh_kafka);
3023 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3024
3025 let base = serde_json::json!({
3026 "connection_config": {"server_url": "nats://x"},
3027 "stream_name": "s",
3028 "consumer_config": {"deliver_policy": "All"}});
3029 let fresh_nats = connector(serde_json::json!({
3030 "transport": {"name": "nats_input", "config": base.clone()}}));
3031 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3032 unreachable!()
3033 };
3034 let mut spelled_out = base;
3035 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3036 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3037 spelled_out["connection_config"]["connection_timeout_secs"] =
3038 secs(nats.connection_config.connection_timeout()).into();
3039 spelled_out["connection_config"]["request_timeout_secs"] =
3040 secs(nats.connection_config.request_timeout()).into();
3041 let stored_nats = connector(serde_json::json!({
3042 "transport": {"name": "nats_input", "config": spelled_out}}));
3043 assert_ne!(stored_nats, fresh_nats);
3044 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3045 }
3046
3047 #[test]
3053 fn superseded_keys_are_normalised_by_a_round_trip() {
3054 let stored = serde_json::json!({
3055 "workers": 4,
3056 "clock_resolution_usecs": 100_000,
3057 "max_buffering_delay_usecs": 0,
3058 "provisioning_timeout_secs": 300,
3059 });
3060
3061 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3062 let written = serde_json::to_value(&config).unwrap();
3063
3064 assert_eq!(written["clock_resolution"], "100ms");
3065 assert_eq!(written["max_buffering_delay"], "0s");
3066 assert_eq!(written["provisioning_timeout"], "5m");
3067 for superseded in [
3068 "clock_resolution_usecs",
3069 "max_buffering_delay_usecs",
3070 "provisioning_timeout_secs",
3071 ] {
3072 assert!(
3073 written.get(superseded).is_none(),
3074 "`{superseded}` survived the round trip: {written}"
3075 );
3076 }
3077
3078 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3081 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3082 }
3083
3084 #[test]
3089 fn ioop_latency_accepts_both_spellings() {
3090 for (json, expected) in [
3091 (r#"{"name": "file", "config": {}}"#, None),
3092 (
3093 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3094 Some(ConfigDuration::from_millis(5)),
3095 ),
3096 (
3097 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3098 Some(ConfigDuration::from_millis(5)),
3099 ),
3100 (
3101 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3102 Some(ConfigDuration::from_secs(1)),
3103 ),
3104 ] {
3105 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3106 let StorageBackendConfig::File(file) = backend else {
3107 panic!("expected the file backend, parsing {json}");
3108 };
3109 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3110 }
3111 }
3112
3113 #[test]
3117 fn clock_resolution_falls_back_to_the_deprecated_field() {
3118 for (json, expected) in [
3119 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3120 (
3121 r#"{"clock_resolution": "100ms"}"#,
3122 ConfigDuration::from_millis(100),
3123 ),
3124 (
3125 r#"{"clock_resolution_usecs": 100000}"#,
3126 ConfigDuration::from_millis(100),
3127 ),
3128 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3129 (
3130 r#"{"clock_resolution_usecs": null}"#,
3131 DEFAULT_CLOCK_RESOLUTION,
3132 ),
3133 ] {
3134 assert_eq!(
3135 serde_json::from_str::<RuntimeConfig>(json)
3136 .unwrap()
3137 .clock_resolution(),
3138 expected,
3139 "parsing {json}"
3140 );
3141 }
3142 }
3143
3144 #[test]
3147 fn deprecated_duration_fields_still_work() {
3148 let runtime: RuntimeConfig = serde_json::from_str(
3149 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3150 )
3151 .unwrap();
3152 assert_eq!(
3153 runtime.max_buffering_delay(),
3154 ConfigDuration::from_millis(5)
3155 );
3156 assert_eq!(
3157 runtime.provisioning_timeout,
3158 Some(ConfigDuration::from_secs(1200))
3159 );
3160
3161 let sync: SyncConfig = serde_json::from_str(
3162 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3163 )
3164 .unwrap();
3165 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3166 assert_eq!(
3167 sync.checkpoint_push_interval(),
3168 Some(ConfigDuration::from_secs(300))
3169 );
3170 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3171
3172 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3173 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3174
3175 let buffer: OutputBufferConfig =
3176 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3177 assert_eq!(
3178 buffer.max_output_buffer_time(),
3179 ConfigDuration::from_millis(250)
3180 );
3181 }
3182
3183 #[test]
3186 fn duration_fields_default_when_unset() {
3187 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3188 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3189 assert_eq!(sync.checkpoint_push_interval(), None);
3190 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3191
3192 let runtime = RuntimeConfig::default();
3193 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3194 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3195 assert_eq!(runtime.provisioning_timeout, None);
3196 }
3197
3198 #[test]
3202 fn storage_options_f64_roundtrip_through_pipeline_config() {
3203 let pc = PipelineConfig {
3204 global: RuntimeConfig {
3205 storage: Some(StorageOptions {
3206 bloom_false_positive_rate: Some(0.01),
3207 ..Default::default()
3208 }),
3209 ..Default::default()
3210 },
3211 multihost: None,
3212 name: Some("test-pipeline".into()),
3213 given_name: None,
3214 storage_config: None,
3215 secrets_dir: None,
3216 inputs: Default::default(),
3217 outputs: Default::default(),
3218 program_ir: None,
3219 };
3220
3221 let json = serde_json::to_string_pretty(&pc).unwrap();
3223 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3224 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3225 );
3226 assert_eq!(
3227 pc2.global.storage.unwrap().bloom_false_positive_rate,
3228 Some(0.01)
3229 );
3230
3231 let value = serde_json::to_value(&pc).unwrap();
3233 let pc3: PipelineConfig = serde_json::from_value(value)
3234 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3235 assert_eq!(
3236 pc3.global.storage.unwrap().bloom_false_positive_rate,
3237 Some(0.01)
3238 );
3239 }
3240}
3241
3242impl FtConfig {
3243 pub fn is_enabled(&self) -> bool {
3244 self.model.is_some()
3245 }
3246
3247 pub fn checkpoint_interval(&self) -> Option<Duration> {
3254 if !self.is_enabled() {
3255 return None;
3256 }
3257
3258 let interval = self
3259 .checkpoint_interval
3260 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3261
3262 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3263 }
3264}
3265
3266mod none_as_string {
3273 use std::marker::PhantomData;
3274
3275 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3276 use serde::ser::{Serialize, Serializer};
3277
3278 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3279 where
3280 S: Serializer,
3281 T: Serialize,
3282 {
3283 match value.as_ref() {
3284 Some(value) => value.serialize(serializer),
3285 None => "none".serialize(serializer),
3286 }
3287 }
3288
3289 struct NoneAsString<T>(PhantomData<fn() -> T>);
3290
3291 impl<'de, T> Visitor<'de> for NoneAsString<T>
3292 where
3293 T: Deserialize<'de>,
3294 {
3295 type Value = Option<T>;
3296
3297 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3298 formatter.write_str("string")
3299 }
3300
3301 fn visit_none<E>(self) -> Result<Self::Value, E>
3302 where
3303 E: serde::de::Error,
3304 {
3305 Ok(None)
3306 }
3307
3308 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3309 where
3310 E: serde::de::Error,
3311 {
3312 if &value.to_ascii_lowercase() == "none" {
3313 Ok(None)
3314 } else {
3315 Ok(Some(T::deserialize(value.into_deserializer())?))
3316 }
3317 }
3318 }
3319
3320 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3321 where
3322 D: Deserializer<'de>,
3323 T: Deserialize<'de>,
3324 {
3325 deserializer.deserialize_str(NoneAsString(PhantomData))
3326 }
3327}
3328
3329fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3332 Schema::OneOf(
3333 OneOfBuilder::new()
3334 .item(RefOr::Ref(Ref::new(format!(
3335 "#/components/schemas/{}",
3336 T::schema().0
3337 ))))
3338 .item(
3339 ObjectBuilder::new()
3340 .schema_type(SchemaType::String)
3341 .enum_values(Some(vec!["none"])),
3342 )
3343 .default(Some(
3344 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3345 ))
3346 .build(),
3347 )
3348}
3349
3350#[derive(
3355 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3356)]
3357#[serde(rename_all = "snake_case")]
3358pub enum FtModel {
3359 AtLeastOnce,
3362
3363 #[default]
3366 ExactlyOnce,
3367}
3368
3369impl FtModel {
3370 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3371 value.map_or("no", |model| model.as_str())
3372 }
3373
3374 pub fn as_str(&self) -> &'static str {
3375 match self {
3376 FtModel::AtLeastOnce => "at_least_once",
3377 FtModel::ExactlyOnce => "exactly_once",
3378 }
3379 }
3380}
3381
3382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3384pub struct FtModelUnknown;
3385
3386impl std::fmt::Display for FtModelUnknown {
3387 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3388 f.write_str("expected `exactly_once` or `at_least_once`")
3389 }
3390}
3391
3392impl std::error::Error for FtModelUnknown {}
3393
3394impl FromStr for FtModel {
3395 type Err = FtModelUnknown;
3396
3397 fn from_str(s: &str) -> Result<Self, Self::Err> {
3398 match s.to_ascii_lowercase().as_str() {
3399 "exactly_once" => Ok(Self::ExactlyOnce),
3400 "at_least_once" => Ok(Self::AtLeastOnce),
3401 _ => Err(FtModelUnknown),
3402 }
3403 }
3404}
3405
3406#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3408pub struct InputEndpointConfig {
3409 pub stream: Cow<'static, str>,
3412
3413 #[serde(flatten)]
3415 pub connector_config: ConnectorConfig,
3416}
3417
3418impl InputEndpointConfig {
3419 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3420 Self {
3421 stream: stream.into(),
3422 connector_config,
3423 }
3424 }
3425}
3426
3427fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3431where
3432 D: Deserializer<'de>,
3433{
3434 let value = Option::<JsonValue>::deserialize(deserializer)?;
3435 match value {
3436 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3437 Some(JsonValue::Array(arr)) => {
3438 let vec = arr
3439 .into_iter()
3440 .map(|item| {
3441 item.as_str()
3442 .map(|s| s.to_string())
3443 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3444 })
3445 .collect::<Result<Vec<String>, _>>()?;
3446 Ok(Some(vec))
3447 }
3448 Some(JsonValue::Null) | None => Ok(None),
3449 _ => Err(serde::de::Error::custom(
3450 "invalid 'start_after' property: expected a string, an array of strings, or null",
3451 )),
3452 }
3453}
3454
3455#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3456pub struct ConnectorConfig {
3457 #[serde(default)]
3470 pub send_snapshot: bool,
3471
3472 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3489 pub soft_delete: bool,
3490
3491 pub transport: TransportConfig,
3493
3494 #[serde(skip_serializing_if = "Option::is_none")]
3496 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3497
3498 pub format: Option<FormatConfig>,
3500
3501 #[serde(skip_serializing_if = "Option::is_none")]
3503 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3504
3505 pub index: Option<String>,
3520
3521 #[serde(flatten)]
3523 pub output_buffer_config: OutputBufferConfig,
3524
3525 #[serde(skip_serializing_if = "Option::is_none")]
3538 pub max_batch_size: Option<u64>,
3539
3540 #[serde(skip_serializing_if = "Option::is_none")]
3553 pub max_worker_batch_size: Option<u64>,
3554
3555 #[serde(default = "default_max_queued_records")]
3574 pub max_queued_records: u64,
3575
3576 #[serde(
3598 default,
3599 alias = "max_queued_bytes",
3600 deserialize_with = "size_max_queued_size",
3601 skip_serializing_if = "Option::is_none"
3602 )]
3603 #[schema(value_type = Option<String>)]
3604 pub max_queued_size: Option<ConfigSize>,
3605
3606 #[serde(default)]
3617 pub paused: bool,
3618
3619 #[serde(default)]
3624 pub labels: Vec<String>,
3625
3626 #[serde(deserialize_with = "deserialize_start_after")]
3632 #[serde(default)]
3633 pub start_after: Option<Vec<String>>,
3634
3635 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3647 pub distributed: bool,
3648}
3649
3650impl ConnectorConfig {
3651 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3652 Self {
3653 send_snapshot: false,
3654 soft_delete: false,
3655 transport,
3656 preprocessor: None,
3657 format,
3658 postprocessor: None,
3659 index: None,
3660 output_buffer_config: Default::default(),
3661 max_batch_size: None,
3662 max_worker_batch_size: None,
3663 max_queued_records: default_max_queued_records(),
3664 max_queued_size: None,
3665 paused: false,
3666 labels: Vec::new(),
3667 start_after: None,
3668 distributed: false,
3669 }
3670 }
3671
3672 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3673 self.max_batch_size = max_batch_size;
3674 self
3675 }
3676
3677 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3678 self.max_queued_records = max_queued_records;
3679 self
3680 }
3681
3682 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3687 let mut a = self.clone();
3688 let mut b = other.clone();
3689 a.paused = false;
3690 b.paused = false;
3691 a.normalize_durations();
3692 b.normalize_durations();
3693 a == b
3694 }
3695
3696 fn normalize_durations(&mut self) {
3707 self.transport.normalize_durations();
3708 self.output_buffer_config.max_output_buffer_time =
3709 Some(self.output_buffer_config.max_output_buffer_time());
3710 if let Some(format) = &mut self.format {
3711 format.normalize_durations();
3712 }
3713 }
3714
3715 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3718 let mut a = self.clone();
3719 let mut b = other.clone();
3720 a.normalize_for_input_checkpoint_replay();
3721 b.normalize_for_input_checkpoint_replay();
3722 a == b
3723 }
3724
3725 fn normalize_for_input_checkpoint_replay(&mut self) {
3726 self.paused = false;
3727 self.max_batch_size = None;
3728 self.max_worker_batch_size = None;
3729 self.max_queued_records = default_max_queued_records();
3730 self.max_queued_size = None;
3731 self.normalize_durations();
3732 }
3733
3734 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3737 self.max_batch_size = other.max_batch_size;
3738 self.max_worker_batch_size = other.max_worker_batch_size;
3739 self.max_queued_records = other.max_queued_records;
3740 self.max_queued_size = other.max_queued_size;
3741 }
3742
3743 pub fn max_queued_records(&self) -> u64 {
3745 self.max_queued_records
3746 }
3747
3748 pub fn max_queued_bytes(&self) -> u64 {
3751 self.max_queued_size
3752 .map(ConfigSize::as_bytes)
3753 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3754 }
3755}
3756
3757#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3758#[serde(default)]
3759pub struct OutputBufferConfig {
3760 pub enable_output_buffer: bool,
3783
3784 #[serde(
3793 default,
3794 alias = "max_output_buffer_time_millis",
3795 deserialize_with = "duration_max_output_buffer_time",
3796 skip_serializing_if = "Option::is_none"
3797 )]
3798 #[schema(value_type = Option<String>)]
3799 pub max_output_buffer_time: Option<ConfigDuration>,
3800
3801 pub max_output_buffer_size_records: usize,
3813}
3814
3815impl OutputBufferConfig {
3816 pub fn max_output_buffer_time(&self) -> ConfigDuration {
3818 self.max_output_buffer_time
3819 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3820 }
3821}
3822
3823impl Default for OutputBufferConfig {
3824 fn default() -> Self {
3825 Self {
3826 enable_output_buffer: false,
3827 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3828 max_output_buffer_time: None,
3829 }
3830 }
3831}
3832
3833#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3835pub struct OutputEndpointConfig {
3836 pub stream: Cow<'static, str>,
3839
3840 #[serde(flatten)]
3842 pub connector_config: ConnectorConfig,
3843}
3844
3845impl OutputEndpointConfig {
3846 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3847 Self {
3848 stream: stream.into(),
3849 connector_config,
3850 }
3851 }
3852}
3853
3854#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3858#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3859pub enum TransportConfig {
3860 FileInput(FileInputConfig),
3861 FileOutput(FileOutputConfig),
3862 NatsInput(Box<NatsInputConfig>),
3865 NatsOutput(NatsOutputConfig),
3866 KafkaInput(KafkaInputConfig),
3867 KafkaOutput(KafkaOutputConfig),
3868 PubSubInput(PubSubInputConfig),
3869 UrlInput(UrlInputConfig),
3870 S3Input(S3InputConfig),
3871 DeltaTableInput(DeltaTableReaderConfig),
3872 DeltaTableOutput(DeltaTableWriterConfig),
3873 #[serde(rename = "dynamodb_output")]
3876 DynamoDBOutput(DynamoDBWriterConfig),
3877 RedisOutput(RedisOutputConfig),
3878 IcebergInput(Box<IcebergReaderConfig>),
3880 PostgresInput(PostgresReaderConfig),
3881 PostgresCdcInput(PostgresCdcReaderConfig),
3882 PostgresOutput(PostgresWriterConfig),
3883 Datagen(DatagenInputConfig),
3884 Nexmark(NexmarkInputConfig),
3885 HttpInput(HttpInputConfig),
3887 HttpOutput(HttpOutputConfig),
3889 AdHocInput(AdHocInputConfig),
3891 ClockInput(ClockConfig),
3892 S2Input(S2InputConfig),
3893 S2Output(S2OutputConfig),
3894 NullOutput,
3896 EmptyInput,
3898}
3899
3900impl TransportConfig {
3901 pub fn normalize_durations(&mut self) {
3904 match self {
3905 TransportConfig::UrlInput(config) => {
3906 config.pause_linger = Some(config.pause_linger());
3907 }
3908 TransportConfig::KafkaInput(config) => {
3909 config.group_join_timeout = Some(config.group_join_timeout());
3910 }
3911 TransportConfig::KafkaOutput(config) => {
3912 config.initialization_timeout = Some(config.initialization_timeout());
3913 }
3914 TransportConfig::NatsInput(config) => {
3915 config.connection_config.connection_timeout =
3916 Some(config.connection_config.connection_timeout());
3917 config.connection_config.request_timeout =
3918 Some(config.connection_config.request_timeout());
3919 config.inactivity_timeout = Some(config.inactivity_timeout());
3920 config.retry_interval = Some(config.retry_interval());
3921 }
3922 TransportConfig::NatsOutput(config) => {
3923 config.connection_config.connection_timeout =
3924 Some(config.connection_config.connection_timeout());
3925 config.connection_config.request_timeout =
3926 Some(config.connection_config.request_timeout());
3927 config.publish_timeout = Some(config.publish_timeout());
3928 }
3929 _ => {}
3930 }
3931 }
3932
3933 pub fn name(&self) -> String {
3934 match self {
3935 TransportConfig::FileInput(_) => "file_input".to_string(),
3936 TransportConfig::FileOutput(_) => "file_output".to_string(),
3937 TransportConfig::NatsInput(_) => "nats_input".to_string(),
3938 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
3939 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
3940 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
3941 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
3942 TransportConfig::UrlInput(_) => "url_input".to_string(),
3943 TransportConfig::S3Input(_) => "s3_input".to_string(),
3944 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
3945 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
3946 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
3947 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
3948 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
3949 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
3950 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
3951 TransportConfig::Datagen(_) => "datagen".to_string(),
3952 TransportConfig::Nexmark(_) => "nexmark".to_string(),
3953 TransportConfig::HttpInput(_) => "http_input".to_string(),
3954 TransportConfig::HttpOutput(_) => "http_output".to_string(),
3955 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
3956 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
3957 TransportConfig::ClockInput(_) => "clock".to_string(),
3958 TransportConfig::S2Input(_) => "s2_input".to_string(),
3959 TransportConfig::S2Output(_) => "s2_output".to_string(),
3960 TransportConfig::NullOutput => "null_output".to_string(),
3961 TransportConfig::EmptyInput => "empty_input".to_string(),
3962 }
3963 }
3964
3965 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
3970 match self {
3971 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
3972 _ => None,
3973 }
3974 }
3975
3976 pub fn is_transient(&self) -> bool {
3979 matches!(
3980 self,
3981 TransportConfig::AdHocInput(_)
3982 | TransportConfig::HttpInput(_)
3983 | TransportConfig::HttpOutput(_)
3984 | TransportConfig::ClockInput(_)
3985 )
3986 }
3987
3988 pub fn is_http_input(&self) -> bool {
3989 matches!(self, TransportConfig::HttpInput(_))
3990 }
3991
3992 pub fn supports_distribution(&self) -> bool {
3996 matches!(
3997 self,
3998 TransportConfig::KafkaInput(_)
3999 | TransportConfig::DeltaTableInput(_)
4000 | TransportConfig::IcebergInput(_)
4001 )
4002 }
4003
4004 pub fn needs_input_choice(&self) -> bool {
4016 matches!(
4017 self,
4018 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4019 )
4020 }
4021
4022 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4025 use crate::adapter_stats::FrontierMerge;
4026 match self {
4027 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4028 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4029 FrontierMerge::Shared
4030 }
4031 _ => FrontierMerge::Opaque,
4032 }
4033 }
4034}
4035
4036#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4039pub struct FormatConfig {
4040 pub name: Cow<'static, str>,
4042
4043 #[serde(default)]
4045 #[schema(value_type = Object)]
4046 pub config: JsonValue,
4047}
4048
4049impl FormatConfig {
4050 pub fn normalize_durations(&mut self) {
4057 if self.name != "avro" {
4058 return;
4059 }
4060 let has_timeout = self.config.as_object().is_some_and(|object| {
4061 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4062 });
4063 if !has_timeout {
4064 return;
4065 }
4066 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4067 self.config.clone(),
4068 ) else {
4069 return;
4070 };
4071 let object = self.config.as_object_mut().unwrap();
4072 object.remove("registry_timeout_secs");
4073 match registry.registry_timeout {
4074 Some(timeout) => object.insert(
4075 "registry_timeout".to_string(),
4076 JsonValue::String(timeout.to_string()),
4077 ),
4078 None => object.remove("registry_timeout"),
4079 };
4080 }
4081}
4082
4083#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4085#[serde(deny_unknown_fields)]
4086pub struct DynamicConfig {
4087 #[serde(default)]
4088 pub resources: DynamicResources,
4089}
4090
4091#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4093#[serde(deny_unknown_fields)]
4094pub struct DynamicResources {
4095 pub cpu_cores_min: Option<f64>,
4096 pub cpu_cores_max: Option<f64>,
4097 #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4100 #[schema(value_type = Option<String>)]
4101 pub memory_min: Option<ConfigSize>,
4102 #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4105 #[schema(value_type = Option<String>)]
4106 pub memory_max: Option<ConfigSize>,
4107}
4108
4109#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4110#[serde(default)]
4111pub struct ResourceConfig {
4112 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4115 pub cpu_cores_min: Option<f64>,
4116
4117 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4120 pub cpu_cores_max: Option<f64>,
4121
4122 #[serde(
4128 alias = "memory_mb_min",
4129 deserialize_with = "size_memory_min",
4130 skip_serializing_if = "Option::is_none"
4131 )]
4132 #[schema(value_type = Option<String>)]
4133 pub memory_min: Option<ConfigSize>,
4134
4135 #[serde(
4141 alias = "memory_mb_max",
4142 deserialize_with = "size_memory_max",
4143 skip_serializing_if = "Option::is_none"
4144 )]
4145 #[schema(value_type = Option<String>)]
4146 pub memory_max: Option<ConfigSize>,
4147
4148 #[serde(
4155 alias = "storage_mb_min",
4156 deserialize_with = "size_storage_min",
4157 skip_serializing_if = "Option::is_none"
4158 )]
4159 #[schema(value_type = Option<String>)]
4160 pub storage_min: Option<ConfigSize>,
4161
4162 #[serde(
4173 alias = "storage_mb_max",
4174 deserialize_with = "size_storage_max",
4175 skip_serializing_if = "Option::is_none"
4176 )]
4177 #[schema(value_type = Option<String>)]
4178 pub storage_max: Option<ConfigSize>,
4179
4180 #[serde(skip_serializing_if = "Option::is_none")]
4182 pub autoscaling: Option<AutoscalingConfig>,
4183
4184 pub storage_class: Option<String>,
4187
4188 #[serde(skip_serializing_if = "Option::is_none")]
4194 pub volume_attributes_class: Option<String>,
4195
4196 pub service_account_name: Option<String>,
4199
4200 pub namespace: Option<String>,
4208}
4209
4210#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4212#[serde(default)]
4213pub struct AutoscalingConfig {
4214 #[serde(skip_serializing_if = "Option::is_none")]
4216 pub storage: Option<StorageAutoscalingConfig>,
4217}
4218
4219#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4222#[serde(default)]
4223pub struct StorageAutoscalingConfig {
4224 #[serde(
4226 deserialize_with = "crate::serde_via_value::deserialize",
4227 skip_serializing_if = "Option::is_none"
4228 )]
4229 pub scale_threshold: Option<f64>,
4230
4231 #[serde(
4238 alias = "scale_threshold_available_mb",
4239 deserialize_with = "size_scale_threshold_available",
4240 skip_serializing_if = "Option::is_none"
4241 )]
4242 #[schema(value_type = Option<String>)]
4243 pub scale_threshold_available: Option<ConfigSize>,
4244
4245 #[serde(
4247 deserialize_with = "crate::serde_via_value::deserialize",
4248 skip_serializing_if = "Option::is_none"
4249 )]
4250 pub scale_factor: Option<f64>,
4251}
4252
4253#[cfg(test)]
4254mod resource_config_tests {
4255 use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
4256 use crate::size::ConfigSize;
4257 use serde_json::json;
4258
4259 #[test]
4260 fn storage_autoscaling_round_trips_through_json() {
4261 let input = json!({
4262 "storage_min": "1G",
4263 "storage_max": "8G",
4264 "autoscaling": {
4265 "storage": {
4266 "scale_threshold": 0.8,
4267 "scale_threshold_available": "10G",
4268 "scale_factor": 2.0
4269 }
4270 }
4271 });
4272 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4273 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4274 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4275 assert_eq!(
4276 config.autoscaling,
4277 Some(AutoscalingConfig {
4278 storage: Some(StorageAutoscalingConfig {
4279 scale_threshold: Some(0.8),
4280 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4281 scale_factor: Some(2.0),
4282 }),
4283 })
4284 );
4285 let output = serde_json::to_value(&config).unwrap();
4286 assert_eq!(output["storage_min"], json!("1G"));
4287 assert_eq!(
4288 output["autoscaling"]["storage"]["scale_threshold"],
4289 json!(0.8)
4290 );
4291 assert_eq!(
4292 output["autoscaling"]["storage"]["scale_threshold_available"],
4293 json!("10G")
4294 );
4295 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4296 }
4297
4298 #[test]
4299 fn autoscaling_fields_default_to_none() {
4300 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4301 assert_eq!(config.storage_min, None);
4302 assert_eq!(config.autoscaling, None);
4303
4304 let output = serde_json::to_value(&config).unwrap();
4307 assert!(output.get("storage_min").is_none());
4308 assert!(output.get("autoscaling").is_none());
4309 assert!(output.get("storage_max").is_none());
4310
4311 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4313 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4314 let output = serde_json::to_value(&config).unwrap();
4315 assert_eq!(output["autoscaling"], input["autoscaling"]);
4316
4317 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4319 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4320 }
4321
4322 #[test]
4323 fn autoscaling_rejects_non_numeric_values() {
4324 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4325 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4326 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4327 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4328 let input = json!({ "storage_mb_min": -1 });
4329 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4330 }
4331}
4332
4333#[cfg(test)]
4334mod sync_config_tests {
4335 use super::SyncConfig;
4336
4337 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4338 SyncConfig {
4339 bucket: bucket.to_owned(),
4340 read_bucket: read_bucket.map(str::to_owned),
4341 ..Default::default()
4342 }
4343 }
4344
4345 #[test]
4346 fn read_bucket_must_differ_from_bucket() {
4347 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4348 assert!(err.contains("different locations"), "{err}");
4349 }
4350
4351 #[test]
4352 fn read_bucket_must_use_the_same_object_store() {
4353 let err = config("gs://ckpts/a", Some("ckpts/b"))
4354 .validate()
4355 .unwrap_err();
4356 assert!(err.contains("same object store"), "{err}");
4357 let err = config("ckpts/a", Some("gs://ckpts/b"))
4358 .validate()
4359 .unwrap_err();
4360 assert!(err.contains("same object store"), "{err}");
4361 }
4362
4363 #[test]
4364 fn matching_object_stores_are_accepted() {
4365 config("gs://ckpts/a", Some("gs://ckpts/b"))
4366 .validate()
4367 .unwrap();
4368 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4369 config("gs://ckpts/a", None).validate().unwrap();
4370 }
4371
4372 #[test]
4373 fn take_bucket_ownership_defaults_to_false() {
4374 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4375 assert!(!sync.take_bucket_ownership);
4376
4377 let sync: SyncConfig =
4378 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4379 .unwrap();
4380 assert!(sync.take_bucket_ownership);
4381 }
4382}
4383
4384#[cfg(test)]
4385mod transport_metadata_tests {
4386 use super::TransportConfig;
4387 use serde_json::json;
4388
4389 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4390 serde_json::from_value(json!({
4391 "name": "nats_input",
4392 "config": {
4393 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4394 "stream_name": "orders",
4395 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4396 },
4397 }))
4398 .unwrap()
4399 }
4400
4401 #[test]
4402 fn nats_input_exposes_consumer_metadata() {
4403 let mut transport = nats_input(json!({ "team": "ingest" }));
4404 let metadata = transport.transport_metadata_mut().unwrap();
4405 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4406
4407 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4408 let TransportConfig::NatsInput(config) = &transport else {
4409 unreachable!()
4410 };
4411 assert_eq!(
4412 config
4413 .consumer_config
4414 .metadata
4415 .get("pipeline")
4416 .map(String::as_str),
4417 Some("orders_pipeline"),
4418 "writes through the returned map must reach the consumer config"
4419 );
4420 }
4421
4422 #[test]
4423 fn transports_without_metadata_return_none() {
4424 let mut transport: TransportConfig = serde_json::from_value(json!({
4425 "name": "file_input",
4426 "config": { "path": "/tmp/input.csv" },
4427 }))
4428 .unwrap();
4429 assert!(transport.transport_metadata_mut().is_none());
4430 }
4431}