1use serde::{Deserialize, Serialize};
2use std::fmt::Display;
3use utoipa::ToSchema;
4
5#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
9pub enum PostgresWriteMode {
10 #[default]
13 #[serde(rename = "materialized")]
14 Materialized,
15
16 #[serde(rename = "cdc")]
21 Cdc,
22}
23
24impl Display for PostgresWriteMode {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 match self {
27 Self::Materialized => write!(f, "materialized"),
28 Self::Cdc => write!(f, "cdc"),
29 }
30 }
31}
32
33#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
35pub struct PostgresTlsConfig {
36 pub ssl_ca_pem: Option<String>,
38
39 pub ssl_ca_location: Option<String>,
41
42 pub ssl_client_pem: Option<String>,
44
45 pub ssl_client_location: Option<String>,
47
48 pub ssl_client_key: Option<String>,
50
51 pub ssl_client_key_location: Option<String>,
53
54 pub ssl_certificate_chain_location: Option<String>,
59
60 pub verify_hostname: Option<bool>,
66}
67
68impl PostgresTlsConfig {
69 pub fn has_tls(&self) -> bool {
70 self.ssl_ca_pem.is_some() || self.ssl_ca_location.is_some()
71 }
72}
73
74#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
81pub struct PostgresCdcBatchConfig {
82 #[serde(default = "default_batch_max_fill_ms")]
89 #[schema(default = default_batch_max_fill_ms)]
90 pub max_fill_ms: u64,
91
92 #[serde(
99 default = "default_batch_memory_budget_ratio",
100 deserialize_with = "crate::serde_via_value::deserialize"
101 )]
102 #[schema(default = default_batch_memory_budget_ratio)]
103 pub memory_budget_ratio: f32,
104
105 #[serde(default = "default_batch_max_bytes")]
112 #[schema(default = default_batch_max_bytes)]
113 pub max_bytes: usize,
114}
115
116impl Default for PostgresCdcBatchConfig {
117 fn default() -> Self {
118 Self {
119 max_fill_ms: default_batch_max_fill_ms(),
120 memory_budget_ratio: default_batch_memory_budget_ratio(),
121 max_bytes: default_batch_max_bytes(),
122 }
123 }
124}
125
126impl Eq for PostgresCdcBatchConfig {}
131
132impl PostgresCdcBatchConfig {
133 pub fn validate(&self) -> Result<(), String> {
134 if !(0.0..=1.0).contains(&self.memory_budget_ratio) || self.memory_budget_ratio == 0.0 {
135 return Err(format!(
136 "batch.memory_budget_ratio must be in the (0.0, 1.0] interval, got {}",
137 self.memory_budget_ratio
138 ));
139 }
140
141 if self.max_bytes == 0 {
142 return Err("batch.max_bytes must be greater than 0, got 0".to_string());
143 }
144
145 Ok(())
146 }
147}
148
149fn default_batch_max_fill_ms() -> u64 {
150 10_000
151}
152
153fn default_batch_memory_budget_ratio() -> f32 {
154 0.2
155}
156
157fn default_batch_max_bytes() -> usize {
158 32 * 1024 * 1024
159}
160
161#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
168pub struct PostgresCdcMemoryBackpressureConfig {
169 #[serde(
174 default = "default_memory_backpressure_activate_threshold",
175 deserialize_with = "crate::serde_via_value::deserialize"
176 )]
177 #[schema(default = default_memory_backpressure_activate_threshold)]
178 pub activate_threshold: f32,
179
180 #[serde(
185 default = "default_memory_backpressure_resume_threshold",
186 deserialize_with = "crate::serde_via_value::deserialize"
187 )]
188 #[schema(default = default_memory_backpressure_resume_threshold)]
189 pub resume_threshold: f32,
190}
191
192impl Default for PostgresCdcMemoryBackpressureConfig {
193 fn default() -> Self {
194 Self {
195 activate_threshold: default_memory_backpressure_activate_threshold(),
196 resume_threshold: default_memory_backpressure_resume_threshold(),
197 }
198 }
199}
200
201impl Eq for PostgresCdcMemoryBackpressureConfig {}
204
205impl PostgresCdcMemoryBackpressureConfig {
206 pub fn validate(&self) -> Result<(), String> {
207 if !(0.0..=1.0).contains(&self.activate_threshold) || self.activate_threshold == 0.0 {
208 return Err(format!(
209 "memory_backpressure.activate_threshold must be in the (0.0, 1.0] interval, got {}",
210 self.activate_threshold
211 ));
212 }
213
214 if !(0.0..=1.0).contains(&self.resume_threshold) || self.resume_threshold == 1.0 {
215 return Err(format!(
216 "memory_backpressure.resume_threshold must be in the [0.0, 1.0) interval, got {}",
217 self.resume_threshold
218 ));
219 }
220
221 if self.resume_threshold >= self.activate_threshold {
222 return Err(format!(
223 "memory_backpressure.resume_threshold ({}) must be lower than \
224 memory_backpressure.activate_threshold ({})",
225 self.resume_threshold, self.activate_threshold
226 ));
227 }
228
229 Ok(())
230 }
231}
232
233fn default_memory_backpressure_activate_threshold() -> f32 {
234 0.85
235}
236
237fn default_memory_backpressure_resume_threshold() -> f32 {
238 0.75
239}
240
241#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
251pub struct PostgresCdcReaderConfig {
252 pub uri: String,
257
258 pub publication: String,
260
261 pub source_table: String,
265
266 #[serde(default = "default_run_source_migrations")]
277 #[schema(default = default_run_source_migrations)]
278 pub run_source_migrations: bool,
279
280 #[serde(flatten)]
282 #[schema(inline)]
283 pub tls: PostgresTlsConfig,
284
285 #[serde(default)]
291 pub batch: PostgresCdcBatchConfig,
292
293 #[serde(default)]
300 pub memory_backpressure: PostgresCdcMemoryBackpressureConfig,
301}
302
303fn default_run_source_migrations() -> bool {
304 true
305}
306
307impl PostgresCdcReaderConfig {
308 pub fn validate(&self) -> Result<(), String> {
309 if self.publication.trim().is_empty() {
310 return Err("publication cannot be empty".to_string());
311 }
312
313 if self.source_table.trim().is_empty() {
314 return Err("source_table cannot be empty".to_string());
315 }
316
317 self.batch.validate()?;
318 self.memory_backpressure.validate()?;
319
320 if self.tls.ssl_client_pem.is_some()
321 || self.tls.ssl_client_location.is_some()
322 || self.tls.ssl_client_key.is_some()
323 || self.tls.ssl_client_key_location.is_some()
324 || self.tls.ssl_certificate_chain_location.is_some()
325 {
326 return Err(
327 "client-certificate TLS options (ssl_client_pem, ssl_client_location, \
328 ssl_client_key, ssl_client_key_location, ssl_certificate_chain_location) \
329 are not supported by the Postgres CDC connector as the underlying etl crate \
330 doesn't support client-certificate TLS yet. CA-based TLS via ssl_ca_pem \
331 or ssl_ca_location is supported. Please file an issue if you require \
332 client-certificate TLS support: https://github.com/feldera/feldera/issues/
333 "
334 .to_string(),
335 );
336 }
337
338 if self.tls.verify_hostname == Some(false) {
339 return Err(
340 "disabling hostname verification is not supported by the Postgres CDC connector"
341 .to_string(),
342 );
343 }
344
345 Ok(())
346 }
347}
348
349#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
351pub struct PostgresReaderConfig {
352 pub uri: String,
355
356 pub query: String,
358
359 #[serde(flatten)]
361 #[schema(inline)]
362 pub tls: PostgresTlsConfig,
363}
364
365#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
367pub struct PostgresWriterConfig {
368 pub uri: String,
371
372 pub table: String,
374
375 #[serde(default)]
381 #[schema(default = PostgresWriteMode::default)]
382 pub mode: PostgresWriteMode,
383
384 #[serde(default = "default_cdc_op_column")]
393 #[schema(default = default_cdc_op_column)]
394 pub cdc_op_column: String,
395
396 #[serde(default = "default_cdc_ts_column")]
404 #[schema(default = default_cdc_ts_column)]
405 pub cdc_ts_column: String,
406
407 #[serde(flatten)]
409 #[schema(inline)]
410 pub tls: PostgresTlsConfig,
411
412 pub max_records_in_buffer: Option<usize>,
414
415 #[schema(default = default_max_buffer_size)]
420 #[serde(default = "default_max_buffer_size")]
421 pub max_buffer_size_bytes: usize,
422
423 #[serde(default)]
437 pub on_conflict_do_nothing: bool,
438
439 #[serde(default = "default_writer_threads")]
443 #[schema(default = default_writer_threads)]
444 pub threads: usize,
445
446 #[serde(default, skip_serializing_if = "Vec::is_empty")]
451 pub extra_columns: Vec<String>,
452}
453
454fn default_max_buffer_size() -> usize {
455 usize::pow(2, 20)
456}
457
458fn default_writer_threads() -> usize {
459 1
460}
461
462fn default_cdc_op_column() -> String {
463 "__feldera_op".to_string()
464}
465
466fn default_cdc_ts_column() -> String {
467 "__feldera_ts".to_string()
468}
469
470impl PostgresWriterConfig {
471 pub fn validate(&self) -> Result<(), String> {
472 match self.mode {
473 PostgresWriteMode::Cdc => {
474 if self.cdc_op_column.trim().is_empty() {
475 return Err("cdc_op_column cannot be empty in CDC mode".to_string());
476 }
477 if self.cdc_ts_column.trim().is_empty() {
478 return Err("cdc_ts_column cannot be empty in CDC mode".to_string());
479 }
480
481 if !self.cdc_op_column.is_ascii() {
482 return Err("cdc_op_column must contain only ASCII characters".to_string());
483 }
484
485 if !self.cdc_ts_column.is_ascii() {
486 return Err("cdc_ts_column must contain only ASCII characters".to_string());
487 }
488
489 if self.on_conflict_do_nothing {
490 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());
491 }
492 }
493 PostgresWriteMode::Materialized => {
494 if self.cdc_ts_column != default_cdc_ts_column()
495 && !self.cdc_ts_column.trim().is_empty()
496 {
497 return Err(
498 "cdc_ts_column must not be set when in MATERIALIZED mode".to_string()
499 );
500 }
501 if self.cdc_op_column != default_cdc_op_column()
502 && !self.cdc_op_column.trim().is_empty()
503 {
504 return Err(
505 "cdc_op_column must not be set when in MATERIALIZED mode".to_string()
506 );
507 }
508 }
509 };
510
511 if self.threads == 0 {
512 return Err("threads must be at least 1".to_string());
513 }
514
515 Ok(())
516 }
517}
518
519#[cfg(test)]
520mod tests {
521 use super::*;
522 use serde_json::json;
523
524 fn postgres_cdc_config(tls: PostgresTlsConfig) -> PostgresCdcReaderConfig {
525 PostgresCdcReaderConfig {
526 uri: "postgres://user:password@localhost:5432/database".to_string(),
527 publication: "publication".to_string(),
528 source_table: "public.table".to_string(),
529 run_source_migrations: true,
530 tls,
531 batch: PostgresCdcBatchConfig::default(),
532 memory_backpressure: PostgresCdcMemoryBackpressureConfig::default(),
533 }
534 }
535
536 #[test]
537 fn postgres_cdc_config_rejects_client_certificate_tls_options() {
538 let config = postgres_cdc_config(PostgresTlsConfig {
539 ssl_client_pem: Some("client".to_string()),
540 ..Default::default()
541 });
542
543 let err = config.validate().unwrap_err();
544 assert!(err.contains("client-certificate TLS options"));
545 assert!(err.contains("client-certificate TLS support"));
546 assert!(!err.contains("doesn't support TLS yet"));
547 }
548
549 #[test]
550 fn postgres_cdc_config_rejects_disabled_hostname_verification() {
551 let config = postgres_cdc_config(PostgresTlsConfig {
552 verify_hostname: Some(false),
553 ..Default::default()
554 });
555
556 let err = config.validate().unwrap_err();
557 assert!(err.contains("disabling hostname verification"));
558 }
559
560 #[test]
561 fn postgres_cdc_config_accepts_default_tls() {
562 let config = postgres_cdc_config(PostgresTlsConfig::default());
563
564 assert!(config.validate().is_ok());
565 }
566
567 #[test]
568 fn postgres_cdc_config_rejects_empty_publication() {
569 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
570 config.publication = " ".to_string();
571
572 let err = config.validate().unwrap_err();
573 assert!(err.contains("publication cannot be empty"));
574 }
575
576 #[test]
577 fn postgres_cdc_config_rejects_empty_source_table() {
578 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
579 config.source_table = "\t".to_string();
580
581 let err = config.validate().unwrap_err();
582 assert!(err.contains("source_table cannot be empty"));
583 }
584
585 #[test]
586 fn postgres_cdc_config_defaults_run_source_migrations_to_true() {
587 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
588 "uri": "postgres://user:password@localhost:5432/database",
589 "publication": "publication",
590 "source_table": "public.table",
591 }))
592 .unwrap();
593
594 assert!(config.run_source_migrations);
595 }
596
597 #[test]
598 fn postgres_cdc_config_honors_run_source_migrations_false() {
599 let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
600 "uri": "postgres://user:password@localhost:5432/database",
601 "publication": "publication",
602 "source_table": "public.table",
603 "run_source_migrations": false,
604 }))
605 .unwrap();
606
607 assert!(!config.run_source_migrations);
608 }
609
610 #[test]
611 fn postgres_cdc_config_round_trips_run_source_migrations() {
612 for enabled in [true, false] {
613 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
614 config.run_source_migrations = enabled;
615 let json = serde_json::to_value(&config).unwrap();
616 assert_eq!(json["run_source_migrations"], enabled);
617 let decoded: PostgresCdcReaderConfig = serde_json::from_value(json).unwrap();
618 assert_eq!(decoded, config);
619 }
620 }
621
622 #[test]
623 fn postgres_cdc_config_deserializes_without_batch_or_memory_backpressure() {
624 let json = r#"{
625 "uri": "postgres://user:password@localhost:5432/database",
626 "publication": "publication",
627 "source_table": "public.table"
628 }"#;
629 let config: PostgresCdcReaderConfig = serde_json::from_str(json).unwrap();
630
631 assert_eq!(config.batch, PostgresCdcBatchConfig::default());
632 assert_eq!(
633 config.memory_backpressure,
634 PostgresCdcMemoryBackpressureConfig::default()
635 );
636 assert!(config.validate().is_ok());
637 }
638
639 #[test]
640 fn postgres_cdc_batch_config_deserializes_with_partial_fields() {
641 let json = r#"{"max_bytes": 4194304}"#;
642 let config: PostgresCdcBatchConfig = serde_json::from_str(json).unwrap();
643
644 assert_eq!(config.max_bytes, 4 * 1024 * 1024);
645 assert_eq!(config.max_fill_ms, default_batch_max_fill_ms());
646 assert_eq!(
647 config.memory_budget_ratio,
648 default_batch_memory_budget_ratio()
649 );
650 config.validate().unwrap();
651 }
652
653 #[test]
654 fn postgres_cdc_batch_config_rejects_zero_memory_budget_ratio() {
655 let config = PostgresCdcBatchConfig {
656 memory_budget_ratio: 0.0,
657 ..Default::default()
658 };
659
660 let err = config.validate().unwrap_err();
661 assert!(err.contains("batch.memory_budget_ratio"));
662 }
663
664 #[test]
665 fn postgres_cdc_batch_config_rejects_out_of_range_memory_budget_ratio() {
666 let config = PostgresCdcBatchConfig {
667 memory_budget_ratio: 1.5,
668 ..Default::default()
669 };
670
671 let err = config.validate().unwrap_err();
672 assert!(err.contains("batch.memory_budget_ratio"));
673 assert!(err.contains("got 1.5"));
674 }
675
676 #[test]
677 fn postgres_cdc_batch_config_rejects_zero_max_bytes() {
678 let config = PostgresCdcBatchConfig {
679 max_bytes: 0,
680 ..Default::default()
681 };
682
683 let err = config.validate().unwrap_err();
684 assert!(err.contains("batch.max_bytes"));
685 }
686
687 #[test]
688 fn postgres_cdc_memory_backpressure_config_rejects_zero_activate_threshold() {
689 let config = PostgresCdcMemoryBackpressureConfig {
690 activate_threshold: 0.0,
691 ..Default::default()
692 };
693
694 let err = config.validate().unwrap_err();
695 assert!(err.contains("memory_backpressure.activate_threshold"));
696 }
697
698 #[test]
699 fn postgres_cdc_memory_backpressure_config_rejects_resume_threshold_of_one() {
700 let config = PostgresCdcMemoryBackpressureConfig {
701 resume_threshold: 1.0,
702 ..Default::default()
703 };
704
705 let err = config.validate().unwrap_err();
706 assert!(err.contains("memory_backpressure.resume_threshold"));
707 }
708
709 #[test]
710 fn postgres_cdc_memory_backpressure_config_rejects_resume_gte_activate() {
711 let config = PostgresCdcMemoryBackpressureConfig {
712 activate_threshold: 0.5,
713 resume_threshold: 0.5,
714 };
715
716 let err = config.validate().unwrap_err();
717 assert!(err.contains("must be lower than"));
718 }
719
720 #[test]
721 fn postgres_cdc_config_rejects_invalid_batch_config() {
722 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
723 config.batch.max_bytes = 0;
724
725 let err = config.validate().unwrap_err();
726 assert!(err.contains("batch.max_bytes"));
727 }
728
729 #[test]
730 fn postgres_cdc_config_rejects_invalid_memory_backpressure_config() {
731 let mut config = postgres_cdc_config(PostgresTlsConfig::default());
732 config.memory_backpressure.activate_threshold = 0.0;
733
734 let err = config.validate().unwrap_err();
735 assert!(err.contains("memory_backpressure.activate_threshold"));
736 }
737
738 #[test]
746 fn postgres_cdc_config_f32_fields_roundtrip_through_pipeline_config() {
747 use crate::config::PipelineConfig;
748
749 let pipeline: PipelineConfig = serde_json::from_value(json!({
750 "name": "cdc_test",
751 "workers": 1,
752 "inputs": {
753 "cdc_in": {
754 "stream": "test_input1",
755 "transport": {
756 "name": "postgres_cdc_input",
757 "config": {
758 "uri": "postgres://user:password@localhost:5432/database",
759 "publication": "publication",
760 "source_table": "public.table",
761 "batch": {"memory_budget_ratio": 0.3},
762 "memory_backpressure": {"activate_threshold": 0.9, "resume_threshold": 0.7},
763 },
764 },
765 },
766 },
767 "outputs": {},
768 }))
769 .unwrap();
770
771 let json = serde_json::to_string(&pipeline).unwrap();
772 let back: PipelineConfig = serde_json::from_str(&json).unwrap();
773 assert_eq!(back, pipeline);
774 }
775}