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}
167
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct PipelineIdentity {
172 pub name: String,
174 pub given_name: Option<String>,
176}
177
178impl Display for PipelineIdentity {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 match &self.given_name {
181 Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
182 None => write!(f, "{}", self.name),
183 }
184 }
185}
186
187#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
193pub struct PipelineConfig {
194 #[serde(flatten)]
196 #[schema(inline)]
197 pub global: RuntimeConfig,
198
199 pub multihost: Option<MultihostConfig>,
207
208 pub name: Option<String>,
214
215 pub given_name: Option<String>,
220
221 #[serde(default)]
227 pub storage_config: Option<StorageConfig>,
228
229 pub secrets_dir: Option<String>,
233
234 #[serde(default)]
236 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
237
238 #[serde(default)]
240 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
241
242 #[serde(default)]
244 pub program_ir: Option<ProgramIr>,
245}
246
247impl PipelineConfig {
248 pub fn max_parallel_connector_init(&self) -> u64 {
249 max(
250 self.global
251 .max_parallel_connector_init
252 .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
253 1,
254 )
255 }
256
257 pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
260 PipelineConfigProgramInfo {
261 inputs: self.inputs.clone(),
262 outputs: self.outputs.clone(),
263 program_ir: self.program_ir.clone(),
264 }
265 }
266
267 pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
268 let (storage_config, storage_options) = storage.unzip();
269 Self {
270 global: RuntimeConfig {
271 storage: storage_options,
272 ..self.global
273 },
274 storage_config,
275 ..self
276 }
277 }
278
279 pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
280 let storage_options = self.global.storage.as_ref();
281 let storage_config = self.storage_config.as_ref();
282 storage_config.zip(storage_options)
283 }
284
285 pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
290 self.name.as_ref().map(|name| PipelineIdentity {
291 name: name.clone(),
292 given_name: self.given_name.clone(),
293 })
294 }
295
296 pub fn secrets_dir(&self) -> &Path {
299 match &self.secrets_dir {
300 Some(dir) => Path::new(dir.as_str()),
301 None => default_secrets_directory(),
302 }
303 }
304
305 pub fn display_summary(&self) -> String {
307 let summary = serde_json::json!({
309 "name": self.name,
310 "given_name": self.given_name,
311 "global": self.global,
312 "storage_config": self.storage_config,
313 "secrets_dir": self.secrets_dir,
314 "inputs": self.inputs,
315 "outputs": self.outputs
316 });
317
318 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
319 }
320}
321
322#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
330pub struct PipelineConfigProgramInfo {
331 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
333
334 #[serde(default)]
336 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
337
338 #[serde(default)]
340 pub program_ir: Option<ProgramIr>,
341}
342
343#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
347pub struct MultihostConfig {
348 pub hosts: usize,
354}
355
356impl Default for MultihostConfig {
357 fn default() -> Self {
358 Self { hosts: 1 }
359 }
360}
361
362#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
364pub struct StorageConfig {
365 pub path: String,
374
375 #[serde(default)]
377 pub cache: StorageCacheConfig,
378}
379
380impl StorageConfig {
381 pub fn path(&self) -> &Path {
382 Path::new(&self.path)
383 }
384}
385
386#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
388#[serde(rename_all = "snake_case")]
389pub enum StorageCacheConfig {
390 #[default]
395 PageCache,
396
397 FelderaCache,
402}
403
404impl StorageCacheConfig {
405 #[cfg(unix)]
406 pub fn to_custom_open_flags(&self) -> i32 {
407 match self {
408 StorageCacheConfig::PageCache => (),
409 StorageCacheConfig::FelderaCache => {
410 #[cfg(target_os = "linux")]
411 return libc::O_DIRECT;
412 }
413 }
414 0
415 }
416}
417
418#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
420#[serde(default)]
421pub struct StorageOptions {
422 pub backend: StorageBackendConfig,
424
425 #[serde(
439 alias = "min_storage_bytes",
440 deserialize_with = "size_min_spill_size",
441 skip_serializing_if = "Option::is_none"
442 )]
443 #[schema(value_type = Option<String>)]
444 pub min_spill_size: Option<ConfigSize>,
445
446 #[serde(
460 alias = "min_step_storage_bytes",
461 deserialize_with = "size_min_step_spill_size",
462 skip_serializing_if = "Option::is_none"
463 )]
464 #[schema(value_type = Option<String>)]
465 pub min_step_spill_size: Option<ConfigSize>,
466
467 pub compression: StorageCompression,
473
474 pub compression_level: Option<i32>,
485
486 #[serde(
495 alias = "cache_mib",
496 deserialize_with = "size_cache_size",
497 skip_serializing_if = "Option::is_none"
498 )]
499 #[schema(value_type = Option<String>)]
500 pub cache_size: Option<ConfigSize>,
501
502 #[serde(skip_serializing_if = "Option::is_none")]
517 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
518 pub bloom_false_positive_rate: Option<f64>,
519}
520
521impl Eq for StorageOptions {}
524
525#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
527#[serde(tag = "name", content = "config", rename_all = "snake_case")]
528pub enum StorageBackendConfig {
529 #[default]
533 Default,
534
535 File(Box<FileBackendConfig>),
539
540 Object(ObjectStorageConfig),
542}
543
544impl Display for StorageBackendConfig {
545 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
546 match self {
547 StorageBackendConfig::Default => write!(f, "default"),
548 StorageBackendConfig::File(_) => write!(f, "file"),
549 StorageBackendConfig::Object(_) => write!(f, "object"),
550 }
551 }
552}
553
554#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
556#[serde(rename_all = "snake_case")]
557pub enum StorageCompression {
558 #[default]
563 Default,
564
565 None,
567
568 Snappy,
570
571 Lz4,
576
577 Zstd,
583}
584
585#[derive(Debug, Clone, Eq, PartialEq)]
586pub enum StartFromCheckpoint {
587 Latest,
588 Uuid(uuid::Uuid),
589}
590
591impl ToSchema<'_> for StartFromCheckpoint {
592 fn schema() -> (
593 &'static str,
594 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
595 ) {
596 (
597 "StartFromCheckpoint",
598 utoipa::openapi::RefOr::T(Schema::OneOf(
599 OneOfBuilder::new()
600 .item(
601 ObjectBuilder::new()
602 .schema_type(SchemaType::String)
603 .enum_values(Some(["latest"].into_iter()))
604 .build(),
605 )
606 .item(
607 ObjectBuilder::new()
608 .schema_type(SchemaType::String)
609 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
610 utoipa::openapi::KnownFormat::Uuid,
611 )))
612 .build(),
613 )
614 .nullable(true)
615 .build(),
616 )),
617 )
618 }
619}
620
621impl<'de> Deserialize<'de> for StartFromCheckpoint {
622 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
623 where
624 D: Deserializer<'de>,
625 {
626 struct StartFromCheckpointVisitor;
627
628 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
629 type Value = StartFromCheckpoint;
630
631 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
632 formatter.write_str("a UUID string or the string \"latest\"")
633 }
634
635 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
636 where
637 E: de::Error,
638 {
639 if value == "latest" {
640 Ok(StartFromCheckpoint::Latest)
641 } else {
642 uuid::Uuid::parse_str(value)
643 .map(StartFromCheckpoint::Uuid)
644 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
645 }
646 }
647 }
648
649 deserializer.deserialize_str(StartFromCheckpointVisitor)
650 }
651}
652
653impl Serialize for StartFromCheckpoint {
654 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
655 where
656 S: serde::Serializer,
657 {
658 match self {
659 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
660 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
661 }
662 }
663}
664
665#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
666pub struct SyncConfig {
667 pub endpoint: Option<String>,
677
678 pub bucket: String,
687
688 pub region: Option<String>,
692
693 pub provider: Option<String>,
700
701 pub access_key: Option<String>,
707
708 pub secret_key: Option<String>,
714
715 pub start_from_checkpoint: Option<StartFromCheckpoint>,
720
721 #[schema(default = std::primitive::bool::default)]
727 #[serde(default)]
728 pub fail_if_no_checkpoint: bool,
729
730 pub transfers: Option<u8>,
733
734 pub checkers: Option<u8>,
737
738 pub ignore_checksum: Option<bool>,
742
743 pub multi_thread_streams: Option<u8>,
746
747 pub multi_thread_cutoff: Option<String>,
752
753 #[schema(default = default_optimize_download_resources)]
764 #[serde(default = "default_optimize_download_resources")]
765 pub optimize_download_resources: bool,
766
767 pub upload_concurrency: Option<u8>,
770
771 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
773 #[schema(default = std::primitive::bool::default)]
774 #[serde(default)]
775 pub standby: bool,
776
777 #[serde(
783 default,
784 alias = "pull_interval",
785 deserialize_with = "duration_standby_pull_interval",
786 skip_serializing_if = "Option::is_none"
787 )]
788 #[schema(value_type = Option<String>, default = default_pull_interval)]
789 pub standby_pull_interval: Option<ConfigDuration>,
790
791 #[serde(
797 default,
798 alias = "push_interval",
799 deserialize_with = "duration_checkpoint_push_interval",
800 skip_serializing_if = "Option::is_none"
801 )]
802 #[schema(value_type = Option<String>)]
803 pub checkpoint_push_interval: Option<ConfigDuration>,
804
805 pub flags: Option<Vec<String>>,
814
815 #[schema(default = default_retention_min_count)]
820 #[serde(default = "default_retention_min_count")]
821 pub retention_min_count: u32,
822
823 #[serde(
827 default,
828 alias = "retention_min_age",
829 deserialize_with = "duration_min_retention",
830 skip_serializing_if = "Option::is_none"
831 )]
832 #[schema(value_type = Option<String>, default = default_retention_min_age)]
833 pub min_retention: Option<ConfigDuration>,
834
835 #[serde(default)]
848 pub read_bucket: Option<String>,
849
850 #[schema(default = std::primitive::bool::default)]
876 #[serde(default)]
877 pub take_bucket_ownership: bool,
878}
879
880fn default_retention_min_count() -> u32 {
881 10
882}
883
884fn default_optimize_download_resources() -> bool {
885 true
886}
887
888impl SyncConfig {
889 pub fn standby_pull_interval(&self) -> ConfigDuration {
896 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
897 }
898
899 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
901 self.checkpoint_push_interval
902 }
903
904 pub fn min_retention(&self) -> ConfigDuration {
907 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
908 }
909
910 pub fn validate(&self) -> Result<(), String> {
911 #[allow(deprecated)]
912 if self.standby {
913 return Err(
914 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
915 );
916 }
917
918 if let Some(ref rb) = self.read_bucket {
919 if rb == &self.bucket {
920 return Err(
921 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
922 .to_owned(),
923 );
924 }
925 if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
928 return Err(format!(
929 "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",
930 self.bucket, rb
931 ));
932 }
933 }
934
935 Ok(())
936 }
937}
938
939fn is_gcs_bucket(bucket: &str) -> bool {
941 bucket.starts_with("gs://")
942}
943
944#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
971pub struct PipelineTemplateConfig {
972 pub name: String,
974 #[schema(default = default_pipeline_template_key)]
978 #[serde(default = "default_pipeline_template_key")]
979 pub key: String,
980}
981
982fn default_pipeline_template_key() -> String {
983 "pipelineTemplate".to_string()
984}
985
986#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
987pub struct ObjectStorageConfig {
988 pub url: String,
1017
1018 #[serde(flatten)]
1051 pub other_options: BTreeMap<String, String>,
1052}
1053
1054#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1056#[serde(default)]
1057pub struct FileBackendConfig {
1058 pub async_threads: Option<bool>,
1064
1065 #[serde(
1070 default,
1071 alias = "ioop_delay",
1072 deserialize_with = "duration_ioop_latency",
1073 skip_serializing_if = "Option::is_none"
1074 )]
1075 #[schema(value_type = Option<String>)]
1076 pub ioop_latency: Option<ConfigDuration>,
1077
1078 pub sync: Option<SyncConfig>,
1080
1081 pub sync_mode: Option<StorageSyncMode>,
1086}
1087
1088#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1094#[serde(rename_all = "snake_case")]
1095pub enum StorageSyncMode {
1096 #[default]
1099 Auto,
1100
1101 Syncfs,
1111
1112 PerFile,
1117}
1118
1119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1122#[serde(default)]
1123pub struct RuntimeConfig {
1124 pub workers: u16,
1134
1135 #[serde(
1163 default,
1164 alias = "max_rss_mb",
1165 deserialize_with = "size_max_rss",
1166 skip_serializing_if = "Option::is_none"
1167 )]
1168 #[schema(value_type = Option<String>)]
1169 pub max_rss: Option<ConfigSize>,
1170
1171 #[serde(
1194 default,
1195 alias = "datafusion_memory_mb",
1196 deserialize_with = "size_datafusion_memory",
1197 skip_serializing_if = "Option::is_none"
1198 )]
1199 #[schema(value_type = Option<String>)]
1200 pub datafusion_memory: Option<ConfigSize>,
1201
1202 pub hosts: usize,
1209
1210 #[serde(deserialize_with = "deserialize_storage_options")]
1222 pub storage: Option<StorageOptions>,
1223
1224 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1226 pub fault_tolerance: FtConfig,
1227
1228 pub cpu_profiler: bool,
1232
1233 pub tracing: bool,
1235
1236 pub tracing_endpoint_jaeger: String,
1238
1239 pub min_batch_size_records: u64,
1247
1248 #[serde(
1251 default,
1252 alias = "max_buffering_delay_usecs",
1253 deserialize_with = "duration_max_buffering_delay",
1254 skip_serializing_if = "Option::is_none"
1255 )]
1256 #[schema(value_type = Option<String>)]
1257 pub max_buffering_delay: Option<ConfigDuration>,
1258
1259 pub resources: ResourceConfig,
1262
1263 #[serde(
1273 default,
1274 alias = "clock_resolution_usecs",
1275 deserialize_with = "duration_clock_resolution",
1276 skip_serializing_if = "Option::is_none"
1277 )]
1278 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1279 pub clock_resolution: Option<ConfigDuration>,
1280
1281 #[schema(value_type = Option<String>, example = "+05:30")]
1292 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1293
1294 pub pin_cpus: Vec<usize>,
1303
1304 #[serde(
1307 default,
1308 alias = "provisioning_timeout_secs",
1309 deserialize_with = "duration_provisioning_timeout",
1310 skip_serializing_if = "Option::is_none"
1311 )]
1312 #[schema(value_type = Option<String>)]
1313 pub provisioning_timeout: Option<ConfigDuration>,
1314
1315 pub max_parallel_connector_init: Option<u64>,
1326
1327 pub init_containers: Option<serde_json::Value>,
1329
1330 pub checkpoint_during_suspend: bool,
1332
1333 pub http_workers: Option<u64>,
1341
1342 pub io_workers: Option<u64>,
1353
1354 #[serde(default)]
1361 pub env: BTreeMap<String, String>,
1362
1363 pub dev_tweaks: DevTweaks,
1365
1366 pub logging: Option<String>,
1375
1376 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1384}
1385
1386fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1388where
1389 D: Deserializer<'de>,
1390{
1391 struct BoolOrStruct;
1392
1393 impl<'de> Visitor<'de> for BoolOrStruct {
1394 type Value = Option<StorageOptions>;
1395
1396 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1397 formatter.write_str("boolean or StorageOptions")
1398 }
1399
1400 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1401 where
1402 E: de::Error,
1403 {
1404 match v {
1405 false => Ok(None),
1406 true => Ok(Some(StorageOptions::default())),
1407 }
1408 }
1409
1410 fn visit_unit<E>(self) -> Result<Self::Value, E>
1411 where
1412 E: de::Error,
1413 {
1414 Ok(None)
1415 }
1416
1417 fn visit_none<E>(self) -> Result<Self::Value, E>
1418 where
1419 E: de::Error,
1420 {
1421 Ok(None)
1422 }
1423
1424 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1425 where
1426 M: MapAccess<'de>,
1427 {
1428 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1429 }
1430 }
1431
1432 deserializer.deserialize_any(BoolOrStruct)
1433}
1434
1435fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1443where
1444 D: Deserializer<'de>,
1445{
1446 struct StringOrStruct;
1447
1448 impl<'de> Visitor<'de> for StringOrStruct {
1449 type Value = FtConfig;
1450
1451 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1452 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1453 }
1454
1455 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1456 where
1457 E: de::Error,
1458 {
1459 match v {
1460 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1461 model: Some(FtModel::default()),
1462 ..FtConfig::default()
1463 }),
1464 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1465 }
1466 }
1467
1468 fn visit_unit<E>(self) -> Result<Self::Value, E>
1469 where
1470 E: de::Error,
1471 {
1472 Ok(FtConfig::default())
1473 }
1474
1475 fn visit_none<E>(self) -> Result<Self::Value, E>
1476 where
1477 E: de::Error,
1478 {
1479 Ok(FtConfig::default())
1480 }
1481
1482 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1483 where
1484 M: MapAccess<'de>,
1485 {
1486 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1487 }
1488 }
1489
1490 deserializer.deserialize_any(StringOrStruct)
1491}
1492
1493impl Default for RuntimeConfig {
1494 fn default() -> Self {
1495 Self {
1496 workers: 8,
1497 max_rss: None,
1498 datafusion_memory: None,
1499 hosts: 1,
1500 storage: Some(StorageOptions::default()),
1501 fault_tolerance: FtConfig::default(),
1502 cpu_profiler: true,
1503 tracing: {
1504 false
1507 },
1508 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1509 min_batch_size_records: 0,
1510 max_buffering_delay: None,
1511 resources: ResourceConfig::default(),
1512 clock_resolution: None,
1513 clock_timezone_offset: None,
1514 pin_cpus: Vec::new(),
1515 provisioning_timeout: None,
1516 max_parallel_connector_init: None,
1517 init_containers: None,
1518 checkpoint_during_suspend: true,
1519 io_workers: None,
1520 http_workers: None,
1521 env: BTreeMap::default(),
1522 dev_tweaks: DevTweaks::default(),
1523 logging: None,
1524 pipeline_template_configmap: None,
1525 }
1526 }
1527}
1528
1529pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1533
1534pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1537
1538impl RuntimeConfig {
1539 pub fn max_buffering_delay(&self) -> ConfigDuration {
1541 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1542 }
1543
1544 pub fn clock_resolution(&self) -> ConfigDuration {
1546 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1547 }
1548
1549 pub fn effective_memory(&self) -> Option<ConfigSize> {
1552 self.max_rss.or(self.resources.memory_max)
1553 }
1554
1555 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1560 if let Some(explicit) = self.datafusion_memory {
1561 return Some(explicit);
1562 }
1563 let effective = self.effective_memory()?.as_bytes();
1564 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1566 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1567 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1568 }
1569}
1570
1571#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1582#[serde(rename_all = "snake_case")]
1583pub struct FtConfig {
1584 #[serde(with = "none_as_string")]
1586 #[serde(default = "default_model")]
1587 #[schema(
1588 schema_with = none_as_string_schema::<FtModel>,
1589 )]
1590 pub model: Option<FtModel>,
1591
1592 #[serde(
1599 default,
1600 alias = "checkpoint_interval_secs",
1601 deserialize_with = "duration_checkpoint_interval",
1602 skip_serializing_if = "Option::is_none"
1603 )]
1604 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1605 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1606}
1607
1608fn default_model() -> Option<FtModel> {
1609 Some(FtModel::default())
1610}
1611
1612pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1632 use crate::duration::LegacyUnit;
1633 use serde_json::{Map, Value};
1634
1635 struct Rule {
1637 new: &'static str,
1638 old: &'static str,
1639 unit: LegacyUnit,
1640 max: u64,
1642 null_allowed: bool,
1645 }
1646 const fn rule(
1647 new: &'static str,
1648 old: &'static str,
1649 unit: LegacyUnit,
1650 max: u64,
1651 null_allowed: bool,
1652 ) -> Rule {
1653 Rule {
1654 new,
1655 old,
1656 unit,
1657 max,
1658 null_allowed,
1659 }
1660 }
1661 const U32: u64 = u32::MAX as u64;
1662 const U64: u64 = u64::MAX;
1663 use LegacyUnit::{Days, Micros, Millis, Secs};
1664
1665 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1666 for rule in rules {
1667 let Some(value) = object.remove(rule.new) else {
1668 continue;
1669 };
1670 let legacy = match &value {
1671 Value::String(text) => match text.parse::<ConfigDuration>() {
1672 Ok(duration) => {
1673 let nanos = std::time::Duration::from(duration).as_nanos();
1674 let unit_nanos = u128::from(rule.unit.nanos());
1675 let whole = nanos.div_ceil(unit_nanos);
1676 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1677 }
1678 Err(_) => {
1679 object.insert(rule.new.to_string(), value);
1680 continue;
1681 }
1682 },
1683 Value::Null if !rule.null_allowed => continue,
1684 other => other.clone(),
1686 };
1687 object.insert(rule.old.to_string(), legacy);
1688 }
1689 }
1690 fn child<'a>(
1691 object: &'a mut Map<String, Value>,
1692 key: &str,
1693 ) -> Option<&'a mut Map<String, Value>> {
1694 object.get_mut(key).and_then(Value::as_object_mut)
1695 }
1696 fn max_expiry(consumer: &mut Map<String, Value>) {
1699 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1700 return;
1701 };
1702 let Ok(duration) = text.parse::<ConfigDuration>() else {
1703 return;
1704 };
1705 let duration = std::time::Duration::from(duration);
1706 consumer.remove("max_expiry");
1707 consumer.insert(
1708 "max_expires".to_string(),
1709 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1710 );
1711 }
1712 fn nats_connection(transport: &mut Map<String, Value>) {
1714 if let Some(connection) = child(transport, "connection_config") {
1715 apply(
1716 connection,
1717 &[
1718 rule(
1719 "connection_timeout",
1720 "connection_timeout_secs",
1721 Secs,
1722 U64,
1723 false,
1724 ),
1725 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1726 ],
1727 );
1728 }
1729 }
1730 fn connector(endpoint: &mut Map<String, Value>) {
1732 apply(
1733 endpoint,
1734 &[rule(
1735 "max_output_buffer_time",
1736 "max_output_buffer_time_millis",
1737 Millis,
1738 U64,
1739 false,
1740 )],
1741 );
1742 let name = endpoint
1743 .get("transport")
1744 .and_then(|transport| transport.get("name"))
1745 .and_then(Value::as_str)
1746 .map(str::to_string);
1747 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1748 match name.as_deref() {
1749 Some("url_input") => apply(
1750 transport,
1751 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1752 ),
1753 Some("kafka_input") => apply(
1754 transport,
1755 &[rule(
1756 "group_join_timeout",
1757 "group_join_timeout_secs",
1758 Secs,
1759 U32,
1760 false,
1761 )],
1762 ),
1763 Some("kafka_output") => apply(
1764 transport,
1765 &[rule(
1766 "initialization_timeout",
1767 "initialization_timeout_secs",
1768 Secs,
1769 U32,
1770 false,
1771 )],
1772 ),
1773 Some("clock_input") => apply(
1774 transport,
1775 &[rule(
1776 "clock_resolution",
1777 "clock_resolution_usecs",
1778 Micros,
1779 U64,
1780 false,
1781 )],
1782 ),
1783 Some("pub_sub_input") => apply(
1784 transport,
1785 &[
1786 rule("timeout", "timeout_seconds", Secs, U32, true),
1787 rule(
1788 "connect_timeout",
1789 "connect_timeout_seconds",
1790 Secs,
1791 U32,
1792 true,
1793 ),
1794 ],
1795 ),
1796 Some("nats_input") => {
1797 apply(
1798 transport,
1799 &[
1800 rule(
1801 "inactivity_timeout",
1802 "inactivity_timeout_secs",
1803 Secs,
1804 U64,
1805 false,
1806 ),
1807 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1808 ],
1809 );
1810 nats_connection(transport);
1811 if let Some(consumer) = child(transport, "consumer_config") {
1812 max_expiry(consumer);
1813 }
1814 }
1815 Some("nats_output") => {
1816 apply(
1817 transport,
1818 &[rule(
1819 "publish_timeout",
1820 "publish_timeout_secs",
1821 Secs,
1822 U64,
1823 false,
1824 )],
1825 );
1826 nats_connection(transport);
1827 }
1828 _ => {}
1829 }
1830 }
1831 let is_avro = endpoint
1832 .get("format")
1833 .and_then(|format| format.get("name"))
1834 .and_then(Value::as_str)
1835 == Some("avro");
1836 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1837 {
1838 apply(
1839 format,
1840 &[rule(
1841 "registry_timeout",
1842 "registry_timeout_secs",
1843 Secs,
1844 U64,
1845 true,
1846 )],
1847 );
1848 }
1849 }
1850
1851 let Some(global) = config.as_object_mut() else {
1852 return;
1853 };
1854 apply(
1855 global,
1856 &[
1857 rule(
1858 "clock_resolution",
1859 "clock_resolution_usecs",
1860 Micros,
1861 U64,
1862 true,
1863 ),
1864 rule(
1865 "max_buffering_delay",
1866 "max_buffering_delay_usecs",
1867 Micros,
1868 U64,
1869 false,
1870 ),
1871 rule(
1872 "provisioning_timeout",
1873 "provisioning_timeout_secs",
1874 Secs,
1875 U64,
1876 true,
1877 ),
1878 ],
1879 );
1880 if let Some(ft) = child(global, "fault_tolerance") {
1881 apply(
1883 ft,
1884 &[rule(
1885 "checkpoint_interval",
1886 "checkpoint_interval_secs",
1887 Secs,
1888 U64,
1889 true,
1890 )],
1891 );
1892 }
1893 let backend = child(global, "storage")
1894 .and_then(|storage| child(storage, "backend"))
1895 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1896 .and_then(|backend| child(backend, "config"));
1897 if let Some(file) = backend {
1898 apply(
1899 file,
1900 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1901 );
1902 if let Some(sync) = child(file, "sync") {
1903 apply(
1904 sync,
1905 &[
1906 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1907 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1908 rule("min_retention", "retention_min_age", Days, U32, false),
1909 ],
1910 );
1911 }
1912 }
1913 for endpoints in ["inputs", "outputs"] {
1914 if let Some(endpoints) = child(global, endpoints) {
1915 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1916 connector(endpoint);
1917 }
1918 }
1919 }
1920}
1921
1922#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1928pub struct LegacySpelling {
1929 pub durations: bool,
1931 pub sizes: bool,
1933}
1934
1935impl LegacySpelling {
1936 pub const NONE: LegacySpelling = LegacySpelling {
1938 durations: false,
1939 sizes: false,
1940 };
1941
1942 pub fn any(self) -> bool {
1944 self.durations || self.sizes
1945 }
1946
1947 pub fn apply(self, config: &mut serde_json::Value) {
1950 if self.durations {
1951 to_legacy_duration_spelling(config);
1952 }
1953 if self.sizes {
1954 to_legacy_size_spelling(config);
1955 }
1956 }
1957}
1958
1959pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
1970 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
1971 use serde_json::{Map, Value};
1972
1973 struct Rule {
1975 new: &'static str,
1976 old: &'static str,
1977 unit: LegacySizeUnit,
1978 }
1979 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
1980 Rule { new, old, unit }
1981 }
1982
1983 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1984 for rule in rules {
1985 let Some(value) = object.remove(rule.new) else {
1986 continue;
1987 };
1988 let legacy = match &value {
1989 Value::String(text) => match text.parse::<ConfigSize>() {
1990 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
1991 Err(_) => {
1992 object.insert(rule.new.to_string(), value);
1993 continue;
1994 }
1995 },
1996 Value::Null => continue,
1998 other => other.clone(),
2000 };
2001 object.insert(rule.old.to_string(), legacy);
2002 }
2003 }
2004 fn child<'a>(
2005 object: &'a mut Map<String, Value>,
2006 key: &str,
2007 ) -> Option<&'a mut Map<String, Value>> {
2008 object.get_mut(key).and_then(Value::as_object_mut)
2009 }
2010 fn connector(endpoint: &mut Map<String, Value>) {
2012 apply(
2013 endpoint,
2014 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2015 );
2016 let name = endpoint
2017 .get("transport")
2018 .and_then(|transport| transport.get("name"))
2019 .and_then(Value::as_str)
2020 .map(str::to_string);
2021 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2022 match name.as_deref() {
2023 Some("file_input") => apply(
2024 transport,
2025 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2026 ),
2027 Some("dynamodb_output" | "postgres_output") => apply(
2028 transport,
2029 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2030 ),
2031 Some("postgres_cdc_input") => {
2032 if let Some(batch) = child(transport, "batch") {
2033 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2034 }
2035 }
2036 _ => {}
2037 }
2038 }
2039 }
2040
2041 let Some(global) = config.as_object_mut() else {
2042 return;
2043 };
2044 apply(
2045 global,
2046 &[
2047 rule("max_rss", "max_rss_mb", Megabytes),
2048 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2049 ],
2050 );
2051 if let Some(storage) = child(global, "storage") {
2052 apply(
2053 storage,
2054 &[
2055 rule("cache_size", "cache_mib", Mebibytes),
2056 rule("min_spill_size", "min_storage_bytes", Bytes),
2057 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2058 ],
2059 );
2060 }
2061 if let Some(resources) = child(global, "resources") {
2062 apply(
2063 resources,
2064 &[
2065 rule("memory_min", "memory_mb_min", Megabytes),
2066 rule("memory_max", "memory_mb_max", Megabytes),
2067 rule("storage_min", "storage_mb_min", Megabytes),
2068 rule("storage_max", "storage_mb_max", Megabytes),
2069 ],
2070 );
2071 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2072 apply(
2073 storage,
2074 &[rule(
2075 "scale_threshold_available",
2076 "scale_threshold_available_mb",
2077 Megabytes,
2078 )],
2079 );
2080 }
2081 }
2082 if let Some(tweaks) = child(global, "dev_tweaks") {
2083 apply(
2084 tweaks,
2085 &[
2086 rule("storage_max", "storage_mb_max", Mebibytes),
2087 rule(
2088 "fbuf_slab_size_per_class",
2089 "fbuf_slab_bytes_per_class",
2090 Bytes,
2091 ),
2092 rule(
2093 "lazy_input_map_key_block_size",
2094 "lazy_input_map_key_block_bytes",
2095 Bytes,
2096 ),
2097 rule(
2098 "exchange_channel_capacity",
2099 "exchange_channel_capacity_bytes",
2100 Bytes,
2101 ),
2102 ],
2103 );
2104 }
2105 for endpoints in ["inputs", "outputs"] {
2106 if let Some(endpoints) = child(global, endpoints) {
2107 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2108 connector(endpoint);
2109 }
2110 }
2111 }
2112}
2113
2114#[cfg(test)]
2115mod test {
2116 use super::deserialize_fault_tolerance;
2117 use crate::config::{
2118 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2119 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2120 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2121 StorageOptions, SyncConfig, TransportConfig,
2122 };
2123 use crate::duration::ConfigDuration;
2124 use crate::size::ConfigSize;
2125 use serde::{Deserialize, Serialize};
2126 use serde_json::json;
2127 use std::time::Duration;
2128
2129 fn assert_reloads<T>(value: serde_json::Value)
2132 where
2133 T: Serialize + for<'de> Deserialize<'de>,
2134 {
2135 let first: T = serde_json::from_value(value.clone())
2136 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2137 let written = serde_json::to_value(&first).unwrap();
2138 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2139 panic!("{value} is written as {written}, which does not load: {e}")
2140 });
2141 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2142 }
2143
2144 #[test]
2149 fn size_settings_reload_from_what_is_written() {
2150 use crate::transport::dynamodb::DynamoDBWriterConfig;
2151 use crate::transport::file::FileInputConfig;
2152 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2153
2154 for number in [0u64, 1, 1_100, u64::MAX] {
2157 assert_reloads::<RuntimeConfig>(json!({
2158 "max_rss_mb": number,
2159 "datafusion_memory_mb": number,
2160 "storage": {"cache_mib": number, "min_storage_bytes": number},
2161 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2162 "dev_tweaks": {"storage_mb_max": number},
2163 }));
2164 }
2165
2166 let max = format!("{}B", u64::MAX);
2167 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2168 assert_reloads::<RuntimeConfig>(json!({
2169 "max_rss": size,
2170 "datafusion_memory": size,
2171 "storage": {
2172 "cache_size": size,
2173 "min_spill_size": size,
2174 "min_step_spill_size": size,
2175 },
2176 "resources": {
2177 "memory_min": size,
2178 "memory_max": size,
2179 "storage_min": size,
2180 "storage_max": size,
2181 "autoscaling": {"storage": {"scale_threshold_available": size}},
2182 },
2183 "dev_tweaks": {
2184 "storage_max": size,
2185 "fbuf_slab_size_per_class": size,
2186 "exchange_channel_capacity": size,
2187 },
2188 }));
2189 assert_reloads::<ConnectorConfig>(json!({
2190 "transport": {
2191 "name": "file_input",
2192 "config": {"path": "input.csv", "buffer_size": size},
2193 },
2194 "max_queued_size": size,
2195 }));
2196 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2197 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2198 assert_reloads::<PostgresWriterConfig>(json!({
2199 "uri": "postgres://localhost/db",
2200 "table": "t",
2201 "max_buffer_size": size,
2202 }));
2203 assert_reloads::<DynamoDBWriterConfig>(json!({
2204 "table": "t",
2205 "region": "us-east-1",
2206 "max_buffer_size": size,
2207 }));
2208 }
2209 }
2210
2211 #[test]
2216 fn soft_delete_is_backward_compatible() {
2217 let config: ConnectorConfig = serde_json::from_value(json!({
2218 "transport": {"name": "empty_input"}
2219 }))
2220 .unwrap();
2221 assert!(!config.soft_delete);
2222
2223 let serialized = serde_json::to_value(&config).unwrap();
2224 assert_eq!(serialized.get("soft_delete"), None);
2225
2226 let config: ConnectorConfig = serde_json::from_value(json!({
2227 "transport": {"name": "empty_input"},
2228 "soft_delete": true
2229 }))
2230 .unwrap();
2231 assert!(config.soft_delete);
2232 assert_eq!(
2233 serde_json::to_value(&config).unwrap().get("soft_delete"),
2234 Some(&json!(true))
2235 );
2236 }
2237
2238 #[test]
2241 fn soft_delete_invalidates_checkpointed_connector_state() {
2242 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2243 let mut soft_delete = config.clone();
2244 soft_delete.soft_delete = true;
2245
2246 assert!(config.equal_for_input_checkpoint_replay(&config));
2247 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2248 }
2249
2250 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2251 PipelineConfig {
2252 global: RuntimeConfig::default(),
2253 multihost: None,
2254 name: name.map(str::to_string),
2255 given_name: None,
2256 storage_config: None,
2257 secrets_dir: None,
2258 inputs: Default::default(),
2259 outputs: Default::default(),
2260 program_ir: None,
2261 }
2262 }
2263
2264 #[test]
2265 fn pipeline_identity_uses_system_and_given_names() {
2266 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2267 config.given_name = Some("my-pipeline".to_string());
2268
2269 let metadata = config.pipeline_identity().unwrap();
2270 assert_eq!(
2271 metadata.name,
2272 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2273 );
2274 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2275 }
2276
2277 #[test]
2278 fn pipeline_identity_is_none_without_system_name() {
2279 assert_eq!(config_with_name(None).pipeline_identity(), None);
2280 }
2281
2282 #[test]
2283 fn resolved_datafusion_memory_explicit_passes_through() {
2284 let config = RuntimeConfig {
2285 max_rss: Some(ConfigSize::from_mb(8_000)),
2286 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2287 ..Default::default()
2288 };
2289 assert_eq!(
2290 config.resolved_datafusion_memory(),
2291 Some(ConfigSize::from_mb(1_500))
2292 );
2293 }
2294
2295 #[test]
2296 fn resolved_datafusion_memory_unconfigured_returns_none() {
2297 let config = RuntimeConfig::default();
2298 assert!(config.max_rss.is_none());
2299 assert!(config.resources.memory_max.is_none());
2300 assert_eq!(config.resolved_datafusion_memory(), None);
2301 }
2302
2303 #[test]
2304 fn resolved_datafusion_memory_small_budget_scales_down() {
2305 let config = RuntimeConfig {
2307 max_rss: Some(ConfigSize::from_mb(256)),
2308 ..Default::default()
2309 };
2310 assert_eq!(
2311 config.resolved_datafusion_memory(),
2312 Some(ConfigSize::from_bytes(12_800_000))
2313 );
2314
2315 let config = RuntimeConfig {
2316 max_rss: Some(ConfigSize::from_mb(512)),
2317 ..Default::default()
2318 };
2319 assert_eq!(
2320 config.resolved_datafusion_memory(),
2321 Some(ConfigSize::from_bytes(25_600_000))
2322 );
2323 }
2324
2325 #[test]
2326 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2327 let config = RuntimeConfig {
2329 max_rss: Some(ConfigSize::from_mb(64_000)),
2330 ..Default::default()
2331 };
2332 assert_eq!(
2333 config.resolved_datafusion_memory(),
2334 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2335 );
2336 }
2337
2338 #[test]
2339 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2340 let config = RuntimeConfig {
2342 max_rss: Some(ConfigSize::from_mb(16_000)),
2343 ..Default::default()
2344 };
2345 assert_eq!(
2346 config.resolved_datafusion_memory(),
2347 Some(ConfigSize::from_mb(800))
2348 );
2349 }
2350
2351 #[test]
2352 fn resolved_datafusion_memory_falls_back_to_resources() {
2353 let config = RuntimeConfig {
2355 max_rss: None,
2356 resources: ResourceConfig {
2357 memory_max: Some(ConfigSize::from_mb(16_000)),
2358 ..Default::default()
2359 },
2360 ..Default::default()
2361 };
2362 assert_eq!(
2363 config.resolved_datafusion_memory(),
2364 Some(ConfigSize::from_mb(800))
2365 );
2366 }
2367
2368 #[test]
2369 fn ft_config() {
2370 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2371 #[serde(default)]
2372 struct Wrapper {
2373 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2374 config: FtConfig,
2375 }
2376
2377 for s in [
2380 "{}",
2381 r#"{"config": null}"#,
2382 r#"{"config": {"model": "none"}}"#,
2383 ] {
2384 let config: Wrapper = serde_json::from_str(s).unwrap();
2385 assert_eq!(config.config.model, None);
2386 assert_eq!(config.config.checkpoint_interval(), None);
2387 }
2388
2389 let s = serde_json::to_string(&Wrapper {
2391 config: FtConfig::default(),
2392 })
2393 .unwrap();
2394 assert!(s.contains("\"none\""));
2395
2396 for s in [
2399 r#"{}"#,
2400 r#"{"checkpoint_interval": "60s"}"#,
2401 r#"{"checkpoint_interval_secs": 60}"#,
2402 ] {
2403 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2404 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2405 assert_eq!(
2406 config.checkpoint_interval(),
2407 Some(Duration::from_secs(60)),
2408 "parsing {s}"
2409 );
2410 }
2411
2412 for s in [
2415 r#"{"checkpoint_interval": null}"#,
2416 r#"{"checkpoint_interval_secs": null}"#,
2417 ] {
2418 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2419 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2420 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2421 }
2422
2423 let error = serde_json::from_str::<FtConfig>(
2426 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2427 )
2428 .unwrap_err()
2429 .to_string();
2430 assert!(error.contains("duplicate field"), "{error}");
2431
2432 for (json, expected_secs) in [
2434 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2435 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2436 ] {
2437 assert_eq!(
2438 serde_json::from_str::<FtConfig>(json)
2439 .unwrap()
2440 .checkpoint_interval(),
2441 Some(Duration::from_secs(expected_secs)),
2442 "parsing {json}"
2443 );
2444 }
2445 }
2446
2447 #[test]
2451 fn legacy_duration_spelling_uses_the_older_keys() {
2452 let mut config = serde_json::json!({
2453 "workers": 2,
2454 "clock_resolution": "250ms",
2455 "max_buffering_delay": "3ms",
2456 "provisioning_timeout": "15m",
2457 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2458 "storage": {"backend": {"name": "file", "config": {
2459 "ioop_latency": "5ms",
2460 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2461 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2462 });
2463 super::to_legacy_duration_spelling(&mut config);
2464 assert_eq!(
2465 config,
2466 serde_json::json!({
2467 "workers": 2,
2468 "clock_resolution_usecs": 250_000,
2469 "max_buffering_delay_usecs": 3_000,
2470 "provisioning_timeout_secs": 900,
2471 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2472 "storage": {"backend": {"name": "file", "config": {
2473 "ioop_delay": 5,
2474 "sync": {"bucket": "b", "pull_interval": 10,
2475 "push_interval": 3_600, "retention_min_age": 30}}}},
2476 })
2477 );
2478 }
2479
2480 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2482 serde_json::json!({
2483 "name": "p",
2484 "clock_resolution": "250ms",
2485 "inputs": {
2486 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2487 "topic": "t", "group_join_timeout": "30s"}}},
2488 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2489 "path": "http://x", "pause_linger": "7s"}}},
2490 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2491 "connection_config": {"server_url": "nats://x",
2492 "connection_timeout": "5s", "request_timeout": "6s"},
2493 "stream_name": "s",
2494 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2495 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2496 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2497 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2498 },
2499 "outputs": {
2500 "v.kafka": {"stream": "v",
2501 "transport": {"name": "kafka_output", "config": {
2502 "topic": "v", "initialization_timeout": "40s"}},
2503 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2504 "registry_timeout": "8s"}},
2505 "enable_output_buffer": true,
2506 "max_output_buffer_time": "500ms"},
2507 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2508 "connection_config": {"server_url": "nats://x",
2509 "connection_timeout": "5s", "request_timeout": "6s"},
2510 "subject": "s", "publish_timeout": "9s"}}},
2511 },
2512 })
2513 }
2514
2515 #[test]
2519 fn legacy_duration_spelling_rewrites_every_connector() {
2520 let mut config = pipeline_with_every_duration_connector();
2521 super::to_legacy_duration_spelling(&mut config);
2522 let i = &config["inputs"];
2523 assert_eq!(
2524 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2525 30
2526 );
2527 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2528 let nats = &i["t.nats"]["transport"]["config"];
2529 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2530 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2531 assert_eq!(nats["inactivity_timeout_secs"], 90);
2532 assert_eq!(nats["retry_interval_secs"], 3);
2533 assert_eq!(
2534 nats["consumer_config"]["max_expires"],
2535 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2536 );
2537 let pubsub = &i["t.pubsub"]["transport"]["config"];
2538 assert_eq!(pubsub["timeout_seconds"], 20);
2539 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2540 let out = &config["outputs"]["v.kafka"];
2541 assert_eq!(
2542 out["transport"]["config"]["initialization_timeout_secs"],
2543 40
2544 );
2545 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2546 assert_eq!(out["max_output_buffer_time_millis"], 500);
2547 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2548 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2549 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2550 assert_eq!(nats["publish_timeout_secs"], 9);
2551
2552 let text = config.to_string();
2554 for new in [
2555 "\"group_join_timeout\"",
2556 "\"pause_linger\"",
2557 "\"connection_timeout\"",
2558 "\"request_timeout\"",
2559 "\"inactivity_timeout\"",
2560 "\"retry_interval\"",
2561 "\"max_expiry\"",
2562 "\"timeout\"",
2563 "\"connect_timeout\"",
2564 "\"initialization_timeout\"",
2565 "\"registry_timeout\"",
2566 "\"max_output_buffer_time\"",
2567 "\"publish_timeout\"",
2568 "\"clock_resolution\"",
2569 ] {
2570 assert!(!text.contains(new), "{new} survived in {text}");
2571 }
2572 }
2573
2574 #[test]
2576 fn legacy_duration_spelling_round_trips_connectors() {
2577 let original: PipelineConfig =
2578 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2579 let mut value = serde_json::to_value(&original).unwrap();
2580 super::to_legacy_duration_spelling(&mut value);
2581 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2582
2583 let registry = |config: &PipelineConfig| {
2586 let format = config.outputs["v.kafka"]
2587 .connector_config
2588 .format
2589 .clone()
2590 .unwrap();
2591 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2592 .unwrap()
2593 .registry_config
2594 .registry_timeout
2595 };
2596 assert_eq!(registry(&reread), registry(&original));
2597 let mut original = original;
2598 for config in [&mut reread, &mut original] {
2599 config
2600 .outputs
2601 .get_mut("v.kafka")
2602 .unwrap()
2603 .connector_config
2604 .format = None;
2605 }
2606 assert_eq!(reread, original);
2607 }
2608
2609 #[test]
2613 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2614 let mut config = serde_json::json!({
2615 "inputs": {
2616 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2617 "group_join_timeout": "100000000000s"}}},
2618 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2619 },
2620 "storage": {"backend": {"name": "file", "config": {
2621 "sync": {"min_retention": "100000000000d"}}}},
2622 });
2623 super::to_legacy_duration_spelling(&mut config);
2624 let i = &config["inputs"];
2625 assert_eq!(
2626 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2627 u64::from(u32::MAX)
2628 );
2629 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2630 assert_eq!(
2631 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2632 u64::from(u32::MAX)
2633 );
2634 }
2635
2636 #[test]
2640 fn legacy_duration_spelling_round_trips() {
2641 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2642 "clock_resolution": "250ms",
2643 "max_buffering_delay": "3ms",
2644 "provisioning_timeout": "15m",
2645 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2646 }))
2647 .unwrap();
2648 let mut value = serde_json::to_value(&original).unwrap();
2649 super::to_legacy_duration_spelling(&mut value);
2650 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2651 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2652 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2653 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2654 assert_eq!(
2655 reread.fault_tolerance.checkpoint_interval(),
2656 original.fault_tolerance.checkpoint_interval()
2657 );
2658 }
2659
2660 #[test]
2665 fn legacy_duration_spelling_edge_cases() {
2666 let mut config = serde_json::json!({
2667 "max_buffering_delay": null,
2668 "provisioning_timeout": "1.5s",
2669 "fault_tolerance": {"checkpoint_interval": null},
2670 "clock_resolution": "10sec",
2671 "storage": {"backend": {"name": "file", "config": {
2672 "ioop_latency": "400us",
2673 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2674 });
2675 super::to_legacy_duration_spelling(&mut config);
2676 assert_eq!(
2677 config,
2678 serde_json::json!({
2679 "provisioning_timeout_secs": 2,
2680 "fault_tolerance": {"checkpoint_interval_secs": null},
2681 "clock_resolution": "10sec",
2682 "storage": {"backend": {"name": "file", "config": {
2683 "ioop_delay": 1,
2684 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2685 })
2686 );
2687
2688 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2690 super::to_legacy_duration_spelling(&mut zero);
2691 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2692
2693 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2695 let mut again = legacy.clone();
2696 super::to_legacy_duration_spelling(&mut again);
2697 assert_eq!(again, legacy);
2698 }
2699
2700 #[test]
2704 fn legacy_size_spelling_uses_the_older_keys() {
2705 let mut config = serde_json::json!({
2706 "workers": 2,
2707 "max_rss": "16G",
2708 "datafusion_memory": "1.5G",
2709 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2710 "resources": {
2711 "memory_min": "4G", "memory_max": "16Gi",
2712 "storage_min": "100G", "storage_max": "400Gi",
2713 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2714 },
2715 "dev_tweaks": {
2716 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2717 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2718 },
2719 "inputs": {
2720 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2721 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2722 "t.cdc": {"stream": "t",
2723 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2724 },
2725 "outputs": {
2726 "v.ddb": {"stream": "v",
2727 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2728 "v.pg": {"stream": "v",
2729 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2730 },
2731 });
2732 super::to_legacy_size_spelling(&mut config);
2733 assert_eq!(
2734 config,
2735 serde_json::json!({
2736 "workers": 2,
2737 "max_rss_mb": 16_000,
2738 "datafusion_memory_mb": 1_500,
2739 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2740 "resources": {
2741 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2743 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2744 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2745 },
2746 "dev_tweaks": {
2747 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2748 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2749 },
2750 "inputs": {
2751 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2752 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2753 "t.cdc": {"stream": "t",
2754 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2755 },
2756 "outputs": {
2757 "v.ddb": {"stream": "v",
2758 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2759 "v.pg": {"stream": "v",
2760 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2761 },
2762 })
2763 );
2764 }
2765
2766 #[test]
2769 fn legacy_size_spelling_round_trips() {
2770 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2771 "name": "p",
2772 "max_rss": "16G",
2773 "datafusion_memory": "1G",
2776 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2777 "resources": {"memory_max": "16G", "storage_max": "400G"},
2778 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2779 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2780 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2781 "outputs": {},
2782 }))
2783 .unwrap();
2784 let mut value = serde_json::to_value(&config).unwrap();
2785 super::to_legacy_size_spelling(&mut value);
2786 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2787 assert_eq!(
2788 value["inputs"]["t.file"]["max_queued_bytes"],
2789 serde_json::json!(1024 * 1024)
2790 );
2791 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2792 assert_eq!(reread, config);
2793 }
2794
2795 #[test]
2798 fn legacy_spelling_applies_each_rename_separately() {
2799 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2800 let mut both = current.clone();
2801 super::LegacySpelling {
2802 durations: true,
2803 sizes: true,
2804 }
2805 .apply(&mut both);
2806 assert_eq!(
2807 both,
2808 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2809 );
2810 let mut sizes_only = current.clone();
2811 super::LegacySpelling {
2812 durations: false,
2813 sizes: true,
2814 }
2815 .apply(&mut sizes_only);
2816 assert_eq!(
2817 sizes_only,
2818 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2819 );
2820 let mut none = current.clone();
2821 super::LegacySpelling::NONE.apply(&mut none);
2822 assert_eq!(none, current);
2823 assert!(!super::LegacySpelling::NONE.any());
2824 }
2825
2826 #[test]
2827 fn legacy_size_spelling_edge_cases() {
2828 let mut config = serde_json::json!({
2831 "max_rss": "lots",
2832 "resources": {"memory_max": null, "memory_min": 4000}
2833 });
2834 super::to_legacy_size_spelling(&mut config);
2835 assert_eq!(
2836 config,
2837 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2838 );
2839
2840 let mut small = serde_json::json!({"max_rss": "1"});
2843 super::to_legacy_size_spelling(&mut small);
2844 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2845
2846 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2848 let mut again = legacy.clone();
2849 super::to_legacy_size_spelling(&mut again);
2850 assert_eq!(again, legacy);
2851 }
2852
2853 #[test]
2862 fn a_stored_default_matches_an_omitted_one() {
2863 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2864 "transport": {
2865 "name": "url_input",
2866 "config": {"path": "http://example.com/x", "pause_timeout": 60},
2867 }
2868 }))
2869 .unwrap();
2870 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2871 "transport": {
2872 "name": "url_input",
2873 "config": {"path": "http://example.com/x"},
2874 }
2875 }))
2876 .unwrap();
2877
2878 assert_ne!(stored, fresh);
2881 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2882
2883 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2885 "transport": {
2886 "name": "url_input",
2887 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2888 }
2889 }))
2890 .unwrap();
2891 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2892 }
2893
2894 #[test]
2902 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2903 let connector = |registry: serde_json::Value| -> ConnectorConfig {
2904 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2905 format
2906 .as_object_mut()
2907 .unwrap()
2908 .extend(registry.as_object().unwrap().clone());
2909 serde_json::from_value(serde_json::json!({
2910 "transport": {
2911 "name": "url_input",
2912 "config": {"path": "http://example.com/x"},
2913 },
2914 "format": {"name": "avro", "config": format},
2915 }))
2916 .unwrap()
2917 };
2918 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2919 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2920 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2921 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2922 let unset = connector(serde_json::json!({}));
2923
2924 assert!(stored.equal_modulo_paused(¤t));
2925 assert!(stored.equal_for_input_checkpoint_replay(¤t));
2926 assert!(current.equal_modulo_paused(&spelled_out));
2927 assert!(!stored.equal_modulo_paused(&changed));
2928 assert!(!stored.equal_modulo_paused(&unset));
2929 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2931 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2932 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2933 }))
2934 .unwrap();
2935 assert!(!json.equal_modulo_paused(&stored));
2936 }
2937
2938 #[test]
2944 fn the_largest_legacy_defaults_still_load() {
2945 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
2946 "enable_output_buffer": false,
2947 "max_output_buffer_time_millis": u64::MAX,
2948 "max_output_buffer_size_records": 10_000_000u64,
2949 }))
2950 .unwrap();
2951 assert_eq!(
2952 buffer.max_output_buffer_time,
2953 Some(ConfigDuration::from_millis(u64::MAX))
2954 );
2955
2956 let sync: SyncConfig =
2958 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
2959 assert_eq!(
2960 sync.min_retention(),
2961 ConfigDuration::from_days(4_000_000_000)
2962 );
2963 }
2964
2965 #[test]
2969 fn a_legacy_number_past_u64_seconds_saturates() {
2970 let sync: SyncConfig =
2971 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
2972 .unwrap();
2973 assert_eq!(
2974 sync.min_retention(),
2975 ConfigDuration::from(std::time::Duration::MAX)
2976 );
2977 }
2978
2979 #[test]
2983 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
2984 fn connector(value: serde_json::Value) -> ConnectorConfig {
2985 serde_json::from_value(value).unwrap()
2986 }
2987 fn secs(duration: ConfigDuration) -> u64 {
2988 std::time::Duration::from(duration).as_secs()
2989 }
2990 let fresh_kafka = connector(serde_json::json!({
2991 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
2992 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
2993 unreachable!()
2994 };
2995 let stored_kafka = connector(serde_json::json!({
2996 "transport": {"name": "kafka_input", "config": {
2997 "topic": "t",
2998 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
2999 assert_ne!(stored_kafka, fresh_kafka);
3000 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3001
3002 let base = serde_json::json!({
3003 "connection_config": {"server_url": "nats://x"},
3004 "stream_name": "s",
3005 "consumer_config": {"deliver_policy": "All"}});
3006 let fresh_nats = connector(serde_json::json!({
3007 "transport": {"name": "nats_input", "config": base.clone()}}));
3008 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3009 unreachable!()
3010 };
3011 let mut spelled_out = base;
3012 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3013 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3014 spelled_out["connection_config"]["connection_timeout_secs"] =
3015 secs(nats.connection_config.connection_timeout()).into();
3016 spelled_out["connection_config"]["request_timeout_secs"] =
3017 secs(nats.connection_config.request_timeout()).into();
3018 let stored_nats = connector(serde_json::json!({
3019 "transport": {"name": "nats_input", "config": spelled_out}}));
3020 assert_ne!(stored_nats, fresh_nats);
3021 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3022 }
3023
3024 #[test]
3030 fn superseded_keys_are_normalised_by_a_round_trip() {
3031 let stored = serde_json::json!({
3032 "workers": 4,
3033 "clock_resolution_usecs": 100_000,
3034 "max_buffering_delay_usecs": 0,
3035 "provisioning_timeout_secs": 300,
3036 });
3037
3038 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3039 let written = serde_json::to_value(&config).unwrap();
3040
3041 assert_eq!(written["clock_resolution"], "100ms");
3042 assert_eq!(written["max_buffering_delay"], "0s");
3043 assert_eq!(written["provisioning_timeout"], "5m");
3044 for superseded in [
3045 "clock_resolution_usecs",
3046 "max_buffering_delay_usecs",
3047 "provisioning_timeout_secs",
3048 ] {
3049 assert!(
3050 written.get(superseded).is_none(),
3051 "`{superseded}` survived the round trip: {written}"
3052 );
3053 }
3054
3055 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3058 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3059 }
3060
3061 #[test]
3066 fn ioop_latency_accepts_both_spellings() {
3067 for (json, expected) in [
3068 (r#"{"name": "file", "config": {}}"#, None),
3069 (
3070 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3071 Some(ConfigDuration::from_millis(5)),
3072 ),
3073 (
3074 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3075 Some(ConfigDuration::from_millis(5)),
3076 ),
3077 (
3078 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3079 Some(ConfigDuration::from_secs(1)),
3080 ),
3081 ] {
3082 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3083 let StorageBackendConfig::File(file) = backend else {
3084 panic!("expected the file backend, parsing {json}");
3085 };
3086 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3087 }
3088 }
3089
3090 #[test]
3094 fn clock_resolution_falls_back_to_the_deprecated_field() {
3095 for (json, expected) in [
3096 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3097 (
3098 r#"{"clock_resolution": "100ms"}"#,
3099 ConfigDuration::from_millis(100),
3100 ),
3101 (
3102 r#"{"clock_resolution_usecs": 100000}"#,
3103 ConfigDuration::from_millis(100),
3104 ),
3105 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3106 (
3107 r#"{"clock_resolution_usecs": null}"#,
3108 DEFAULT_CLOCK_RESOLUTION,
3109 ),
3110 ] {
3111 assert_eq!(
3112 serde_json::from_str::<RuntimeConfig>(json)
3113 .unwrap()
3114 .clock_resolution(),
3115 expected,
3116 "parsing {json}"
3117 );
3118 }
3119 }
3120
3121 #[test]
3124 fn deprecated_duration_fields_still_work() {
3125 let runtime: RuntimeConfig = serde_json::from_str(
3126 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3127 )
3128 .unwrap();
3129 assert_eq!(
3130 runtime.max_buffering_delay(),
3131 ConfigDuration::from_millis(5)
3132 );
3133 assert_eq!(
3134 runtime.provisioning_timeout,
3135 Some(ConfigDuration::from_secs(1200))
3136 );
3137
3138 let sync: SyncConfig = serde_json::from_str(
3139 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3140 )
3141 .unwrap();
3142 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3143 assert_eq!(
3144 sync.checkpoint_push_interval(),
3145 Some(ConfigDuration::from_secs(300))
3146 );
3147 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3148
3149 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3150 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3151
3152 let buffer: OutputBufferConfig =
3153 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3154 assert_eq!(
3155 buffer.max_output_buffer_time(),
3156 ConfigDuration::from_millis(250)
3157 );
3158 }
3159
3160 #[test]
3163 fn duration_fields_default_when_unset() {
3164 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3165 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3166 assert_eq!(sync.checkpoint_push_interval(), None);
3167 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3168
3169 let runtime = RuntimeConfig::default();
3170 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3171 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3172 assert_eq!(runtime.provisioning_timeout, None);
3173 }
3174
3175 #[test]
3179 fn storage_options_f64_roundtrip_through_pipeline_config() {
3180 let pc = PipelineConfig {
3181 global: RuntimeConfig {
3182 storage: Some(StorageOptions {
3183 bloom_false_positive_rate: Some(0.01),
3184 ..Default::default()
3185 }),
3186 ..Default::default()
3187 },
3188 multihost: None,
3189 name: Some("test-pipeline".into()),
3190 given_name: None,
3191 storage_config: None,
3192 secrets_dir: None,
3193 inputs: Default::default(),
3194 outputs: Default::default(),
3195 program_ir: None,
3196 };
3197
3198 let json = serde_json::to_string_pretty(&pc).unwrap();
3200 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3201 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3202 );
3203 assert_eq!(
3204 pc2.global.storage.unwrap().bloom_false_positive_rate,
3205 Some(0.01)
3206 );
3207
3208 let value = serde_json::to_value(&pc).unwrap();
3210 let pc3: PipelineConfig = serde_json::from_value(value)
3211 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3212 assert_eq!(
3213 pc3.global.storage.unwrap().bloom_false_positive_rate,
3214 Some(0.01)
3215 );
3216 }
3217}
3218
3219impl FtConfig {
3220 pub fn is_enabled(&self) -> bool {
3221 self.model.is_some()
3222 }
3223
3224 pub fn checkpoint_interval(&self) -> Option<Duration> {
3231 if !self.is_enabled() {
3232 return None;
3233 }
3234
3235 let interval = self
3236 .checkpoint_interval
3237 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3238
3239 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3240 }
3241}
3242
3243mod none_as_string {
3250 use std::marker::PhantomData;
3251
3252 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3253 use serde::ser::{Serialize, Serializer};
3254
3255 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3256 where
3257 S: Serializer,
3258 T: Serialize,
3259 {
3260 match value.as_ref() {
3261 Some(value) => value.serialize(serializer),
3262 None => "none".serialize(serializer),
3263 }
3264 }
3265
3266 struct NoneAsString<T>(PhantomData<fn() -> T>);
3267
3268 impl<'de, T> Visitor<'de> for NoneAsString<T>
3269 where
3270 T: Deserialize<'de>,
3271 {
3272 type Value = Option<T>;
3273
3274 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3275 formatter.write_str("string")
3276 }
3277
3278 fn visit_none<E>(self) -> Result<Self::Value, E>
3279 where
3280 E: serde::de::Error,
3281 {
3282 Ok(None)
3283 }
3284
3285 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3286 where
3287 E: serde::de::Error,
3288 {
3289 if &value.to_ascii_lowercase() == "none" {
3290 Ok(None)
3291 } else {
3292 Ok(Some(T::deserialize(value.into_deserializer())?))
3293 }
3294 }
3295 }
3296
3297 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3298 where
3299 D: Deserializer<'de>,
3300 T: Deserialize<'de>,
3301 {
3302 deserializer.deserialize_str(NoneAsString(PhantomData))
3303 }
3304}
3305
3306fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3309 Schema::OneOf(
3310 OneOfBuilder::new()
3311 .item(RefOr::Ref(Ref::new(format!(
3312 "#/components/schemas/{}",
3313 T::schema().0
3314 ))))
3315 .item(
3316 ObjectBuilder::new()
3317 .schema_type(SchemaType::String)
3318 .enum_values(Some(vec!["none"])),
3319 )
3320 .default(Some(
3321 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3322 ))
3323 .build(),
3324 )
3325}
3326
3327#[derive(
3332 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3333)]
3334#[serde(rename_all = "snake_case")]
3335pub enum FtModel {
3336 AtLeastOnce,
3339
3340 #[default]
3343 ExactlyOnce,
3344}
3345
3346impl FtModel {
3347 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3348 value.map_or("no", |model| model.as_str())
3349 }
3350
3351 pub fn as_str(&self) -> &'static str {
3352 match self {
3353 FtModel::AtLeastOnce => "at_least_once",
3354 FtModel::ExactlyOnce => "exactly_once",
3355 }
3356 }
3357}
3358
3359#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3361pub struct FtModelUnknown;
3362
3363impl std::fmt::Display for FtModelUnknown {
3364 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3365 f.write_str("expected `exactly_once` or `at_least_once`")
3366 }
3367}
3368
3369impl std::error::Error for FtModelUnknown {}
3370
3371impl FromStr for FtModel {
3372 type Err = FtModelUnknown;
3373
3374 fn from_str(s: &str) -> Result<Self, Self::Err> {
3375 match s.to_ascii_lowercase().as_str() {
3376 "exactly_once" => Ok(Self::ExactlyOnce),
3377 "at_least_once" => Ok(Self::AtLeastOnce),
3378 _ => Err(FtModelUnknown),
3379 }
3380 }
3381}
3382
3383#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3385pub struct InputEndpointConfig {
3386 pub stream: Cow<'static, str>,
3389
3390 #[serde(flatten)]
3392 pub connector_config: ConnectorConfig,
3393}
3394
3395impl InputEndpointConfig {
3396 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3397 Self {
3398 stream: stream.into(),
3399 connector_config,
3400 }
3401 }
3402}
3403
3404fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3408where
3409 D: Deserializer<'de>,
3410{
3411 let value = Option::<JsonValue>::deserialize(deserializer)?;
3412 match value {
3413 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3414 Some(JsonValue::Array(arr)) => {
3415 let vec = arr
3416 .into_iter()
3417 .map(|item| {
3418 item.as_str()
3419 .map(|s| s.to_string())
3420 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3421 })
3422 .collect::<Result<Vec<String>, _>>()?;
3423 Ok(Some(vec))
3424 }
3425 Some(JsonValue::Null) | None => Ok(None),
3426 _ => Err(serde::de::Error::custom(
3427 "invalid 'start_after' property: expected a string, an array of strings, or null",
3428 )),
3429 }
3430}
3431
3432#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3433pub struct ConnectorConfig {
3434 #[serde(default)]
3447 pub send_snapshot: bool,
3448
3449 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3466 pub soft_delete: bool,
3467
3468 pub transport: TransportConfig,
3470
3471 #[serde(skip_serializing_if = "Option::is_none")]
3473 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3474
3475 pub format: Option<FormatConfig>,
3477
3478 #[serde(skip_serializing_if = "Option::is_none")]
3480 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3481
3482 pub index: Option<String>,
3497
3498 #[serde(flatten)]
3500 pub output_buffer_config: OutputBufferConfig,
3501
3502 #[serde(skip_serializing_if = "Option::is_none")]
3515 pub max_batch_size: Option<u64>,
3516
3517 #[serde(skip_serializing_if = "Option::is_none")]
3530 pub max_worker_batch_size: Option<u64>,
3531
3532 #[serde(default = "default_max_queued_records")]
3551 pub max_queued_records: u64,
3552
3553 #[serde(
3575 default,
3576 alias = "max_queued_bytes",
3577 deserialize_with = "size_max_queued_size",
3578 skip_serializing_if = "Option::is_none"
3579 )]
3580 #[schema(value_type = Option<String>)]
3581 pub max_queued_size: Option<ConfigSize>,
3582
3583 #[serde(default)]
3594 pub paused: bool,
3595
3596 #[serde(default)]
3601 pub labels: Vec<String>,
3602
3603 #[serde(deserialize_with = "deserialize_start_after")]
3609 #[serde(default)]
3610 pub start_after: Option<Vec<String>>,
3611
3612 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3624 pub distributed: bool,
3625}
3626
3627impl ConnectorConfig {
3628 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3629 Self {
3630 send_snapshot: false,
3631 soft_delete: false,
3632 transport,
3633 preprocessor: None,
3634 format,
3635 postprocessor: None,
3636 index: None,
3637 output_buffer_config: Default::default(),
3638 max_batch_size: None,
3639 max_worker_batch_size: None,
3640 max_queued_records: default_max_queued_records(),
3641 max_queued_size: None,
3642 paused: false,
3643 labels: Vec::new(),
3644 start_after: None,
3645 distributed: false,
3646 }
3647 }
3648
3649 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3650 self.max_batch_size = max_batch_size;
3651 self
3652 }
3653
3654 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3655 self.max_queued_records = max_queued_records;
3656 self
3657 }
3658
3659 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3664 let mut a = self.clone();
3665 let mut b = other.clone();
3666 a.paused = false;
3667 b.paused = false;
3668 a.normalize_durations();
3669 b.normalize_durations();
3670 a == b
3671 }
3672
3673 fn normalize_durations(&mut self) {
3684 self.transport.normalize_durations();
3685 self.output_buffer_config.max_output_buffer_time =
3686 Some(self.output_buffer_config.max_output_buffer_time());
3687 if let Some(format) = &mut self.format {
3688 format.normalize_durations();
3689 }
3690 }
3691
3692 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3695 let mut a = self.clone();
3696 let mut b = other.clone();
3697 a.normalize_for_input_checkpoint_replay();
3698 b.normalize_for_input_checkpoint_replay();
3699 a == b
3700 }
3701
3702 fn normalize_for_input_checkpoint_replay(&mut self) {
3703 self.paused = false;
3704 self.max_batch_size = None;
3705 self.max_worker_batch_size = None;
3706 self.max_queued_records = default_max_queued_records();
3707 self.max_queued_size = None;
3708 self.normalize_durations();
3709 }
3710
3711 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3714 self.max_batch_size = other.max_batch_size;
3715 self.max_worker_batch_size = other.max_worker_batch_size;
3716 self.max_queued_records = other.max_queued_records;
3717 self.max_queued_size = other.max_queued_size;
3718 }
3719
3720 pub fn max_queued_records(&self) -> u64 {
3722 self.max_queued_records
3723 }
3724
3725 pub fn max_queued_bytes(&self) -> u64 {
3728 self.max_queued_size
3729 .map(ConfigSize::as_bytes)
3730 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3731 }
3732}
3733
3734#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3735#[serde(default)]
3736pub struct OutputBufferConfig {
3737 pub enable_output_buffer: bool,
3760
3761 #[serde(
3770 default,
3771 alias = "max_output_buffer_time_millis",
3772 deserialize_with = "duration_max_output_buffer_time",
3773 skip_serializing_if = "Option::is_none"
3774 )]
3775 #[schema(value_type = Option<String>)]
3776 pub max_output_buffer_time: Option<ConfigDuration>,
3777
3778 pub max_output_buffer_size_records: usize,
3790}
3791
3792impl OutputBufferConfig {
3793 pub fn max_output_buffer_time(&self) -> ConfigDuration {
3795 self.max_output_buffer_time
3796 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3797 }
3798}
3799
3800impl Default for OutputBufferConfig {
3801 fn default() -> Self {
3802 Self {
3803 enable_output_buffer: false,
3804 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3805 max_output_buffer_time: None,
3806 }
3807 }
3808}
3809
3810#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3812pub struct OutputEndpointConfig {
3813 pub stream: Cow<'static, str>,
3816
3817 #[serde(flatten)]
3819 pub connector_config: ConnectorConfig,
3820}
3821
3822impl OutputEndpointConfig {
3823 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3824 Self {
3825 stream: stream.into(),
3826 connector_config,
3827 }
3828 }
3829}
3830
3831#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3835#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3836pub enum TransportConfig {
3837 FileInput(FileInputConfig),
3838 FileOutput(FileOutputConfig),
3839 NatsInput(Box<NatsInputConfig>),
3842 NatsOutput(NatsOutputConfig),
3843 KafkaInput(KafkaInputConfig),
3844 KafkaOutput(KafkaOutputConfig),
3845 PubSubInput(PubSubInputConfig),
3846 UrlInput(UrlInputConfig),
3847 S3Input(S3InputConfig),
3848 DeltaTableInput(DeltaTableReaderConfig),
3849 DeltaTableOutput(DeltaTableWriterConfig),
3850 #[serde(rename = "dynamodb_output")]
3853 DynamoDBOutput(DynamoDBWriterConfig),
3854 RedisOutput(RedisOutputConfig),
3855 IcebergInput(Box<IcebergReaderConfig>),
3857 PostgresInput(PostgresReaderConfig),
3858 PostgresCdcInput(PostgresCdcReaderConfig),
3859 PostgresOutput(PostgresWriterConfig),
3860 Datagen(DatagenInputConfig),
3861 Nexmark(NexmarkInputConfig),
3862 HttpInput(HttpInputConfig),
3864 HttpOutput(HttpOutputConfig),
3866 AdHocInput(AdHocInputConfig),
3868 ClockInput(ClockConfig),
3869 S2Input(S2InputConfig),
3870 S2Output(S2OutputConfig),
3871 NullOutput,
3873 EmptyInput,
3875}
3876
3877impl TransportConfig {
3878 pub fn normalize_durations(&mut self) {
3881 match self {
3882 TransportConfig::UrlInput(config) => {
3883 config.pause_linger = Some(config.pause_linger());
3884 }
3885 TransportConfig::KafkaInput(config) => {
3886 config.group_join_timeout = Some(config.group_join_timeout());
3887 }
3888 TransportConfig::KafkaOutput(config) => {
3889 config.initialization_timeout = Some(config.initialization_timeout());
3890 }
3891 TransportConfig::NatsInput(config) => {
3892 config.connection_config.connection_timeout =
3893 Some(config.connection_config.connection_timeout());
3894 config.connection_config.request_timeout =
3895 Some(config.connection_config.request_timeout());
3896 config.inactivity_timeout = Some(config.inactivity_timeout());
3897 config.retry_interval = Some(config.retry_interval());
3898 }
3899 TransportConfig::NatsOutput(config) => {
3900 config.connection_config.connection_timeout =
3901 Some(config.connection_config.connection_timeout());
3902 config.connection_config.request_timeout =
3903 Some(config.connection_config.request_timeout());
3904 config.publish_timeout = Some(config.publish_timeout());
3905 }
3906 _ => {}
3907 }
3908 }
3909
3910 pub fn name(&self) -> String {
3911 match self {
3912 TransportConfig::FileInput(_) => "file_input".to_string(),
3913 TransportConfig::FileOutput(_) => "file_output".to_string(),
3914 TransportConfig::NatsInput(_) => "nats_input".to_string(),
3915 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
3916 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
3917 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
3918 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
3919 TransportConfig::UrlInput(_) => "url_input".to_string(),
3920 TransportConfig::S3Input(_) => "s3_input".to_string(),
3921 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
3922 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
3923 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
3924 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
3925 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
3926 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
3927 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
3928 TransportConfig::Datagen(_) => "datagen".to_string(),
3929 TransportConfig::Nexmark(_) => "nexmark".to_string(),
3930 TransportConfig::HttpInput(_) => "http_input".to_string(),
3931 TransportConfig::HttpOutput(_) => "http_output".to_string(),
3932 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
3933 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
3934 TransportConfig::ClockInput(_) => "clock".to_string(),
3935 TransportConfig::S2Input(_) => "s2_input".to_string(),
3936 TransportConfig::S2Output(_) => "s2_output".to_string(),
3937 TransportConfig::NullOutput => "null_output".to_string(),
3938 TransportConfig::EmptyInput => "empty_input".to_string(),
3939 }
3940 }
3941
3942 pub fn is_transient(&self) -> bool {
3945 matches!(
3946 self,
3947 TransportConfig::AdHocInput(_)
3948 | TransportConfig::HttpInput(_)
3949 | TransportConfig::HttpOutput(_)
3950 | TransportConfig::ClockInput(_)
3951 )
3952 }
3953
3954 pub fn is_http_input(&self) -> bool {
3955 matches!(self, TransportConfig::HttpInput(_))
3956 }
3957
3958 pub fn supports_distribution(&self) -> bool {
3962 matches!(
3963 self,
3964 TransportConfig::KafkaInput(_)
3965 | TransportConfig::DeltaTableInput(_)
3966 | TransportConfig::IcebergInput(_)
3967 )
3968 }
3969
3970 pub fn needs_input_choice(&self) -> bool {
3982 matches!(
3983 self,
3984 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
3985 )
3986 }
3987
3988 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
3991 use crate::adapter_stats::FrontierMerge;
3992 match self {
3993 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
3994 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
3995 FrontierMerge::Shared
3996 }
3997 _ => FrontierMerge::Opaque,
3998 }
3999 }
4000}
4001
4002#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4005pub struct FormatConfig {
4006 pub name: Cow<'static, str>,
4008
4009 #[serde(default)]
4011 #[schema(value_type = Object)]
4012 pub config: JsonValue,
4013}
4014
4015impl FormatConfig {
4016 pub fn normalize_durations(&mut self) {
4023 if self.name != "avro" {
4024 return;
4025 }
4026 let has_timeout = self.config.as_object().is_some_and(|object| {
4027 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4028 });
4029 if !has_timeout {
4030 return;
4031 }
4032 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4033 self.config.clone(),
4034 ) else {
4035 return;
4036 };
4037 let object = self.config.as_object_mut().unwrap();
4038 object.remove("registry_timeout_secs");
4039 match registry.registry_timeout {
4040 Some(timeout) => object.insert(
4041 "registry_timeout".to_string(),
4042 JsonValue::String(timeout.to_string()),
4043 ),
4044 None => object.remove("registry_timeout"),
4045 };
4046 }
4047}
4048
4049#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4050#[serde(default)]
4051pub struct ResourceConfig {
4052 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4055 pub cpu_cores_min: Option<f64>,
4056
4057 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4060 pub cpu_cores_max: Option<f64>,
4061
4062 #[serde(
4068 alias = "memory_mb_min",
4069 deserialize_with = "size_memory_min",
4070 skip_serializing_if = "Option::is_none"
4071 )]
4072 #[schema(value_type = Option<String>)]
4073 pub memory_min: Option<ConfigSize>,
4074
4075 #[serde(
4081 alias = "memory_mb_max",
4082 deserialize_with = "size_memory_max",
4083 skip_serializing_if = "Option::is_none"
4084 )]
4085 #[schema(value_type = Option<String>)]
4086 pub memory_max: Option<ConfigSize>,
4087
4088 #[serde(
4095 alias = "storage_mb_min",
4096 deserialize_with = "size_storage_min",
4097 skip_serializing_if = "Option::is_none"
4098 )]
4099 #[schema(value_type = Option<String>)]
4100 pub storage_min: Option<ConfigSize>,
4101
4102 #[serde(
4113 alias = "storage_mb_max",
4114 deserialize_with = "size_storage_max",
4115 skip_serializing_if = "Option::is_none"
4116 )]
4117 #[schema(value_type = Option<String>)]
4118 pub storage_max: Option<ConfigSize>,
4119
4120 #[serde(skip_serializing_if = "Option::is_none")]
4122 pub autoscaling: Option<AutoscalingConfig>,
4123
4124 pub storage_class: Option<String>,
4127
4128 #[serde(skip_serializing_if = "Option::is_none")]
4134 pub volume_attributes_class: Option<String>,
4135
4136 pub service_account_name: Option<String>,
4139
4140 pub namespace: Option<String>,
4148}
4149
4150#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4152#[serde(default)]
4153pub struct AutoscalingConfig {
4154 #[serde(skip_serializing_if = "Option::is_none")]
4156 pub storage: Option<StorageAutoscalingConfig>,
4157}
4158
4159#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4162#[serde(default)]
4163pub struct StorageAutoscalingConfig {
4164 #[serde(
4166 deserialize_with = "crate::serde_via_value::deserialize",
4167 skip_serializing_if = "Option::is_none"
4168 )]
4169 pub scale_threshold: Option<f64>,
4170
4171 #[serde(
4178 alias = "scale_threshold_available_mb",
4179 deserialize_with = "size_scale_threshold_available",
4180 skip_serializing_if = "Option::is_none"
4181 )]
4182 #[schema(value_type = Option<String>)]
4183 pub scale_threshold_available: Option<ConfigSize>,
4184
4185 #[serde(
4187 deserialize_with = "crate::serde_via_value::deserialize",
4188 skip_serializing_if = "Option::is_none"
4189 )]
4190 pub scale_factor: Option<f64>,
4191}
4192
4193#[cfg(test)]
4194mod resource_config_tests {
4195 use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
4196 use crate::size::ConfigSize;
4197 use serde_json::json;
4198
4199 #[test]
4200 fn storage_autoscaling_round_trips_through_json() {
4201 let input = json!({
4202 "storage_min": "1G",
4203 "storage_max": "8G",
4204 "autoscaling": {
4205 "storage": {
4206 "scale_threshold": 0.8,
4207 "scale_threshold_available": "10G",
4208 "scale_factor": 2.0
4209 }
4210 }
4211 });
4212 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4213 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4214 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4215 assert_eq!(
4216 config.autoscaling,
4217 Some(AutoscalingConfig {
4218 storage: Some(StorageAutoscalingConfig {
4219 scale_threshold: Some(0.8),
4220 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4221 scale_factor: Some(2.0),
4222 }),
4223 })
4224 );
4225 let output = serde_json::to_value(&config).unwrap();
4226 assert_eq!(output["storage_min"], json!("1G"));
4227 assert_eq!(
4228 output["autoscaling"]["storage"]["scale_threshold"],
4229 json!(0.8)
4230 );
4231 assert_eq!(
4232 output["autoscaling"]["storage"]["scale_threshold_available"],
4233 json!("10G")
4234 );
4235 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4236 }
4237
4238 #[test]
4239 fn autoscaling_fields_default_to_none() {
4240 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4241 assert_eq!(config.storage_min, None);
4242 assert_eq!(config.autoscaling, None);
4243
4244 let output = serde_json::to_value(&config).unwrap();
4247 assert!(output.get("storage_min").is_none());
4248 assert!(output.get("autoscaling").is_none());
4249 assert!(output.get("storage_max").is_none());
4250
4251 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4253 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4254 let output = serde_json::to_value(&config).unwrap();
4255 assert_eq!(output["autoscaling"], input["autoscaling"]);
4256
4257 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4259 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4260 }
4261
4262 #[test]
4263 fn autoscaling_rejects_non_numeric_values() {
4264 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4265 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4266 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4267 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4268 let input = json!({ "storage_mb_min": -1 });
4269 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4270 }
4271}
4272
4273#[cfg(test)]
4274mod sync_config_tests {
4275 use super::SyncConfig;
4276
4277 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4278 SyncConfig {
4279 bucket: bucket.to_owned(),
4280 read_bucket: read_bucket.map(str::to_owned),
4281 ..Default::default()
4282 }
4283 }
4284
4285 #[test]
4286 fn read_bucket_must_differ_from_bucket() {
4287 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4288 assert!(err.contains("different locations"), "{err}");
4289 }
4290
4291 #[test]
4292 fn read_bucket_must_use_the_same_object_store() {
4293 let err = config("gs://ckpts/a", Some("ckpts/b"))
4294 .validate()
4295 .unwrap_err();
4296 assert!(err.contains("same object store"), "{err}");
4297 let err = config("ckpts/a", Some("gs://ckpts/b"))
4298 .validate()
4299 .unwrap_err();
4300 assert!(err.contains("same object store"), "{err}");
4301 }
4302
4303 #[test]
4304 fn matching_object_stores_are_accepted() {
4305 config("gs://ckpts/a", Some("gs://ckpts/b"))
4306 .validate()
4307 .unwrap();
4308 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4309 config("gs://ckpts/a", None).validate().unwrap();
4310 }
4311
4312 #[test]
4313 fn take_bucket_ownership_defaults_to_false() {
4314 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4315 assert!(!sync.take_bucket_ownership);
4316
4317 let sync: SyncConfig =
4318 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4319 .unwrap();
4320 assert!(sync.take_bucket_ownership);
4321 }
4322}