udb 0.4.21

Universal Data Broker — a Rust gRPC broker over multiple databases (Postgres, MySQL, SQLite, MongoDB, ClickHouse, Cassandra, MSSQL, Redis, Qdrant, S3, Neo4j, …) with per-tenant RLS, 2PC, sagas, and CDC.
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
//! config.rs split — backends group (Phase G).
use super::*;

/// Configuration for a single PostgreSQL connection role (primary / backup / signal).
///
/// PostgreSQL is the only backend that hosts the migration ledger tables.
/// The Go UDB service resolves DSN strings from these fields.
/// Mirrors the legacy Go service `DBConfig` shape.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct DbConfig {
    /// Deployment mode: `SelfHosted` (Docker / on-premise) or `Cloud` (Neon,
    /// Supabase, RDS, Aiven, etc.).  Drives TLS defaults and pooler DSN format.
    pub deploy: BackendDeployConfig,
    /// PostgreSQL host (e.g. `"localhost"`, Neon project hostname).
    pub host: String,
    /// TCP port, defaults to `5432`.
    pub port: u16,
    /// Database name.
    pub database: String,
    /// Role / user name.
    pub role: String,
    /// Password (resolved from env; never logged or serialised in cleartext).
    pub password: String,
    /// SSL mode: `"require"`, `"disable"`, `"prefer"`.  When empty, derived
    /// from `deploy.mode`: Cloud → `"require"`, SelfHosted → `"prefer"`.
    pub ssl_mode: String,
    /// Pooler DSN (PgBouncer / Neon pooled endpoint) for application traffic.
    pub pooler_dsn: String,
    /// Direct DSN (non-pooled) for migrations and DDL.
    pub direct_dsn: String,
    /// Maximum open connections in the pooler. Zero uses
    /// `DEFAULT_DB_MAX_OPEN_CONNS`; backend instances may override it.
    pub max_open_conns: i32,
    /// Maximum idle connections in the pooler.
    pub max_idle_conns: i32,
    /// Connection max lifetime in seconds. Zero uses the system-wide default.
    pub conn_max_lifetime_secs: u64,
    /// Connection max idle time in seconds. Zero uses the system-wide default.
    pub conn_max_idle_secs: u64,
    /// Minimum connections in the pool. Default is the system-wide
    /// `DEFAULT_DB_MIN_CONNECTIONS`; per-instance values win.
    #[serde(default = "five_i32")]
    pub min_connections: i32,
    /// Connection acquire timeout in seconds. Default is the system-wide
    /// `DEFAULT_DB_ACQUIRE_TIMEOUT_SECS`; per-instance values win.
    #[serde(default = "ten_u64")]
    pub acquire_timeout_secs: u64,
}

// Manual `Debug` that redacts credential material (`password`, `pooler_dsn`,
// `direct_dsn` may embed userinfo) so a `{:?}` of this config never leaks a
// secret into logs. Non-secret fields print normally to preserve debuggability.
impl std::fmt::Debug for DbConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DbConfig")
            .field("deploy", &self.deploy)
            .field("host", &self.host)
            .field("port", &self.port)
            .field("database", &self.database)
            .field("role", &self.role)
            .field("password", &"[redacted]")
            .field("ssl_mode", &self.ssl_mode)
            .field("pooler_dsn", &"[redacted]")
            .field("direct_dsn", &"[redacted]")
            .field("max_open_conns", &self.max_open_conns)
            .field("max_idle_conns", &self.max_idle_conns)
            .field("conn_max_lifetime_secs", &self.conn_max_lifetime_secs)
            .field("conn_max_idle_secs", &self.conn_max_idle_secs)
            .field("min_connections", &self.min_connections)
            .field("acquire_timeout_secs", &self.acquire_timeout_secs)
            .finish()
    }
}

impl DbConfig {
    /// Returns `true` when the minimum required fields (`host`, `database`, `role`) are set.
    pub fn is_configured(&self) -> bool {
        !self.host.is_empty() && !self.database.is_empty() && !self.role.is_empty()
    }

    /// Returns the effective SSL mode, falling back to a deploy-mode default when
    /// `ssl_mode` is empty:  Cloud → `"require"`, SelfHosted → `"prefer"`.
    pub fn effective_ssl_mode(&self) -> &str {
        if !self.ssl_mode.is_empty() {
            return &self.ssl_mode;
        }
        match self.deploy.mode {
            DeployMode::Cloud => "require",
            DeployMode::SelfHosted => "prefer",
        }
    }

    /// Returns a log-safe masked representation (host + role; password redacted).
    pub fn masked_log(&self) -> String {
        format!(
            "host={} db={} role={} ssl={} deploy={}",
            self.host,
            self.database,
            self.role,
            self.effective_ssl_mode(),
            self.deploy.mode.as_str(),
        )
    }
}

// ── Tier 2: Redis (Cache) ─────────────────────────────────────────────────────

/// Connection configuration for the Redis cache tier.
///
/// Used for: session cache, rate-limit counters, read-through cache, feature flags.
/// Spec §16.1 Tier 2.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct RedisConfig {
    /// Deployment mode: `SelfHosted` (Docker / on-premise) or `Cloud`
    /// (Upstash, Redis Enterprise Cloud, ElastiCache, etc.).
    /// Cloud mode enables TLS by default on the connection.
    pub deploy: BackendDeployConfig,
    /// Redis host.  Defaults to `"localhost"`.
    pub host: String,
    /// Redis TCP port.  Defaults to `6379`.
    pub port: u16,
    /// Authentication password (ACL or `requirepass`; env-resolved).
    pub password: String,
    /// Logical database index (0–15).  Default: `0`.
    pub database: u8,
    /// Maximum number of connections in the pool.  Default: `20`.
    pub pool_size: u32,
    /// Minimum number of idle connections kept open.  Default: `2`.
    pub min_idle_conns: u32,
    /// Maximum number of retries on failure.  Default: `3`.
    pub max_retries: u32,
    /// Raw connection string (DSN). When set, takes precedence over host/port.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dsn: Option<String>,
    /// Enable TLS for the connection.  When not set explicitly, derived from
    /// `deploy.mode`: Cloud → `true`, SelfHosted → `false`.
    pub tls_enabled: bool,
    /// Default key TTL in seconds.  `0` = no expiry.  Default: `3600` (1 h).
    pub default_ttl_secs: u64,
    /// Sentinel / Cluster mode: `"standalone"`, `"sentinel"`, `"cluster"`.
    pub mode: String,
    /// Sentinel master name (only used when `mode = "sentinel"`).
    pub sentinel_master: String,
}

// Manual `Debug` redacting the auth `password` and raw `dsn` (which may embed
// `requirepass`/userinfo). Non-secret connection metadata prints normally.
impl std::fmt::Debug for RedisConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RedisConfig")
            .field("deploy", &self.deploy)
            .field("host", &self.host)
            .field("port", &self.port)
            .field("password", &"[redacted]")
            .field("database", &self.database)
            .field("pool_size", &self.pool_size)
            .field("min_idle_conns", &self.min_idle_conns)
            .field("max_retries", &self.max_retries)
            .field("dsn", &self.dsn.as_ref().map(|_| "[redacted]"))
            .field("tls_enabled", &self.tls_enabled)
            .field("default_ttl_secs", &self.default_ttl_secs)
            .field("mode", &self.mode)
            .field("sentinel_master", &self.sentinel_master)
            .finish()
    }
}

impl RedisConfig {
    /// Returns `true` when host or dsn is non-empty.
    pub fn is_configured(&self) -> bool {
        !self.host.is_empty() || self.dsn.as_ref().map(|d| !d.is_empty()).unwrap_or(false)
    }

    /// Returns whether TLS is active, honouring the explicit field first,
    /// then falling back to the deploy-mode default (Cloud → true).
    pub fn effective_tls(&self) -> bool {
        if self.tls_enabled {
            return true;
        }
        self.deploy.tls_required()
    }

    /// Returns a log-safe representation.
    pub fn masked_log(&self) -> String {
        format!(
            "host={}:{} db={} tls={} mode={} deploy={}",
            self.host,
            self.port,
            self.database,
            self.effective_tls(),
            self.mode,
            self.deploy.mode.as_str(),
        )
    }

    /// Returns the effective TCP port, defaulting to `6379`.
    pub fn effective_port(&self) -> u16 {
        if self.port > 0 { self.port } else { 6379 }
    }
}

// ── Tier 3: Qdrant (Vector store) ────────────────────────────────────────────

/// Connection configuration for the Qdrant vector store tier.
///
/// Used for: embedding similarity search, OCR correction history,
/// template clustering.  Spec §16.1 Tier 3.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct QdrantConfig {
    /// Deployment mode: `SelfHosted` (Docker / on-premise) or `Cloud`
    /// (Qdrant Cloud).  Cloud mode requires an API key and TLS.
    pub deploy: BackendDeployConfig,
    /// Qdrant host.  Defaults to `"localhost"`.
    pub host: String,
    /// gRPC port (preferred for high-throughput).  Defaults to `6334`.
    pub grpc_port: u16,
    /// HTTP/REST port (health checks, admin UI).  Defaults to `6333`.
    pub http_port: u16,
    /// API key for Qdrant Cloud or secured on-premise deployments.
    pub api_key: String,
    /// Enable TLS on the gRPC channel.  When not set explicitly, derived from
    /// `deploy.mode`: Cloud → `true`, SelfHosted → `false`.
    pub tls_enabled: bool,
    /// Default vector dimension (must match embedding model output).
    /// e.g. `1536` for OpenAI `text-embedding-3-small`.
    pub default_dimension: u32,
    /// Default distance metric: `"Cosine"`, `"Euclid"`, `"Dot"`.  Default: `"Cosine"`.
    pub default_distance: String,
    /// Maximum retries on transient gRPC errors.  Default: `3`.
    pub max_retries: u32,
    /// Raw URL / DSN. When set, takes precedence over host/port.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

// Manual `Debug` redacting the `api_key`. The `url`/host fields are non-secret
// endpoint metadata and print normally.
impl std::fmt::Debug for QdrantConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QdrantConfig")
            .field("deploy", &self.deploy)
            .field("host", &self.host)
            .field("grpc_port", &self.grpc_port)
            .field("http_port", &self.http_port)
            .field("api_key", &"[redacted]")
            .field("tls_enabled", &self.tls_enabled)
            .field("default_dimension", &self.default_dimension)
            .field("default_distance", &self.default_distance)
            .field("max_retries", &self.max_retries)
            .field("url", &self.url)
            .finish()
    }
}

impl QdrantConfig {
    /// Returns `true` when host or url is non-empty.
    pub fn is_configured(&self) -> bool {
        !self.host.is_empty() || self.url.as_ref().map(|u| !u.is_empty()).unwrap_or(false)
    }

    /// Returns whether TLS is active, honouring the explicit field first,
    /// then falling back to the deploy-mode default (Cloud → true).
    pub fn effective_tls(&self) -> bool {
        if self.tls_enabled {
            return true;
        }
        self.deploy.tls_required()
    }

    /// Returns a log-safe representation.
    pub fn masked_log(&self) -> String {
        format!(
            "host={} grpc={} http={} tls={} dim={} dist={} deploy={}",
            self.host,
            self.effective_grpc_port(),
            self.effective_http_port(),
            self.effective_tls(),
            self.default_dimension,
            self.default_distance,
            self.deploy.mode.as_str(),
        )
    }

    /// Returns the effective gRPC port, defaulting to `6334`.
    pub fn effective_grpc_port(&self) -> u16 {
        if self.grpc_port > 0 {
            self.grpc_port
        } else {
            6334
        }
    }

    /// Returns the effective HTTP port, defaulting to `6333`.
    pub fn effective_http_port(&self) -> u16 {
        if self.http_port > 0 {
            self.http_port
        } else {
            6333
        }
    }

    /// Returns the effective distance metric, defaulting to `"Cosine"`.
    pub fn effective_distance(&self) -> &str {
        if self.default_distance.is_empty() {
            "Cosine"
        } else {
            &self.default_distance
        }
    }
}

// ── Tier 4: MinIO (Object store) ──────────────────────────────────────────────

/// Connection configuration for the MinIO / S3-compatible object store tier.
///
/// Used for: OCR artifact storage, processed document exports, model archives.
/// Spec §16.1 Tier 4.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct MinioConfig {
    /// Deployment mode: `SelfHosted` (Docker MinIO / on-premise) or `Cloud`
    /// (AWS S3, GCS, Azure Blob, DigitalOcean Spaces, Tigris, etc.).
    /// Cloud mode enables TLS by default and may affect endpoint resolution.
    pub deploy: BackendDeployConfig,
    /// MinIO / S3 endpoint URL, e.g. `"http://minio:9000"` or `"https://s3.amazonaws.com"`.
    pub endpoint: String,
    /// Access key ID (env-resolved).
    pub access_key: String,
    /// Secret access key (env-resolved; never logged).
    pub secret_key: String,
    /// Enable SSL/TLS for the endpoint.  When not set explicitly, derived from
    /// `deploy.mode`: Cloud → `true`, SelfHosted → `false`.
    pub use_ssl: bool,
    /// Optional prefix prepended to all bucket names.  e.g. `"tenant-a-"`.
    pub bucket_prefix: String,
    /// AWS/MinIO region.  Default: `"us-east-1"`.
    pub region: String,
    /// Maximum upload/download retries.  Default: `3`.
    pub max_retries: u32,
    /// Part size (bytes) for multipart uploads.  Default: `64 MiB`.
    pub multipart_part_size_bytes: u64,
}

// Manual `Debug` redacting the S3/MinIO credential pair (`access_key`,
// `secret_key`) — the same pair the `masked_log` helper omits. Endpoint/region
// metadata prints normally.
impl std::fmt::Debug for MinioConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MinioConfig")
            .field("deploy", &self.deploy)
            .field("endpoint", &self.endpoint)
            .field("access_key", &"[redacted]")
            .field("secret_key", &"[redacted]")
            .field("use_ssl", &self.use_ssl)
            .field("bucket_prefix", &self.bucket_prefix)
            .field("region", &self.region)
            .field("max_retries", &self.max_retries)
            .field("multipart_part_size_bytes", &self.multipart_part_size_bytes)
            .finish()
    }
}

impl MinioConfig {
    /// Returns `true` when endpoint is non-empty.
    pub fn is_configured(&self) -> bool {
        !self.endpoint.is_empty()
    }

    /// Returns whether SSL/TLS is active, honouring the explicit `use_ssl` field
    /// first, then falling back to the deploy-mode default (Cloud → true).
    pub fn effective_ssl(&self) -> bool {
        if self.use_ssl {
            return true;
        }
        self.deploy.tls_required()
    }

    /// Returns a log-safe representation (secret key redacted).
    pub fn masked_log(&self) -> String {
        format!(
            "endpoint={} region={} ssl={} prefix={} deploy={}",
            self.endpoint,
            self.effective_region(),
            self.effective_ssl(),
            self.bucket_prefix,
            self.deploy.mode.as_str(),
        )
    }

    /// Returns the effective region, defaulting to `"us-east-1"`.
    pub fn effective_region(&self) -> &str {
        if self.region.is_empty() {
            "us-east-1"
        } else {
            &self.region
        }
    }

    /// Returns the qualified bucket name for a given logical bucket.
    pub fn qualified_bucket(&self, logical_name: &str) -> String {
        format!("{}{}", self.bucket_prefix, logical_name)
    }
}

// ── Failover config ───────────────────────────────────────────────────────────

/// Controls automatic failover from primary to backup DB.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct FailoverConfig {
    /// Enable automatic failover when the primary DB is unhealthy.
    pub enabled: bool,
    /// Number of consecutive health-check failures before triggering failover.
    pub failure_threshold: u32,
    /// Minimum interval between failovers, e.g. `"5m"`.
    pub cooldown: String,
}

// ── Audit event sink ─────────────────────────────────────────────────────────

/// Destination type for the audit event sink.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AuditSinkKind {
    /// No audit sink — events are discarded (default, backward compatible).
    #[default]
    None,
    /// Emit audit events as structured JSON lines to stdout.
    Stdout,
    /// Append audit events to a file.
    File,
    /// Publish audit events to a Kafka topic.
    Kafka,
    /// Insert audit events into a PostgreSQL table.
    Postgres,
}

/// Configuration for the UDB audit event sink.
///
/// Loaded from env-vars at startup:
///   `UDB_AUDIT_SINK`             — sink kind (`none`|`stdout`|`file`|`kafka`|`postgres`)
///   `UDB_AUDIT_FILE_PATH`        — path when sink=file
///   `UDB_AUDIT_KAFKA_TOPIC`      — Kafka topic when sink=kafka
///   `UDB_AUDIT_KAFKA_BROKERS`    — comma-separated brokers when sink=kafka
///   `UDB_AUDIT_PG_TABLE`         — fully-qualified table name when sink=postgres
///   `UDB_AUDIT_MIN_SEVERITY`     — minimum severity to emit (`info`|`warn`|`error`); default `info`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct AuditSinkConfig {
    pub kind: AuditSinkKind,
    /// Target file path (used when `kind == File`).
    pub file_path: Option<String>,
    /// Kafka topic (used when `kind == Kafka`).
    pub kafka_topic: Option<String>,
    /// Comma-separated Kafka broker list (used when `kind == Kafka`).
    pub kafka_brokers: Option<String>,
    /// Fully-qualified PostgreSQL table for audit rows (used when `kind == Postgres`).
    pub pg_table: Option<String>,
    /// Minimum severity to emit.  Accepts `"info"`, `"warn"`, `"error"`.
    pub min_severity: String,
}

impl Default for AuditSinkConfig {
    /// Default audit config: the documented `min_severity` default is `info`.
    /// A derived `Default` would leave `min_severity` empty, which `validate()`
    /// (correctly) rejects — so an audit section absent from `backends.yaml`
    /// would fail validation. Pin the documented default here instead.
    fn default() -> Self {
        Self {
            kind: AuditSinkKind::default(),
            file_path: None,
            kafka_topic: None,
            kafka_brokers: None,
            pg_table: None,
            min_severity: "info".to_string(),
        }
    }
}

impl AuditSinkConfig {
    /// Load configuration from environment variables.
    pub fn from_env() -> Self {
        let kind = match std::env::var("UDB_AUDIT_SINK")
            .unwrap_or_default()
            .to_lowercase()
            .as_str()
        {
            "stdout" => AuditSinkKind::Stdout,
            "file" => AuditSinkKind::File,
            "kafka" => AuditSinkKind::Kafka,
            "postgres" | "pg" => AuditSinkKind::Postgres,
            _ => AuditSinkKind::None,
        };
        let min_severity = std::env::var("UDB_AUDIT_MIN_SEVERITY")
            .ok()
            .filter(|value| !value.trim().is_empty())
            .unwrap_or_else(|| "info".to_string());
        Self {
            kind,
            file_path: std::env::var("UDB_AUDIT_FILE_PATH")
                .ok()
                .filter(|v| !v.is_empty()),
            kafka_topic: std::env::var("UDB_AUDIT_KAFKA_TOPIC")
                .ok()
                .filter(|v| !v.is_empty()),
            kafka_brokers: std::env::var("UDB_AUDIT_KAFKA_BROKERS")
                .ok()
                .filter(|v| !v.is_empty()),
            pg_table: std::env::var("UDB_AUDIT_PG_TABLE")
                .ok()
                .filter(|v| !v.is_empty()),
            min_severity,
        }
    }

    /// Overlay env-provided fields onto an existing (file-loaded) config,
    /// touching only fields whose env var is present so YAML audit-sink config
    /// is preserved rather than wiped.
    pub fn merge_env(&mut self) {
        if let Ok(raw) = std::env::var("UDB_AUDIT_SINK") {
            self.kind = match raw.to_lowercase().as_str() {
                "stdout" => AuditSinkKind::Stdout,
                "file" => AuditSinkKind::File,
                "kafka" => AuditSinkKind::Kafka,
                "postgres" | "pg" => AuditSinkKind::Postgres,
                _ => AuditSinkKind::None,
            };
        }
        if let Some(v) = std::env::var("UDB_AUDIT_MIN_SEVERITY")
            .ok()
            .filter(|v| !v.is_empty())
        {
            self.min_severity = v;
        }
        if let Some(v) = std::env::var("UDB_AUDIT_FILE_PATH")
            .ok()
            .filter(|v| !v.is_empty())
        {
            self.file_path = Some(v);
        }
        if let Some(v) = std::env::var("UDB_AUDIT_KAFKA_TOPIC")
            .ok()
            .filter(|v| !v.is_empty())
        {
            self.kafka_topic = Some(v);
        }
        if let Some(v) = std::env::var("UDB_AUDIT_KAFKA_BROKERS")
            .ok()
            .filter(|v| !v.is_empty())
        {
            self.kafka_brokers = Some(v);
        }
        if let Some(v) = std::env::var("UDB_AUDIT_PG_TABLE")
            .ok()
            .filter(|v| !v.is_empty())
        {
            self.pg_table = Some(v);
        }
    }

    /// Returns `true` when the sink is active (i.e. not `None`).
    pub fn is_active(&self) -> bool {
        self.kind != AuditSinkKind::None
    }

    /// Returns a validation error if the configuration is inconsistent.
    pub fn validate(&self) -> Vec<String> {
        let mut errors = Vec::new();
        match self.kind {
            AuditSinkKind::File if self.file_path.is_none() => {
                errors
                    .push("UDB_AUDIT_SINK=file requires UDB_AUDIT_FILE_PATH to be set".to_string());
            }
            AuditSinkKind::Kafka if self.kafka_topic.is_none() => {
                errors.push(
                    "UDB_AUDIT_SINK=kafka requires UDB_AUDIT_KAFKA_TOPIC to be set".to_string(),
                );
            }
            AuditSinkKind::Kafka if self.kafka_brokers.is_none() => {
                errors.push(
                    "UDB_AUDIT_SINK=kafka requires UDB_AUDIT_KAFKA_BROKERS to be set".to_string(),
                );
            }
            AuditSinkKind::Postgres if self.pg_table.is_none() => {
                errors.push(
                    "UDB_AUDIT_SINK=postgres requires UDB_AUDIT_PG_TABLE to be set".to_string(),
                );
            }
            _ => {}
        }
        match self.min_severity.as_str() {
            // Empty = unset → falls back to the documented `info` default.
            "" | "info" | "warn" | "error" => {}
            other => errors.push(format!(
                "UDB_AUDIT_MIN_SEVERITY='{other}' is not valid; use 'info', 'warn', or 'error'"
            )),
        }
        errors
    }
}

#[cfg(test)]
mod secret_no_leak {
    use super::*;

    // Item 4.6 — every backend config that holds a credential must redact it in
    // its `{:?}` output so secrets never reach logs through a Debug formatter.
    const CANARY: &str = "udb-canary-SECRET";

    #[test]
    fn db_config_debug_redacts_secrets() {
        let cfg = DbConfig {
            password: CANARY.to_string(),
            pooler_dsn: format!("postgres://u:{CANARY}@h/db"),
            direct_dsn: format!("postgres://u:{CANARY}@h/db"),
            host: "h".to_string(),
            ..Default::default()
        };
        let dbg = format!("{cfg:?}");
        assert!(!dbg.contains(CANARY), "DbConfig leaked a secret: {dbg}");
        assert!(dbg.contains("host"), "DbConfig dropped debuggable fields");
    }

    #[test]
    fn redis_config_debug_redacts_secrets() {
        let cfg = RedisConfig {
            password: CANARY.to_string(),
            dsn: Some(format!("redis://:{CANARY}@h")),
            ..Default::default()
        };
        let dbg = format!("{cfg:?}");
        assert!(!dbg.contains(CANARY), "RedisConfig leaked a secret: {dbg}");
    }

    #[test]
    fn qdrant_config_debug_redacts_secrets() {
        let cfg = QdrantConfig {
            api_key: CANARY.to_string(),
            ..Default::default()
        };
        let dbg = format!("{cfg:?}");
        assert!(!dbg.contains(CANARY), "QdrantConfig leaked a secret: {dbg}");
    }

    #[test]
    fn minio_config_debug_redacts_secrets() {
        let cfg = MinioConfig {
            access_key: CANARY.to_string(),
            secret_key: CANARY.to_string(),
            ..Default::default()
        };
        let dbg = format!("{cfg:?}");
        assert!(!dbg.contains(CANARY), "MinioConfig leaked a secret: {dbg}");
    }
}

// ── Top-level UDB config ──────────────────────────────────────────────────────