hammerwork 1.15.5

A high-performance, database-driven job queue for Rust with PostgreSQL and MySQL support, featuring job prioritization, cron scheduling, event streaming (Kafka/Kinesis/PubSub), webhooks, rate limiting, Prometheus metrics, and comprehensive monitoring
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
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
//! Configuration management for Hammerwork job queue.
//!
//! This module provides comprehensive configuration options for the Hammerwork job queue,
//! including database settings, worker configuration, webhook settings, streaming configuration,
//! and monitoring options.

use crate::{
    events::EventConfig, priority::PriorityWeights, rate_limit::ThrottleConfig,
    retry::RetryStrategy,
};

#[cfg(feature = "webhooks")]
use crate::webhooks::WebhookConfig;

#[cfg(feature = "alerting")]
use crate::alerting::AlertingConfig;

#[cfg(feature = "metrics")]
use crate::metrics::MetricsConfig;

#[cfg(any(
    feature = "streaming",
    feature = "kafka",
    feature = "google-pubsub",
    feature = "kinesis"
))]
use crate::streaming::StreamConfig;
use chrono::Duration;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, path::PathBuf, time::Duration as StdDuration};

/// Module for serializing std::time::Duration as human-readable strings
mod duration_secs {
    use serde::{Deserialize, Deserializer, Serializer};
    use std::time::Duration;

    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let secs = duration.as_secs();
        if secs == 0 {
            serializer.serialize_str("0s")
        } else if secs % 3600 == 0 {
            serializer.serialize_str(&format!("{}h", secs / 3600))
        } else if secs % 60 == 0 {
            serializer.serialize_str(&format!("{}m", secs / 60))
        } else {
            serializer.serialize_str(&format!("{}s", secs))
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s = String::deserialize(deserializer)?;
        parse_duration(&s).map_err(D::Error::custom)
    }

    /// Parse a duration string like "30s", "5m", "1h", "90", etc.
    fn parse_duration(s: &str) -> Result<Duration, String> {
        let s = s.trim();

        // Handle just numbers (assume seconds)
        if let Ok(secs) = s.parse::<u64>() {
            return Ok(Duration::from_secs(secs));
        }

        // Handle suffixed durations
        if s.len() < 2 {
            return Err(format!("Invalid duration format: {}", s));
        }

        let (num_str, suffix) = s.split_at(s.len() - 1);
        let num: u64 = num_str
            .parse()
            .map_err(|_| format!("Invalid number in duration: {}", num_str))?;

        match suffix {
            "s" => Ok(Duration::from_secs(num)),
            "m" => Ok(Duration::from_secs(num * 60)),
            "h" => Ok(Duration::from_secs(num * 3600)),
            "d" => Ok(Duration::from_secs(num * 86400)),
            _ => Err(format!(
                "Invalid duration suffix: {}. Use s, m, h, or d",
                suffix
            )),
        }
    }
}

/// Module for serializing chrono::Duration as human-readable strings (in days)
mod chrono_duration_days {
    use chrono::Duration;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let days = duration.num_days();
        if days == 0 {
            serializer.serialize_str("0d")
        } else {
            serializer.serialize_str(&format!("{}d", days))
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s = String::deserialize(deserializer)?;
        parse_chrono_duration(&s).map_err(D::Error::custom)
    }

    /// Parse a duration string like "30d", "7d", etc.
    pub fn parse_chrono_duration(s: &str) -> Result<Duration, String> {
        let s = s.trim();

        // Handle just numbers (assume days)
        if let Ok(days) = s.parse::<i64>() {
            return Ok(Duration::days(days));
        }

        // Handle suffixed durations
        if s.len() < 2 {
            return Err(format!("Invalid duration format: {}", s));
        }

        let (num_str, suffix) = s.split_at(s.len() - 1);
        let num: i64 = num_str
            .parse()
            .map_err(|_| format!("Invalid number in duration: {}", num_str))?;

        match suffix {
            "d" => Ok(Duration::days(num)),
            _ => Err(format!(
                "Invalid duration suffix: {}. Use d for days",
                suffix
            )),
        }
    }
}

/// Module for serializing Option<chrono::Duration> as human-readable strings (in days)
mod chrono_duration_days_option {
    use chrono::Duration;
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match duration {
            Some(d) => super::chrono_duration_days::serialize(d, serializer),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let opt: Option<String> = Option::deserialize(deserializer)?;
        match opt {
            Some(s) => super::chrono_duration_days::parse_chrono_duration(&s)
                .map(Some)
                .map_err(serde::de::Error::custom),
            None => Ok(None),
        }
    }
}

/// Main configuration for the Hammerwork job queue system.
///
/// This struct contains all configuration options for the Hammerwork job queue,
/// including database connection, worker settings, webhook configuration,
/// streaming settings, and monitoring options.
///
/// # Examples
///
/// ```rust
/// use hammerwork::config::HammerworkConfig;
///
/// // Create with defaults
/// let config = HammerworkConfig::default();
///
/// // Use builder pattern
/// let config = HammerworkConfig::new()
///     .with_database_url("postgresql://localhost/hammerwork")
///     .with_worker_pool_size(5)
///     .with_job_timeout(std::time::Duration::from_secs(300));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct HammerworkConfig {
    /// Database configuration
    pub database: DatabaseConfig,

    /// Worker configuration
    pub worker: WorkerConfig,

    /// Event system configuration
    pub events: EventConfig,

    /// Webhook configurations
    #[cfg(feature = "webhooks")]
    pub webhooks: WebhookConfigs,

    /// Streaming configurations
    #[cfg(any(
        feature = "streaming",
        feature = "kafka",
        feature = "google-pubsub",
        feature = "kinesis"
    ))]
    pub streaming: StreamingConfigs,

    /// Alerting configuration
    #[cfg(feature = "alerting")]
    pub alerting: AlertingConfig,

    /// Metrics configuration
    #[cfg(feature = "metrics")]
    pub metrics: MetricsConfig,

    /// Archive configuration
    pub archive: ArchiveConfig,

    /// Rate limiting configuration
    pub rate_limiting: RateLimitingConfig,

    /// Logging and tracing configuration
    pub logging: LoggingConfig,
}

impl HammerworkConfig {
    /// Create a new configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the database URL
    pub fn with_database_url(mut self, url: &str) -> Self {
        self.database.url = url.to_string();
        self
    }

    /// Set the database pool size
    pub fn with_database_pool_size(mut self, size: u32) -> Self {
        self.database.pool_size = size;
        self
    }

    /// Set the worker pool size
    pub fn with_worker_pool_size(mut self, size: usize) -> Self {
        self.worker.pool_size = size;
        self
    }

    /// Set job timeout duration
    pub fn with_job_timeout(mut self, timeout: StdDuration) -> Self {
        self.worker.job_timeout = timeout;
        self
    }

    /// Enable or disable event publishing
    pub fn with_events_enabled(mut self, enabled: bool) -> Self {
        if enabled {
            self.events.max_buffer_size = 10_000;
        } else {
            self.events.max_buffer_size = 0;
        }
        self
    }

    /// Load configuration from a TOML file
    pub fn from_file(path: &str) -> crate::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        let config: Self = toml::from_str(&content)?;
        Ok(config)
    }

    /// Save configuration to a TOML file
    pub fn save_to_file(&self, path: &str) -> crate::Result<()> {
        let content = toml::to_string_pretty(self)?;
        std::fs::write(path, content)?;
        Ok(())
    }

    /// Load configuration from environment variables
    pub fn from_env() -> crate::Result<Self> {
        let mut config = Self::default();

        // Database configuration
        if let Ok(url) = std::env::var("HAMMERWORK_DATABASE_URL") {
            config.database.url = url;
        }
        if let Ok(pool_size) = std::env::var("HAMMERWORK_DATABASE_POOL_SIZE") {
            config.database.pool_size = pool_size.parse().unwrap_or(config.database.pool_size);
        }

        // Worker configuration
        if let Ok(pool_size) = std::env::var("HAMMERWORK_WORKER_POOL_SIZE") {
            config.worker.pool_size = pool_size.parse().unwrap_or(config.worker.pool_size);
        }
        if let Ok(timeout) = std::env::var("HAMMERWORK_JOB_TIMEOUT_SECONDS") {
            if let Ok(seconds) = timeout.parse::<u64>() {
                config.worker.job_timeout = StdDuration::from_secs(seconds);
            }
        }

        // Event configuration
        if let Ok(buffer_size) = std::env::var("HAMMERWORK_EVENT_BUFFER_SIZE") {
            config.events.max_buffer_size =
                buffer_size.parse().unwrap_or(config.events.max_buffer_size);
        }

        Ok(config)
    }
}

/// Database configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    /// Database connection URL
    pub url: String,

    /// Connection pool size
    pub pool_size: u32,

    /// Connection timeout in seconds
    pub connection_timeout_secs: u64,

    /// Whether to run migrations automatically
    pub auto_migrate: bool,

    /// Whether to create tables if they don't exist
    pub create_tables: bool,
}

impl Default for DatabaseConfig {
    fn default() -> Self {
        Self {
            url: "postgresql://localhost/hammerwork".to_string(),
            pool_size: 10,
            connection_timeout_secs: 30,
            auto_migrate: false,
            create_tables: true,
        }
    }
}

/// Worker configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerConfig {
    /// Number of workers in the pool
    pub pool_size: usize,

    /// Polling interval for checking new jobs
    #[serde(with = "duration_secs")]
    pub polling_interval: StdDuration,

    /// Default job timeout
    #[serde(with = "duration_secs")]
    pub job_timeout: StdDuration,

    /// Priority weights for job selection
    pub priority_weights: PriorityWeights,

    /// Retry strategy for failed jobs
    pub retry_strategy: RetryStrategy,

    /// Whether to enable autoscaling
    pub autoscaling_enabled: bool,

    /// Minimum number of workers (for autoscaling)
    pub min_workers: usize,

    /// Maximum number of workers (for autoscaling)
    pub max_workers: usize,
}

impl Default for WorkerConfig {
    fn default() -> Self {
        Self {
            pool_size: 4,
            polling_interval: StdDuration::from_millis(500),
            job_timeout: StdDuration::from_secs(300), // 5 minutes
            priority_weights: PriorityWeights::default(),
            retry_strategy: RetryStrategy::exponential(
                StdDuration::from_secs(1),
                2.0,
                Some(StdDuration::from_secs(300)),
            ),
            autoscaling_enabled: false,
            min_workers: 1,
            max_workers: 16,
        }
    }
}

/// Webhook configurations container
#[cfg(feature = "webhooks")]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WebhookConfigs {
    /// List of configured webhooks
    pub webhooks: Vec<WebhookConfig>,

    /// Global webhook settings
    pub global_settings: WebhookGlobalSettings,
}

/// Global webhook settings
#[cfg(feature = "webhooks")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebhookGlobalSettings {
    /// Maximum concurrent webhook deliveries
    pub max_concurrent_deliveries: usize,

    /// Maximum response body size to store
    pub max_response_body_size: usize,

    /// Whether to log webhook deliveries
    pub log_deliveries: bool,

    /// User agent string for requests
    pub user_agent: String,
}

#[cfg(feature = "webhooks")]
impl Default for WebhookGlobalSettings {
    fn default() -> Self {
        Self {
            max_concurrent_deliveries: 100,
            max_response_body_size: 64 * 1024, // 64KB
            log_deliveries: true,
            user_agent: format!("hammerwork-webhooks/{}", env!("CARGO_PKG_VERSION")),
        }
    }
}

/// Streaming configurations container
#[cfg(any(
    feature = "streaming",
    feature = "kafka",
    feature = "google-pubsub",
    feature = "kinesis"
))]
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct StreamingConfigs {
    /// List of configured streams
    pub streams: Vec<StreamConfig>,

    /// Global streaming settings  
    pub global_settings: StreamingGlobalSettings,
}

/// Simple event filter for when webhooks feature is disabled
#[cfg(not(feature = "webhooks"))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimpleEventFilter {
    /// Event types to include
    pub event_types: Vec<String>,

    /// Queue names to include
    pub queue_names: Vec<String>,

    /// Whether to include payload data
    pub include_payload: bool,
}

#[cfg(not(feature = "webhooks"))]
impl Default for SimpleEventFilter {
    fn default() -> Self {
        Self {
            event_types: vec!["completed".to_string(), "failed".to_string()],
            queue_names: Vec::new(),
            include_payload: false,
        }
    }
}

/// Global streaming settings
#[cfg(any(
    feature = "streaming",
    feature = "kafka",
    feature = "google-pubsub",
    feature = "kinesis"
))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingGlobalSettings {
    /// Maximum concurrent stream processors
    pub max_concurrent_processors: usize,

    /// Whether to log stream operations
    pub log_operations: bool,

    /// Global buffer flush interval in seconds
    pub global_flush_interval_secs: u64,
}

#[cfg(any(
    feature = "streaming",
    feature = "kafka",
    feature = "google-pubsub",
    feature = "kinesis"
))]
impl Default for StreamingGlobalSettings {
    fn default() -> Self {
        Self {
            max_concurrent_processors: 50,
            log_operations: true,
            global_flush_interval_secs: 10,
        }
    }
}

/// Archive configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArchiveConfig {
    /// Whether archiving is enabled
    pub enabled: bool,

    /// Directory for storing archived jobs
    pub archive_directory: PathBuf,

    /// Compression level (0-9, 0=no compression)
    pub compression_level: u32,

    /// Archive jobs older than this duration
    #[serde(with = "chrono_duration_days")]
    pub archive_after: Duration,

    /// Delete archived files older than this duration
    #[serde(with = "chrono_duration_days_option")]
    pub delete_after: Option<Duration>,

    /// Maximum archive file size in bytes
    pub max_file_size_bytes: u64,

    /// Whether to include job payloads in archives
    pub include_payloads: bool,
}

impl Default for ArchiveConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            archive_directory: PathBuf::from("./archives"),
            compression_level: 6,
            archive_after: Duration::days(30),
            delete_after: Some(Duration::days(365)),
            max_file_size_bytes: 100 * 1024 * 1024, // 100MB
            include_payloads: true,
        }
    }
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RateLimitingConfig {
    /// Whether rate limiting is enabled
    pub enabled: bool,

    /// Default throttle configuration
    pub default_throttle: ThrottleConfig,

    /// Per-queue throttle configurations
    pub queue_throttles: HashMap<String, ThrottleConfig>,
}

/// Logging and tracing configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    /// Log level (trace, debug, info, warn, error)
    pub level: String,

    /// Whether to enable structured JSON logging
    pub json_format: bool,

    /// Whether to include file and line information
    pub include_location: bool,

    /// Whether to enable OpenTelemetry tracing
    pub enable_tracing: bool,

    /// OpenTelemetry endpoint URL
    pub tracing_endpoint: Option<String>,

    /// Service name for tracing
    pub service_name: String,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            json_format: false,
            include_location: false,
            enable_tracing: false,
            tracing_endpoint: None,
            service_name: "hammerwork".to_string(),
        }
    }
}

/// Helper functions for creating configurations
impl HammerworkConfig {
    /// Create a configuration for development use
    pub fn development() -> Self {
        Self {
            database: DatabaseConfig {
                url: "postgresql://localhost/hammerwork_dev".to_string(),
                pool_size: 5,
                auto_migrate: true,
                ..Default::default()
            },
            worker: WorkerConfig {
                pool_size: 2,
                polling_interval: StdDuration::from_millis(100),
                ..Default::default()
            },
            events: EventConfig {
                max_buffer_size: 1000,
                log_events: true,
                ..Default::default()
            },
            logging: LoggingConfig {
                level: "debug".to_string(),
                include_location: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Create a configuration for production use
    pub fn production() -> Self {
        Self {
            database: DatabaseConfig {
                pool_size: 20,
                connection_timeout_secs: 60,
                auto_migrate: false,
                ..Default::default()
            },
            worker: WorkerConfig {
                pool_size: 8,
                autoscaling_enabled: true,
                min_workers: 4,
                max_workers: 32,
                ..Default::default()
            },
            events: EventConfig {
                max_buffer_size: 50_000,
                log_events: false,
                ..Default::default()
            },
            archive: ArchiveConfig {
                enabled: true,
                compression_level: 9,
                ..Default::default()
            },
            rate_limiting: RateLimitingConfig {
                enabled: true,
                ..Default::default()
            },
            logging: LoggingConfig {
                level: "info".to_string(),
                json_format: true,
                enable_tracing: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Add a webhook configuration
    #[cfg(feature = "webhooks")]
    pub fn add_webhook(mut self, webhook: WebhookConfig) -> Self {
        self.webhooks.webhooks.push(webhook);
        self
    }

    /// Add a stream configuration
    #[cfg(any(
        feature = "streaming",
        feature = "kafka",
        feature = "google-pubsub",
        feature = "kinesis"
    ))]
    pub fn add_stream(mut self, stream: StreamConfig) -> Self {
        self.streaming.streams.push(stream);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(any(
        feature = "streaming",
        feature = "kafka",
        feature = "google-pubsub",
        feature = "kinesis"
    ))]
    use crate::streaming::StreamBackend;
    use tempfile::tempdir;

    #[test]
    fn test_config_creation() {
        let config = HammerworkConfig::new()
            .with_database_url("postgresql://localhost/test")
            .with_worker_pool_size(8)
            .with_job_timeout(StdDuration::from_secs(600));

        assert_eq!(config.database.url, "postgresql://localhost/test");
        assert_eq!(config.worker.pool_size, 8);
        assert_eq!(config.worker.job_timeout, StdDuration::from_secs(600));
    }

    #[test]
    fn test_development_config() {
        let config = HammerworkConfig::development();
        assert_eq!(config.database.url, "postgresql://localhost/hammerwork_dev");
        assert_eq!(config.worker.pool_size, 2);
        assert!(config.database.auto_migrate);
        assert_eq!(config.logging.level, "debug");
    }

    #[test]
    fn test_production_config() {
        let config = HammerworkConfig::production();
        assert_eq!(config.database.pool_size, 20);
        assert_eq!(config.worker.pool_size, 8);
        assert!(config.worker.autoscaling_enabled);
        assert!(config.archive.enabled);
        assert!(config.rate_limiting.enabled);
        assert!(config.logging.json_format);
    }

    #[test]
    fn test_config_file_operations() {
        let dir = tempdir().unwrap();
        let config_path = dir.path().join("hammerwork.toml");

        let config = HammerworkConfig::new()
            .with_database_url("mysql://localhost/test")
            .with_worker_pool_size(6);

        // Save config
        println!("Testing TOML serialization...");
        let toml_result = toml::to_string_pretty(&config);
        println!("TOML result: {:?}", toml_result);

        config.save_to_file(config_path.to_str().unwrap()).unwrap();

        // Load config
        let loaded_config = HammerworkConfig::from_file(config_path.to_str().unwrap()).unwrap();

        assert_eq!(loaded_config.database.url, "mysql://localhost/test");
        assert_eq!(loaded_config.worker.pool_size, 6);
    }

    #[test]
    fn test_env_config() {
        unsafe {
            std::env::set_var("HAMMERWORK_DATABASE_URL", "postgresql://env/test");
            std::env::set_var("HAMMERWORK_WORKER_POOL_SIZE", "12");
            std::env::set_var("HAMMERWORK_JOB_TIMEOUT_SECONDS", "900");
        }

        let config = HammerworkConfig::from_env().unwrap();

        assert_eq!(config.database.url, "postgresql://env/test");
        assert_eq!(config.worker.pool_size, 12);
        assert_eq!(config.worker.job_timeout, StdDuration::from_secs(900));

        // Clean up
        unsafe {
            std::env::remove_var("HAMMERWORK_DATABASE_URL");
            std::env::remove_var("HAMMERWORK_WORKER_POOL_SIZE");
            std::env::remove_var("HAMMERWORK_JOB_TIMEOUT_SECONDS");
        }
    }

    #[test]
    fn test_duration_serialization() {
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let config_path = dir.path().join("duration_test.toml");

        // Create config with various durations
        let mut config = HammerworkConfig::new();
        config.worker.polling_interval = StdDuration::from_secs(30); // Should serialize as "30s"
        config.worker.job_timeout = StdDuration::from_secs(300); // Should serialize as "5m"

        // Save to TOML
        config.save_to_file(config_path.to_str().unwrap()).unwrap();

        // Read the TOML content to verify human-readable format
        let toml_content = std::fs::read_to_string(&config_path).unwrap();
        assert!(toml_content.contains("polling_interval = \"30s\""));
        assert!(toml_content.contains("job_timeout = \"5m\""));

        // Load back and verify values
        let loaded_config = HammerworkConfig::from_file(config_path.to_str().unwrap()).unwrap();
        assert_eq!(
            loaded_config.worker.polling_interval,
            StdDuration::from_secs(30)
        );
        assert_eq!(
            loaded_config.worker.job_timeout,
            StdDuration::from_secs(300)
        );

        // Test parsing various duration formats
        let test_durations = [
            ("30", StdDuration::from_secs(30)),
            ("30s", StdDuration::from_secs(30)),
            ("5m", StdDuration::from_secs(300)),
            ("2h", StdDuration::from_secs(7200)),
            ("1d", StdDuration::from_secs(86400)),
        ];

        for (duration_str, expected) in test_durations.iter() {
            let toml_content = format!(
                r#"
[database]
url = "postgresql://localhost/test"
pool_size = 10
connection_timeout_secs = 30
auto_migrate = false
create_tables = true

[worker]
pool_size = 4
polling_interval = "{}"
job_timeout = "5m"
autoscaling_enabled = false
min_workers = 1
max_workers = 10

[worker.priority_weights]
strict_priority = false
fairness_factor = 0.1

[worker.priority_weights.weights]
Background = 1
Low = 2
Normal = 5
High = 10
Critical = 20

[worker.retry_strategy]
type = "Exponential"
base_ms = 1000
multiplier = 2.0
max_delay_ms = 60000

[events]
max_buffer_size = 1000
include_payload_default = false
max_payload_size_bytes = 65536
log_events = false

[webhooks]
webhooks = []

[webhooks.global_settings]
max_concurrent_deliveries = 100
max_response_body_size = 65536
log_deliveries = true
user_agent = "hammerwork-webhooks/1.13.0"

[streaming]
streams = []

[streaming.global_settings]
max_concurrent_processors = 50
log_operations = true
global_flush_interval_secs = 10

[alerting]
targets = []
enabled = true

[alerting.cooldown_period]
secs = 300
nanos = 0

[alerting.custom_thresholds]

[metrics]
registry_name = "hammerwork"
collect_histograms = true
custom_gauges = []
custom_histograms = []
update_interval = 15

[metrics.custom_labels]

[archive]
enabled = false
archive_directory = "./archives"
compression_level = 6
archive_after = "30d"
delete_after = "365d"
max_file_size_bytes = 104857600
include_payloads = true

[rate_limiting]
enabled = false

[rate_limiting.default_throttle]
enabled = true

[rate_limiting.queue_throttles]

[logging]
level = "info"
json_format = false
include_location = false
enable_tracing = false
service_name = "hammerwork"
"#,
                duration_str
            );

            let config: HammerworkConfig = toml::from_str(&toml_content).unwrap();
            assert_eq!(
                config.worker.polling_interval, *expected,
                "Failed to parse duration: {}",
                duration_str
            );
        }
    }

    #[cfg(feature = "webhooks")]
    #[test]
    fn test_webhook_config() {
        let webhook = WebhookConfig {
            name: "Test Webhook".to_string(),
            url: "https://api.example.com/webhook".to_string(),
            ..Default::default()
        };

        let config = HammerworkConfig::new().add_webhook(webhook);
        assert_eq!(config.webhooks.webhooks.len(), 1);
        assert_eq!(config.webhooks.webhooks[0].name, "Test Webhook");
    }

    #[test]
    #[cfg(any(
        feature = "streaming",
        feature = "kafka",
        feature = "google-pubsub",
        feature = "kinesis"
    ))]
    fn test_stream_config() {
        let stream = StreamConfig {
            name: "Test Stream".to_string(),
            backend: StreamBackend::PubSub {
                project_id: "test-project".to_string(),
                topic_name: "test-topic".to_string(),
                service_account_key: None,
                config: HashMap::new(),
            },
            ..Default::default()
        };

        let config = HammerworkConfig::new().add_stream(stream);
        assert_eq!(config.streaming.streams.len(), 1);
        assert_eq!(config.streaming.streams[0].name, "Test Stream");
    }

    #[test]
    fn test_default_configs() {
        let database_config = DatabaseConfig::default();
        assert_eq!(database_config.url, "postgresql://localhost/hammerwork");
        assert_eq!(database_config.pool_size, 10);

        let worker_config = WorkerConfig::default();
        assert_eq!(worker_config.pool_size, 4);
        assert_eq!(
            worker_config.polling_interval,
            StdDuration::from_millis(500)
        );

        let archive_config = ArchiveConfig::default();
        assert!(!archive_config.enabled);
        assert_eq!(archive_config.compression_level, 6);

        let logging_config = LoggingConfig::default();
        assert_eq!(logging_config.level, "info");
        assert!(!logging_config.json_format);
    }
}