1use crate::size::{ConfigSize, LegacySizeUnit};
2use serde::{Deserialize, Serialize};
3use std::fmt::Display;
4use utoipa::ToSchema;
5
6#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
10pub enum PostgresWriteMode {
11 #[default]
14 #[serde(rename = "materialized")]
15 Materialized,
16
17 #[serde(rename = "cdc")]
22 Cdc,
23}
24
25impl Display for PostgresWriteMode {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 match self {
28 Self::Materialized => write!(f, "materialized"),
29 Self::Cdc => write!(f, "cdc"),
30 }
31 }
32}
33
34#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
36pub struct PostgresTlsConfig {
37 pub ssl_ca_pem: Option<String>,
39
40 pub ssl_ca_location: Option<String>,
42
43 pub ssl_client_pem: Option<String>,
45
46 pub ssl_client_location: Option<String>,
48
49 pub ssl_client_key: Option<String>,
51
52 pub ssl_client_key_location: Option<String>,
54
55 pub ssl_certificate_chain_location: Option<String>,
60
61 pub verify_hostname: Option<bool>,
67}
68
69impl PostgresTlsConfig {
70 pub fn has_tls(&self) -> bool {
71 self.ssl_ca_pem.is_some() || self.ssl_ca_location.is_some()
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
82pub struct PostgresCdcBatchConfig {
83 #[serde(default = "default_batch_max_fill_ms")]
90 #[schema(default = default_batch_max_fill_ms)]
91 pub max_fill_ms: u64,
92
93 #[serde(
100 default = "default_batch_memory_budget_ratio",
101 deserialize_with = "crate::serde_via_value::deserialize"
102 )]
103 #[schema(default = default_batch_memory_budget_ratio)]
104 pub memory_budget_ratio: f32,
105
106 #[serde(
116 default = "default_batch_max_size",
117 alias = "max_bytes",
118 deserialize_with = "size_batch_max_size"
119 )]
120 #[schema(value_type = String, default = schema_default_batch_max_size)]
121 pub max_size: ConfigSize,
122}
123
124impl Default for PostgresCdcBatchConfig {
125 fn default() -> Self {
126 Self {
127 max_fill_ms: default_batch_max_fill_ms(),
128 memory_budget_ratio: default_batch_memory_budget_ratio(),
129 max_size: default_batch_max_size(),
130 }
131 }
132}
133
134impl Eq for PostgresCdcBatchConfig {}
139
140impl PostgresCdcBatchConfig {
141 pub fn validate(&self) -> Result<(), String> {
142 if !(0.0..=1.0).contains(&self.memory_budget_ratio) || self.memory_budget_ratio == 0.0 {
143 return Err(format!(
144 "batch.memory_budget_ratio must be in the (0.0, 1.0] interval, got {}",
145 self.memory_budget_ratio
146 ));
147 }
148
149 if self.max_size.is_zero() {
150 return Err("batch.max_size must be greater than 0, got 0".to_string());
151 }
152
153 Ok(())
154 }
155}
156
157fn default_batch_max_fill_ms() -> u64 {
158 10_000
159}
160
161fn default_batch_memory_budget_ratio() -> f32 {
162 0.2
163}
164
165fn default_batch_max_size() -> ConfigSize {
166 ConfigSize::from_mib(32)
167}
168fn schema_default_batch_max_size() -> String {
169 default_batch_max_size().to_string()
170}
171crate::required_size_setting!(size_batch_max_size, "max_size", LegacySizeUnit::Bytes);
172
173#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
180pub struct PostgresCdcMemoryBackpressureConfig {
181 #[serde(
186 default = "default_memory_backpressure_activate_threshold",
187 deserialize_with = "crate::serde_via_value::deserialize"
188 )]
189 #[schema(default = default_memory_backpressure_activate_threshold)]
190 pub activate_threshold: f32,
191
192 #[serde(
197 default = "default_memory_backpressure_resume_threshold",
198 deserialize_with = "crate::serde_via_value::deserialize"
199 )]
200 #[schema(default = default_memory_backpressure_resume_threshold)]
201 pub resume_threshold: f32,
202}
203
204impl Default for PostgresCdcMemoryBackpressureConfig {
205 fn default() -> Self {
206 Self {
207 activate_threshold: default_memory_backpressure_activate_threshold(),
208 resume_threshold: default_memory_backpressure_resume_threshold(),
209 }
210 }
211}
212
213impl Eq for PostgresCdcMemoryBackpressureConfig {}
216
217impl PostgresCdcMemoryBackpressureConfig {
218 pub fn validate(&self) -> Result<(), String> {
219 if !(0.0..=1.0).contains(&self.activate_threshold) || self.activate_threshold == 0.0 {
220 return Err(format!(
221 "memory_backpressure.activate_threshold must be in the (0.0, 1.0] interval, got {}",
222 self.activate_threshold
223 ));
224 }
225
226 if !(0.0..=1.0).contains(&self.resume_threshold) || self.resume_threshold == 1.0 {
227 return Err(format!(
228 "memory_backpressure.resume_threshold must be in the [0.0, 1.0) interval, got {}",
229 self.resume_threshold
230 ));
231 }
232
233 if self.resume_threshold >= self.activate_threshold {
234 return Err(format!(
235 "memory_backpressure.resume_threshold ({}) must be lower than \
236 memory_backpressure.activate_threshold ({})",
237 self.resume_threshold, self.activate_threshold
238 ));
239 }
240
241 Ok(())
242 }
243}
244
245fn default_memory_backpressure_activate_threshold() -> f32 {
246 0.85
247}
248
249fn default_memory_backpressure_resume_threshold() -> f32 {
250 0.75
251}
252
253#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
263pub struct PostgresCdcReaderConfig {
264 pub uri: String,
269
270 pub publication: String,
272
273 pub source_table: String,
277
278 #[serde(default = "default_run_source_migrations")]
289 #[schema(default = default_run_source_migrations)]
290 pub run_source_migrations: bool,
291
292 #[serde(flatten)]
294 #[schema(inline)]
295 pub tls: PostgresTlsConfig,
296
297 #[serde(default)]
303 pub batch: PostgresCdcBatchConfig,
304
305 #[serde(default)]
312 pub memory_backpressure: PostgresCdcMemoryBackpressureConfig,
313}
314
315fn default_run_source_migrations() -> bool {
316 true
317}
318
319impl PostgresCdcReaderConfig {
320 pub fn validate(&self) -> Result<(), String> {
321 if self.publication.trim().is_empty() {
322 return Err("publication cannot be empty".to_string());
323 }
324
325 if self.source_table.trim().is_empty() {
326 return Err("source_table cannot be empty".to_string());
327 }
328
329 self.batch.validate()?;
330 self.memory_backpressure.validate()?;
331
332 if self.tls.ssl_client_pem.is_some()
333 || self.tls.ssl_client_location.is_some()
334 || self.tls.ssl_client_key.is_some()
335 || self.tls.ssl_client_key_location.is_some()
336 || self.tls.ssl_certificate_chain_location.is_some()
337 {
338 return Err(
339 "client-certificate TLS options (ssl_client_pem, ssl_client_location, \
340 ssl_client_key, ssl_client_key_location, ssl_certificate_chain_location) \
341 are not supported by the Postgres CDC connector as the underlying etl crate \
342 doesn't support client-certificate TLS yet. CA-based TLS via ssl_ca_pem \
343 or ssl_ca_location is supported. Please file an issue if you require \
344 client-certificate TLS support: https://github.com/feldera/feldera/issues/
345 "
346 .to_string(),
347 );
348 }
349
350 if self.tls.verify_hostname == Some(false) {
351 return Err(
352 "disabling hostname verification is not supported by the Postgres CDC connector"
353 .to_string(),
354 );
355 }
356
357 Ok(())
358 }
359}
360
361#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
363pub struct PostgresReaderConfig {
364 pub uri: String,
367
368 pub query: String,
370
371 #[serde(flatten)]
373 #[schema(inline)]
374 pub tls: PostgresTlsConfig,
375}
376
377#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
379pub struct PostgresWriterConfig {
380 pub uri: String,
383
384 pub table: String,
386
387 #[serde(default)]
393 #[schema(default = PostgresWriteMode::default)]
394 pub mode: PostgresWriteMode,
395
396 #[serde(default = "default_cdc_op_column")]
405 #[schema(default = default_cdc_op_column)]
406 pub cdc_op_column: String,
407
408 #[serde(default = "default_cdc_ts_column")]
416 #[schema(default = default_cdc_ts_column)]
417 pub cdc_ts_column: String,
418
419 #[serde(flatten)]
421 #[schema(inline)]
422 pub tls: PostgresTlsConfig,
423
424 pub max_records_in_buffer: Option<usize>,
426
427 #[schema(value_type = String, default = schema_default_max_buffer_size)]
435 #[serde(
436 default = "default_max_buffer_size",
437 alias = "max_buffer_size_bytes",
438 deserialize_with = "size_max_buffer_size"
439 )]
440 pub max_buffer_size: ConfigSize,
441
442 #[serde(default)]
456 pub on_conflict_do_nothing: bool,
457
458 #[serde(default = "default_writer_threads")]
462 #[schema(default = default_writer_threads)]
463 pub threads: usize,
464
465 #[serde(default, skip_serializing_if = "Vec::is_empty")]
470 pub extra_columns: Vec<String>,
471}
472
473fn default_max_buffer_size() -> ConfigSize {
474 ConfigSize::from_mib(1)
475}
476fn schema_default_max_buffer_size() -> String {
477 default_max_buffer_size().to_string()
478}
479crate::required_size_setting!(
480 size_max_buffer_size,
481 "max_buffer_size",
482 LegacySizeUnit::Bytes
483);
484
485fn default_writer_threads() -> usize {
486 1
487}
488
489fn default_cdc_op_column() -> String {
490 "__feldera_op".to_string()
491}
492
493fn default_cdc_ts_column() -> String {
494 "__feldera_ts".to_string()
495}
496
497impl PostgresWriterConfig {
498 pub fn validate(&self) -> Result<(), String> {
499 match self.mode {
500 PostgresWriteMode::Cdc => {
501 if self.cdc_op_column.trim().is_empty() {
502 return Err("cdc_op_column cannot be empty in CDC mode".to_string());
503 }
504 if self.cdc_ts_column.trim().is_empty() {
505 return Err("cdc_ts_column cannot be empty in CDC mode".to_string());
506 }
507
508 if !self.cdc_op_column.is_ascii() {
509 return Err("cdc_op_column must contain only ASCII characters".to_string());
510 }
511
512 if !self.cdc_ts_column.is_ascii() {
513 return Err("cdc_ts_column must contain only ASCII characters".to_string());
514 }
515
516 if self.on_conflict_do_nothing {
517 return Err("on_conflict_do_nothing not supported in CDC mode since all operations are performed as append-only INSERTs into the target table".to_string());
518 }
519 }
520 PostgresWriteMode::Materialized => {
521 if self.cdc_ts_column != default_cdc_ts_column()
522 && !self.cdc_ts_column.trim().is_empty()
523 {
524 return Err(
525 "cdc_ts_column must not be set when in MATERIALIZED mode".to_string()
526 );
527 }
528 if self.cdc_op_column != default_cdc_op_column()
529 && !self.cdc_op_column.trim().is_empty()
530 {
531 return Err(
532 "cdc_op_column must not be set when in MATERIALIZED mode".to_string()
533 );
534 }
535 }
536 };
537
538 if self.threads == 0 {
539 return Err("threads must be at least 1".to_string());
540 }
541
542 Ok(())
543 }
544}
545
546impl crate::sensitive::SensitiveValues for PostgresReaderConfig {
547 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
548 crate::sensitive::visit_connection_string("uri", &self.uri, visit);
550 crate::sensitive::visit_optional(
551 "ssl_client_key",
552 self.tls.ssl_client_key.as_deref(),
553 visit,
554 );
555 }
556}
557
558impl crate::sensitive::SensitiveValues for PostgresCdcReaderConfig {
559 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
560 crate::sensitive::visit_connection_string("uri", &self.uri, visit);
562 crate::sensitive::visit_optional(
563 "ssl_client_key",
564 self.tls.ssl_client_key.as_deref(),
565 visit,
566 );
567 }
568}
569
570impl crate::sensitive::SensitiveValues for PostgresWriterConfig {
571 fn visit_sensitive_values(&self, visit: &mut dyn FnMut(&str, &str)) {
572 crate::sensitive::visit_connection_string("uri", &self.uri, visit);
574 crate::sensitive::visit_optional(
575 "ssl_client_key",
576 self.tls.ssl_client_key.as_deref(),
577 visit,
578 );
579 }
580}
581
582#[cfg(test)]
583mod tests {
584 use super::*;
585 use serde_json::json;
586
587 fn postgres_cdc_config(tls: PostgresTlsConfig) -> PostgresCdcReaderConfig {
588 PostgresCdcReaderConfig {
589 uri: "postgres://user:password@localhost:5432/database".to_string(),
590 publication: "publication".to_string(),
591 source_table: "public.table".to_string(),
592 run_source_migrations: true,
593 tls,
594 batch: PostgresCdcBatchConfig::default(),
595 memory_backpressure: PostgresCdcMemoryBackpressureConfig::default(),
596 }
597 }
598
599 #[test]
600 fn postgres_cdc_config_rejects_client_certificate_tls_options() {
601 let config = postgres_cdc_config(PostgresTlsConfig {
602 ssl_client_pem: Some("client".to_string()),
603 ..Default::default()
604 });
605
606 let err = config.validate().unwrap_err();
607 assert!(err.contains("client-certificate TLS options"));
608 assert!(err.contains("client-certificate TLS support"));
609 assert!(!err.contains("doesn't support TLS yet"));
610 }
611
612 #[test]
613 fn postgres_cdc_config_rejects_disabled_hostname_verification() {
614 let config = postgres_cdc_config(PostgresTlsConfig {
615 verify_hostname: Some(false),
616 ..Default::default()
617 });
618
619 let err = config.validate().unwrap_err();
620 assert!(err.contains("disabling hostname verification"));
621 }
622
623 #[test]
624 fn postgres_cdc_config_accepts_default_tls() {
625 let config = postgres_cdc_config(PostgresTlsConfig::default());
626
627 assert!(config.validate().is_ok());
628 }
629
630 #[test]
631 fn postgres_cdc_config_rejects_empty_publication() {
632 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
633 config.publication = " ".to_string();
634
635 let err = config.validate().unwrap_err();
636 assert!(err.contains("publication cannot be empty"));
637 }
638
639 #[test]
640 fn postgres_cdc_config_rejects_empty_source_table() {
641 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
642 config.source_table = "\t".to_string();
643
644 let err = config.validate().unwrap_err();
645 assert!(err.contains("source_table cannot be empty"));
646 }
647
648 #[test]
649 fn postgres_cdc_config_defaults_run_source_migrations_to_true() {
650 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
651 "uri": "postgres://user:password@localhost:5432/database",
652 "publication": "publication",
653 "source_table": "public.table",
654 }))
655 .unwrap();
656
657 assert!(config.run_source_migrations);
658 }
659
660 #[test]
661 fn postgres_cdc_config_honors_run_source_migrations_false() {
662 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
663 "uri": "postgres://user:password@localhost:5432/database",
664 "publication": "publication",
665 "source_table": "public.table",
666 "run_source_migrations": false,
667 }))
668 .unwrap();
669
670 assert!(!config.run_source_migrations);
671 }
672
673 #[test]
674 fn postgres_cdc_config_round_trips_run_source_migrations() {
675 for enabled in [true, false] {
676 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
677 config.run_source_migrations = enabled;
678 let json = serde_json::to_value(&config).unwrap();
679 assert_eq!(json["run_source_migrations"], enabled);
680 let decoded: PostgresCdcReaderConfig = serde_json::from_value(json).unwrap();
681 assert_eq!(decoded, config);
682 }
683 }
684
685 #[test]
686 fn postgres_cdc_config_deserializes_without_batch_or_memory_backpressure() {
687 let json = r#"{
688 "uri": "postgres://user:password@localhost:5432/database",
689 "publication": "publication",
690 "source_table": "public.table"
691 }"#;
692 let config: PostgresCdcReaderConfig = serde_json::from_str(json).unwrap();
693
694 assert_eq!(config.batch, PostgresCdcBatchConfig::default());
695 assert_eq!(
696 config.memory_backpressure,
697 PostgresCdcMemoryBackpressureConfig::default()
698 );
699 assert!(config.validate().is_ok());
700 }
701
702 #[test]
703 fn postgres_cdc_batch_config_deserializes_with_partial_fields() {
704 let json = r#"{"max_size": "4Mi"}"#;
705 let config: PostgresCdcBatchConfig = serde_json::from_str(json).unwrap();
706
707 assert_eq!(config.max_size, ConfigSize::from_mib(4));
708 let legacy: PostgresCdcBatchConfig =
710 serde_json::from_str(r#"{"max_bytes": 4194304}"#).unwrap();
711 assert_eq!(legacy.max_size, ConfigSize::from_mib(4));
712 assert_eq!(config.max_fill_ms, default_batch_max_fill_ms());
713 assert_eq!(
714 config.memory_budget_ratio,
715 default_batch_memory_budget_ratio()
716 );
717 config.validate().unwrap();
718 }
719
720 #[test]
721 fn postgres_cdc_batch_config_rejects_zero_memory_budget_ratio() {
722 let config = PostgresCdcBatchConfig {
723 memory_budget_ratio: 0.0,
724 ..Default::default()
725 };
726
727 let err = config.validate().unwrap_err();
728 assert!(err.contains("batch.memory_budget_ratio"));
729 }
730
731 #[test]
732 fn postgres_cdc_batch_config_rejects_out_of_range_memory_budget_ratio() {
733 let config = PostgresCdcBatchConfig {
734 memory_budget_ratio: 1.5,
735 ..Default::default()
736 };
737
738 let err = config.validate().unwrap_err();
739 assert!(err.contains("batch.memory_budget_ratio"));
740 assert!(err.contains("got 1.5"));
741 }
742
743 #[test]
744 fn postgres_cdc_batch_config_rejects_zero_max_size() {
745 let config = PostgresCdcBatchConfig {
746 max_size: ConfigSize::ZERO,
747 ..Default::default()
748 };
749
750 let err = config.validate().unwrap_err();
751 assert!(err.contains("batch.max_size"));
752 }
753
754 #[test]
755 fn postgres_cdc_memory_backpressure_config_rejects_zero_activate_threshold() {
756 let config = PostgresCdcMemoryBackpressureConfig {
757 activate_threshold: 0.0,
758 ..Default::default()
759 };
760
761 let err = config.validate().unwrap_err();
762 assert!(err.contains("memory_backpressure.activate_threshold"));
763 }
764
765 #[test]
766 fn postgres_cdc_memory_backpressure_config_rejects_resume_threshold_of_one() {
767 let config = PostgresCdcMemoryBackpressureConfig {
768 resume_threshold: 1.0,
769 ..Default::default()
770 };
771
772 let err = config.validate().unwrap_err();
773 assert!(err.contains("memory_backpressure.resume_threshold"));
774 }
775
776 #[test]
777 fn postgres_cdc_memory_backpressure_config_rejects_resume_gte_activate() {
778 let config = PostgresCdcMemoryBackpressureConfig {
779 activate_threshold: 0.5,
780 resume_threshold: 0.5,
781 };
782
783 let err = config.validate().unwrap_err();
784 assert!(err.contains("must be lower than"));
785 }
786
787 #[test]
788 fn postgres_cdc_config_rejects_invalid_batch_config() {
789 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
790 config.batch.max_size = ConfigSize::ZERO;
791
792 let err = config.validate().unwrap_err();
793 assert!(err.contains("batch.max_size"));
794 }
795
796 #[test]
797 fn postgres_cdc_config_rejects_invalid_memory_backpressure_config() {
798 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
799 config.memory_backpressure.activate_threshold = 0.0;
800
801 let err = config.validate().unwrap_err();
802 assert!(err.contains("memory_backpressure.activate_threshold"));
803 }
804
805 #[test]
813 fn postgres_cdc_config_f32_fields_roundtrip_through_pipeline_config() {
814 use crate::config::PipelineConfig;
815
816 let pipeline: PipelineConfig = serde_json::from_value(json!({
817 "name": "cdc_test",
818 "workers": 1,
819 "inputs": {
820 "cdc_in": {
821 "stream": "test_input1",
822 "transport": {
823 "name": "postgres_cdc_input",
824 "config": {
825 "uri": "postgres://user:password@localhost:5432/database",
826 "publication": "publication",
827 "source_table": "public.table",
828 "batch": {"memory_budget_ratio": 0.3},
829 "memory_backpressure": {"activate_threshold": 0.9, "resume_threshold": 0.7},
830 },
831 },
832 },
833 },
834 "outputs": {},
835 }))
836 .unwrap();
837
838 let json = serde_json::to_string(&pipeline).unwrap();
839 let back: PipelineConfig = serde_json::from_str(&json).unwrap();
840 assert_eq!(back, pipeline);
841 }
842}