obscura-server 0.5.0

A server for relaying secure messages using the Signal Protocol
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
use clap::{Args, Parser};
use ipnetwork::IpNetwork;

#[derive(Clone, Debug, Parser)]
#[command(version, about, long_about = None)]
pub struct Config {
    /// Global time-to-live for messages and attachments in days
    #[arg(long, env = "OBSCURA_TTL_DAYS", default_value_t = Config::default().ttl_days)]
    pub ttl_days: i64,

    #[command(flatten)]
    pub database: DatabaseConfig,

    #[command(flatten)]
    pub server: ServerConfig,

    #[command(flatten)]
    pub auth: AuthConfig,

    #[command(flatten)]
    pub rate_limit: RateLimitConfig,

    #[command(flatten)]
    pub health: HealthConfig,

    #[command(flatten)]
    pub messaging: MessagingConfig,

    #[command(flatten)]
    pub notifications: NotificationConfig,

    #[command(flatten)]
    pub pubsub: PubSubConfig,

    #[command(flatten)]
    pub websocket: WsConfig,

    #[command(flatten)]
    pub backup: BackupConfig,

    #[command(flatten)]
    pub attachment: AttachmentConfig,

    #[command(flatten)]
    pub storage: StorageConfig,

    #[command(flatten)]
    pub telemetry: TelemetryConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            ttl_days: 30,
            database: DatabaseConfig::default(),
            server: ServerConfig::default(),
            auth: AuthConfig::default(),
            rate_limit: RateLimitConfig::default(),
            health: HealthConfig::default(),
            messaging: MessagingConfig::default(),
            notifications: NotificationConfig::default(),
            pubsub: PubSubConfig::default(),
            websocket: WsConfig::default(),
            backup: BackupConfig::default(),
            attachment: AttachmentConfig::default(),
            storage: StorageConfig::default(),
            telemetry: TelemetryConfig::default(),
        }
    }
}

impl Config {
    #[must_use]
    pub fn load() -> Self {
        Self::parse()
    }
}

#[derive(Clone, Debug, Args)]
pub struct DatabaseConfig {
    /// Database connection URL
    #[arg(
        long = "db-url",
        id = "database_url",
        env = "OBSCURA_DATABASE_URL",
        default_value_t = DatabaseConfig::default().url
    )]
    pub url: String,

    /// Maximum number of connections in the pool
    #[arg(long = "db-max-connections", env = "OBSCURA_DATABASE_MAX_CONNECTIONS", default_value_t = DatabaseConfig::default().max_connections)]
    pub max_connections: u32,

    /// Minimum number of connections to keep idle in the pool
    #[arg(long = "db-min-connections", env = "OBSCURA_DATABASE_MIN_CONNECTIONS", default_value_t = DatabaseConfig::default().min_connections)]
    pub min_connections: u32,

    /// Seconds to wait before timing out on acquiring a connection
    #[arg(long = "db-acquire-timeout-secs", env = "OBSCURA_DATABASE_ACQUIRE_TIMEOUT_SECS", default_value_t = DatabaseConfig::default().acquire_timeout_secs)]
    pub acquire_timeout_secs: u64,

    /// Seconds before an idle connection is closed
    #[arg(long = "db-idle-timeout-secs", env = "OBSCURA_DATABASE_IDLE_TIMEOUT_SECS", default_value_t = DatabaseConfig::default().idle_timeout_secs)]
    pub idle_timeout_secs: u64,

    /// Seconds before a connection is retired and replaced
    #[arg(long = "db-max-lifetime-secs", env = "OBSCURA_DATABASE_MAX_LIFETIME_SECS", default_value_t = DatabaseConfig::default().max_lifetime_secs)]
    pub max_lifetime_secs: u64,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: "postgres://user:password@localhost/signal_server".to_string(),
            max_connections: 20,
            min_connections: 5,
            acquire_timeout_secs: 3,
            idle_timeout_secs: 600,
            max_lifetime_secs: 1800,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct PubSubConfig {
    /// `PubSub` connection URL (e.g. <redis://localhost:6379>)
    #[arg(
        long = "pubsub-url",
        id = "pubsub_url",
        env = "OBSCURA_PUBSUB_URL",
        default_value_t = PubSubConfig::default().url
    )]
    pub url: String,

    /// Minimum backoff time for `PubSub` reconnection in seconds
    #[arg(long = "pubsub-min-backoff-secs", env = "OBSCURA_PUBSUB_MIN_BACKOFF_SECS", default_value_t = PubSubConfig::default().min_backoff_secs)]
    pub min_backoff_secs: u64,

    /// Maximum backoff time for `PubSub` reconnection in seconds
    #[arg(long = "pubsub-max-backoff-secs", env = "OBSCURA_PUBSUB_MAX_BACKOFF_SECS", default_value_t = PubSubConfig::default().max_backoff_secs)]
    pub max_backoff_secs: u64,
}

impl Default for PubSubConfig {
    fn default() -> Self {
        Self { url: "redis://localhost:6379".to_string(), min_backoff_secs: 1, max_backoff_secs: 30 }
    }
}

#[derive(Clone, Debug, Default, clap::ValueEnum)]
pub enum LogFormat {
    #[default]
    Text,
    Json,
}

#[derive(Clone, Debug, Args)]
pub struct TelemetryConfig {
    /// OTLP Endpoint for traces and metrics (e.g. <http://localhost:4318>)
    /// If not set, OTLP export is disabled (logs only).
    #[arg(long, env = "OBSCURA_TELEMETRY_OTLP_ENDPOINT")]
    pub otlp_endpoint: Option<String>,

    /// Log format (text or json)
    #[arg(long, env = "OBSCURA_TELEMETRY_LOG_FORMAT", default_value_t = TelemetryConfig::default().log_format)]
    pub log_format: LogFormat,

    /// Trace sampling ratio (0.0 to 1.0)
    #[arg(long, env = "OBSCURA_TELEMETRY_TRACE_SAMPLING_RATIO", default_value_t = TelemetryConfig::default().trace_sampling_ratio)]
    pub trace_sampling_ratio: f64,

    /// Metric export interval in seconds
    #[arg(long, env = "OBSCURA_TELEMETRY_METRICS_EXPORT_INTERVAL_SECS", default_value_t = TelemetryConfig::default().metrics_export_interval_secs)]
    pub metrics_export_interval_secs: u64,

    /// OTLP export timeout in seconds
    #[arg(long, env = "OBSCURA_TELEMETRY_EXPORT_TIMEOUT_SECS", default_value_t = TelemetryConfig::default().export_timeout_secs)]
    pub export_timeout_secs: u64,
}

impl Default for TelemetryConfig {
    fn default() -> Self {
        Self {
            otlp_endpoint: None,
            log_format: LogFormat::Text,
            trace_sampling_ratio: 1.0,
            metrics_export_interval_secs: 60,
            export_timeout_secs: 10,
        }
    }
}

impl std::fmt::Display for LogFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Text => write!(f, "text"),
            Self::Json => write!(f, "json"),
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct ServerConfig {
    /// Host to listen on
    #[arg(long = "server-host", env = "OBSCURA_SERVER_HOST", default_value_t = ServerConfig::default().host)]
    pub host: String,

    /// Port to listen on
    #[arg(long = "server-port", env = "OBSCURA_SERVER_PORT", default_value_t = ServerConfig::default().port)]
    pub port: u16,

    /// Management port for health checks and metrics
    #[arg(long, env = "OBSCURA_SERVER_MGMT_PORT", default_value_t = ServerConfig::default().mgmt_port)]
    pub mgmt_port: u16,

    /// How long to wait for background tasks to finish during shutdown in seconds
    #[arg(long = "server-shutdown-timeout-secs", env = "OBSCURA_SERVER_SHUTDOWN_TIMEOUT_SECS", default_value_t = ServerConfig::default().shutdown_timeout_secs)]
    pub shutdown_timeout_secs: u64,

    /// Timeout for standard requests in seconds
    #[arg(long = "server-request-timeout-secs", env = "OBSCURA_SERVER_REQUEST_TIMEOUT_SECS", default_value_t = ServerConfig::default().request_timeout_secs)]
    pub request_timeout_secs: u64,

    /// Global catch-all safety timeout in seconds
    #[arg(long = "server-global-timeout-secs", env = "OBSCURA_SERVER_GLOBAL_TIMEOUT_SECS", default_value_t = ServerConfig::default().global_timeout_secs)]
    pub global_timeout_secs: u64,

    /// Comma-separated list of CIDRs to trust for X-Forwarded-For IP extraction
    #[arg(
        long,
        env = "OBSCURA_SERVER_TRUSTED_PROXIES",
        default_value = "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,127.0.0.1/32",
        value_delimiter = ','
    )]
    pub trusted_proxies: Vec<IpNetwork>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 3000,
            mgmt_port: 9090,
            shutdown_timeout_secs: 5,
            request_timeout_secs: 30,
            global_timeout_secs: 600,
            trusted_proxies: vec![
                "10.0.0.0/8".parse().expect("Invalid default CIDR for private network"),
                "172.16.0.0/12".parse().expect("Invalid default CIDR for private network"),
                "192.168.0.0/16".parse().expect("Invalid default CIDR for private network"),
                "127.0.0.1/32".parse().expect("Invalid default CIDR for localhost"),
            ],
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct AuthConfig {
    /// Secret key for JWT signing
    #[arg(long = "auth-jwt-secret", env = "OBSCURA_AUTH_JWT_SECRET", default_value_t = AuthConfig::default().jwt_secret)]
    pub jwt_secret: String,

    /// Access token time-to-live in seconds
    #[arg(long = "auth-token-ttl-secs", env = "OBSCURA_AUTH_TOKEN_TTL_SECS", default_value_t = AuthConfig::default().access_token_ttl_secs)]
    pub access_token_ttl_secs: u64,

    /// Refresh token time-to-live in days
    #[arg(long = "auth-refresh-token-ttl-days", env = "OBSCURA_AUTH_REFRESH_TOKEN_TTL_DAYS", default_value_t = AuthConfig::default().refresh_token_ttl_days)]
    pub refresh_token_ttl_days: i64,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            jwt_secret: "change_me_in_production".to_string(),
            access_token_ttl_secs: 900,
            refresh_token_ttl_days: 30,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct RateLimitConfig {
    /// Requests per second allowed for standard endpoints
    #[arg(long = "rate-limit-per-second", env = "OBSCURA_RATE_LIMIT_PER_SECOND", default_value_t = RateLimitConfig::default().per_second)]
    pub per_second: u32,

    /// Burst allowance for standard endpoints
    #[arg(long = "rate-limit-burst", env = "OBSCURA_RATE_LIMIT_BURST", default_value_t = RateLimitConfig::default().burst)]
    pub burst: u32,

    /// Stricter rate limit for expensive auth-related endpoints (register/login)
    #[arg(long = "auth-rate-limit-per-second", env = "OBSCURA_RATE_LIMIT_AUTH_PER_SECOND", default_value_t = RateLimitConfig::default().auth_per_second)]
    pub auth_per_second: u32,

    /// Burst allowance for expensive auth-related endpoints
    #[arg(long = "auth-rate-limit-burst", env = "OBSCURA_RATE_LIMIT_AUTH_BURST", default_value_t = RateLimitConfig::default().auth_burst)]
    pub auth_burst: u32,
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self { per_second: 10, burst: 20, auth_per_second: 1, auth_burst: 3 }
    }
}

#[derive(Clone, Debug, Args)]
pub struct MessagingConfig {
    /// Maximum number of messages in a user's inbox
    #[arg(long = "messaging-inbox-max-size", env = "OBSCURA_MESSAGING_INBOX_MAX_SIZE", default_value_t = MessagingConfig::default().max_inbox_size)]
    pub max_inbox_size: i64,

    /// How often to run the message cleanup task
    #[arg(
        long = "messaging-cleanup-interval-secs",
        id = "messaging_cleanup_interval_secs",
        env = "OBSCURA_MESSAGING_CLEANUP_INTERVAL_SECS",
        default_value_t = MessagingConfig::default().cleanup_interval_secs
    )]
    pub cleanup_interval_secs: u64,

    /// Maximum number of messages to process in a single batch
    #[arg(long = "messaging-batch-limit", env = "OBSCURA_MESSAGING_BATCH_LIMIT", default_value_t = MessagingConfig::default().batch_limit)]
    pub batch_limit: i64,

    /// Threshold of one-time prekeys to trigger a refill notification
    #[arg(long = "pre-key-refill-threshold", env = "OBSCURA_PRE_KEY_REFILL_THRESHOLD", default_value_t = MessagingConfig::default().pre_key_refill_threshold)]
    pub pre_key_refill_threshold: i32,

    /// Maximum number of one-time prekeys allowed per user
    #[arg(long = "pre-keys-max", env = "OBSCURA_PRE_KEYS_MAX", default_value_t = MessagingConfig::default().max_pre_keys)]
    pub max_pre_keys: i64,
}

impl Default for MessagingConfig {
    fn default() -> Self {
        Self {
            max_inbox_size: 1000,
            cleanup_interval_secs: 300,
            batch_limit: 50,
            pre_key_refill_threshold: 20,
            max_pre_keys: 100,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct NotificationConfig {
    /// How often to run the notification cleanup
    #[arg(long = "notifications-cleanup-interval-secs", env = "OBSCURA_NOTIFICATIONS_CLEANUP_INTERVAL_SECS", default_value_t = NotificationConfig::default().cleanup_interval_secs)]
    pub cleanup_interval_secs: u64,

    /// Capacity of the global notification dispatcher channel
    #[arg(long = "notifications-global-channel-capacity", env = "OBSCURA_NOTIFICATIONS_GLOBAL_CHANNEL_CAPACITY", default_value_t = NotificationConfig::default().global_channel_capacity)]
    pub global_channel_capacity: usize,

    /// Capacity of the per-user notification channel
    #[arg(long = "notifications-user-channel-capacity", env = "OBSCURA_NOTIFICATIONS_USER_CHANNEL_CAPACITY", default_value_t = NotificationConfig::default().user_channel_capacity)]
    pub user_channel_capacity: usize,

    /// Delay in seconds before a push notification is sent as a fallback
    #[arg(long = "notifications-push-delay-secs", env = "OBSCURA_NOTIFICATIONS_PUSH_DELAY_SECS", default_value_t = NotificationConfig::default().push_delay_secs)]
    pub push_delay_secs: u64,

    /// Interval in seconds for the notification worker to poll for due jobs
    #[arg(long = "notifications-worker-interval-secs", env = "OBSCURA_NOTIFICATIONS_WORKER_INTERVAL_SECS", default_value_t = NotificationConfig::default().worker_interval_secs)]
    pub worker_interval_secs: u64,

    /// Maximum number of concurrent push notification requests (also used as Redis poll limit)
    #[arg(long = "notifications-worker-concurrency", env = "OBSCURA_NOTIFICATIONS_WORKER_CONCURRENCY", default_value_t = NotificationConfig::default().worker_concurrency)]
    pub worker_concurrency: usize,

    /// Redis key for the push notification job queue
    #[arg(long = "notifications-push-queue-key", env = "OBSCURA_NOTIFICATIONS_PUSH_QUEUE_KEY", default_value_t = NotificationConfig::default().push_queue_key)]
    pub push_queue_key: String,

    /// Redis `PubSub` channel prefix for user notifications
    #[arg(long = "notifications-channel-prefix", env = "OBSCURA_NOTIFICATIONS_CHANNEL_PREFIX", default_value_t = NotificationConfig::default().channel_prefix)]
    pub channel_prefix: String,

    /// How long a push job is leased by a worker in seconds
    #[arg(long = "notifications-visibility-timeout-secs", env = "OBSCURA_NOTIFICATIONS_VISIBILITY_TIMEOUT_SECS", default_value_t = NotificationConfig::default().visibility_timeout_secs)]
    pub visibility_timeout_secs: u64,

    /// How often the invalid token cleanup flushes to the database in seconds
    #[arg(long = "notifications-invalid-token-cleanup-interval-secs", env = "OBSCURA_NOTIFICATIONS_INVALID_TOKEN_CLEANUP_INTERVAL_SECS", default_value_t = NotificationConfig::default().invalid_token_cleanup_interval_secs)]
    pub invalid_token_cleanup_interval_secs: u64,

    /// Maximum number of invalid tokens to delete in a single batch
    #[arg(long = "notifications-invalid-token-cleanup-batch-size", env = "OBSCURA_NOTIFICATIONS_INVALID_TOKEN_CLEANUP_BATCH_SIZE", default_value_t = NotificationConfig::default().invalid_token_cleanup_batch_size)]
    pub invalid_token_cleanup_batch_size: usize,

    /// Capacity of the invalid token cleanup channel
    #[arg(long = "notifications-invalid-token-cleanup-channel-capacity", env = "OBSCURA_NOTIFICATIONS_INVALID_TOKEN_CLEANUP_CHANNEL_CAPACITY", default_value_t = NotificationConfig::default().invalid_token_cleanup_channel_capacity)]
    pub invalid_token_cleanup_channel_capacity: usize,
}

impl Default for NotificationConfig {
    fn default() -> Self {
        Self {
            cleanup_interval_secs: 60,
            global_channel_capacity: 1024,
            user_channel_capacity: 64,
            push_delay_secs: 2,
            worker_interval_secs: 1,
            worker_concurrency: 100,
            push_queue_key: "jobs:push_notifications".to_string(),
            channel_prefix: "user:".to_string(),
            visibility_timeout_secs: 30,
            invalid_token_cleanup_interval_secs: 5,
            invalid_token_cleanup_batch_size: 50,
            invalid_token_cleanup_channel_capacity: 256,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct WsConfig {
    /// Size of the outbound message buffer
    #[arg(long = "ws-outbound-buffer-size", env = "OBSCURA_WS_OUTBOUND_BUFFER_SIZE", default_value_t = WsConfig::default().outbound_buffer_size)]
    pub outbound_buffer_size: usize,

    /// Size of the acknowledgment buffer
    #[arg(long = "ws-ack-buffer-size", env = "OBSCURA_WS_ACK_BUFFER_SIZE", default_value_t = WsConfig::default().ack_buffer_size)]
    pub ack_buffer_size: usize,

    /// Number of acknowledgments to batch before flushing
    #[arg(long = "ws-ack-batch-size", env = "OBSCURA_WS_ACK_BATCH_SIZE", default_value_t = WsConfig::default().ack_batch_size)]
    pub ack_batch_size: usize,

    /// How often to flush pending acknowledgments
    #[arg(long = "ws-ack-flush-interval-ms", env = "OBSCURA_WS_ACK_FLUSH_INTERVAL_MS", default_value_t = WsConfig::default().ack_flush_interval_ms)]
    pub ack_flush_interval_ms: u64,

    /// How often to send a WebSocket ping frame in seconds (0 to disable)
    #[arg(long = "ws-ping-interval-secs", env = "OBSCURA_WS_PING_INTERVAL_SECS", default_value_t = WsConfig::default().ping_interval_secs)]
    pub ping_interval_secs: u64,

    /// How long to wait for a pong response before closing the connection in seconds
    #[arg(long = "ws-ping-timeout-secs", env = "OBSCURA_WS_PING_TIMEOUT_SECS", default_value_t = WsConfig::default().ping_timeout_secs)]
    pub ping_timeout_secs: u64,
}

impl Default for WsConfig {
    fn default() -> Self {
        Self {
            outbound_buffer_size: 32,
            ack_buffer_size: 1000,
            ack_batch_size: 100,
            ack_flush_interval_ms: 500,
            ping_interval_secs: 30,
            ping_timeout_secs: 10,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct BackupConfig {
    /// S3 prefix for logical namespacing of backups.
    #[arg(
        long = "backup-prefix",
        id = "backup_prefix",
        env = "OBSCURA_BACKUP_PREFIX",
        default_value_t = BackupConfig::default().prefix
    )]
    pub prefix: String,

    /// Max backup size in bytes (Default: 2MB)
    #[arg(
        long = "backup-max-size-bytes",
        id = "backup_max_size_bytes",
        env = "OBSCURA_BACKUP_MAX_SIZE_BYTES",
        default_value_t = BackupConfig::default().max_size_bytes
    )]
    pub max_size_bytes: usize,

    /// Min backup size in bytes (Default: 32 bytes)
    #[arg(
        long = "backup-min-size-bytes",
        id = "backup_min_size_bytes",
        env = "OBSCURA_BACKUP_MIN_SIZE_BYTES",
        default_value_t = BackupConfig::default().min_size_bytes
    )]
    pub min_size_bytes: usize,

    /// S3 streaming timeout in seconds
    #[arg(
        long = "backup-timeout-secs",
        id = "backup_timeout_secs",
        env = "OBSCURA_BACKUP_TIMEOUT_SECS",
        default_value_t = BackupConfig::default().request_timeout_secs
    )]
    pub request_timeout_secs: u64,

    /// Grace period for "UPLOADING" state before cleanup in minutes
    #[arg(
        long = "backup-stale-threshold-mins",
        id = "backup_stale_threshold_mins",
        env = "OBSCURA_BACKUP_STALE_THRESHOLD_MINS",
        default_value_t = BackupConfig::default().stale_threshold_mins
    )]
    pub stale_threshold_mins: i64,

    /// Frequency of background cleanup worker cycles in seconds
    #[arg(
        long = "backup-cleanup-interval-secs",
        id = "backup_cleanup_interval_secs",
        env = "OBSCURA_BACKUP_CLEANUP_INTERVAL_SECS",
        default_value_t = BackupConfig::default().cleanup_interval_secs
    )]
    pub cleanup_interval_secs: u64,
}

impl Default for BackupConfig {
    fn default() -> Self {
        Self {
            prefix: "backups/".to_string(),
            max_size_bytes: 2_097_152,
            min_size_bytes: 32,
            request_timeout_secs: 60,
            stale_threshold_mins: 30,
            cleanup_interval_secs: 300,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct AttachmentConfig {
    /// Max attachment size in bytes (Default: 50MB)
    #[arg(
        long = "attachment-max-size-bytes",
        id = "attachment_max_size_bytes",
        env = "OBSCURA_ATTACHMENT_MAX_SIZE_BYTES",
        default_value_t = AttachmentConfig::default().max_size_bytes
    )]
    pub max_size_bytes: usize,

    /// Min attachment size in bytes (Default: 1 byte)
    #[arg(
        long = "attachment-min-size-bytes",
        id = "attachment_min_size_bytes",
        env = "OBSCURA_ATTACHMENT_MIN_SIZE_BYTES",
        default_value_t = AttachmentConfig::default().min_size_bytes
    )]
    pub min_size_bytes: usize,

    /// S3 prefix for logical namespacing of attachments.
    #[arg(
        long = "attachment-prefix",
        id = "attachment_prefix",
        env = "OBSCURA_ATTACHMENT_PREFIX",
        default_value_t = AttachmentConfig::default().prefix
    )]
    pub prefix: String,

    /// How often to run the attachment cleanup task in seconds
    #[arg(
        long = "attachment-cleanup-interval-secs",
        id = "attachment_cleanup_interval_secs",
        env = "OBSCURA_ATTACHMENT_CLEANUP_INTERVAL_SECS",
        default_value_t = AttachmentConfig::default().cleanup_interval_secs
    )]
    pub cleanup_interval_secs: u64,

    /// Maximum number of attachments to delete in a single batch
    #[arg(
        long = "attachment-cleanup-batch-size",
        id = "attachment_cleanup_batch_size",
        env = "OBSCURA_ATTACHMENT_CLEANUP_BATCH_SIZE",
        default_value_t = AttachmentConfig::default().cleanup_batch_size
    )]
    pub cleanup_batch_size: u64,

    /// S3 streaming timeout in seconds
    #[arg(
        long = "attachment-timeout-secs",
        id = "attachment_timeout_secs",
        env = "OBSCURA_ATTACHMENT_TIMEOUT_SECS",
        default_value_t = AttachmentConfig::default().request_timeout_secs
    )]
    pub request_timeout_secs: u64,
}

impl Default for AttachmentConfig {
    fn default() -> Self {
        Self {
            max_size_bytes: 52_428_800,
            min_size_bytes: 1,
            prefix: "attachments/".to_string(),
            cleanup_interval_secs: 3600,
            cleanup_batch_size: 100,
            request_timeout_secs: 120,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct StorageConfig {
    /// Storage bucket name
    #[arg(
        long = "storage-bucket",
        id = "storage_bucket",
        env = "OBSCURA_STORAGE_BUCKET",
        default_value_t = StorageConfig::default().bucket
    )]
    pub bucket: String,

    /// Storage region
    #[arg(
        long = "storage-region",
        id = "storage_region",
        env = "OBSCURA_STORAGE_REGION",
        default_value_t = StorageConfig::default().region
    )]
    pub region: String,

    /// Custom storage endpoint (useful for `MinIO` or other S3-compatible services)
    #[arg(long = "storage-endpoint", id = "storage_endpoint", env = "OBSCURA_STORAGE_ENDPOINT")]
    pub endpoint: Option<String>,

    /// Storage access key
    #[arg(long = "storage-access-key", id = "storage_access_key", env = "OBSCURA_STORAGE_ACCESS_KEY")]
    pub access_key: Option<String>,

    /// Storage secret key
    #[arg(long = "storage-secret-key", id = "storage_secret_key", env = "OBSCURA_STORAGE_SECRET_KEY")]
    pub secret_key: Option<String>,

    /// Force path style (required for many `MinIO` setups: <http://host/bucket/key>)
    #[arg(
        long = "storage-force-path-style",
        id = "storage_force_path_style",
        env = "OBSCURA_STORAGE_FORCE_PATH_STYLE",
        default_value_t = StorageConfig::default().force_path_style
    )]
    pub force_path_style: bool,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            bucket: "obscura-storage".to_string(),
            region: "us-east-1".to_string(),
            endpoint: None,
            access_key: None,
            secret_key: None,
            force_path_style: false,
        }
    }
}

#[derive(Clone, Debug, Args)]
pub struct HealthConfig {
    /// Timeout for database health check in milliseconds
    #[arg(
        long = "health-db-timeout-ms",
        id = "health_db_timeout_ms",
        env = "OBSCURA_HEALTH_DB_TIMEOUT_MS",
        default_value_t = HealthConfig::default().db_timeout_ms
    )]
    pub db_timeout_ms: u64,

    /// Timeout for storage health check in milliseconds
    #[arg(
        long = "health-storage-timeout-ms",
        id = "health_storage_timeout_ms",
        env = "OBSCURA_HEALTH_STORAGE_TIMEOUT_MS",
        default_value_t = HealthConfig::default().storage_timeout_ms
    )]
    pub storage_timeout_ms: u64,

    /// Timeout for pubsub health check in milliseconds
    #[arg(
        long = "health-pubsub-timeout-ms",
        id = "health_pubsub_timeout_ms",
        env = "OBSCURA_HEALTH_PUBSUB_TIMEOUT_MS",
        default_value_t = HealthConfig::default().pubsub_timeout_ms
    )]
    pub pubsub_timeout_ms: u64,
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self { db_timeout_ms: 2000, storage_timeout_ms: 2000, pubsub_timeout_ms: 2000 }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn verify_cli() {
        Config::command().debug_assert();
    }
}