Skip to main content

feldera_types/transport/
postgres.rs

1use crate::size::{ConfigSize, LegacySizeUnit};
2use serde::{Deserialize, Serialize};
3use std::fmt::Display;
4use utoipa::ToSchema;
5
6/// PostgreSQL write mode.
7///
8/// Determines how the PostgreSQL output connector writes data to the target table.
9#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
10pub enum PostgresWriteMode {
11    /// Materialized mode: perform direct INSERT, UPDATE, and DELETE operations on the table.
12    /// This is the default behavior and maintains the postgres table as a materialized snapshot of the output view.
13    #[default]
14    #[serde(rename = "materialized")]
15    Materialized,
16
17    /// CDC (Change Data Capture) mode: write all operations as INSERT operations
18    /// into a Postgres table that serves as an append-only event log.
19    /// In this mode, inserts, updates, and deletes are all represented as new rows
20    /// with metadata columns describing the operation type and timestamp.
21    #[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/// TLS/SSL configuration for PostgreSQL connectors.
35#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
36pub struct PostgresTlsConfig {
37    /// A sequence of CA certificates in PEM format.
38    pub ssl_ca_pem: Option<String>,
39
40    /// Path to a file containing a sequence of CA certificates in PEM format.
41    pub ssl_ca_location: Option<String>,
42
43    /// The client certificate in PEM format.
44    pub ssl_client_pem: Option<String>,
45
46    /// Path to the client certificate.
47    pub ssl_client_location: Option<String>,
48
49    /// The client certificate key in PEM format.
50    pub ssl_client_key: Option<String>,
51
52    /// Path to the client certificate key.
53    pub ssl_client_key_location: Option<String>,
54
55    /// The path to the certificate chain file.
56    /// The file must contain a sequence of PEM-formatted certificates,
57    /// the first being the leaf certificate, and the remainder forming
58    /// the chain of certificates up to and including the trusted root certificate.
59    pub ssl_certificate_chain_location: Option<String>,
60
61    /// True to enable hostname verification when using TLS. True by default.
62    ///
63    /// When false, the certificate chain is still verified against the
64    /// trusted CA; only the requirement that the server name appears in the
65    /// certificate is lifted.
66    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/// Batch processing configuration for the Postgres CDC connector.
76///
77/// Controls how replication events are buffered into a batch before being
78/// flushed to Feldera. Mirrors the batch configuration of the underlying
79/// `etl` replication library; fields omitted from the configuration fall
80/// back to `etl`'s own defaults.
81#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
82pub struct PostgresCdcBatchConfig {
83    /// Maximum time, in milliseconds, to wait before flushing a partially
84    /// filled batch. This is the latency bound for batching: once the first
85    /// event enters a batch, the batch is flushed when this timer elapses,
86    /// even if `max_size` was not reached.
87    ///
88    /// Default: 10000 (10 seconds).
89    #[serde(default = "default_batch_max_fill_ms")]
90    #[schema(default = default_batch_max_fill_ms)]
91    pub max_fill_ms: u64,
92
93    /// Ratio of process memory reserved for incoming replication batch
94    /// bytes, in the `(0.0, 1.0]` interval. The configured memory is divided
95    /// by the number of active streams at runtime, so each stream gets only
96    /// a per-stream share of the global memory budget.
97    ///
98    /// Default: 0.2.
99    #[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    /// Maximum preferred size for one batch per active stream, such as
107    /// `"32Mi"`. This is a ceiling, not a target: the runtime still chooses
108    /// the smaller value between this limit and the memory-ratio budget
109    /// computed from `memory_budget_ratio`.
110    ///
111    /// Default: `"32Mi"`, the same as etl.
112    ///
113    /// Before release 0.367.0 this setting was `max_bytes`, a number of
114    /// bytes. That name is deprecated but still read.
115    #[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
134// `f32` doesn't implement `Eq` because of NaN, so it can't be derived here.
135// `validate()` rejects NaN/out-of-range ratios, so equality is reflexive for
136// any value that passes validation; this lets `PostgresCdcReaderConfig` (and
137// its containing `TransportConfig` enum) keep deriving `Eq`.
138impl 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/// Memory-based backpressure configuration for the Postgres CDC connector.
174///
175/// When the connector's memory usage rises above `activate_threshold`, it
176/// pauses reading further replication events until usage drops back below
177/// `resume_threshold`. Mirrors the memory backpressure configuration of the
178/// underlying `etl` replication library.
179#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
180pub struct PostgresCdcMemoryBackpressureConfig {
181    /// Memory usage ratio above which backpressure is activated, in the
182    /// `(0.0, 1.0]` interval.
183    ///
184    /// Default: 0.85.
185    #[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    /// Memory usage ratio below which backpressure is released, in the
193    /// `[0.0, 1.0)` interval. Must be lower than `activate_threshold`.
194    ///
195    /// Default: 0.75.
196    #[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
213// See the corresponding `impl Eq for PostgresCdcBatchConfig` above for why
214// this is sound despite the `f32` fields.
215impl 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/// Postgres CDC input connector configuration.
254///
255/// Uses logical replication to capture ongoing changes from a Postgres database.
256/// Requires a pre-created publication. Automatic source migrations require a
257/// superuser; with administrator-installed source objects and
258/// `run_source_migrations = false`, a replication role with the documented
259/// source-table and etl state-store privileges can be used instead.
260/// Tables must have primary keys and `REPLICA IDENTITY FULL` is recommended
261/// for UPDATE/DELETE support.
262#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
263pub struct PostgresCdcReaderConfig {
264    /// Postgres connection URI. Automatic source migrations require a superuser.
265    /// With `run_source_migrations = false`, the user needs REPLICATION and the
266    /// grants described in [Running as a non-superuser](https://docs.feldera.com/connectors/sources/postgresql-cdc#running-as-a-non-superuser).
267    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
268    pub uri: String,
269
270    /// Name of the pre-created Postgres publication to replicate from.
271    pub publication: String,
272
273    /// Postgres table to replicate, schema-qualified (e.g. "public.orders").
274    /// A name given without a schema refers to a table in "public".
275    /// Must be included in the publication.
276    pub source_table: String,
277
278    /// Whether the connector runs etl's source migrations on startup.
279    ///
280    /// The source migrations install the schema helper functions and the
281    /// `ddl_command_end` event trigger. Creating the event trigger requires a
282    /// superuser, so a de-elevated role can set this to `false` and have an
283    /// administrator install the source objects out-of-band. Disabling this
284    /// does not skip the state-store migrations, which run on every start
285    /// regardless.
286    ///
287    /// Default: `true`.
288    #[serde(default = "default_run_source_migrations")]
289    #[schema(default = default_run_source_migrations)]
290    pub run_source_migrations: bool,
291
292    /// TLS/SSL configuration.
293    #[serde(flatten)]
294    #[schema(inline)]
295    pub tls: PostgresTlsConfig,
296
297    /// Batch processing configuration.
298    ///
299    /// Controls how replication events are buffered before being flushed to
300    /// Feldera. When omitted, uses the defaults listed on each field, which
301    /// match the underlying `etl` library's defaults.
302    #[serde(default)]
303    pub batch: PostgresCdcBatchConfig,
304
305    /// Memory-based backpressure configuration.
306    ///
307    /// Controls when the connector pauses reading further replication
308    /// events to avoid exceeding available memory. When omitted, uses the
309    /// defaults listed on each field, which match the underlying `etl`
310    /// library's defaults.
311    #[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/// Postgres input connector configuration.
362#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
363pub struct PostgresReaderConfig {
364    /// Postgres URI.
365    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
366    pub uri: String,
367
368    /// Query that specifies what data to fetch from postgres.
369    pub query: String,
370
371    /// TLS/SSL configuration.
372    #[serde(flatten)]
373    #[schema(inline)]
374    pub tls: PostgresTlsConfig,
375}
376
377/// Postgres output connector configuration.
378#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
379pub struct PostgresWriterConfig {
380    /// Postgres URI.
381    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
382    pub uri: String,
383
384    /// The table to write the output to.
385    pub table: String,
386
387    /// Write mode for the connector.
388    ///
389    /// - `materialized` (default): Perform direct INSERT, UPDATE, and DELETE operations on the table.
390    /// - `cdc`: Write all operations as INSERT operations into an append-only event log
391    ///   with additional metadata columns describing the operation type and timestamp.
392    #[serde(default)]
393    #[schema(default = PostgresWriteMode::default)]
394    pub mode: PostgresWriteMode,
395
396    /// Name of the operation metadata column in CDC mode.
397    ///
398    /// Only used when `mode = "cdc"`. This column will contain:
399    /// - `"i"` for insert operations
400    /// - `"u"` for upsert operations
401    /// - `"d"` for delete operations
402    ///
403    /// Default: `"__feldera_op"`
404    #[serde(default = "default_cdc_op_column")]
405    #[schema(default = default_cdc_op_column)]
406    pub cdc_op_column: String,
407
408    /// Name of the timestamp metadata column in CDC mode.
409    ///
410    /// Only used when `mode = "cdc"`. This column will contain the timestamp
411    /// (in RFC 3339 format) when the batch of updates was output
412    /// by the pipeline.
413    ///
414    /// Default: `"__feldera_ts"`
415    #[serde(default = "default_cdc_ts_column")]
416    #[schema(default = default_cdc_ts_column)]
417    pub cdc_ts_column: String,
418
419    /// TLS/SSL configuration.
420    #[serde(flatten)]
421    #[schema(inline)]
422    pub tls: PostgresTlsConfig,
423
424    /// The maximum number of records in a single buffer.
425    pub max_records_in_buffer: Option<usize>,
426
427    /// The maximum buffer size for a single operation, such as `"1Mi"`.
428    /// Note that the buffers of `INSERT`, `UPDATE` and `DELETE` queries are
429    /// separate.
430    /// Default: `"1Mi"`.
431    ///
432    /// Before release 0.367.0 this setting was `max_buffer_size_bytes`, a
433    /// number of bytes. That name is deprecated but still read.
434    #[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    /// Specifies how the connector handles conflicts when executing an `INSERT`
443    /// into a table with a primary key. By default, an existing row with the same
444    /// key is overwritten. Setting this flag to `true` preserves the existing row
445    /// and ignores the new insert.
446    ///
447    /// This setting does not affect `UPDATE` statements, which always replace the
448    /// value associated with the key.
449    ///
450    /// This setting is not supported when `mode = "cdc"`, since all operations
451    /// are performed as append-only `INSERT`s into the target table.
452    /// Any conflict in CDC mode will result in an error.
453    ///
454    /// Default: `false`
455    #[serde(default)]
456    pub on_conflict_do_nothing: bool,
457
458    /// The number of threads to use during encoding.
459    ///
460    /// Default: 1
461    #[serde(default = "default_writer_threads")]
462    #[schema(default = default_writer_threads)]
463    pub threads: usize,
464
465    /// The names of the extra columns in the Postgres table that are not part of the view schema.
466    ///
467    /// These connector can write user-defined values, configured using the `set_extra_columns` connector command,
468    /// to these columns.
469    #[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        // The superseded spelling still reads, as a number of bytes.
673        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    /// Regression test: the `f32` fields must survive the JSON-string
770    /// round-trip a checkpoint takes through `PipelineConfig`, whose
771    /// `InputEndpointConfig` flattens the connector config. With `serde_json`'s
772    /// `arbitrary_precision` feature enabled, the serde `Content` buffer that
773    /// `#[serde(flatten)]` uses represents floats as maps, which breaks plain
774    /// `f32` deserialization (serde-rs/json#1157). `serde_via_value` on each
775    /// `f32` field fixes this.
776    #[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}