feldera-types 0.377.0

Public API types for Feldera
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
use crate::size::{ConfigSize, LegacySizeUnit};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use utoipa::ToSchema;

/// PostgreSQL write mode.
///
/// Determines how the PostgreSQL output connector writes data to the target table.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
pub enum PostgresWriteMode {
    /// Materialized mode: perform direct INSERT, UPDATE, and DELETE operations on the table.
    /// This is the default behavior and maintains the postgres table as a materialized snapshot of the output view.
    #[default]
    #[serde(rename = "materialized")]
    Materialized,

    /// CDC (Change Data Capture) mode: write all operations as INSERT operations
    /// into a Postgres table that serves as an append-only event log.
    /// In this mode, inserts, updates, and deletes are all represented as new rows
    /// with metadata columns describing the operation type and timestamp.
    #[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"),
        }
    }
}

/// TLS/SSL configuration for PostgreSQL connectors.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema, Default)]
pub struct PostgresTlsConfig {
    /// A sequence of CA certificates in PEM format.
    pub ssl_ca_pem: Option<String>,

    /// Path to a file containing a sequence of CA certificates in PEM format.
    pub ssl_ca_location: Option<String>,

    /// The client certificate in PEM format.
    pub ssl_client_pem: Option<String>,

    /// Path to the client certificate.
    pub ssl_client_location: Option<String>,

    /// The client certificate key in PEM format.
    pub ssl_client_key: Option<String>,

    /// Path to the client certificate key.
    pub ssl_client_key_location: Option<String>,

    /// The path to the certificate chain file.
    /// The file must contain a sequence of PEM-formatted certificates,
    /// the first being the leaf certificate, and the remainder forming
    /// the chain of certificates up to and including the trusted root certificate.
    pub ssl_certificate_chain_location: Option<String>,

    /// True to enable hostname verification when using TLS. True by default.
    ///
    /// When false, the certificate chain is still verified against the
    /// trusted CA; only the requirement that the server name appears in the
    /// certificate is lifted.
    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()
    }
}

/// Batch processing configuration for the Postgres CDC connector.
///
/// Controls how replication events are buffered into a batch before being
/// flushed to Feldera. Mirrors the batch configuration of the underlying
/// `etl` replication library; fields omitted from the configuration fall
/// back to `etl`'s own defaults.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcBatchConfig {
    /// Maximum time, in milliseconds, to wait before flushing a partially
    /// filled batch. This is the latency bound for batching: once the first
    /// event enters a batch, the batch is flushed when this timer elapses,
    /// even if `max_size` was not reached.
    ///
    /// Default: 10000 (10 seconds).
    #[serde(default = "default_batch_max_fill_ms")]
    #[schema(default = default_batch_max_fill_ms)]
    pub max_fill_ms: u64,

    /// Ratio of process memory reserved for incoming replication batch
    /// bytes, in the `(0.0, 1.0]` interval. The configured memory is divided
    /// by the number of active streams at runtime, so each stream gets only
    /// a per-stream share of the global memory budget.
    ///
    /// Default: 0.2.
    #[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,

    /// Maximum preferred size for one batch per active stream, such as
    /// `"32Mi"`. This is a ceiling, not a target: the runtime still chooses
    /// the smaller value between this limit and the memory-ratio budget
    /// computed from `memory_budget_ratio`.
    ///
    /// Default: `"32Mi"`, the same as etl.
    ///
    /// Before release 0.367.0 this setting was `max_bytes`, a number of
    /// bytes. That name is deprecated but still read.
    #[serde(
        default = "default_batch_max_size",
        alias = "max_bytes",
        deserialize_with = "size_batch_max_size"
    )]
    #[schema(value_type = String, default = schema_default_batch_max_size)]
    pub max_size: ConfigSize,
}

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_size: default_batch_max_size(),
        }
    }
}

// `f32` doesn't implement `Eq` because of NaN, so it can't be derived here.
// `validate()` rejects NaN/out-of-range ratios, so equality is reflexive for
// any value that passes validation; this lets `PostgresCdcReaderConfig` (and
// its containing `TransportConfig` enum) keep deriving `Eq`.
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_size.is_zero() {
            return Err("batch.max_size 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_size() -> ConfigSize {
    ConfigSize::from_mib(32)
}
fn schema_default_batch_max_size() -> String {
    default_batch_max_size().to_string()
}
crate::required_size_setting!(size_batch_max_size, "max_size", LegacySizeUnit::Bytes);

/// Memory-based backpressure configuration for the Postgres CDC connector.
///
/// When the connector's memory usage rises above `activate_threshold`, it
/// pauses reading further replication events until usage drops back below
/// `resume_threshold`. Mirrors the memory backpressure configuration of the
/// underlying `etl` replication library.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcMemoryBackpressureConfig {
    /// Memory usage ratio above which backpressure is activated, in the
    /// `(0.0, 1.0]` interval.
    ///
    /// Default: 0.85.
    #[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,

    /// Memory usage ratio below which backpressure is released, in the
    /// `[0.0, 1.0)` interval. Must be lower than `activate_threshold`.
    ///
    /// Default: 0.75.
    #[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(),
        }
    }
}

// See the corresponding `impl Eq for PostgresCdcBatchConfig` above for why
// this is sound despite the `f32` fields.
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
}

/// Postgres CDC input connector configuration.
///
/// Uses logical replication to capture ongoing changes from a Postgres database.
/// Requires a pre-created publication. Automatic source migrations require a
/// superuser; with administrator-installed source objects and
/// `run_source_migrations = false`, a replication role with the documented
/// source-table and etl state-store privileges can be used instead.
/// Tables must have primary keys and `REPLICA IDENTITY FULL` is recommended
/// for UPDATE/DELETE support.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresCdcReaderConfig {
    /// Postgres connection URI. Automatic source migrations require a superuser.
    /// With `run_source_migrations = false`, the user needs REPLICATION and the
    /// grants described in [Running as a non-superuser](https://docs.feldera.com/connectors/sources/postgresql-cdc#running-as-a-non-superuser).
    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
    pub uri: String,

    /// Name of the pre-created Postgres publication to replicate from.
    pub publication: String,

    /// Postgres table to replicate, schema-qualified (e.g. "public.orders").
    /// A name given without a schema refers to a table in "public".
    /// Must be included in the publication.
    pub source_table: String,

    /// Whether the connector runs etl's source migrations on startup.
    ///
    /// The source migrations install the schema helper functions and the
    /// `ddl_command_end` event trigger. Creating the event trigger requires a
    /// superuser, so a de-elevated role can set this to `false` and have an
    /// administrator install the source objects out-of-band. Disabling this
    /// does not skip the state-store migrations, which run on every start
    /// regardless.
    ///
    /// Default: `true`.
    #[serde(default = "default_run_source_migrations")]
    #[schema(default = default_run_source_migrations)]
    pub run_source_migrations: bool,

    /// TLS/SSL configuration.
    #[serde(flatten)]
    #[schema(inline)]
    pub tls: PostgresTlsConfig,

    /// Batch processing configuration.
    ///
    /// Controls how replication events are buffered before being flushed to
    /// Feldera. When omitted, uses the defaults listed on each field, which
    /// match the underlying `etl` library's defaults.
    #[serde(default)]
    pub batch: PostgresCdcBatchConfig,

    /// Memory-based backpressure configuration.
    ///
    /// Controls when the connector pauses reading further replication
    /// events to avoid exceeding available memory. When omitted, uses the
    /// defaults listed on each field, which match the underlying `etl`
    /// library's defaults.
    #[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(())
    }
}

/// Postgres input connector configuration.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresReaderConfig {
    /// Postgres URI.
    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
    pub uri: String,

    /// Query that specifies what data to fetch from postgres.
    pub query: String,

    /// TLS/SSL configuration.
    #[serde(flatten)]
    #[schema(inline)]
    pub tls: PostgresTlsConfig,
}

/// Postgres output connector configuration.
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
pub struct PostgresWriterConfig {
    /// Postgres URI.
    /// See: <https://docs.rs/tokio-postgres/0.7.12/tokio_postgres/config/struct.Config.html>
    pub uri: String,

    /// The table to write the output to.
    pub table: String,

    /// Write mode for the connector.
    ///
    /// - `materialized` (default): Perform direct INSERT, UPDATE, and DELETE operations on the table.
    /// - `cdc`: Write all operations as INSERT operations into an append-only event log
    ///   with additional metadata columns describing the operation type and timestamp.
    #[serde(default)]
    #[schema(default = PostgresWriteMode::default)]
    pub mode: PostgresWriteMode,

    /// Name of the operation metadata column in CDC mode.
    ///
    /// Only used when `mode = "cdc"`. This column will contain:
    /// - `"i"` for insert operations
    /// - `"u"` for upsert operations
    /// - `"d"` for delete operations
    ///
    /// Default: `"__feldera_op"`
    #[serde(default = "default_cdc_op_column")]
    #[schema(default = default_cdc_op_column)]
    pub cdc_op_column: String,

    /// Name of the timestamp metadata column in CDC mode.
    ///
    /// Only used when `mode = "cdc"`. This column will contain the timestamp
    /// (in RFC 3339 format) when the batch of updates was output
    /// by the pipeline.
    ///
    /// Default: `"__feldera_ts"`
    #[serde(default = "default_cdc_ts_column")]
    #[schema(default = default_cdc_ts_column)]
    pub cdc_ts_column: String,

    /// TLS/SSL configuration.
    #[serde(flatten)]
    #[schema(inline)]
    pub tls: PostgresTlsConfig,

    /// The maximum number of records in a single buffer.
    pub max_records_in_buffer: Option<usize>,

    /// The maximum buffer size for a single operation, such as `"1Mi"`.
    /// Note that the buffers of `INSERT`, `UPDATE` and `DELETE` queries are
    /// separate.
    /// Default: `"1Mi"`.
    ///
    /// Before release 0.367.0 this setting was `max_buffer_size_bytes`, a
    /// number of bytes. That name is deprecated but still read.
    #[schema(value_type = String, default = schema_default_max_buffer_size)]
    #[serde(
        default = "default_max_buffer_size",
        alias = "max_buffer_size_bytes",
        deserialize_with = "size_max_buffer_size"
    )]
    pub max_buffer_size: ConfigSize,

    /// Specifies how the connector handles conflicts when executing an `INSERT`
    /// into a table with a primary key. By default, an existing row with the same
    /// key is overwritten. Setting this flag to `true` preserves the existing row
    /// and ignores the new insert.
    ///
    /// This setting does not affect `UPDATE` statements, which always replace the
    /// value associated with the key.
    ///
    /// This setting is not supported when `mode = "cdc"`, since all operations
    /// are performed as append-only `INSERT`s into the target table.
    /// Any conflict in CDC mode will result in an error.
    ///
    /// Default: `false`
    #[serde(default)]
    pub on_conflict_do_nothing: bool,

    /// The number of threads to use during encoding.
    ///
    /// Default: 1
    #[serde(default = "default_writer_threads")]
    #[schema(default = default_writer_threads)]
    pub threads: usize,

    /// The names of the extra columns in the Postgres table that are not part of the view schema.
    ///
    /// These connector can write user-defined values, configured using the `set_extra_columns` connector command,
    /// to these columns.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extra_columns: Vec<String>,
}

fn default_max_buffer_size() -> ConfigSize {
    ConfigSize::from_mib(1)
}
fn schema_default_max_buffer_size() -> String {
    default_max_buffer_size().to_string()
}
crate::required_size_setting!(
    size_max_buffer_size,
    "max_buffer_size",
    LegacySizeUnit::Bytes
);

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_size": "4Mi"}"#;
        let config: PostgresCdcBatchConfig = serde_json::from_str(json).unwrap();

        assert_eq!(config.max_size, ConfigSize::from_mib(4));
        // The superseded spelling still reads, as a number of bytes.
        let legacy: PostgresCdcBatchConfig =
            serde_json::from_str(r#"{"max_bytes": 4194304}"#).unwrap();
        assert_eq!(legacy.max_size, ConfigSize::from_mib(4));
        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_size() {
        let config = PostgresCdcBatchConfig {
            max_size: ConfigSize::ZERO,
            ..Default::default()
        };

        let err = config.validate().unwrap_err();
        assert!(err.contains("batch.max_size"));
    }

    #[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_size = ConfigSize::ZERO;

        let err = config.validate().unwrap_err();
        assert!(err.contains("batch.max_size"));
    }

    #[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"));
    }

    /// Regression test: the `f32` fields must survive the JSON-string
    /// round-trip a checkpoint takes through `PipelineConfig`, whose
    /// `InputEndpointConfig` flattens the connector config. With `serde_json`'s
    /// `arbitrary_precision` feature enabled, the serde `Content` buffer that
    /// `#[serde(flatten)]` uses represents floats as maps, which breaks plain
    /// `f32` deserialization (serde-rs/json#1157). `serde_via_value` on each
    /// `f32` field fixes this.
    #[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);
    }
}