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
546#[cfg(test)]
547mod tests {
548 use super::*;
549 use serde_json::json;
550
551 fn postgres_cdc_config(tls: PostgresTlsConfig) -> PostgresCdcReaderConfig {
552 PostgresCdcReaderConfig {
553 uri: "postgres://user:password@localhost:5432/database".to_string(),
554 publication: "publication".to_string(),
555 source_table: "public.table".to_string(),
556 run_source_migrations: true,
557 tls,
558 batch: PostgresCdcBatchConfig::default(),
559 memory_backpressure: PostgresCdcMemoryBackpressureConfig::default(),
560 }
561 }
562
563 #[test]
564 fn postgres_cdc_config_rejects_client_certificate_tls_options() {
565 let config = postgres_cdc_config(PostgresTlsConfig {
566 ssl_client_pem: Some("client".to_string()),
567 ..Default::default()
568 });
569
570 let err = config.validate().unwrap_err();
571 assert!(err.contains("client-certificate TLS options"));
572 assert!(err.contains("client-certificate TLS support"));
573 assert!(!err.contains("doesn't support TLS yet"));
574 }
575
576 #[test]
577 fn postgres_cdc_config_rejects_disabled_hostname_verification() {
578 let config = postgres_cdc_config(PostgresTlsConfig {
579 verify_hostname: Some(false),
580 ..Default::default()
581 });
582
583 let err = config.validate().unwrap_err();
584 assert!(err.contains("disabling hostname verification"));
585 }
586
587 #[test]
588 fn postgres_cdc_config_accepts_default_tls() {
589 let config = postgres_cdc_config(PostgresTlsConfig::default());
590
591 assert!(config.validate().is_ok());
592 }
593
594 #[test]
595 fn postgres_cdc_config_rejects_empty_publication() {
596 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
597 config.publication = " ".to_string();
598
599 let err = config.validate().unwrap_err();
600 assert!(err.contains("publication cannot be empty"));
601 }
602
603 #[test]
604 fn postgres_cdc_config_rejects_empty_source_table() {
605 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
606 config.source_table = "\t".to_string();
607
608 let err = config.validate().unwrap_err();
609 assert!(err.contains("source_table cannot be empty"));
610 }
611
612 #[test]
613 fn postgres_cdc_config_defaults_run_source_migrations_to_true() {
614 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
615 "uri": "postgres://user:password@localhost:5432/database",
616 "publication": "publication",
617 "source_table": "public.table",
618 }))
619 .unwrap();
620
621 assert!(config.run_source_migrations);
622 }
623
624 #[test]
625 fn postgres_cdc_config_honors_run_source_migrations_false() {
626 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
627 "uri": "postgres://user:password@localhost:5432/database",
628 "publication": "publication",
629 "source_table": "public.table",
630 "run_source_migrations": false,
631 }))
632 .unwrap();
633
634 assert!(!config.run_source_migrations);
635 }
636
637 #[test]
638 fn postgres_cdc_config_round_trips_run_source_migrations() {
639 for enabled in [true, false] {
640 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
641 config.run_source_migrations = enabled;
642 let json = serde_json::to_value(&config).unwrap();
643 assert_eq!(json["run_source_migrations"], enabled);
644 let decoded: PostgresCdcReaderConfig = serde_json::from_value(json).unwrap();
645 assert_eq!(decoded, config);
646 }
647 }
648
649 #[test]
650 fn postgres_cdc_config_deserializes_without_batch_or_memory_backpressure() {
651 let json = r#"{
652 "uri": "postgres://user:password@localhost:5432/database",
653 "publication": "publication",
654 "source_table": "public.table"
655 }"#;
656 let config: PostgresCdcReaderConfig = serde_json::from_str(json).unwrap();
657
658 assert_eq!(config.batch, PostgresCdcBatchConfig::default());
659 assert_eq!(
660 config.memory_backpressure,
661 PostgresCdcMemoryBackpressureConfig::default()
662 );
663 assert!(config.validate().is_ok());
664 }
665
666 #[test]
667 fn postgres_cdc_batch_config_deserializes_with_partial_fields() {
668 let json = r#"{"max_size": "4Mi"}"#;
669 let config: PostgresCdcBatchConfig = serde_json::from_str(json).unwrap();
670
671 assert_eq!(config.max_size, ConfigSize::from_mib(4));
672 let legacy: PostgresCdcBatchConfig =
674 serde_json::from_str(r#"{"max_bytes": 4194304}"#).unwrap();
675 assert_eq!(legacy.max_size, ConfigSize::from_mib(4));
676 assert_eq!(config.max_fill_ms, default_batch_max_fill_ms());
677 assert_eq!(
678 config.memory_budget_ratio,
679 default_batch_memory_budget_ratio()
680 );
681 config.validate().unwrap();
682 }
683
684 #[test]
685 fn postgres_cdc_batch_config_rejects_zero_memory_budget_ratio() {
686 let config = PostgresCdcBatchConfig {
687 memory_budget_ratio: 0.0,
688 ..Default::default()
689 };
690
691 let err = config.validate().unwrap_err();
692 assert!(err.contains("batch.memory_budget_ratio"));
693 }
694
695 #[test]
696 fn postgres_cdc_batch_config_rejects_out_of_range_memory_budget_ratio() {
697 let config = PostgresCdcBatchConfig {
698 memory_budget_ratio: 1.5,
699 ..Default::default()
700 };
701
702 let err = config.validate().unwrap_err();
703 assert!(err.contains("batch.memory_budget_ratio"));
704 assert!(err.contains("got 1.5"));
705 }
706
707 #[test]
708 fn postgres_cdc_batch_config_rejects_zero_max_size() {
709 let config = PostgresCdcBatchConfig {
710 max_size: ConfigSize::ZERO,
711 ..Default::default()
712 };
713
714 let err = config.validate().unwrap_err();
715 assert!(err.contains("batch.max_size"));
716 }
717
718 #[test]
719 fn postgres_cdc_memory_backpressure_config_rejects_zero_activate_threshold() {
720 let config = PostgresCdcMemoryBackpressureConfig {
721 activate_threshold: 0.0,
722 ..Default::default()
723 };
724
725 let err = config.validate().unwrap_err();
726 assert!(err.contains("memory_backpressure.activate_threshold"));
727 }
728
729 #[test]
730 fn postgres_cdc_memory_backpressure_config_rejects_resume_threshold_of_one() {
731 let config = PostgresCdcMemoryBackpressureConfig {
732 resume_threshold: 1.0,
733 ..Default::default()
734 };
735
736 let err = config.validate().unwrap_err();
737 assert!(err.contains("memory_backpressure.resume_threshold"));
738 }
739
740 #[test]
741 fn postgres_cdc_memory_backpressure_config_rejects_resume_gte_activate() {
742 let config = PostgresCdcMemoryBackpressureConfig {
743 activate_threshold: 0.5,
744 resume_threshold: 0.5,
745 };
746
747 let err = config.validate().unwrap_err();
748 assert!(err.contains("must be lower than"));
749 }
750
751 #[test]
752 fn postgres_cdc_config_rejects_invalid_batch_config() {
753 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
754 config.batch.max_size = ConfigSize::ZERO;
755
756 let err = config.validate().unwrap_err();
757 assert!(err.contains("batch.max_size"));
758 }
759
760 #[test]
761 fn postgres_cdc_config_rejects_invalid_memory_backpressure_config() {
762 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
763 config.memory_backpressure.activate_threshold = 0.0;
764
765 let err = config.validate().unwrap_err();
766 assert!(err.contains("memory_backpressure.activate_threshold"));
767 }
768
769 #[test]
777 fn postgres_cdc_config_f32_fields_roundtrip_through_pipeline_config() {
778 use crate::config::PipelineConfig;
779
780 let pipeline: PipelineConfig = serde_json::from_value(json!({
781 "name": "cdc_test",
782 "workers": 1,
783 "inputs": {
784 "cdc_in": {
785 "stream": "test_input1",
786 "transport": {
787 "name": "postgres_cdc_input",
788 "config": {
789 "uri": "postgres://user:password@localhost:5432/database",
790 "publication": "publication",
791 "source_table": "public.table",
792 "batch": {"memory_budget_ratio": 0.3},
793 "memory_backpressure": {"activate_threshold": 0.9, "resume_threshold": 0.7},
794 },
795 },
796 },
797 },
798 "outputs": {},
799 }))
800 .unwrap();
801
802 let json = serde_json::to_string(&pipeline).unwrap();
803 let back: PipelineConfig = serde_json::from_str(&json).unwrap();
804 assert_eq!(back, pipeline);
805 }
806}