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 mod ignored;
49pub use dev_tweaks::DevTweaks;
50
51const DEFAULT_MAX_PARALLEL_CONNECTOR_INIT: u64 = 10;
52
53const DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS: usize = 10_000_000;
55
56pub const fn default_max_queued_records() -> u64 {
58 1_000_000
59}
60
61pub const DEFAULT_MAX_WORKER_BATCH_SIZE: u64 = 10_000;
62
63pub const DEFAULT_CLOCK_RESOLUTION: ConfigDuration = ConfigDuration::from_secs(1);
65
66pub const DEFAULT_CHECKPOINT_INTERVAL: ConfigDuration = ConfigDuration::from_secs(60);
68
69pub const DEFAULT_PULL_INTERVAL: ConfigDuration = ConfigDuration::from_secs(10);
71
72pub const DEFAULT_RETENTION_MIN_AGE: ConfigDuration = ConfigDuration::from_days(30);
74
75fn default_clock_resolution() -> String {
78 DEFAULT_CLOCK_RESOLUTION.to_string()
79}
80fn default_checkpoint_interval() -> String {
81 DEFAULT_CHECKPOINT_INTERVAL.to_string()
82}
83fn default_pull_interval() -> String {
84 DEFAULT_PULL_INTERVAL.to_string()
85}
86fn default_retention_min_age() -> String {
87 DEFAULT_RETENTION_MIN_AGE.to_string()
88}
89
90duration_setting!(
91 duration_standby_pull_interval,
92 "standby_pull_interval",
93 LegacyUnit::Secs
94);
95duration_setting!(
96 duration_checkpoint_push_interval,
97 "checkpoint_push_interval",
98 LegacyUnit::Secs
99);
100duration_setting!(duration_min_retention, "min_retention", LegacyUnit::Days);
101duration_setting!(duration_ioop_latency, "ioop_latency", LegacyUnit::Millis);
102duration_setting!(
103 duration_max_buffering_delay,
104 "max_buffering_delay",
105 LegacyUnit::Micros
106);
107duration_setting!(
108 duration_clock_resolution,
109 "clock_resolution",
110 LegacyUnit::Micros
111);
112duration_setting!(
113 duration_provisioning_timeout,
114 "provisioning_timeout",
115 LegacyUnit::Secs
116);
117nullable_duration_setting!(
118 duration_checkpoint_interval,
119 "checkpoint_interval",
120 LegacyUnit::Secs
121);
122duration_setting!(
123 duration_max_output_buffer_time,
124 "max_output_buffer_time",
125 LegacyUnit::Millis
126);
127size_setting!(size_max_rss, "max_rss", LegacySizeUnit::Megabytes);
128size_setting!(
129 size_datafusion_memory,
130 "datafusion_memory",
131 LegacySizeUnit::Megabytes
132);
133size_setting!(size_cache_size, "cache_size", LegacySizeUnit::Mebibytes);
134size_setting!(size_min_spill_size, "min_spill_size", LegacySizeUnit::Bytes);
135size_setting!(
136 size_min_step_spill_size,
137 "min_step_spill_size",
138 LegacySizeUnit::Bytes
139);
140size_setting!(size_memory_min, "memory_min", LegacySizeUnit::Megabytes);
141size_setting!(size_memory_max, "memory_max", LegacySizeUnit::Megabytes);
142size_setting!(size_storage_min, "storage_min", LegacySizeUnit::Megabytes);
143size_setting!(size_storage_max, "storage_max", LegacySizeUnit::Megabytes);
144size_setting!(
145 size_scale_threshold_available,
146 "scale_threshold_available",
147 LegacySizeUnit::Megabytes
148);
149size_setting!(
150 size_max_queued_size,
151 "max_queued_size",
152 LegacySizeUnit::Bytes
153);
154
155#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
157pub struct ProgramIr {
158 pub mir: HashMap<MirNodeId, MirNode>,
160 pub program_schema: serde_json::Value,
162 #[serde(default)]
166 pub circuit_ir: Option<serde_json::Value>,
167 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub udf_library: Option<UdfLibrary>,
172}
173
174#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
176pub struct UdfLibrary {
177 pub source_checksum: String,
179 pub integrity_checksum: String,
181}
182
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct PipelineIdentity {
187 pub name: String,
189 pub given_name: Option<String>,
191}
192
193impl Display for PipelineIdentity {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195 match &self.given_name {
196 Some(given_name) => write!(f, "{given_name} (id: {})", self.name),
197 None => write!(f, "{}", self.name),
198 }
199 }
200}
201
202#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
208pub struct PipelineConfig {
209 #[serde(flatten)]
211 #[schema(inline)]
212 pub global: RuntimeConfig,
213
214 pub multihost: Option<MultihostConfig>,
222
223 pub name: Option<String>,
229
230 pub given_name: Option<String>,
235
236 #[serde(default)]
242 pub storage_config: Option<StorageConfig>,
243
244 pub secrets_dir: Option<String>,
248
249 #[serde(default)]
251 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
252
253 #[serde(default)]
255 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
256
257 #[serde(default)]
259 pub program_ir: Option<ProgramIr>,
260}
261
262impl PipelineConfig {
263 pub fn max_parallel_connector_init(&self) -> u64 {
264 max(
265 self.global
266 .max_parallel_connector_init
267 .unwrap_or(DEFAULT_MAX_PARALLEL_CONNECTOR_INIT),
268 1,
269 )
270 }
271
272 pub fn program_info_subset(&self) -> PipelineConfigProgramInfo {
275 PipelineConfigProgramInfo {
276 inputs: self.inputs.clone(),
277 outputs: self.outputs.clone(),
278 program_ir: self.program_ir.clone(),
279 }
280 }
281
282 pub fn with_storage(self, storage: Option<(StorageConfig, StorageOptions)>) -> Self {
283 let (storage_config, storage_options) = storage.unzip();
284 Self {
285 global: RuntimeConfig {
286 storage: storage_options,
287 ..self.global
288 },
289 storage_config,
290 ..self
291 }
292 }
293
294 pub fn storage(&self) -> Option<(&StorageConfig, &StorageOptions)> {
295 let storage_options = self.global.storage.as_ref();
296 let storage_config = self.storage_config.as_ref();
297 storage_config.zip(storage_options)
298 }
299
300 pub fn pipeline_identity(&self) -> Option<PipelineIdentity> {
305 self.name.as_ref().map(|name| PipelineIdentity {
306 name: name.clone(),
307 given_name: self.given_name.clone(),
308 })
309 }
310
311 pub fn secrets_dir(&self) -> &Path {
314 match &self.secrets_dir {
315 Some(dir) => Path::new(dir.as_str()),
316 None => default_secrets_directory(),
317 }
318 }
319
320 pub fn display_summary(&self) -> String {
322 let summary = serde_json::json!({
324 "name": self.name,
325 "given_name": self.given_name,
326 "global": self.global,
327 "storage_config": self.storage_config,
328 "secrets_dir": self.secrets_dir,
329 "inputs": self.inputs,
330 "outputs": self.outputs
331 });
332
333 serde_json::to_string_pretty(&summary).unwrap_or_else(|_| "{}".to_string())
334 }
335}
336
337#[derive(Default, Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]
345pub struct PipelineConfigProgramInfo {
346 pub inputs: BTreeMap<Cow<'static, str>, InputEndpointConfig>,
348
349 #[serde(default)]
351 pub outputs: BTreeMap<Cow<'static, str>, OutputEndpointConfig>,
352
353 #[serde(default)]
355 pub program_ir: Option<ProgramIr>,
356}
357
358#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
362pub struct MultihostConfig {
363 pub hosts: usize,
369}
370
371impl Default for MultihostConfig {
372 fn default() -> Self {
373 Self { hosts: 1 }
374 }
375}
376
377#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
379pub struct StorageConfig {
380 pub path: String,
389
390 #[serde(default)]
392 pub cache: StorageCacheConfig,
393}
394
395impl StorageConfig {
396 pub fn path(&self) -> &Path {
397 Path::new(&self.path)
398 }
399}
400
401#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug, PartialEq, Eq, ToSchema)]
403#[serde(rename_all = "snake_case")]
404pub enum StorageCacheConfig {
405 #[default]
410 PageCache,
411
412 FelderaCache,
417}
418
419impl StorageCacheConfig {
420 #[cfg(unix)]
421 pub fn to_custom_open_flags(&self) -> i32 {
422 match self {
423 StorageCacheConfig::PageCache => (),
424 StorageCacheConfig::FelderaCache => {
425 #[cfg(target_os = "linux")]
426 return libc::O_DIRECT;
427 }
428 }
429 0
430 }
431}
432
433#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
435#[serde(default)]
436pub struct StorageOptions {
437 pub backend: StorageBackendConfig,
439
440 #[serde(
454 alias = "min_storage_bytes",
455 deserialize_with = "size_min_spill_size",
456 skip_serializing_if = "Option::is_none"
457 )]
458 #[schema(value_type = Option<String>)]
459 pub min_spill_size: Option<ConfigSize>,
460
461 #[serde(
475 alias = "min_step_storage_bytes",
476 deserialize_with = "size_min_step_spill_size",
477 skip_serializing_if = "Option::is_none"
478 )]
479 #[schema(value_type = Option<String>)]
480 pub min_step_spill_size: Option<ConfigSize>,
481
482 pub compression: StorageCompression,
488
489 pub compression_level: Option<i32>,
500
501 #[serde(
510 alias = "cache_mib",
511 deserialize_with = "size_cache_size",
512 skip_serializing_if = "Option::is_none"
513 )]
514 #[schema(value_type = Option<String>)]
515 pub cache_size: Option<ConfigSize>,
516
517 #[serde(skip_serializing_if = "Option::is_none")]
532 #[serde(default, deserialize_with = "crate::serde_via_value::deserialize")]
533 pub bloom_false_positive_rate: Option<f64>,
534}
535
536impl Eq for StorageOptions {}
539
540#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
542#[serde(tag = "name", content = "config", rename_all = "snake_case")]
543pub enum StorageBackendConfig {
544 #[default]
548 Default,
549
550 File(Box<FileBackendConfig>),
554
555 Object(ObjectStorageConfig),
557}
558
559impl Display for StorageBackendConfig {
560 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
561 match self {
562 StorageBackendConfig::Default => write!(f, "default"),
563 StorageBackendConfig::File(_) => write!(f, "file"),
564 StorageBackendConfig::Object(_) => write!(f, "object"),
565 }
566 }
567}
568
569#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
571#[serde(rename_all = "snake_case")]
572pub enum StorageCompression {
573 #[default]
578 Default,
579
580 None,
582
583 Snappy,
585
586 Lz4,
591
592 Zstd,
598}
599
600#[derive(Debug, Clone, Eq, PartialEq)]
601pub enum StartFromCheckpoint {
602 Latest,
603 Uuid(uuid::Uuid),
604}
605
606impl ToSchema<'_> for StartFromCheckpoint {
607 fn schema() -> (
608 &'static str,
609 utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
610 ) {
611 (
612 "StartFromCheckpoint",
613 utoipa::openapi::RefOr::T(Schema::OneOf(
614 OneOfBuilder::new()
615 .item(
616 ObjectBuilder::new()
617 .schema_type(SchemaType::String)
618 .enum_values(Some(["latest"].into_iter()))
619 .build(),
620 )
621 .item(
622 ObjectBuilder::new()
623 .schema_type(SchemaType::String)
624 .format(Some(utoipa::openapi::SchemaFormat::KnownFormat(
625 utoipa::openapi::KnownFormat::Uuid,
626 )))
627 .build(),
628 )
629 .nullable(true)
630 .build(),
631 )),
632 )
633 }
634}
635
636impl<'de> Deserialize<'de> for StartFromCheckpoint {
637 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
638 where
639 D: Deserializer<'de>,
640 {
641 struct StartFromCheckpointVisitor;
642
643 impl<'de> Visitor<'de> for StartFromCheckpointVisitor {
644 type Value = StartFromCheckpoint;
645
646 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
647 formatter.write_str("a UUID string or the string \"latest\"")
648 }
649
650 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
651 where
652 E: de::Error,
653 {
654 if value == "latest" {
655 Ok(StartFromCheckpoint::Latest)
656 } else {
657 uuid::Uuid::parse_str(value)
658 .map(StartFromCheckpoint::Uuid)
659 .map_err(|_| E::invalid_value(serde::de::Unexpected::Str(value), &self))
660 }
661 }
662 }
663
664 deserializer.deserialize_str(StartFromCheckpointVisitor)
665 }
666}
667
668impl Serialize for StartFromCheckpoint {
669 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
670 where
671 S: serde::Serializer,
672 {
673 match self {
674 StartFromCheckpoint::Latest => serializer.serialize_str("latest"),
675 StartFromCheckpoint::Uuid(uuid) => serializer.serialize_str(&uuid.to_string()),
676 }
677 }
678}
679
680#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
681pub struct SyncConfig {
682 pub endpoint: Option<String>,
692
693 pub bucket: String,
702
703 pub region: Option<String>,
707
708 pub provider: Option<String>,
715
716 pub access_key: Option<String>,
722
723 pub secret_key: Option<String>,
729
730 pub start_from_checkpoint: Option<StartFromCheckpoint>,
735
736 #[schema(default = std::primitive::bool::default)]
742 #[serde(default)]
743 pub fail_if_no_checkpoint: bool,
744
745 pub transfers: Option<u8>,
748
749 pub checkers: Option<u8>,
752
753 pub ignore_checksum: Option<bool>,
757
758 pub multi_thread_streams: Option<u8>,
761
762 pub multi_thread_cutoff: Option<String>,
767
768 #[schema(default = default_optimize_download_resources)]
779 #[serde(default = "default_optimize_download_resources")]
780 pub optimize_download_resources: bool,
781
782 pub upload_concurrency: Option<u8>,
785
786 #[deprecated(note = "Use `initial=standby` when starting the pipeline instead.")]
788 #[schema(default = std::primitive::bool::default)]
789 #[serde(default)]
790 pub standby: bool,
791
792 #[serde(
798 default,
799 alias = "pull_interval",
800 deserialize_with = "duration_standby_pull_interval",
801 skip_serializing_if = "Option::is_none"
802 )]
803 #[schema(value_type = Option<String>, default = default_pull_interval)]
804 pub standby_pull_interval: Option<ConfigDuration>,
805
806 #[serde(
812 default,
813 alias = "push_interval",
814 deserialize_with = "duration_checkpoint_push_interval",
815 skip_serializing_if = "Option::is_none"
816 )]
817 #[schema(value_type = Option<String>)]
818 pub checkpoint_push_interval: Option<ConfigDuration>,
819
820 pub flags: Option<Vec<String>>,
829
830 #[schema(default = default_retention_min_count)]
835 #[serde(default = "default_retention_min_count")]
836 pub retention_min_count: u32,
837
838 #[serde(
842 default,
843 alias = "retention_min_age",
844 deserialize_with = "duration_min_retention",
845 skip_serializing_if = "Option::is_none"
846 )]
847 #[schema(value_type = Option<String>, default = default_retention_min_age)]
848 pub min_retention: Option<ConfigDuration>,
849
850 #[serde(default)]
863 pub read_bucket: Option<String>,
864
865 #[schema(default = std::primitive::bool::default)]
891 #[serde(default)]
892 pub take_bucket_ownership: bool,
893}
894
895fn default_retention_min_count() -> u32 {
896 10
897}
898
899fn default_optimize_download_resources() -> bool {
900 true
901}
902
903impl SyncConfig {
904 pub fn standby_pull_interval(&self) -> ConfigDuration {
911 self.standby_pull_interval.unwrap_or(DEFAULT_PULL_INTERVAL)
912 }
913
914 pub fn checkpoint_push_interval(&self) -> Option<ConfigDuration> {
916 self.checkpoint_push_interval
917 }
918
919 pub fn min_retention(&self) -> ConfigDuration {
922 self.min_retention.unwrap_or(DEFAULT_RETENTION_MIN_AGE)
923 }
924
925 pub fn validate(&self) -> Result<(), String> {
926 #[allow(deprecated)]
927 if self.standby {
928 return Err(
929 "The `standby` config field has been deprecated. Use `initial=standby` when starting the pipeline instead.".to_owned()
930 );
931 }
932
933 if let Some(ref rb) = self.read_bucket {
934 if rb == &self.bucket {
935 return Err(
936 "invalid sync config: `read_bucket` and `bucket` must point to different locations"
937 .to_owned(),
938 );
939 }
940 if is_gcs_bucket(rb) != is_gcs_bucket(&self.bucket) {
943 return Err(format!(
944 "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",
945 self.bucket, rb
946 ));
947 }
948 }
949
950 Ok(())
951 }
952}
953
954fn is_gcs_bucket(bucket: &str) -> bool {
956 bucket.starts_with("gs://")
957}
958
959#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
995pub struct PipelineTemplateConfig {
996 pub name: String,
998 #[schema(default = default_pipeline_template_key)]
1002 #[serde(default = "default_pipeline_template_key")]
1003 pub key: String,
1004}
1005
1006fn default_pipeline_template_key() -> String {
1007 "pipelineTemplate".to_string()
1008}
1009
1010#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1011pub struct ObjectStorageConfig {
1012 pub url: String,
1041
1042 #[serde(flatten)]
1075 pub other_options: BTreeMap<String, String>,
1076}
1077
1078#[derive(Debug, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1080#[serde(default)]
1081pub struct FileBackendConfig {
1082 pub async_threads: Option<bool>,
1088
1089 #[serde(
1094 default,
1095 alias = "ioop_delay",
1096 deserialize_with = "duration_ioop_latency",
1097 skip_serializing_if = "Option::is_none"
1098 )]
1099 #[schema(value_type = Option<String>)]
1100 pub ioop_latency: Option<ConfigDuration>,
1101
1102 pub sync: Option<SyncConfig>,
1104
1105 pub sync_mode: Option<StorageSyncMode>,
1110}
1111
1112#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1118#[serde(rename_all = "snake_case")]
1119pub enum StorageSyncMode {
1120 #[default]
1123 Auto,
1124
1125 Syncfs,
1135
1136 PerFile,
1141}
1142
1143#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
1146#[serde(default)]
1147pub struct RuntimeConfig {
1148 pub workers: u16,
1158
1159 #[serde(
1187 default,
1188 alias = "max_rss_mb",
1189 deserialize_with = "size_max_rss",
1190 skip_serializing_if = "Option::is_none"
1191 )]
1192 #[schema(value_type = Option<String>)]
1193 pub max_rss: Option<ConfigSize>,
1194
1195 #[serde(
1218 default,
1219 alias = "datafusion_memory_mb",
1220 deserialize_with = "size_datafusion_memory",
1221 skip_serializing_if = "Option::is_none"
1222 )]
1223 #[schema(value_type = Option<String>)]
1224 pub datafusion_memory: Option<ConfigSize>,
1225
1226 pub hosts: usize,
1233
1234 #[serde(deserialize_with = "deserialize_storage_options")]
1246 pub storage: Option<StorageOptions>,
1247
1248 #[serde(deserialize_with = "deserialize_fault_tolerance")]
1250 pub fault_tolerance: FtConfig,
1251
1252 pub cpu_profiler: bool,
1256
1257 pub tracing: bool,
1259
1260 pub tracing_endpoint_jaeger: String,
1262
1263 pub min_batch_size_records: u64,
1271
1272 #[serde(
1275 default,
1276 alias = "max_buffering_delay_usecs",
1277 deserialize_with = "duration_max_buffering_delay",
1278 skip_serializing_if = "Option::is_none"
1279 )]
1280 #[schema(value_type = Option<String>)]
1281 pub max_buffering_delay: Option<ConfigDuration>,
1282
1283 pub resources: ResourceConfig,
1286
1287 #[serde(
1297 default,
1298 alias = "clock_resolution_usecs",
1299 deserialize_with = "duration_clock_resolution",
1300 skip_serializing_if = "Option::is_none"
1301 )]
1302 #[schema(value_type = Option<String>, default = default_clock_resolution)]
1303 pub clock_resolution: Option<ConfigDuration>,
1304
1305 #[schema(value_type = Option<String>, example = "+05:30")]
1316 pub clock_timezone_offset: Option<ClockTimezoneOffset>,
1317
1318 pub pin_cpus: Vec<usize>,
1327
1328 #[serde(
1331 default,
1332 alias = "provisioning_timeout_secs",
1333 deserialize_with = "duration_provisioning_timeout",
1334 skip_serializing_if = "Option::is_none"
1335 )]
1336 #[schema(value_type = Option<String>)]
1337 pub provisioning_timeout: Option<ConfigDuration>,
1338
1339 pub max_parallel_connector_init: Option<u64>,
1350
1351 pub init_containers: Option<serde_json::Value>,
1353
1354 pub checkpoint_during_suspend: bool,
1356
1357 pub http_workers: Option<u64>,
1365
1366 pub io_workers: Option<u64>,
1377
1378 #[serde(default)]
1385 pub env: BTreeMap<String, String>,
1386
1387 pub dev_tweaks: DevTweaks,
1389
1390 pub logging: Option<String>,
1399
1400 pub pipeline_template_configmap: Option<PipelineTemplateConfig>,
1408}
1409
1410fn deserialize_storage_options<'de, D>(deserializer: D) -> Result<Option<StorageOptions>, D::Error>
1412where
1413 D: Deserializer<'de>,
1414{
1415 struct BoolOrStruct;
1416
1417 impl<'de> Visitor<'de> for BoolOrStruct {
1418 type Value = Option<StorageOptions>;
1419
1420 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1421 formatter.write_str("boolean or StorageOptions")
1422 }
1423
1424 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1425 where
1426 E: de::Error,
1427 {
1428 match v {
1429 false => Ok(None),
1430 true => Ok(Some(StorageOptions::default())),
1431 }
1432 }
1433
1434 fn visit_unit<E>(self) -> Result<Self::Value, E>
1435 where
1436 E: de::Error,
1437 {
1438 Ok(None)
1439 }
1440
1441 fn visit_none<E>(self) -> Result<Self::Value, E>
1442 where
1443 E: de::Error,
1444 {
1445 Ok(None)
1446 }
1447
1448 fn visit_map<M>(self, map: M) -> Result<Option<StorageOptions>, M::Error>
1449 where
1450 M: MapAccess<'de>,
1451 {
1452 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
1453 }
1454 }
1455
1456 deserializer.deserialize_any(BoolOrStruct)
1457}
1458
1459fn deserialize_fault_tolerance<'de, D>(deserializer: D) -> Result<FtConfig, D::Error>
1467where
1468 D: Deserializer<'de>,
1469{
1470 struct StringOrStruct;
1471
1472 impl<'de> Visitor<'de> for StringOrStruct {
1473 type Value = FtConfig;
1474
1475 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1476 formatter.write_str("none or FtConfig or 'initial_state' or 'latest_checkpoint'")
1477 }
1478
1479 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1480 where
1481 E: de::Error,
1482 {
1483 match v {
1484 "initial_state" | "latest_checkpoint" => Ok(FtConfig {
1485 model: Some(FtModel::default()),
1486 ..FtConfig::default()
1487 }),
1488 _ => Err(de::Error::invalid_value(de::Unexpected::Str(v), &self)),
1489 }
1490 }
1491
1492 fn visit_unit<E>(self) -> Result<Self::Value, E>
1493 where
1494 E: de::Error,
1495 {
1496 Ok(FtConfig::default())
1497 }
1498
1499 fn visit_none<E>(self) -> Result<Self::Value, E>
1500 where
1501 E: de::Error,
1502 {
1503 Ok(FtConfig::default())
1504 }
1505
1506 fn visit_map<M>(self, map: M) -> Result<FtConfig, M::Error>
1507 where
1508 M: MapAccess<'de>,
1509 {
1510 Deserialize::deserialize(de::value::MapAccessDeserializer::new(map))
1511 }
1512 }
1513
1514 deserializer.deserialize_any(StringOrStruct)
1515}
1516
1517impl Default for RuntimeConfig {
1518 fn default() -> Self {
1519 Self {
1520 workers: 8,
1521 max_rss: None,
1522 datafusion_memory: None,
1523 hosts: 1,
1524 storage: Some(StorageOptions::default()),
1525 fault_tolerance: FtConfig::default(),
1526 cpu_profiler: true,
1527 tracing: {
1528 false
1531 },
1532 tracing_endpoint_jaeger: "127.0.0.1:6831".to_string(),
1533 min_batch_size_records: 0,
1534 max_buffering_delay: None,
1535 resources: ResourceConfig::default(),
1536 clock_resolution: None,
1537 clock_timezone_offset: None,
1538 pin_cpus: Vec::new(),
1539 provisioning_timeout: None,
1540 max_parallel_connector_init: None,
1541 init_containers: None,
1542 checkpoint_during_suspend: true,
1543 io_workers: None,
1544 http_workers: None,
1545 env: BTreeMap::default(),
1546 dev_tweaks: DevTweaks::default(),
1547 logging: None,
1548 pipeline_template_configmap: None,
1549 }
1550 }
1551}
1552
1553pub const DEFAULT_DATAFUSION_MEMORY_CEILING: ConfigSize = ConfigSize::from_mb(2048);
1557
1558pub const DEFAULT_DATAFUSION_MEMORY_PERCENT: u64 = 5;
1561
1562impl RuntimeConfig {
1563 pub fn max_buffering_delay(&self) -> ConfigDuration {
1565 self.max_buffering_delay.unwrap_or(ConfigDuration::ZERO)
1566 }
1567
1568 pub fn clock_resolution(&self) -> ConfigDuration {
1570 self.clock_resolution.unwrap_or(DEFAULT_CLOCK_RESOLUTION)
1571 }
1572
1573 pub fn effective_memory(&self) -> Option<ConfigSize> {
1576 self.max_rss.or(self.resources.memory_max)
1577 }
1578
1579 pub fn resolved_datafusion_memory(&self) -> Option<ConfigSize> {
1584 if let Some(explicit) = self.datafusion_memory {
1585 return Some(explicit);
1586 }
1587 let effective = self.effective_memory()?.as_bytes();
1588 let fraction = u128::from(effective) * u128::from(DEFAULT_DATAFUSION_MEMORY_PERCENT) / 100;
1590 let fraction = u64::try_from(fraction).unwrap_or(u64::MAX);
1591 Some(ConfigSize::from_bytes(fraction).min(DEFAULT_DATAFUSION_MEMORY_CEILING))
1592 }
1593}
1594
1595#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
1606#[serde(rename_all = "snake_case")]
1607pub struct FtConfig {
1608 #[serde(with = "none_as_string")]
1610 #[serde(default = "default_model")]
1611 #[schema(
1612 schema_with = none_as_string_schema::<FtModel>,
1613 )]
1614 pub model: Option<FtModel>,
1615
1616 #[serde(
1623 default,
1624 alias = "checkpoint_interval_secs",
1625 deserialize_with = "duration_checkpoint_interval",
1626 skip_serializing_if = "Option::is_none"
1627 )]
1628 #[schema(value_type = Option<String>, default = default_checkpoint_interval)]
1629 pub checkpoint_interval: Option<Option<ConfigDuration>>,
1630}
1631
1632fn default_model() -> Option<FtModel> {
1633 Some(FtModel::default())
1634}
1635
1636pub fn to_legacy_duration_spelling(config: &mut serde_json::Value) {
1656 use crate::duration::LegacyUnit;
1657 use serde_json::{Map, Value};
1658
1659 struct Rule {
1661 new: &'static str,
1662 old: &'static str,
1663 unit: LegacyUnit,
1664 max: u64,
1666 null_allowed: bool,
1669 }
1670 const fn rule(
1671 new: &'static str,
1672 old: &'static str,
1673 unit: LegacyUnit,
1674 max: u64,
1675 null_allowed: bool,
1676 ) -> Rule {
1677 Rule {
1678 new,
1679 old,
1680 unit,
1681 max,
1682 null_allowed,
1683 }
1684 }
1685 const U32: u64 = u32::MAX as u64;
1686 const U64: u64 = u64::MAX;
1687 use LegacyUnit::{Days, Micros, Millis, Secs};
1688
1689 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
1690 for rule in rules {
1691 let Some(value) = object.remove(rule.new) else {
1692 continue;
1693 };
1694 let legacy = match &value {
1695 Value::String(text) => match text.parse::<ConfigDuration>() {
1696 Ok(duration) => {
1697 let nanos = std::time::Duration::from(duration).as_nanos();
1698 let unit_nanos = u128::from(rule.unit.nanos());
1699 let whole = nanos.div_ceil(unit_nanos);
1700 Value::from(u64::try_from(whole).unwrap_or(U64).min(rule.max))
1701 }
1702 Err(_) => {
1703 object.insert(rule.new.to_string(), value);
1704 continue;
1705 }
1706 },
1707 Value::Null if !rule.null_allowed => continue,
1708 other => other.clone(),
1710 };
1711 object.insert(rule.old.to_string(), legacy);
1712 }
1713 }
1714 fn child<'a>(
1715 object: &'a mut Map<String, Value>,
1716 key: &str,
1717 ) -> Option<&'a mut Map<String, Value>> {
1718 object.get_mut(key).and_then(Value::as_object_mut)
1719 }
1720 fn max_expiry(consumer: &mut Map<String, Value>) {
1723 let Some(Value::String(text)) = consumer.get("max_expiry") else {
1724 return;
1725 };
1726 let Ok(duration) = text.parse::<ConfigDuration>() else {
1727 return;
1728 };
1729 let duration = std::time::Duration::from(duration);
1730 consumer.remove("max_expiry");
1731 consumer.insert(
1732 "max_expires".to_string(),
1733 serde_json::json!({"secs": duration.as_secs(), "nanos": duration.subsec_nanos()}),
1734 );
1735 }
1736 fn nats_connection(transport: &mut Map<String, Value>) {
1738 if let Some(connection) = child(transport, "connection_config") {
1739 apply(
1740 connection,
1741 &[
1742 rule(
1743 "connection_timeout",
1744 "connection_timeout_secs",
1745 Secs,
1746 U64,
1747 false,
1748 ),
1749 rule("request_timeout", "request_timeout_secs", Secs, U64, false),
1750 ],
1751 );
1752 }
1753 }
1754 fn connector(endpoint: &mut Map<String, Value>) {
1756 apply(
1757 endpoint,
1758 &[rule(
1759 "max_output_buffer_time",
1760 "max_output_buffer_time_millis",
1761 Millis,
1762 U64,
1763 false,
1764 )],
1765 );
1766 let name = endpoint
1767 .get("transport")
1768 .and_then(|transport| transport.get("name"))
1769 .and_then(Value::as_str)
1770 .map(str::to_string);
1771 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
1772 match name.as_deref() {
1773 Some("url_input") => apply(
1774 transport,
1775 &[rule("pause_linger", "pause_timeout", Secs, U32, false)],
1776 ),
1777 Some("kafka_input") => apply(
1778 transport,
1779 &[rule(
1780 "group_join_timeout",
1781 "group_join_timeout_secs",
1782 Secs,
1783 U32,
1784 false,
1785 )],
1786 ),
1787 Some("kafka_output") => apply(
1788 transport,
1789 &[rule(
1790 "initialization_timeout",
1791 "initialization_timeout_secs",
1792 Secs,
1793 U32,
1794 false,
1795 )],
1796 ),
1797 Some("clock_input") => apply(
1798 transport,
1799 &[rule(
1800 "clock_resolution",
1801 "clock_resolution_usecs",
1802 Micros,
1803 U64,
1804 false,
1805 )],
1806 ),
1807 Some("pub_sub_input") => apply(
1808 transport,
1809 &[
1810 rule("timeout", "timeout_seconds", Secs, U32, true),
1811 rule(
1812 "connect_timeout",
1813 "connect_timeout_seconds",
1814 Secs,
1815 U32,
1816 true,
1817 ),
1818 ],
1819 ),
1820 Some("nats_input") => {
1821 apply(
1822 transport,
1823 &[
1824 rule(
1825 "inactivity_timeout",
1826 "inactivity_timeout_secs",
1827 Secs,
1828 U64,
1829 false,
1830 ),
1831 rule("retry_interval", "retry_interval_secs", Secs, U64, false),
1832 ],
1833 );
1834 nats_connection(transport);
1835 if let Some(consumer) = child(transport, "consumer_config") {
1836 max_expiry(consumer);
1837 }
1838 }
1839 Some("nats_output") => {
1840 apply(
1841 transport,
1842 &[rule(
1843 "publish_timeout",
1844 "publish_timeout_secs",
1845 Secs,
1846 U64,
1847 false,
1848 )],
1849 );
1850 nats_connection(transport);
1851 }
1852 _ => {}
1853 }
1854 }
1855 let is_avro = endpoint
1856 .get("format")
1857 .and_then(|format| format.get("name"))
1858 .and_then(Value::as_str)
1859 == Some("avro");
1860 if is_avro && let Some(format) = child(endpoint, "format").and_then(|f| child(f, "config"))
1861 {
1862 apply(
1863 format,
1864 &[rule(
1865 "registry_timeout",
1866 "registry_timeout_secs",
1867 Secs,
1868 U64,
1869 true,
1870 )],
1871 );
1872 }
1873 }
1874
1875 let Some(global) = config.as_object_mut() else {
1876 return;
1877 };
1878 apply(
1879 global,
1880 &[
1881 rule(
1882 "clock_resolution",
1883 "clock_resolution_usecs",
1884 Micros,
1885 U64,
1886 true,
1887 ),
1888 rule(
1889 "max_buffering_delay",
1890 "max_buffering_delay_usecs",
1891 Micros,
1892 U64,
1893 false,
1894 ),
1895 rule(
1896 "provisioning_timeout",
1897 "provisioning_timeout_secs",
1898 Secs,
1899 U64,
1900 true,
1901 ),
1902 ],
1903 );
1904 if let Some(ft) = child(global, "fault_tolerance") {
1905 apply(
1907 ft,
1908 &[rule(
1909 "checkpoint_interval",
1910 "checkpoint_interval_secs",
1911 Secs,
1912 U64,
1913 true,
1914 )],
1915 );
1916 }
1917 let backend = child(global, "storage")
1918 .and_then(|storage| child(storage, "backend"))
1919 .filter(|backend| backend.get("name").and_then(Value::as_str) == Some("file"))
1920 .and_then(|backend| child(backend, "config"));
1921 if let Some(file) = backend {
1922 apply(
1923 file,
1924 &[rule("ioop_latency", "ioop_delay", Millis, U64, true)],
1925 );
1926 if let Some(sync) = child(file, "sync") {
1927 apply(
1928 sync,
1929 &[
1930 rule("standby_pull_interval", "pull_interval", Secs, U64, false),
1931 rule("checkpoint_push_interval", "push_interval", Secs, U64, true),
1932 rule("min_retention", "retention_min_age", Days, U32, false),
1933 ],
1934 );
1935 }
1936 }
1937 for endpoints in ["inputs", "outputs"] {
1938 if let Some(endpoints) = child(global, endpoints) {
1939 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
1940 connector(endpoint);
1941 }
1942 }
1943 }
1944}
1945
1946#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1952pub struct LegacySpelling {
1953 pub durations: bool,
1955 pub sizes: bool,
1957}
1958
1959impl LegacySpelling {
1960 pub const NONE: LegacySpelling = LegacySpelling {
1962 durations: false,
1963 sizes: false,
1964 };
1965
1966 pub fn any(self) -> bool {
1968 self.durations || self.sizes
1969 }
1970
1971 pub fn apply(self, config: &mut serde_json::Value) {
1974 if self.durations {
1975 to_legacy_duration_spelling(config);
1976 }
1977 if self.sizes {
1978 to_legacy_size_spelling(config);
1979 }
1980 }
1981}
1982
1983pub fn to_legacy_size_spelling(config: &mut serde_json::Value) {
1994 use crate::size::LegacySizeUnit::{self, Bytes, Mebibytes, Megabytes};
1995 use serde_json::{Map, Value};
1996
1997 struct Rule {
1999 new: &'static str,
2000 old: &'static str,
2001 unit: LegacySizeUnit,
2002 }
2003 const fn rule(new: &'static str, old: &'static str, unit: LegacySizeUnit) -> Rule {
2004 Rule { new, old, unit }
2005 }
2006
2007 fn apply(object: &mut Map<String, Value>, rules: &[Rule]) {
2008 for rule in rules {
2009 let Some(value) = object.remove(rule.new) else {
2010 continue;
2011 };
2012 let legacy = match &value {
2013 Value::String(text) => match text.parse::<ConfigSize>() {
2014 Ok(size) => Value::from(size.as_bytes().div_ceil(rule.unit.bytes())),
2015 Err(_) => {
2016 object.insert(rule.new.to_string(), value);
2017 continue;
2018 }
2019 },
2020 Value::Null => continue,
2022 other => other.clone(),
2024 };
2025 object.insert(rule.old.to_string(), legacy);
2026 }
2027 }
2028 fn child<'a>(
2029 object: &'a mut Map<String, Value>,
2030 key: &str,
2031 ) -> Option<&'a mut Map<String, Value>> {
2032 object.get_mut(key).and_then(Value::as_object_mut)
2033 }
2034 fn connector(endpoint: &mut Map<String, Value>) {
2036 apply(
2037 endpoint,
2038 &[rule("max_queued_size", "max_queued_bytes", Bytes)],
2039 );
2040 let name = endpoint
2041 .get("transport")
2042 .and_then(|transport| transport.get("name"))
2043 .and_then(Value::as_str)
2044 .map(str::to_string);
2045 if let Some(transport) = child(endpoint, "transport").and_then(|t| child(t, "config")) {
2046 match name.as_deref() {
2047 Some("file_input") => apply(
2048 transport,
2049 &[rule("buffer_size", "buffer_size_bytes", Bytes)],
2050 ),
2051 Some("dynamodb_output" | "postgres_output") => apply(
2052 transport,
2053 &[rule("max_buffer_size", "max_buffer_size_bytes", Bytes)],
2054 ),
2055 Some("postgres_cdc_input") => {
2056 if let Some(batch) = child(transport, "batch") {
2057 apply(batch, &[rule("max_size", "max_bytes", Bytes)]);
2058 }
2059 }
2060 _ => {}
2061 }
2062 }
2063 }
2064
2065 let Some(global) = config.as_object_mut() else {
2066 return;
2067 };
2068 apply(
2069 global,
2070 &[
2071 rule("max_rss", "max_rss_mb", Megabytes),
2072 rule("datafusion_memory", "datafusion_memory_mb", Megabytes),
2073 ],
2074 );
2075 if let Some(storage) = child(global, "storage") {
2076 apply(
2077 storage,
2078 &[
2079 rule("cache_size", "cache_mib", Mebibytes),
2080 rule("min_spill_size", "min_storage_bytes", Bytes),
2081 rule("min_step_spill_size", "min_step_storage_bytes", Bytes),
2082 ],
2083 );
2084 }
2085 if let Some(resources) = child(global, "resources") {
2086 apply(
2087 resources,
2088 &[
2089 rule("memory_min", "memory_mb_min", Megabytes),
2090 rule("memory_max", "memory_mb_max", Megabytes),
2091 rule("storage_min", "storage_mb_min", Megabytes),
2092 rule("storage_max", "storage_mb_max", Megabytes),
2093 ],
2094 );
2095 if let Some(storage) = child(resources, "autoscaling").and_then(|a| child(a, "storage")) {
2096 apply(
2097 storage,
2098 &[rule(
2099 "scale_threshold_available",
2100 "scale_threshold_available_mb",
2101 Megabytes,
2102 )],
2103 );
2104 }
2105 }
2106 if let Some(tweaks) = child(global, "dev_tweaks") {
2107 apply(
2108 tweaks,
2109 &[
2110 rule("storage_max", "storage_mb_max", Mebibytes),
2111 rule(
2112 "fbuf_slab_size_per_class",
2113 "fbuf_slab_bytes_per_class",
2114 Bytes,
2115 ),
2116 rule(
2117 "lazy_input_map_key_block_size",
2118 "lazy_input_map_key_block_bytes",
2119 Bytes,
2120 ),
2121 rule(
2122 "exchange_channel_capacity",
2123 "exchange_channel_capacity_bytes",
2124 Bytes,
2125 ),
2126 ],
2127 );
2128 }
2129 for endpoints in ["inputs", "outputs"] {
2130 if let Some(endpoints) = child(global, endpoints) {
2131 for endpoint in endpoints.values_mut().filter_map(Value::as_object_mut) {
2132 connector(endpoint);
2133 }
2134 }
2135 }
2136}
2137
2138#[cfg(test)]
2139mod test {
2140 use super::deserialize_fault_tolerance;
2141 use crate::config::{
2142 ConnectorConfig, DEFAULT_CLOCK_RESOLUTION, DEFAULT_DATAFUSION_MEMORY_CEILING,
2143 DEFAULT_PULL_INTERVAL, DEFAULT_RETENTION_MIN_AGE, FileBackendConfig, FtConfig, FtModel,
2144 OutputBufferConfig, PipelineConfig, ResourceConfig, RuntimeConfig, StorageBackendConfig,
2145 StorageOptions, SyncConfig, TransportConfig,
2146 };
2147 use crate::duration::ConfigDuration;
2148 use crate::size::ConfigSize;
2149 use serde::{Deserialize, Serialize};
2150 use serde_json::json;
2151 use std::time::Duration;
2152
2153 fn assert_reloads<T>(value: serde_json::Value)
2156 where
2157 T: Serialize + for<'de> Deserialize<'de>,
2158 {
2159 let first: T = serde_json::from_value(value.clone())
2160 .unwrap_or_else(|e| panic!("{value} does not load: {e}"));
2161 let written = serde_json::to_value(&first).unwrap();
2162 let second: T = serde_json::from_value(written.clone()).unwrap_or_else(|e| {
2163 panic!("{value} is written as {written}, which does not load: {e}")
2164 });
2165 assert_eq!(serde_json::to_value(&second).unwrap(), written, "{value}");
2166 }
2167
2168 #[test]
2173 fn size_settings_reload_from_what_is_written() {
2174 use crate::transport::dynamodb::DynamoDBWriterConfig;
2175 use crate::transport::file::FileInputConfig;
2176 use crate::transport::postgres::{PostgresCdcBatchConfig, PostgresWriterConfig};
2177
2178 for number in [0u64, 1, 1_100, u64::MAX] {
2181 assert_reloads::<RuntimeConfig>(json!({
2182 "max_rss_mb": number,
2183 "datafusion_memory_mb": number,
2184 "storage": {"cache_mib": number, "min_storage_bytes": number},
2185 "resources": {"memory_mb_min": number, "storage_mb_max": number},
2186 "dev_tweaks": {"storage_mb_max": number},
2187 }));
2188 }
2189
2190 let max = format!("{}B", u64::MAX);
2191 for size in ["0B", "1B", "999B", "1.1Gi", "1.1G", "16G", "8Gi", &max] {
2192 assert_reloads::<RuntimeConfig>(json!({
2193 "max_rss": size,
2194 "datafusion_memory": size,
2195 "storage": {
2196 "cache_size": size,
2197 "min_spill_size": size,
2198 "min_step_spill_size": size,
2199 },
2200 "resources": {
2201 "memory_min": size,
2202 "memory_max": size,
2203 "storage_min": size,
2204 "storage_max": size,
2205 "autoscaling": {"storage": {"scale_threshold_available": size}},
2206 },
2207 "dev_tweaks": {
2208 "storage_max": size,
2209 "fbuf_slab_size_per_class": size,
2210 "exchange_channel_capacity": size,
2211 },
2212 }));
2213 assert_reloads::<ConnectorConfig>(json!({
2214 "transport": {
2215 "name": "file_input",
2216 "config": {"path": "input.csv", "buffer_size": size},
2217 },
2218 "max_queued_size": size,
2219 }));
2220 assert_reloads::<FileInputConfig>(json!({"path": "input.csv", "buffer_size": size}));
2221 assert_reloads::<PostgresCdcBatchConfig>(json!({"max_size": size}));
2222 assert_reloads::<PostgresWriterConfig>(json!({
2223 "uri": "postgres://localhost/db",
2224 "table": "t",
2225 "max_buffer_size": size,
2226 }));
2227 assert_reloads::<DynamoDBWriterConfig>(json!({
2228 "table": "t",
2229 "region": "us-east-1",
2230 "max_buffer_size": size,
2231 }));
2232 }
2233 }
2234
2235 #[test]
2240 fn soft_delete_is_backward_compatible() {
2241 let config: ConnectorConfig = serde_json::from_value(json!({
2242 "transport": {"name": "empty_input"}
2243 }))
2244 .unwrap();
2245 assert!(!config.soft_delete);
2246
2247 let serialized = serde_json::to_value(&config).unwrap();
2248 assert_eq!(serialized.get("soft_delete"), None);
2249
2250 let config: ConnectorConfig = serde_json::from_value(json!({
2251 "transport": {"name": "empty_input"},
2252 "soft_delete": true
2253 }))
2254 .unwrap();
2255 assert!(config.soft_delete);
2256 assert_eq!(
2257 serde_json::to_value(&config).unwrap().get("soft_delete"),
2258 Some(&json!(true))
2259 );
2260 }
2261
2262 #[test]
2265 fn soft_delete_invalidates_checkpointed_connector_state() {
2266 let config = ConnectorConfig::new(TransportConfig::EmptyInput, None);
2267 let mut soft_delete = config.clone();
2268 soft_delete.soft_delete = true;
2269
2270 assert!(config.equal_for_input_checkpoint_replay(&config));
2271 assert!(!config.equal_for_input_checkpoint_replay(&soft_delete));
2272 }
2273
2274 fn config_with_name(name: Option<&str>) -> PipelineConfig {
2275 PipelineConfig {
2276 global: RuntimeConfig::default(),
2277 multihost: None,
2278 name: name.map(str::to_string),
2279 given_name: None,
2280 storage_config: None,
2281 secrets_dir: None,
2282 inputs: Default::default(),
2283 outputs: Default::default(),
2284 program_ir: None,
2285 }
2286 }
2287
2288 #[test]
2289 fn pipeline_identity_uses_system_and_given_names() {
2290 let mut config = config_with_name(Some("pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"));
2291 config.given_name = Some("my-pipeline".to_string());
2292
2293 let metadata = config.pipeline_identity().unwrap();
2294 assert_eq!(
2295 metadata.name,
2296 "pipeline-018f6f57-4e15-7438-91af-3fd21ff2a8d3"
2297 );
2298 assert_eq!(metadata.given_name.as_deref(), Some("my-pipeline"));
2299 }
2300
2301 #[test]
2302 fn pipeline_identity_is_none_without_system_name() {
2303 assert_eq!(config_with_name(None).pipeline_identity(), None);
2304 }
2305
2306 #[test]
2307 fn resolved_datafusion_memory_explicit_passes_through() {
2308 let config = RuntimeConfig {
2309 max_rss: Some(ConfigSize::from_mb(8_000)),
2310 datafusion_memory: Some(ConfigSize::from_mb(1_500)),
2311 ..Default::default()
2312 };
2313 assert_eq!(
2314 config.resolved_datafusion_memory(),
2315 Some(ConfigSize::from_mb(1_500))
2316 );
2317 }
2318
2319 #[test]
2320 fn resolved_datafusion_memory_unconfigured_returns_none() {
2321 let config = RuntimeConfig::default();
2322 assert!(config.max_rss.is_none());
2323 assert!(config.resources.memory_max.is_none());
2324 assert_eq!(config.resolved_datafusion_memory(), None);
2325 }
2326
2327 #[test]
2328 fn resolved_datafusion_memory_small_budget_scales_down() {
2329 let config = RuntimeConfig {
2331 max_rss: Some(ConfigSize::from_mb(256)),
2332 ..Default::default()
2333 };
2334 assert_eq!(
2335 config.resolved_datafusion_memory(),
2336 Some(ConfigSize::from_bytes(12_800_000))
2337 );
2338
2339 let config = RuntimeConfig {
2340 max_rss: Some(ConfigSize::from_mb(512)),
2341 ..Default::default()
2342 };
2343 assert_eq!(
2344 config.resolved_datafusion_memory(),
2345 Some(ConfigSize::from_bytes(25_600_000))
2346 );
2347 }
2348
2349 #[test]
2350 fn resolved_datafusion_memory_clamps_to_ceiling_for_large_budgets() {
2351 let config = RuntimeConfig {
2353 max_rss: Some(ConfigSize::from_mb(64_000)),
2354 ..Default::default()
2355 };
2356 assert_eq!(
2357 config.resolved_datafusion_memory(),
2358 Some(DEFAULT_DATAFUSION_MEMORY_CEILING),
2359 );
2360 }
2361
2362 #[test]
2363 fn resolved_datafusion_memory_midrange_uses_five_percent() {
2364 let config = RuntimeConfig {
2366 max_rss: Some(ConfigSize::from_mb(16_000)),
2367 ..Default::default()
2368 };
2369 assert_eq!(
2370 config.resolved_datafusion_memory(),
2371 Some(ConfigSize::from_mb(800))
2372 );
2373 }
2374
2375 #[test]
2376 fn resolved_datafusion_memory_falls_back_to_resources() {
2377 let config = RuntimeConfig {
2379 max_rss: None,
2380 resources: ResourceConfig {
2381 memory_max: Some(ConfigSize::from_mb(16_000)),
2382 ..Default::default()
2383 },
2384 ..Default::default()
2385 };
2386 assert_eq!(
2387 config.resolved_datafusion_memory(),
2388 Some(ConfigSize::from_mb(800))
2389 );
2390 }
2391
2392 #[test]
2393 fn ft_config() {
2394 #[derive(Serialize, Deserialize, Default, PartialEq, Eq, Debug)]
2395 #[serde(default)]
2396 struct Wrapper {
2397 #[serde(deserialize_with = "deserialize_fault_tolerance")]
2398 config: FtConfig,
2399 }
2400
2401 for s in [
2404 "{}",
2405 r#"{"config": null}"#,
2406 r#"{"config": {"model": "none"}}"#,
2407 ] {
2408 let config: Wrapper = serde_json::from_str(s).unwrap();
2409 assert_eq!(config.config.model, None);
2410 assert_eq!(config.config.checkpoint_interval(), None);
2411 }
2412
2413 let s = serde_json::to_string(&Wrapper {
2415 config: FtConfig::default(),
2416 })
2417 .unwrap();
2418 assert!(s.contains("\"none\""));
2419
2420 for s in [
2423 r#"{}"#,
2424 r#"{"checkpoint_interval": "60s"}"#,
2425 r#"{"checkpoint_interval_secs": 60}"#,
2426 ] {
2427 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2428 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2429 assert_eq!(
2430 config.checkpoint_interval(),
2431 Some(Duration::from_secs(60)),
2432 "parsing {s}"
2433 );
2434 }
2435
2436 for s in [
2439 r#"{"checkpoint_interval": null}"#,
2440 r#"{"checkpoint_interval_secs": null}"#,
2441 ] {
2442 let config = serde_json::from_str::<FtConfig>(s).unwrap();
2443 assert_eq!(config.model, Some(FtModel::default()), "parsing {s}");
2444 assert_eq!(config.checkpoint_interval(), None, "parsing {s}");
2445 }
2446
2447 let error = serde_json::from_str::<FtConfig>(
2450 r#"{"checkpoint_interval": "5m", "checkpoint_interval_secs": 10}"#,
2451 )
2452 .unwrap_err()
2453 .to_string();
2454 assert!(error.contains("duplicate field"), "{error}");
2455
2456 for (json, expected_secs) in [
2458 (r#"{"checkpoint_interval": "1ms"}"#, 1),
2459 (r#"{"checkpoint_interval": "10h"}"#, 3600),
2460 ] {
2461 assert_eq!(
2462 serde_json::from_str::<FtConfig>(json)
2463 .unwrap()
2464 .checkpoint_interval(),
2465 Some(Duration::from_secs(expected_secs)),
2466 "parsing {json}"
2467 );
2468 }
2469 }
2470
2471 #[test]
2475 fn legacy_duration_spelling_uses_the_older_keys() {
2476 let mut config = serde_json::json!({
2477 "workers": 2,
2478 "clock_resolution": "250ms",
2479 "max_buffering_delay": "3ms",
2480 "provisioning_timeout": "15m",
2481 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2482 "storage": {"backend": {"name": "file", "config": {
2483 "ioop_latency": "5ms",
2484 "sync": {"bucket": "b", "standby_pull_interval": "10s",
2485 "checkpoint_push_interval": "1h", "min_retention": "30d"}}}},
2486 });
2487 super::to_legacy_duration_spelling(&mut config);
2488 assert_eq!(
2489 config,
2490 serde_json::json!({
2491 "workers": 2,
2492 "clock_resolution_usecs": 250_000,
2493 "max_buffering_delay_usecs": 3_000,
2494 "provisioning_timeout_secs": 900,
2495 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval_secs": 20},
2496 "storage": {"backend": {"name": "file", "config": {
2497 "ioop_delay": 5,
2498 "sync": {"bucket": "b", "pull_interval": 10,
2499 "push_interval": 3_600, "retention_min_age": 30}}}},
2500 })
2501 );
2502 }
2503
2504 fn pipeline_with_every_duration_connector() -> serde_json::Value {
2506 serde_json::json!({
2507 "name": "p",
2508 "clock_resolution": "250ms",
2509 "inputs": {
2510 "t.kafka": {"stream": "t", "transport": {"name": "kafka_input", "config": {
2511 "topic": "t", "group_join_timeout": "30s"}}},
2512 "t.url": {"stream": "t", "transport": {"name": "url_input", "config": {
2513 "path": "http://x", "pause_linger": "7s"}}},
2514 "t.nats": {"stream": "t", "transport": {"name": "nats_input", "config": {
2515 "connection_config": {"server_url": "nats://x",
2516 "connection_timeout": "5s", "request_timeout": "6s"},
2517 "stream_name": "s",
2518 "consumer_config": {"deliver_policy": "All", "max_expiry": "45.5s"},
2519 "inactivity_timeout": "90s", "retry_interval": "3s"}}},
2520 "t.pubsub": {"stream": "t", "transport": {"name": "pub_sub_input", "config": {
2521 "subscription": "s", "timeout": "20s", "connect_timeout": "4s"}}},
2522 },
2523 "outputs": {
2524 "v.kafka": {"stream": "v",
2525 "transport": {"name": "kafka_output", "config": {
2526 "topic": "v", "initialization_timeout": "40s"}},
2527 "format": {"name": "avro", "config": {"registry_urls": ["http://r"],
2528 "registry_timeout": "8s"}},
2529 "enable_output_buffer": true,
2530 "max_output_buffer_time": "500ms"},
2531 "v.nats": {"stream": "v", "transport": {"name": "nats_output", "config": {
2532 "connection_config": {"server_url": "nats://x",
2533 "connection_timeout": "5s", "request_timeout": "6s"},
2534 "subject": "s", "publish_timeout": "9s"}}},
2535 },
2536 })
2537 }
2538
2539 #[test]
2543 fn legacy_duration_spelling_rewrites_every_connector() {
2544 let mut config = pipeline_with_every_duration_connector();
2545 super::to_legacy_duration_spelling(&mut config);
2546 let i = &config["inputs"];
2547 assert_eq!(
2548 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2549 30
2550 );
2551 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 7);
2552 let nats = &i["t.nats"]["transport"]["config"];
2553 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2554 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2555 assert_eq!(nats["inactivity_timeout_secs"], 90);
2556 assert_eq!(nats["retry_interval_secs"], 3);
2557 assert_eq!(
2558 nats["consumer_config"]["max_expires"],
2559 serde_json::json!({"secs": 45, "nanos": 500_000_000})
2560 );
2561 let pubsub = &i["t.pubsub"]["transport"]["config"];
2562 assert_eq!(pubsub["timeout_seconds"], 20);
2563 assert_eq!(pubsub["connect_timeout_seconds"], 4);
2564 let out = &config["outputs"]["v.kafka"];
2565 assert_eq!(
2566 out["transport"]["config"]["initialization_timeout_secs"],
2567 40
2568 );
2569 assert_eq!(out["format"]["config"]["registry_timeout_secs"], 8);
2570 assert_eq!(out["max_output_buffer_time_millis"], 500);
2571 let nats = &config["outputs"]["v.nats"]["transport"]["config"];
2572 assert_eq!(nats["connection_config"]["connection_timeout_secs"], 5);
2573 assert_eq!(nats["connection_config"]["request_timeout_secs"], 6);
2574 assert_eq!(nats["publish_timeout_secs"], 9);
2575
2576 let text = config.to_string();
2578 for new in [
2579 "\"group_join_timeout\"",
2580 "\"pause_linger\"",
2581 "\"connection_timeout\"",
2582 "\"request_timeout\"",
2583 "\"inactivity_timeout\"",
2584 "\"retry_interval\"",
2585 "\"max_expiry\"",
2586 "\"timeout\"",
2587 "\"connect_timeout\"",
2588 "\"initialization_timeout\"",
2589 "\"registry_timeout\"",
2590 "\"max_output_buffer_time\"",
2591 "\"publish_timeout\"",
2592 "\"clock_resolution\"",
2593 ] {
2594 assert!(!text.contains(new), "{new} survived in {text}");
2595 }
2596 }
2597
2598 #[test]
2600 fn legacy_duration_spelling_round_trips_connectors() {
2601 let original: PipelineConfig =
2602 serde_json::from_value(pipeline_with_every_duration_connector()).unwrap();
2603 let mut value = serde_json::to_value(&original).unwrap();
2604 super::to_legacy_duration_spelling(&mut value);
2605 let mut reread: PipelineConfig = serde_json::from_value(value).unwrap();
2606
2607 let registry = |config: &PipelineConfig| {
2610 let format = config.outputs["v.kafka"]
2611 .connector_config
2612 .format
2613 .clone()
2614 .unwrap();
2615 serde_json::from_value::<crate::format::avro::AvroEncoderConfig>(format.config)
2616 .unwrap()
2617 .registry_config
2618 .registry_timeout
2619 };
2620 assert_eq!(registry(&reread), registry(&original));
2621 let mut original = original;
2622 for config in [&mut reread, &mut original] {
2623 config
2624 .outputs
2625 .get_mut("v.kafka")
2626 .unwrap()
2627 .connector_config
2628 .format = None;
2629 }
2630 assert_eq!(reread, original);
2631 }
2632
2633 #[test]
2637 fn legacy_duration_spelling_caps_and_keeps_bare_numbers() {
2638 let mut config = serde_json::json!({
2639 "inputs": {
2640 "t.kafka": {"transport": {"name": "kafka_input", "config": {
2641 "group_join_timeout": "100000000000s"}}},
2642 "t.url": {"transport": {"name": "url_input", "config": {"pause_linger": 9}}},
2643 },
2644 "storage": {"backend": {"name": "file", "config": {
2645 "sync": {"min_retention": "100000000000d"}}}},
2646 });
2647 super::to_legacy_duration_spelling(&mut config);
2648 let i = &config["inputs"];
2649 assert_eq!(
2650 i["t.kafka"]["transport"]["config"]["group_join_timeout_secs"],
2651 u64::from(u32::MAX)
2652 );
2653 assert_eq!(i["t.url"]["transport"]["config"]["pause_timeout"], 9);
2654 assert_eq!(
2655 config["storage"]["backend"]["config"]["sync"]["retention_min_age"],
2656 u64::from(u32::MAX)
2657 );
2658 }
2659
2660 #[test]
2664 fn legacy_duration_spelling_round_trips() {
2665 let original: RuntimeConfig = serde_json::from_value(serde_json::json!({
2666 "clock_resolution": "250ms",
2667 "max_buffering_delay": "3ms",
2668 "provisioning_timeout": "15m",
2669 "fault_tolerance": {"model": "at_least_once", "checkpoint_interval": "20s"},
2670 }))
2671 .unwrap();
2672 let mut value = serde_json::to_value(&original).unwrap();
2673 super::to_legacy_duration_spelling(&mut value);
2674 let reread: RuntimeConfig = serde_json::from_value(value).unwrap();
2675 assert_eq!(reread.clock_resolution(), original.clock_resolution());
2676 assert_eq!(reread.max_buffering_delay(), original.max_buffering_delay());
2677 assert_eq!(reread.provisioning_timeout, original.provisioning_timeout);
2678 assert_eq!(
2679 reread.fault_tolerance.checkpoint_interval(),
2680 original.fault_tolerance.checkpoint_interval()
2681 );
2682 }
2683
2684 #[test]
2689 fn legacy_duration_spelling_edge_cases() {
2690 let mut config = serde_json::json!({
2691 "max_buffering_delay": null,
2692 "provisioning_timeout": "1.5s",
2693 "fault_tolerance": {"checkpoint_interval": null},
2694 "clock_resolution": "10sec",
2695 "storage": {"backend": {"name": "file", "config": {
2696 "ioop_latency": "400us",
2697 "sync": {"bucket": "b", "min_retention": "11h", "standby_pull_interval": "400ms"}}}},
2698 });
2699 super::to_legacy_duration_spelling(&mut config);
2700 assert_eq!(
2701 config,
2702 serde_json::json!({
2703 "provisioning_timeout_secs": 2,
2704 "fault_tolerance": {"checkpoint_interval_secs": null},
2705 "clock_resolution": "10sec",
2706 "storage": {"backend": {"name": "file", "config": {
2707 "ioop_delay": 1,
2708 "sync": {"bucket": "b", "retention_min_age": 1, "pull_interval": 1}}}},
2709 })
2710 );
2711
2712 let mut zero = serde_json::json!({"provisioning_timeout": "0"});
2714 super::to_legacy_duration_spelling(&mut zero);
2715 assert_eq!(zero, serde_json::json!({"provisioning_timeout_secs": 0}));
2716
2717 let legacy = serde_json::json!({"clock_resolution_usecs": 5, "workers": 1});
2719 let mut again = legacy.clone();
2720 super::to_legacy_duration_spelling(&mut again);
2721 assert_eq!(again, legacy);
2722 }
2723
2724 #[test]
2728 fn legacy_size_spelling_uses_the_older_keys() {
2729 let mut config = serde_json::json!({
2730 "workers": 2,
2731 "max_rss": "16G",
2732 "datafusion_memory": "1.5G",
2733 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi", "min_step_spill_size": "0"},
2734 "resources": {
2735 "memory_min": "4G", "memory_max": "16Gi",
2736 "storage_min": "100G", "storage_max": "400Gi",
2737 "autoscaling": {"storage": {"scale_threshold_available": "10G", "scale_factor": 2.0}}
2738 },
2739 "dev_tweaks": {
2740 "storage_max": "1Gi", "fbuf_slab_size_per_class": "16Mi",
2741 "lazy_input_map_key_block_size": "32Ki", "exchange_channel_capacity": "10M"
2742 },
2743 "inputs": {
2744 "t.file": {"stream": "t", "max_queued_size": "1Mi",
2745 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}},
2746 "t.cdc": {"stream": "t",
2747 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_size": "32Mi"}}}},
2748 },
2749 "outputs": {
2750 "v.ddb": {"stream": "v",
2751 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size": "1Mi"}}},
2752 "v.pg": {"stream": "v",
2753 "transport": {"name": "postgres_output", "config": {"max_buffer_size": "2Mi"}}},
2754 },
2755 });
2756 super::to_legacy_size_spelling(&mut config);
2757 assert_eq!(
2758 config,
2759 serde_json::json!({
2760 "workers": 2,
2761 "max_rss_mb": 16_000,
2762 "datafusion_memory_mb": 1_500,
2763 "storage": {"cache_mib": 4096, "min_storage_bytes": 10 * 1024 * 1024, "min_step_storage_bytes": 0},
2764 "resources": {
2765 "memory_mb_min": 4_000, "memory_mb_max": 17_180,
2767 "storage_mb_min": 100_000, "storage_mb_max": 429_497,
2768 "autoscaling": {"storage": {"scale_threshold_available_mb": 10_000, "scale_factor": 2.0}}
2769 },
2770 "dev_tweaks": {
2771 "storage_mb_max": 1024, "fbuf_slab_bytes_per_class": 16 * 1024 * 1024,
2772 "lazy_input_map_key_block_bytes": 32 * 1024, "exchange_channel_capacity_bytes": 10_000_000
2773 },
2774 "inputs": {
2775 "t.file": {"stream": "t", "max_queued_bytes": 1024 * 1024,
2776 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size_bytes": 64 * 1024}}},
2777 "t.cdc": {"stream": "t",
2778 "transport": {"name": "postgres_cdc_input", "config": {"batch": {"max_bytes": 32 * 1024 * 1024}}}},
2779 },
2780 "outputs": {
2781 "v.ddb": {"stream": "v",
2782 "transport": {"name": "dynamodb_output", "config": {"max_buffer_size_bytes": 1024 * 1024}}},
2783 "v.pg": {"stream": "v",
2784 "transport": {"name": "postgres_output", "config": {"max_buffer_size_bytes": 2 * 1024 * 1024}}},
2785 },
2786 })
2787 );
2788 }
2789
2790 #[test]
2793 fn legacy_size_spelling_round_trips() {
2794 let config: PipelineConfig = serde_json::from_value(serde_json::json!({
2795 "name": "p",
2796 "max_rss": "16G",
2797 "datafusion_memory": "1G",
2800 "storage": {"cache_size": "4Gi", "min_spill_size": "10Mi"},
2801 "resources": {"memory_max": "16G", "storage_max": "400G"},
2802 "dev_tweaks": {"lazy_input_map_key_block_size": "32Ki"},
2803 "inputs": {"t.file": {"stream": "t", "max_queued_size": "1Mi",
2804 "transport": {"name": "file_input", "config": {"path": "x", "buffer_size": "64Ki"}}}},
2805 "outputs": {},
2806 }))
2807 .unwrap();
2808 let mut value = serde_json::to_value(&config).unwrap();
2809 super::to_legacy_size_spelling(&mut value);
2810 assert_eq!(value["max_rss_mb"], serde_json::json!(16_000));
2811 assert_eq!(
2812 value["inputs"]["t.file"]["max_queued_bytes"],
2813 serde_json::json!(1024 * 1024)
2814 );
2815 let reread: PipelineConfig = serde_json::from_value(value).unwrap();
2816 assert_eq!(reread, config);
2817 }
2818
2819 #[test]
2822 fn legacy_spelling_applies_each_rename_separately() {
2823 let current = serde_json::json!({"clock_resolution": "1s", "max_rss": "16G"});
2824 let mut both = current.clone();
2825 super::LegacySpelling {
2826 durations: true,
2827 sizes: true,
2828 }
2829 .apply(&mut both);
2830 assert_eq!(
2831 both,
2832 serde_json::json!({"clock_resolution_usecs": 1_000_000, "max_rss_mb": 16_000})
2833 );
2834 let mut sizes_only = current.clone();
2835 super::LegacySpelling {
2836 durations: false,
2837 sizes: true,
2838 }
2839 .apply(&mut sizes_only);
2840 assert_eq!(
2841 sizes_only,
2842 serde_json::json!({"clock_resolution": "1s", "max_rss_mb": 16_000})
2843 );
2844 let mut none = current.clone();
2845 super::LegacySpelling::NONE.apply(&mut none);
2846 assert_eq!(none, current);
2847 assert!(!super::LegacySpelling::NONE.any());
2848 }
2849
2850 #[test]
2851 fn legacy_size_spelling_edge_cases() {
2852 let mut config = serde_json::json!({
2855 "max_rss": "lots",
2856 "resources": {"memory_max": null, "memory_min": 4000}
2857 });
2858 super::to_legacy_size_spelling(&mut config);
2859 assert_eq!(
2860 config,
2861 serde_json::json!({"max_rss": "lots", "resources": {"memory_mb_min": 4000}})
2862 );
2863
2864 let mut small = serde_json::json!({"max_rss": "1"});
2867 super::to_legacy_size_spelling(&mut small);
2868 assert_eq!(small, serde_json::json!({"max_rss_mb": 1}));
2869
2870 let legacy = serde_json::json!({"max_rss_mb": 5, "workers": 1});
2872 let mut again = legacy.clone();
2873 super::to_legacy_size_spelling(&mut again);
2874 assert_eq!(again, legacy);
2875 }
2876
2877 #[test]
2886 fn a_stored_default_matches_an_omitted_one() {
2887 let stored: ConnectorConfig = serde_json::from_value(serde_json::json!({
2888 "transport": {
2889 "name": "url_input",
2890 "config": {"path": "http://example.com/x", "pause_timeout": 60},
2891 }
2892 }))
2893 .unwrap();
2894 let fresh: ConnectorConfig = serde_json::from_value(serde_json::json!({
2895 "transport": {
2896 "name": "url_input",
2897 "config": {"path": "http://example.com/x"},
2898 }
2899 }))
2900 .unwrap();
2901
2902 assert_ne!(stored, fresh);
2905 assert!(stored.equal_for_input_checkpoint_replay(&fresh));
2906
2907 let changed: ConnectorConfig = serde_json::from_value(serde_json::json!({
2909 "transport": {
2910 "name": "url_input",
2911 "config": {"path": "http://example.com/x", "pause_linger": "90s"},
2912 }
2913 }))
2914 .unwrap();
2915 assert!(!stored.equal_for_input_checkpoint_replay(&changed));
2916 }
2917
2918 #[test]
2926 fn an_avro_registry_timeout_compares_equal_across_the_rename() {
2927 let connector = |registry: serde_json::Value| -> ConnectorConfig {
2928 let mut format = serde_json::json!({"registry_urls": ["http://registry:8081"]});
2929 format
2930 .as_object_mut()
2931 .unwrap()
2932 .extend(registry.as_object().unwrap().clone());
2933 serde_json::from_value(serde_json::json!({
2934 "transport": {
2935 "name": "url_input",
2936 "config": {"path": "http://example.com/x"},
2937 },
2938 "format": {"name": "avro", "config": format},
2939 }))
2940 .unwrap()
2941 };
2942 let stored = connector(serde_json::json!({"registry_timeout_secs": 10}));
2943 let current = connector(serde_json::json!({"registry_timeout": "10s"}));
2944 let spelled_out = connector(serde_json::json!({"registry_timeout": "10000ms"}));
2945 let changed = connector(serde_json::json!({"registry_timeout": "11s"}));
2946 let unset = connector(serde_json::json!({}));
2947
2948 assert!(stored.equal_modulo_paused(¤t));
2949 assert!(stored.equal_for_input_checkpoint_replay(¤t));
2950 assert!(current.equal_modulo_paused(&spelled_out));
2951 assert!(!stored.equal_modulo_paused(&changed));
2952 assert!(!stored.equal_modulo_paused(&unset));
2953 let json: ConnectorConfig = serde_json::from_value(serde_json::json!({
2955 "transport": {"name": "url_input", "config": {"path": "http://example.com/x"}},
2956 "format": {"name": "json", "config": {"registry_timeout_secs": 10}},
2957 }))
2958 .unwrap();
2959 assert!(!json.equal_modulo_paused(&stored));
2960 }
2961
2962 #[test]
2968 fn the_largest_legacy_defaults_still_load() {
2969 let buffer: OutputBufferConfig = serde_json::from_value(serde_json::json!({
2970 "enable_output_buffer": false,
2971 "max_output_buffer_time_millis": u64::MAX,
2972 "max_output_buffer_size_records": 10_000_000u64,
2973 }))
2974 .unwrap();
2975 assert_eq!(
2976 buffer.max_output_buffer_time,
2977 Some(ConfigDuration::from_millis(u64::MAX))
2978 );
2979
2980 let sync: SyncConfig =
2982 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 4000000000}"#).unwrap();
2983 assert_eq!(
2984 sync.min_retention(),
2985 ConfigDuration::from_days(4_000_000_000)
2986 );
2987 }
2988
2989 #[test]
2993 fn a_legacy_number_past_u64_seconds_saturates() {
2994 let sync: SyncConfig =
2995 serde_json::from_str(r#"{"bucket": "b", "retention_min_age": 18446744073709551615}"#)
2996 .unwrap();
2997 assert_eq!(
2998 sync.min_retention(),
2999 ConfigDuration::from(std::time::Duration::MAX)
3000 );
3001 }
3002
3003 #[test]
3007 fn spelled_out_defaults_match_for_kafka_input_and_nats() {
3008 fn connector(value: serde_json::Value) -> ConnectorConfig {
3009 serde_json::from_value(value).unwrap()
3010 }
3011 fn secs(duration: ConfigDuration) -> u64 {
3012 std::time::Duration::from(duration).as_secs()
3013 }
3014 let fresh_kafka = connector(serde_json::json!({
3015 "transport": {"name": "kafka_input", "config": {"topic": "t"}}}));
3016 let TransportConfig::KafkaInput(kafka) = &fresh_kafka.transport else {
3017 unreachable!()
3018 };
3019 let stored_kafka = connector(serde_json::json!({
3020 "transport": {"name": "kafka_input", "config": {
3021 "topic": "t",
3022 "group_join_timeout_secs": secs(kafka.group_join_timeout())}}}));
3023 assert_ne!(stored_kafka, fresh_kafka);
3024 assert!(stored_kafka.equal_for_input_checkpoint_replay(&fresh_kafka));
3025
3026 let base = serde_json::json!({
3027 "connection_config": {"server_url": "nats://x"},
3028 "stream_name": "s",
3029 "consumer_config": {"deliver_policy": "All"}});
3030 let fresh_nats = connector(serde_json::json!({
3031 "transport": {"name": "nats_input", "config": base.clone()}}));
3032 let TransportConfig::NatsInput(nats) = &fresh_nats.transport else {
3033 unreachable!()
3034 };
3035 let mut spelled_out = base;
3036 spelled_out["inactivity_timeout_secs"] = secs(nats.inactivity_timeout()).into();
3037 spelled_out["retry_interval_secs"] = secs(nats.retry_interval()).into();
3038 spelled_out["connection_config"]["connection_timeout_secs"] =
3039 secs(nats.connection_config.connection_timeout()).into();
3040 spelled_out["connection_config"]["request_timeout_secs"] =
3041 secs(nats.connection_config.request_timeout()).into();
3042 let stored_nats = connector(serde_json::json!({
3043 "transport": {"name": "nats_input", "config": spelled_out}}));
3044 assert_ne!(stored_nats, fresh_nats);
3045 assert!(stored_nats.equal_for_input_checkpoint_replay(&fresh_nats));
3046 }
3047
3048 #[test]
3054 fn superseded_keys_are_normalised_by_a_round_trip() {
3055 let stored = serde_json::json!({
3056 "workers": 4,
3057 "clock_resolution_usecs": 100_000,
3058 "max_buffering_delay_usecs": 0,
3059 "provisioning_timeout_secs": 300,
3060 });
3061
3062 let config: RuntimeConfig = serde_json::from_value(stored).unwrap();
3063 let written = serde_json::to_value(&config).unwrap();
3064
3065 assert_eq!(written["clock_resolution"], "100ms");
3066 assert_eq!(written["max_buffering_delay"], "0s");
3067 assert_eq!(written["provisioning_timeout"], "5m");
3068 for superseded in [
3069 "clock_resolution_usecs",
3070 "max_buffering_delay_usecs",
3071 "provisioning_timeout_secs",
3072 ] {
3073 assert!(
3074 written.get(superseded).is_none(),
3075 "`{superseded}` survived the round trip: {written}"
3076 );
3077 }
3078
3079 let reparsed: RuntimeConfig = serde_json::from_value(written.clone()).unwrap();
3082 assert_eq!(serde_json::to_value(&reparsed).unwrap(), written);
3083 }
3084
3085 #[test]
3090 fn ioop_latency_accepts_both_spellings() {
3091 for (json, expected) in [
3092 (r#"{"name": "file", "config": {}}"#, None),
3093 (
3094 r#"{"name": "file", "config": {"ioop_latency": "5ms"}}"#,
3095 Some(ConfigDuration::from_millis(5)),
3096 ),
3097 (
3098 r#"{"name": "file", "config": {"ioop_delay": 5}}"#,
3099 Some(ConfigDuration::from_millis(5)),
3100 ),
3101 (
3102 r#"{"name": "file", "config": {"ioop_latency": "1s"}}"#,
3103 Some(ConfigDuration::from_secs(1)),
3104 ),
3105 ] {
3106 let backend: StorageBackendConfig = serde_json::from_str(json).unwrap();
3107 let StorageBackendConfig::File(file) = backend else {
3108 panic!("expected the file backend, parsing {json}");
3109 };
3110 assert_eq!(file.ioop_latency, expected, "parsing {json}");
3111 }
3112 }
3113
3114 #[test]
3118 fn clock_resolution_falls_back_to_the_deprecated_field() {
3119 for (json, expected) in [
3120 (r#"{}"#, DEFAULT_CLOCK_RESOLUTION),
3121 (
3122 r#"{"clock_resolution": "100ms"}"#,
3123 ConfigDuration::from_millis(100),
3124 ),
3125 (
3126 r#"{"clock_resolution_usecs": 100000}"#,
3127 ConfigDuration::from_millis(100),
3128 ),
3129 (r#"{"clock_resolution": null}"#, DEFAULT_CLOCK_RESOLUTION),
3130 (
3131 r#"{"clock_resolution_usecs": null}"#,
3132 DEFAULT_CLOCK_RESOLUTION,
3133 ),
3134 ] {
3135 assert_eq!(
3136 serde_json::from_str::<RuntimeConfig>(json)
3137 .unwrap()
3138 .clock_resolution(),
3139 expected,
3140 "parsing {json}"
3141 );
3142 }
3143 }
3144
3145 #[test]
3148 fn deprecated_duration_fields_still_work() {
3149 let runtime: RuntimeConfig = serde_json::from_str(
3150 r#"{"max_buffering_delay_usecs": 5000, "provisioning_timeout_secs": 1200}"#,
3151 )
3152 .unwrap();
3153 assert_eq!(
3154 runtime.max_buffering_delay(),
3155 ConfigDuration::from_millis(5)
3156 );
3157 assert_eq!(
3158 runtime.provisioning_timeout,
3159 Some(ConfigDuration::from_secs(1200))
3160 );
3161
3162 let sync: SyncConfig = serde_json::from_str(
3163 r#"{"bucket": "b", "pull_interval": 30, "push_interval": 300, "retention_min_age": 7}"#,
3164 )
3165 .unwrap();
3166 assert_eq!(sync.standby_pull_interval(), ConfigDuration::from_secs(30));
3167 assert_eq!(
3168 sync.checkpoint_push_interval(),
3169 Some(ConfigDuration::from_secs(300))
3170 );
3171 assert_eq!(sync.min_retention(), ConfigDuration::from_days(7));
3172
3173 let storage: FileBackendConfig = serde_json::from_str(r#"{"ioop_delay": 5}"#).unwrap();
3174 assert_eq!(storage.ioop_latency, Some(ConfigDuration::from_millis(5)));
3175
3176 let buffer: OutputBufferConfig =
3177 serde_json::from_str(r#"{"max_output_buffer_time_millis": 250}"#).unwrap();
3178 assert_eq!(
3179 buffer.max_output_buffer_time(),
3180 ConfigDuration::from_millis(250)
3181 );
3182 }
3183
3184 #[test]
3187 fn duration_fields_default_when_unset() {
3188 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "b"}"#).unwrap();
3189 assert_eq!(sync.standby_pull_interval(), DEFAULT_PULL_INTERVAL);
3190 assert_eq!(sync.checkpoint_push_interval(), None);
3191 assert_eq!(sync.min_retention(), DEFAULT_RETENTION_MIN_AGE);
3192
3193 let runtime = RuntimeConfig::default();
3194 assert_eq!(runtime.max_buffering_delay(), ConfigDuration::ZERO);
3195 assert_eq!(runtime.clock_resolution(), DEFAULT_CLOCK_RESOLUTION);
3196 assert_eq!(runtime.provisioning_timeout, None);
3197 }
3198
3199 #[test]
3203 fn storage_options_f64_roundtrip_through_pipeline_config() {
3204 let pc = PipelineConfig {
3205 global: RuntimeConfig {
3206 storage: Some(StorageOptions {
3207 bloom_false_positive_rate: Some(0.01),
3208 ..Default::default()
3209 }),
3210 ..Default::default()
3211 },
3212 multihost: None,
3213 name: Some("test-pipeline".into()),
3214 given_name: None,
3215 storage_config: None,
3216 secrets_dir: None,
3217 inputs: Default::default(),
3218 outputs: Default::default(),
3219 program_ir: None,
3220 };
3221
3222 let json = serde_json::to_string_pretty(&pc).unwrap();
3224 let pc2: PipelineConfig = serde_json::from_str(&json).expect(
3225 "JSON string round-trip of PipelineConfig with f64 StorageOptions must succeed",
3226 );
3227 assert_eq!(
3228 pc2.global.storage.unwrap().bloom_false_positive_rate,
3229 Some(0.01)
3230 );
3231
3232 let value = serde_json::to_value(&pc).unwrap();
3234 let pc3: PipelineConfig = serde_json::from_value(value)
3235 .expect("Value round-trip of PipelineConfig with f64 StorageOptions must succeed");
3236 assert_eq!(
3237 pc3.global.storage.unwrap().bloom_false_positive_rate,
3238 Some(0.01)
3239 );
3240 }
3241}
3242
3243impl FtConfig {
3244 pub fn is_enabled(&self) -> bool {
3245 self.model.is_some()
3246 }
3247
3248 pub fn checkpoint_interval(&self) -> Option<Duration> {
3255 if !self.is_enabled() {
3256 return None;
3257 }
3258
3259 let interval = self
3260 .checkpoint_interval
3261 .unwrap_or(Some(DEFAULT_CHECKPOINT_INTERVAL))?;
3262
3263 Some(Duration::from(interval).clamp(Duration::from_secs(1), Duration::from_secs(3600)))
3264 }
3265}
3266
3267mod none_as_string {
3274 use std::marker::PhantomData;
3275
3276 use serde::de::{Deserialize, Deserializer, IntoDeserializer, Visitor};
3277 use serde::ser::{Serialize, Serializer};
3278
3279 pub(super) fn serialize<S, T>(value: &Option<T>, serializer: S) -> Result<S::Ok, S::Error>
3280 where
3281 S: Serializer,
3282 T: Serialize,
3283 {
3284 match value.as_ref() {
3285 Some(value) => value.serialize(serializer),
3286 None => "none".serialize(serializer),
3287 }
3288 }
3289
3290 struct NoneAsString<T>(PhantomData<fn() -> T>);
3291
3292 impl<'de, T> Visitor<'de> for NoneAsString<T>
3293 where
3294 T: Deserialize<'de>,
3295 {
3296 type Value = Option<T>;
3297
3298 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
3299 formatter.write_str("string")
3300 }
3301
3302 fn visit_none<E>(self) -> Result<Self::Value, E>
3303 where
3304 E: serde::de::Error,
3305 {
3306 Ok(None)
3307 }
3308
3309 fn visit_str<E>(self, value: &str) -> Result<Option<T>, E>
3310 where
3311 E: serde::de::Error,
3312 {
3313 if &value.to_ascii_lowercase() == "none" {
3314 Ok(None)
3315 } else {
3316 Ok(Some(T::deserialize(value.into_deserializer())?))
3317 }
3318 }
3319 }
3320
3321 pub(super) fn deserialize<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
3322 where
3323 D: Deserializer<'de>,
3324 T: Deserialize<'de>,
3325 {
3326 deserializer.deserialize_str(NoneAsString(PhantomData))
3327 }
3328}
3329
3330fn none_as_string_schema<'a, T: ToSchema<'a> + Default + Serialize>() -> Schema {
3333 Schema::OneOf(
3334 OneOfBuilder::new()
3335 .item(RefOr::Ref(Ref::new(format!(
3336 "#/components/schemas/{}",
3337 T::schema().0
3338 ))))
3339 .item(
3340 ObjectBuilder::new()
3341 .schema_type(SchemaType::String)
3342 .enum_values(Some(vec!["none"])),
3343 )
3344 .default(Some(
3345 serde_json::to_value(T::default()).expect("Failed to serialize default value"),
3346 ))
3347 .build(),
3348 )
3349}
3350
3351#[derive(
3356 Debug, Copy, Clone, Default, Eq, PartialEq, PartialOrd, Ord, Serialize, Deserialize, ToSchema,
3357)]
3358#[serde(rename_all = "snake_case")]
3359pub enum FtModel {
3360 AtLeastOnce,
3363
3364 #[default]
3367 ExactlyOnce,
3368}
3369
3370impl FtModel {
3371 pub fn option_as_str(value: Option<FtModel>) -> &'static str {
3372 value.map_or("no", |model| model.as_str())
3373 }
3374
3375 pub fn as_str(&self) -> &'static str {
3376 match self {
3377 FtModel::AtLeastOnce => "at_least_once",
3378 FtModel::ExactlyOnce => "exactly_once",
3379 }
3380 }
3381}
3382
3383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3385pub struct FtModelUnknown;
3386
3387impl std::fmt::Display for FtModelUnknown {
3388 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3389 f.write_str("expected `exactly_once` or `at_least_once`")
3390 }
3391}
3392
3393impl std::error::Error for FtModelUnknown {}
3394
3395impl FromStr for FtModel {
3396 type Err = FtModelUnknown;
3397
3398 fn from_str(s: &str) -> Result<Self, Self::Err> {
3399 match s.to_ascii_lowercase().as_str() {
3400 "exactly_once" => Ok(Self::ExactlyOnce),
3401 "at_least_once" => Ok(Self::AtLeastOnce),
3402 _ => Err(FtModelUnknown),
3403 }
3404 }
3405}
3406
3407#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3409pub struct InputEndpointConfig {
3410 pub stream: Cow<'static, str>,
3413
3414 #[serde(flatten)]
3416 pub connector_config: ConnectorConfig,
3417}
3418
3419impl InputEndpointConfig {
3420 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3421 Self {
3422 stream: stream.into(),
3423 connector_config,
3424 }
3425 }
3426}
3427
3428fn deserialize_start_after<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
3432where
3433 D: Deserializer<'de>,
3434{
3435 let value = Option::<JsonValue>::deserialize(deserializer)?;
3436 match value {
3437 Some(JsonValue::String(s)) => Ok(Some(vec![s])),
3438 Some(JsonValue::Array(arr)) => {
3439 let vec = arr
3440 .into_iter()
3441 .map(|item| {
3442 item.as_str()
3443 .map(|s| s.to_string())
3444 .ok_or_else(|| serde::de::Error::custom("invalid 'start_after' property: expected a string, an array of strings, or null"))
3445 })
3446 .collect::<Result<Vec<String>, _>>()?;
3447 Ok(Some(vec))
3448 }
3449 Some(JsonValue::Null) | None => Ok(None),
3450 _ => Err(serde::de::Error::custom(
3451 "invalid 'start_after' property: expected a string, an array of strings, or null",
3452 )),
3453 }
3454}
3455
3456#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3457pub struct ConnectorConfig {
3458 #[serde(default)]
3471 pub send_snapshot: bool,
3472
3473 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3490 pub soft_delete: bool,
3491
3492 pub transport: TransportConfig,
3494
3495 #[serde(skip_serializing_if = "Option::is_none")]
3497 pub preprocessor: Option<Vec<PreprocessorConfig>>,
3498
3499 pub format: Option<FormatConfig>,
3501
3502 #[serde(skip_serializing_if = "Option::is_none")]
3504 pub postprocessor: Option<Vec<PostprocessorConfig>>,
3505
3506 pub index: Option<String>,
3521
3522 #[serde(flatten)]
3524 pub output_buffer_config: OutputBufferConfig,
3525
3526 #[serde(skip_serializing_if = "Option::is_none")]
3539 pub max_batch_size: Option<u64>,
3540
3541 #[serde(skip_serializing_if = "Option::is_none")]
3554 pub max_worker_batch_size: Option<u64>,
3555
3556 #[serde(default = "default_max_queued_records")]
3577 pub max_queued_records: u64,
3578
3579 #[serde(
3602 default,
3603 alias = "max_queued_bytes",
3604 deserialize_with = "size_max_queued_size",
3605 skip_serializing_if = "Option::is_none"
3606 )]
3607 #[schema(value_type = Option<String>)]
3608 pub max_queued_size: Option<ConfigSize>,
3609
3610 #[serde(default)]
3621 pub paused: bool,
3622
3623 #[serde(default)]
3628 pub labels: Vec<String>,
3629
3630 #[serde(deserialize_with = "deserialize_start_after")]
3636 #[serde(default)]
3637 pub start_after: Option<Vec<String>>,
3638
3639 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3651 pub distributed: bool,
3652}
3653
3654impl ConnectorConfig {
3655 pub fn new(transport: TransportConfig, format: Option<FormatConfig>) -> Self {
3656 Self {
3657 send_snapshot: false,
3658 soft_delete: false,
3659 transport,
3660 preprocessor: None,
3661 format,
3662 postprocessor: None,
3663 index: None,
3664 output_buffer_config: Default::default(),
3665 max_batch_size: None,
3666 max_worker_batch_size: None,
3667 max_queued_records: default_max_queued_records(),
3668 max_queued_size: None,
3669 paused: false,
3670 labels: Vec::new(),
3671 start_after: None,
3672 distributed: false,
3673 }
3674 }
3675
3676 pub fn with_max_batch_size(mut self, max_batch_size: Option<u64>) -> Self {
3677 self.max_batch_size = max_batch_size;
3678 self
3679 }
3680
3681 pub fn with_max_queued_records(mut self, max_queued_records: u64) -> Self {
3682 self.max_queued_records = max_queued_records;
3683 self
3684 }
3685
3686 pub fn equal_modulo_paused(&self, other: &Self) -> bool {
3691 let mut a = self.clone();
3692 let mut b = other.clone();
3693 a.paused = false;
3694 b.paused = false;
3695 a.normalize_durations();
3696 b.normalize_durations();
3697 a == b
3698 }
3699
3700 fn normalize_durations(&mut self) {
3711 self.transport.normalize_durations();
3712 self.output_buffer_config.max_output_buffer_time =
3713 Some(self.output_buffer_config.max_output_buffer_time());
3714 if let Some(format) = &mut self.format {
3715 format.normalize_durations();
3716 }
3717 }
3718
3719 pub fn equal_for_input_checkpoint_replay(&self, other: &Self) -> bool {
3722 let mut a = self.clone();
3723 let mut b = other.clone();
3724 a.normalize_for_input_checkpoint_replay();
3725 b.normalize_for_input_checkpoint_replay();
3726 a == b
3727 }
3728
3729 fn normalize_for_input_checkpoint_replay(&mut self) {
3730 self.paused = false;
3731 self.max_batch_size = None;
3732 self.max_worker_batch_size = None;
3733 self.max_queued_records = default_max_queued_records();
3734 self.max_queued_size = None;
3735 self.normalize_durations();
3736 }
3737
3738 pub fn apply_input_checkpoint_replay_config_from(&mut self, other: &Self) {
3741 self.max_batch_size = other.max_batch_size;
3742 self.max_worker_batch_size = other.max_worker_batch_size;
3743 self.max_queued_records = other.max_queued_records;
3744 self.max_queued_size = other.max_queued_size;
3745 }
3746
3747 pub fn max_queued_records(&self) -> u64 {
3749 self.max_queued_records
3750 }
3751
3752 pub fn max_queued_bytes(&self) -> u64 {
3755 self.max_queued_size
3756 .map(ConfigSize::as_bytes)
3757 .unwrap_or_else(|| self.max_queued_records().saturating_mul(1000))
3758 }
3759}
3760
3761#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3762#[serde(default)]
3763pub struct OutputBufferConfig {
3764 pub enable_output_buffer: bool,
3787
3788 #[serde(
3797 default,
3798 alias = "max_output_buffer_time_millis",
3799 deserialize_with = "duration_max_output_buffer_time",
3800 skip_serializing_if = "Option::is_none"
3801 )]
3802 #[schema(value_type = Option<String>)]
3803 pub max_output_buffer_time: Option<ConfigDuration>,
3804
3805 pub max_output_buffer_size_records: usize,
3817}
3818
3819impl OutputBufferConfig {
3820 pub fn max_output_buffer_time(&self) -> ConfigDuration {
3822 self.max_output_buffer_time
3823 .unwrap_or(ConfigDuration::from_millis(u64::MAX))
3824 }
3825}
3826
3827impl Default for OutputBufferConfig {
3828 fn default() -> Self {
3829 Self {
3830 enable_output_buffer: false,
3831 max_output_buffer_size_records: DEFAULT_MAX_OUTPUT_BUFFER_SIZE_RECORDS,
3832 max_output_buffer_time: None,
3833 }
3834 }
3835}
3836
3837#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3839pub struct OutputEndpointConfig {
3840 pub stream: Cow<'static, str>,
3843
3844 #[serde(flatten)]
3846 pub connector_config: ConnectorConfig,
3847}
3848
3849impl OutputEndpointConfig {
3850 pub fn new(stream: impl Into<Cow<'static, str>>, connector_config: ConnectorConfig) -> Self {
3851 Self {
3852 stream: stream.into(),
3853 connector_config,
3854 }
3855 }
3856}
3857
3858#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)]
3862#[serde(tag = "name", content = "config", rename_all = "snake_case")]
3863pub enum TransportConfig {
3864 FileInput(FileInputConfig),
3865 FileOutput(FileOutputConfig),
3866 NatsInput(Box<NatsInputConfig>),
3869 NatsOutput(NatsOutputConfig),
3870 KafkaInput(KafkaInputConfig),
3871 KafkaOutput(KafkaOutputConfig),
3872 PubSubInput(PubSubInputConfig),
3873 UrlInput(UrlInputConfig),
3874 S3Input(S3InputConfig),
3875 DeltaTableInput(DeltaTableReaderConfig),
3876 DeltaTableOutput(DeltaTableWriterConfig),
3877 #[serde(rename = "dynamodb_output")]
3880 DynamoDBOutput(DynamoDBWriterConfig),
3881 RedisOutput(RedisOutputConfig),
3882 IcebergInput(Box<IcebergReaderConfig>),
3884 PostgresInput(PostgresReaderConfig),
3885 PostgresCdcInput(PostgresCdcReaderConfig),
3886 PostgresOutput(PostgresWriterConfig),
3887 Datagen(DatagenInputConfig),
3888 Nexmark(NexmarkInputConfig),
3889 HttpInput(HttpInputConfig),
3891 HttpOutput(HttpOutputConfig),
3893 AdHocInput(AdHocInputConfig),
3895 ClockInput(ClockConfig),
3896 S2Input(S2InputConfig),
3897 S2Output(S2OutputConfig),
3898 NullOutput,
3900 EmptyInput,
3902}
3903
3904impl TransportConfig {
3905 pub fn normalize_durations(&mut self) {
3908 match self {
3909 TransportConfig::UrlInput(config) => {
3910 config.pause_linger = Some(config.pause_linger());
3911 }
3912 TransportConfig::KafkaInput(config) => {
3913 config.group_join_timeout = Some(config.group_join_timeout());
3914 }
3915 TransportConfig::KafkaOutput(config) => {
3916 config.initialization_timeout = Some(config.initialization_timeout());
3917 }
3918 TransportConfig::NatsInput(config) => {
3919 config.connection_config.connection_timeout =
3920 Some(config.connection_config.connection_timeout());
3921 config.connection_config.request_timeout =
3922 Some(config.connection_config.request_timeout());
3923 config.inactivity_timeout = Some(config.inactivity_timeout());
3924 config.retry_interval = Some(config.retry_interval());
3925 }
3926 TransportConfig::NatsOutput(config) => {
3927 config.connection_config.connection_timeout =
3928 Some(config.connection_config.connection_timeout());
3929 config.connection_config.request_timeout =
3930 Some(config.connection_config.request_timeout());
3931 config.publish_timeout = Some(config.publish_timeout());
3932 }
3933 _ => {}
3934 }
3935 }
3936
3937 pub fn name(&self) -> String {
3938 match self {
3939 TransportConfig::FileInput(_) => "file_input".to_string(),
3940 TransportConfig::FileOutput(_) => "file_output".to_string(),
3941 TransportConfig::NatsInput(_) => "nats_input".to_string(),
3942 TransportConfig::NatsOutput(_) => "nats_output".to_string(),
3943 TransportConfig::KafkaInput(_) => "kafka_input".to_string(),
3944 TransportConfig::KafkaOutput(_) => "kafka_output".to_string(),
3945 TransportConfig::PubSubInput(_) => "pub_sub_input".to_string(),
3946 TransportConfig::UrlInput(_) => "url_input".to_string(),
3947 TransportConfig::S3Input(_) => "s3_input".to_string(),
3948 TransportConfig::DeltaTableInput(_) => "delta_table_input".to_string(),
3949 TransportConfig::DeltaTableOutput(_) => "delta_table_output".to_string(),
3950 TransportConfig::DynamoDBOutput(_) => "dynamodb_output".to_string(),
3951 TransportConfig::IcebergInput(_) => "iceberg_input".to_string(),
3952 TransportConfig::PostgresInput(_) => "postgres_input".to_string(),
3953 TransportConfig::PostgresCdcInput(_) => "postgres_cdc_input".to_string(),
3954 TransportConfig::PostgresOutput(_) => "postgres_output".to_string(),
3955 TransportConfig::Datagen(_) => "datagen".to_string(),
3956 TransportConfig::Nexmark(_) => "nexmark".to_string(),
3957 TransportConfig::HttpInput(_) => "http_input".to_string(),
3958 TransportConfig::HttpOutput(_) => "http_output".to_string(),
3959 TransportConfig::AdHocInput(_) => "adhoc_input".to_string(),
3960 TransportConfig::RedisOutput(_) => "redis_output".to_string(),
3961 TransportConfig::ClockInput(_) => "clock".to_string(),
3962 TransportConfig::S2Input(_) => "s2_input".to_string(),
3963 TransportConfig::S2Output(_) => "s2_output".to_string(),
3964 TransportConfig::NullOutput => "null_output".to_string(),
3965 TransportConfig::EmptyInput => "empty_input".to_string(),
3966 }
3967 }
3968
3969 pub fn transport_metadata_mut(&mut self) -> Option<&mut HashMap<String, String>> {
3974 match self {
3975 TransportConfig::NatsInput(cfg) => Some(&mut cfg.consumer_config.metadata),
3976 _ => None,
3977 }
3978 }
3979
3980 pub fn is_transient(&self) -> bool {
3983 matches!(
3984 self,
3985 TransportConfig::AdHocInput(_)
3986 | TransportConfig::HttpInput(_)
3987 | TransportConfig::HttpOutput(_)
3988 | TransportConfig::ClockInput(_)
3989 )
3990 }
3991
3992 pub fn is_http_input(&self) -> bool {
3993 matches!(self, TransportConfig::HttpInput(_))
3994 }
3995
3996 pub fn supports_distribution(&self) -> bool {
4000 matches!(
4001 self,
4002 TransportConfig::KafkaInput(_)
4003 | TransportConfig::DeltaTableInput(_)
4004 | TransportConfig::IcebergInput(_)
4005 )
4006 }
4007
4008 pub fn needs_input_choice(&self) -> bool {
4020 matches!(
4021 self,
4022 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_)
4023 )
4024 }
4025
4026 pub fn frontier_merge(&self) -> crate::adapter_stats::FrontierMerge {
4029 use crate::adapter_stats::FrontierMerge;
4030 match self {
4031 TransportConfig::KafkaInput(_) => FrontierMerge::Partitioned,
4032 TransportConfig::DeltaTableInput(_) | TransportConfig::IcebergInput(_) => {
4033 FrontierMerge::Shared
4034 }
4035 _ => FrontierMerge::Opaque,
4036 }
4037 }
4038}
4039
4040#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize, ToSchema)]
4043pub struct FormatConfig {
4044 pub name: Cow<'static, str>,
4046
4047 #[serde(default)]
4049 #[schema(value_type = Object)]
4050 pub config: JsonValue,
4051}
4052
4053impl FormatConfig {
4054 pub fn normalize_durations(&mut self) {
4061 if self.name != "avro" {
4062 return;
4063 }
4064 let has_timeout = self.config.as_object().is_some_and(|object| {
4065 object.contains_key("registry_timeout") || object.contains_key("registry_timeout_secs")
4066 });
4067 if !has_timeout {
4068 return;
4069 }
4070 let Ok(registry) = serde_json::from_value::<crate::format::avro::AvroSchemaRegistryConfig>(
4071 self.config.clone(),
4072 ) else {
4073 return;
4074 };
4075 let object = self.config.as_object_mut().unwrap();
4076 object.remove("registry_timeout_secs");
4077 match registry.registry_timeout {
4078 Some(timeout) => object.insert(
4079 "registry_timeout".to_string(),
4080 JsonValue::String(timeout.to_string()),
4081 ),
4082 None => object.remove("registry_timeout"),
4083 };
4084 }
4085}
4086
4087#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4089#[serde(deny_unknown_fields)]
4090pub struct DynamicConfig {
4091 #[serde(default)]
4092 pub resources: DynamicResources,
4093}
4094
4095#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
4097#[serde(deny_unknown_fields)]
4098pub struct DynamicResources {
4099 pub cpu_cores_min: Option<f64>,
4100 pub cpu_cores_max: Option<f64>,
4101 #[serde(default, alias = "memory_mb_min", deserialize_with = "size_memory_min")]
4104 #[schema(value_type = Option<String>)]
4105 pub memory_min: Option<ConfigSize>,
4106 #[serde(default, alias = "memory_mb_max", deserialize_with = "size_memory_max")]
4109 #[schema(value_type = Option<String>)]
4110 pub memory_max: Option<ConfigSize>,
4111}
4112
4113#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4114#[serde(default)]
4115pub struct ResourceConfig {
4116 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4119 pub cpu_cores_min: Option<f64>,
4120
4121 #[serde(deserialize_with = "crate::serde_via_value::deserialize")]
4124 pub cpu_cores_max: Option<f64>,
4125
4126 #[serde(
4132 alias = "memory_mb_min",
4133 deserialize_with = "size_memory_min",
4134 skip_serializing_if = "Option::is_none"
4135 )]
4136 #[schema(value_type = Option<String>)]
4137 pub memory_min: Option<ConfigSize>,
4138
4139 #[serde(
4145 alias = "memory_mb_max",
4146 deserialize_with = "size_memory_max",
4147 skip_serializing_if = "Option::is_none"
4148 )]
4149 #[schema(value_type = Option<String>)]
4150 pub memory_max: Option<ConfigSize>,
4151
4152 #[serde(
4159 alias = "storage_mb_min",
4160 deserialize_with = "size_storage_min",
4161 skip_serializing_if = "Option::is_none"
4162 )]
4163 #[schema(value_type = Option<String>)]
4164 pub storage_min: Option<ConfigSize>,
4165
4166 #[serde(
4177 alias = "storage_mb_max",
4178 deserialize_with = "size_storage_max",
4179 skip_serializing_if = "Option::is_none"
4180 )]
4181 #[schema(value_type = Option<String>)]
4182 pub storage_max: Option<ConfigSize>,
4183
4184 #[serde(skip_serializing_if = "Option::is_none")]
4186 pub autoscaling: Option<AutoscalingConfig>,
4187
4188 pub storage_class: Option<String>,
4191
4192 #[serde(skip_serializing_if = "Option::is_none")]
4198 pub volume_attributes_class: Option<String>,
4199
4200 pub service_account_name: Option<String>,
4203
4204 pub namespace: Option<String>,
4212}
4213
4214#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4216#[serde(default)]
4217pub struct AutoscalingConfig {
4218 #[serde(skip_serializing_if = "Option::is_none")]
4220 pub storage: Option<StorageAutoscalingConfig>,
4221}
4222
4223#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, ToSchema)]
4226#[serde(default)]
4227pub struct StorageAutoscalingConfig {
4228 #[serde(
4230 deserialize_with = "crate::serde_via_value::deserialize",
4231 skip_serializing_if = "Option::is_none"
4232 )]
4233 pub scale_threshold: Option<f64>,
4234
4235 #[serde(
4242 alias = "scale_threshold_available_mb",
4243 deserialize_with = "size_scale_threshold_available",
4244 skip_serializing_if = "Option::is_none"
4245 )]
4246 #[schema(value_type = Option<String>)]
4247 pub scale_threshold_available: Option<ConfigSize>,
4248
4249 #[serde(
4251 deserialize_with = "crate::serde_via_value::deserialize",
4252 skip_serializing_if = "Option::is_none"
4253 )]
4254 pub scale_factor: Option<f64>,
4255}
4256
4257#[cfg(test)]
4258mod resource_config_tests {
4259 use super::{AutoscalingConfig, ResourceConfig, StorageAutoscalingConfig};
4260 use crate::size::ConfigSize;
4261 use serde_json::json;
4262
4263 #[test]
4264 fn storage_autoscaling_round_trips_through_json() {
4265 let input = json!({
4266 "storage_min": "1G",
4267 "storage_max": "8G",
4268 "autoscaling": {
4269 "storage": {
4270 "scale_threshold": 0.8,
4271 "scale_threshold_available": "10G",
4272 "scale_factor": 2.0
4273 }
4274 }
4275 });
4276 let config: ResourceConfig = serde_json::from_value(input).unwrap();
4277 assert_eq!(config.storage_min, Some(ConfigSize::from_mb(1000)));
4278 assert_eq!(config.storage_max, Some(ConfigSize::from_mb(8000)));
4279 assert_eq!(
4280 config.autoscaling,
4281 Some(AutoscalingConfig {
4282 storage: Some(StorageAutoscalingConfig {
4283 scale_threshold: Some(0.8),
4284 scale_threshold_available: Some(ConfigSize::from_mb(10000)),
4285 scale_factor: Some(2.0),
4286 }),
4287 })
4288 );
4289 let output = serde_json::to_value(&config).unwrap();
4290 assert_eq!(output["storage_min"], json!("1G"));
4291 assert_eq!(
4292 output["autoscaling"]["storage"]["scale_threshold"],
4293 json!(0.8)
4294 );
4295 assert_eq!(
4296 output["autoscaling"]["storage"]["scale_threshold_available"],
4297 json!("10G")
4298 );
4299 assert_eq!(output["autoscaling"]["storage"]["scale_factor"], json!(2.0));
4300 }
4301
4302 #[test]
4303 fn autoscaling_fields_default_to_none() {
4304 let config: ResourceConfig = serde_json::from_value(json!({})).unwrap();
4305 assert_eq!(config.storage_min, None);
4306 assert_eq!(config.autoscaling, None);
4307
4308 let output = serde_json::to_value(&config).unwrap();
4311 assert!(output.get("storage_min").is_none());
4312 assert!(output.get("autoscaling").is_none());
4313 assert!(output.get("storage_max").is_none());
4314
4315 let input = json!({ "autoscaling": { "storage": { "scale_threshold": 0.9 } } });
4317 let config: ResourceConfig = serde_json::from_value(input.clone()).unwrap();
4318 let output = serde_json::to_value(&config).unwrap();
4319 assert_eq!(output["autoscaling"], input["autoscaling"]);
4320
4321 let config: ResourceConfig = serde_json::from_value(json!({ "autoscaling": {} })).unwrap();
4323 assert_eq!(config.autoscaling, Some(AutoscalingConfig::default()));
4324 }
4325
4326 #[test]
4327 fn autoscaling_rejects_non_numeric_values() {
4328 let input = json!({ "autoscaling": { "storage": { "scale_threshold": "high" } } });
4329 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4330 let input = json!({ "autoscaling": { "storage": { "scale_threshold_available_mb": -1 } } });
4331 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4332 let input = json!({ "storage_mb_min": -1 });
4333 assert!(serde_json::from_value::<ResourceConfig>(input).is_err());
4334 }
4335}
4336
4337#[cfg(test)]
4338mod sync_config_tests {
4339 use super::SyncConfig;
4340
4341 fn config(bucket: &str, read_bucket: Option<&str>) -> SyncConfig {
4342 SyncConfig {
4343 bucket: bucket.to_owned(),
4344 read_bucket: read_bucket.map(str::to_owned),
4345 ..Default::default()
4346 }
4347 }
4348
4349 #[test]
4350 fn read_bucket_must_differ_from_bucket() {
4351 let err = config("ckpts/a", Some("ckpts/a")).validate().unwrap_err();
4352 assert!(err.contains("different locations"), "{err}");
4353 }
4354
4355 #[test]
4356 fn read_bucket_must_use_the_same_object_store() {
4357 let err = config("gs://ckpts/a", Some("ckpts/b"))
4358 .validate()
4359 .unwrap_err();
4360 assert!(err.contains("same object store"), "{err}");
4361 let err = config("ckpts/a", Some("gs://ckpts/b"))
4362 .validate()
4363 .unwrap_err();
4364 assert!(err.contains("same object store"), "{err}");
4365 }
4366
4367 #[test]
4368 fn matching_object_stores_are_accepted() {
4369 config("gs://ckpts/a", Some("gs://ckpts/b"))
4370 .validate()
4371 .unwrap();
4372 config("ckpts/a", Some("s3://ckpts/b")).validate().unwrap();
4373 config("gs://ckpts/a", None).validate().unwrap();
4374 }
4375
4376 #[test]
4377 fn take_bucket_ownership_defaults_to_false() {
4378 let sync: SyncConfig = serde_json::from_str(r#"{"bucket": "ckpts/a"}"#).unwrap();
4379 assert!(!sync.take_bucket_ownership);
4380
4381 let sync: SyncConfig =
4382 serde_json::from_str(r#"{"bucket": "ckpts/a", "take_bucket_ownership": true}"#)
4383 .unwrap();
4384 assert!(sync.take_bucket_ownership);
4385 }
4386}
4387
4388#[cfg(test)]
4389mod transport_metadata_tests {
4390 use super::TransportConfig;
4391 use serde_json::json;
4392
4393 fn nats_input(metadata: serde_json::Value) -> TransportConfig {
4394 serde_json::from_value(json!({
4395 "name": "nats_input",
4396 "config": {
4397 "connection_config": { "server_url": "nats://127.0.0.1:4222" },
4398 "stream_name": "orders",
4399 "consumer_config": { "deliver_policy": "All", "metadata": metadata },
4400 },
4401 }))
4402 .unwrap()
4403 }
4404
4405 #[test]
4406 fn nats_input_exposes_consumer_metadata() {
4407 let mut transport = nats_input(json!({ "team": "ingest" }));
4408 let metadata = transport.transport_metadata_mut().unwrap();
4409 assert_eq!(metadata.get("team").map(String::as_str), Some("ingest"));
4410
4411 metadata.insert("pipeline".to_string(), "orders_pipeline".to_string());
4412 let TransportConfig::NatsInput(config) = &transport else {
4413 unreachable!()
4414 };
4415 assert_eq!(
4416 config
4417 .consumer_config
4418 .metadata
4419 .get("pipeline")
4420 .map(String::as_str),
4421 Some("orders_pipeline"),
4422 "writes through the returned map must reach the consumer config"
4423 );
4424 }
4425
4426 #[test]
4427 fn transports_without_metadata_return_none() {
4428 let mut transport: TransportConfig = serde_json::from_value(json!({
4429 "name": "file_input",
4430 "config": { "path": "/tmp/input.csv" },
4431 }))
4432 .unwrap();
4433 assert!(transport.transport_metadata_mut().is_none());
4434 }
4435}