Skip to main content

feldera_types/transport/
postgres.rs

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