use serde::{Deserialize, Serialize};
use std::fmt::Display;
use utoipa::ToSchema;
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
pub enum PostgresWriteMode {
#[default]
#[serde(rename = "materialized")]
Materialized,
#[serde(rename = "cdc")]
Cdc,
}
impl Display for PostgresWriteMode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Materialized => write!(f, "materialized"),
Self::Cdc => write!(f, "cdc"),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
pub struct PostgresTlsConfig {
pub ssl_ca_pem: Option<String>,
pub ssl_ca_location: Option<String>,
pub ssl_client_pem: Option<String>,
pub ssl_client_location: Option<String>,
pub ssl_client_key: Option<String>,
pub ssl_client_key_location: Option<String>,
pub ssl_certificate_chain_location: Option<String>,
pub verify_hostname: Option<bool>,
}
impl PostgresTlsConfig {
pub fn has_tls(&self) -> bool {
self.ssl_ca_pem.is_some() || self.ssl_ca_location.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcBatchConfig {
#[serde(default = "default_batch_max_fill_ms")]
#[schema(default = default_batch_max_fill_ms)]
pub max_fill_ms: u64,
#[serde(
default = "default_batch_memory_budget_ratio",
deserialize_with = "crate::serde_via_value::deserialize"
)]
#[schema(default = default_batch_memory_budget_ratio)]
pub memory_budget_ratio: f32,
#[serde(default = "default_batch_max_bytes")]
#[schema(default = default_batch_max_bytes)]
pub max_bytes: usize,
}
impl Default for PostgresCdcBatchConfig {
fn default() -> Self {
Self {
max_fill_ms: default_batch_max_fill_ms(),
memory_budget_ratio: default_batch_memory_budget_ratio(),
max_bytes: default_batch_max_bytes(),
}
}
}
impl Eq for PostgresCdcBatchConfig {}
impl PostgresCdcBatchConfig {
pub fn validate(&self) -> Result<(), String> {
if !(0.0..=1.0).contains(&self.memory_budget_ratio) || self.memory_budget_ratio == 0.0 {
return Err(format!(
"batch.memory_budget_ratio must be in the (0.0, 1.0] interval, got {}",
self.memory_budget_ratio
));
}
if self.max_bytes == 0 {
return Err("batch.max_bytes must be greater than 0, got 0".to_string());
}
Ok(())
}
}
fn default_batch_max_fill_ms() -> u64 {
10_000
}
fn default_batch_memory_budget_ratio() -> f32 {
0.2
}
fn default_batch_max_bytes() -> usize {
32 * 1024 * 1024
}
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcMemoryBackpressureConfig {
#[serde(
default = "default_memory_backpressure_activate_threshold",
deserialize_with = "crate::serde_via_value::deserialize"
)]
#[schema(default = default_memory_backpressure_activate_threshold)]
pub activate_threshold: f32,
#[serde(
default = "default_memory_backpressure_resume_threshold",
deserialize_with = "crate::serde_via_value::deserialize"
)]
#[schema(default = default_memory_backpressure_resume_threshold)]
pub resume_threshold: f32,
}
impl Default for PostgresCdcMemoryBackpressureConfig {
fn default() -> Self {
Self {
activate_threshold: default_memory_backpressure_activate_threshold(),
resume_threshold: default_memory_backpressure_resume_threshold(),
}
}
}
impl Eq for PostgresCdcMemoryBackpressureConfig {}
impl PostgresCdcMemoryBackpressureConfig {
pub fn validate(&self) -> Result<(), String> {
if !(0.0..=1.0).contains(&self.activate_threshold) || self.activate_threshold == 0.0 {
return Err(format!(
"memory_backpressure.activate_threshold must be in the (0.0, 1.0] interval, got {}",
self.activate_threshold
));
}
if !(0.0..=1.0).contains(&self.resume_threshold) || self.resume_threshold == 1.0 {
return Err(format!(
"memory_backpressure.resume_threshold must be in the [0.0, 1.0) interval, got {}",
self.resume_threshold
));
}
if self.resume_threshold >= self.activate_threshold {
return Err(format!(
"memory_backpressure.resume_threshold ({}) must be lower than \
memory_backpressure.activate_threshold ({})",
self.resume_threshold, self.activate_threshold
));
}
Ok(())
}
}
fn default_memory_backpressure_activate_threshold() -> f32 {
0.85
}
fn default_memory_backpressure_resume_threshold() -> f32 {
0.75
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcReaderConfig {
pub uri: String,
pub publication: String,
pub source_table: String,
#[serde(default = "default_run_source_migrations")]
#[schema(default = default_run_source_migrations)]
pub run_source_migrations: bool,
#[serde(flatten)]
#[schema(inline)]
pub tls: PostgresTlsConfig,
#[serde(default)]
pub batch: PostgresCdcBatchConfig,
#[serde(default)]
pub memory_backpressure: PostgresCdcMemoryBackpressureConfig,
}
fn default_run_source_migrations() -> bool {
true
}
impl PostgresCdcReaderConfig {
pub fn validate(&self) -> Result<(), String> {
if self.publication.trim().is_empty() {
return Err("publication cannot be empty".to_string());
}
if self.source_table.trim().is_empty() {
return Err("source_table cannot be empty".to_string());
}
self.batch.validate()?;
self.memory_backpressure.validate()?;
if self.tls.ssl_client_pem.is_some()
|| self.tls.ssl_client_location.is_some()
|| self.tls.ssl_client_key.is_some()
|| self.tls.ssl_client_key_location.is_some()
|| self.tls.ssl_certificate_chain_location.is_some()
{
return Err(
"client-certificate TLS options (ssl_client_pem, ssl_client_location, \
ssl_client_key, ssl_client_key_location, ssl_certificate_chain_location) \
are not supported by the Postgres CDC connector as the underlying etl crate \
doesn't support client-certificate TLS yet. CA-based TLS via ssl_ca_pem \
or ssl_ca_location is supported. Please file an issue if you require \
client-certificate TLS support: https://github.com/feldera/feldera/issues/
"
.to_string(),
);
}
if self.tls.verify_hostname == Some(false) {
return Err(
"disabling hostname verification is not supported by the Postgres CDC connector"
.to_string(),
);
}
Ok(())
}
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresReaderConfig {
pub uri: String,
pub query: String,
#[serde(flatten)]
#[schema(inline)]
pub tls: PostgresTlsConfig,
}
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresWriterConfig {
pub uri: String,
pub table: String,
#[serde(default)]
#[schema(default = PostgresWriteMode::default)]
pub mode: PostgresWriteMode,
#[serde(default = "default_cdc_op_column")]
#[schema(default = default_cdc_op_column)]
pub cdc_op_column: String,
#[serde(default = "default_cdc_ts_column")]
#[schema(default = default_cdc_ts_column)]
pub cdc_ts_column: String,
#[serde(flatten)]
#[schema(inline)]
pub tls: PostgresTlsConfig,
pub max_records_in_buffer: Option<usize>,
#[schema(default = default_max_buffer_size)]
#[serde(default = "default_max_buffer_size")]
pub max_buffer_size_bytes: usize,
#[serde(default)]
pub on_conflict_do_nothing: bool,
#[serde(default = "default_writer_threads")]
#[schema(default = default_writer_threads)]
pub threads: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub extra_columns: Vec<String>,
}
fn default_max_buffer_size() -> usize {
usize::pow(2, 20)
}
fn default_writer_threads() -> usize {
1
}
fn default_cdc_op_column() -> String {
"__feldera_op".to_string()
}
fn default_cdc_ts_column() -> String {
"__feldera_ts".to_string()
}
impl PostgresWriterConfig {
pub fn validate(&self) -> Result<(), String> {
match self.mode {
PostgresWriteMode::Cdc => {
if self.cdc_op_column.trim().is_empty() {
return Err("cdc_op_column cannot be empty in CDC mode".to_string());
}
if self.cdc_ts_column.trim().is_empty() {
return Err("cdc_ts_column cannot be empty in CDC mode".to_string());
}
if !self.cdc_op_column.is_ascii() {
return Err("cdc_op_column must contain only ASCII characters".to_string());
}
if !self.cdc_ts_column.is_ascii() {
return Err("cdc_ts_column must contain only ASCII characters".to_string());
}
if self.on_conflict_do_nothing {
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());
}
}
PostgresWriteMode::Materialized => {
if self.cdc_ts_column != default_cdc_ts_column()
&& !self.cdc_ts_column.trim().is_empty()
{
return Err(
"cdc_ts_column must not be set when in MATERIALIZED mode".to_string()
);
}
if self.cdc_op_column != default_cdc_op_column()
&& !self.cdc_op_column.trim().is_empty()
{
return Err(
"cdc_op_column must not be set when in MATERIALIZED mode".to_string()
);
}
}
};
if self.threads == 0 {
return Err("threads must be at least 1".to_string());
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn postgres_cdc_config(tls: PostgresTlsConfig) -> PostgresCdcReaderConfig {
PostgresCdcReaderConfig {
uri: "postgres://user:password@localhost:5432/database".to_string(),
publication: "publication".to_string(),
source_table: "public.table".to_string(),
run_source_migrations: true,
tls,
batch: PostgresCdcBatchConfig::default(),
memory_backpressure: PostgresCdcMemoryBackpressureConfig::default(),
}
}
#[test]
fn postgres_cdc_config_rejects_client_certificate_tls_options() {
let config = postgres_cdc_config(PostgresTlsConfig {
ssl_client_pem: Some("client".to_string()),
..Default::default()
});
let err = config.validate().unwrap_err();
assert!(err.contains("client-certificate TLS options"));
assert!(err.contains("client-certificate TLS support"));
assert!(!err.contains("doesn't support TLS yet"));
}
#[test]
fn postgres_cdc_config_rejects_disabled_hostname_verification() {
let config = postgres_cdc_config(PostgresTlsConfig {
verify_hostname: Some(false),
..Default::default()
});
let err = config.validate().unwrap_err();
assert!(err.contains("disabling hostname verification"));
}
#[test]
fn postgres_cdc_config_accepts_default_tls() {
let config = postgres_cdc_config(PostgresTlsConfig::default());
assert!(config.validate().is_ok());
}
#[test]
fn postgres_cdc_config_rejects_empty_publication() {
let mut config = postgres_cdc_config(PostgresTlsConfig::default());
config.publication = " ".to_string();
let err = config.validate().unwrap_err();
assert!(err.contains("publication cannot be empty"));
}
#[test]
fn postgres_cdc_config_rejects_empty_source_table() {
let mut config = postgres_cdc_config(PostgresTlsConfig::default());
config.source_table = "\t".to_string();
let err = config.validate().unwrap_err();
assert!(err.contains("source_table cannot be empty"));
}
#[test]
fn postgres_cdc_config_defaults_run_source_migrations_to_true() {
let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
"uri": "postgres://user:password@localhost:5432/database",
"publication": "publication",
"source_table": "public.table",
}))
.unwrap();
assert!(config.run_source_migrations);
}
#[test]
fn postgres_cdc_config_honors_run_source_migrations_false() {
let config: PostgresCdcReaderConfig = serde_json::from_value(json!({
"uri": "postgres://user:password@localhost:5432/database",
"publication": "publication",
"source_table": "public.table",
"run_source_migrations": false,
}))
.unwrap();
assert!(!config.run_source_migrations);
}
#[test]
fn postgres_cdc_config_round_trips_run_source_migrations() {
for enabled in [true, false] {
let mut config = postgres_cdc_config(PostgresTlsConfig::default());
config.run_source_migrations = enabled;
let json = serde_json::to_value(&config).unwrap();
assert_eq!(json["run_source_migrations"], enabled);
let decoded: PostgresCdcReaderConfig = serde_json::from_value(json).unwrap();
assert_eq!(decoded, config);
}
}
#[test]
fn postgres_cdc_config_deserializes_without_batch_or_memory_backpressure() {
let json = r#"{
"uri": "postgres://user:password@localhost:5432/database",
"publication": "publication",
"source_table": "public.table"
}"#;
let config: PostgresCdcReaderConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.batch, PostgresCdcBatchConfig::default());
assert_eq!(
config.memory_backpressure,
PostgresCdcMemoryBackpressureConfig::default()
);
assert!(config.validate().is_ok());
}
#[test]
fn postgres_cdc_batch_config_deserializes_with_partial_fields() {
let json = r#"{"max_bytes": 4194304}"#;
let config: PostgresCdcBatchConfig = serde_json::from_str(json).unwrap();
assert_eq!(config.max_bytes, 4 * 1024 * 1024);
assert_eq!(config.max_fill_ms, default_batch_max_fill_ms());
assert_eq!(
config.memory_budget_ratio,
default_batch_memory_budget_ratio()
);
config.validate().unwrap();
}
#[test]
fn postgres_cdc_batch_config_rejects_zero_memory_budget_ratio() {
let config = PostgresCdcBatchConfig {
memory_budget_ratio: 0.0,
..Default::default()
};
let err = config.validate().unwrap_err();
assert!(err.contains("batch.memory_budget_ratio"));
}
#[test]
fn postgres_cdc_batch_config_rejects_out_of_range_memory_budget_ratio() {
let config = PostgresCdcBatchConfig {
memory_budget_ratio: 1.5,
..Default::default()
};
let err = config.validate().unwrap_err();
assert!(err.contains("batch.memory_budget_ratio"));
assert!(err.contains("got 1.5"));
}
#[test]
fn postgres_cdc_batch_config_rejects_zero_max_bytes() {
let config = PostgresCdcBatchConfig {
max_bytes: 0,
..Default::default()
};
let err = config.validate().unwrap_err();
assert!(err.contains("batch.max_bytes"));
}
#[test]
fn postgres_cdc_memory_backpressure_config_rejects_zero_activate_threshold() {
let config = PostgresCdcMemoryBackpressureConfig {
activate_threshold: 0.0,
..Default::default()
};
let err = config.validate().unwrap_err();
assert!(err.contains("memory_backpressure.activate_threshold"));
}
#[test]
fn postgres_cdc_memory_backpressure_config_rejects_resume_threshold_of_one() {
let config = PostgresCdcMemoryBackpressureConfig {
resume_threshold: 1.0,
..Default::default()
};
let err = config.validate().unwrap_err();
assert!(err.contains("memory_backpressure.resume_threshold"));
}
#[test]
fn postgres_cdc_memory_backpressure_config_rejects_resume_gte_activate() {
let config = PostgresCdcMemoryBackpressureConfig {
activate_threshold: 0.5,
resume_threshold: 0.5,
};
let err = config.validate().unwrap_err();
assert!(err.contains("must be lower than"));
}
#[test]
fn postgres_cdc_config_rejects_invalid_batch_config() {
let mut config = postgres_cdc_config(PostgresTlsConfig::default());
config.batch.max_bytes = 0;
let err = config.validate().unwrap_err();
assert!(err.contains("batch.max_bytes"));
}
#[test]
fn postgres_cdc_config_rejects_invalid_memory_backpressure_config() {
let mut config = postgres_cdc_config(PostgresTlsConfig::default());
config.memory_backpressure.activate_threshold = 0.0;
let err = config.validate().unwrap_err();
assert!(err.contains("memory_backpressure.activate_threshold"));
}
#[test]
fn postgres_cdc_config_f32_fields_roundtrip_through_pipeline_config() {
use crate::config::PipelineConfig;
let pipeline: PipelineConfig = serde_json::from_value(json!({
"name": "cdc_test",
"workers": 1,
"inputs": {
"cdc_in": {
"stream": "test_input1",
"transport": {
"name": "postgres_cdc_input",
"config": {
"uri": "postgres://user:password@localhost:5432/database",
"publication": "publication",
"source_table": "public.table",
"batch": {"memory_budget_ratio": 0.3},
"memory_backpressure": {"activate_threshold": 0.9, "resume_threshold": 0.7},
},
},
},
},
"outputs": {},
}))
.unwrap();
let json = serde_json::to_string(&pipeline).unwrap();
let back: PipelineConfig = serde_json::from_str(&json).unwrap();
assert_eq!(back, pipeline);
}
}