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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Job payload encryption and PII protection for Hammerwork.
//!
//! This module provides encryption capabilities for job payloads to protect sensitive data
//! such as personally identifiable information (PII). It supports multiple encryption
//! algorithms, field-level encryption, and configurable retention policies.
//!
//! # Features
//!
//! - **Multiple Encryption Algorithms**: AES-256-GCM, ChaCha20-Poly1305
//! - **Field-Level Encryption**: Encrypt specific fields containing PII
//! - **Key Management**: Support for static keys, key rotation, and external key management
//! - **Retention Policies**: Automatic cleanup of encrypted data after specified periods
//! - **Performance Optimized**: Minimal overhead for non-encrypted jobs
//!
//! # Examples
//!
//! ## Basic Job Encryption
//!
//! ```rust,no_run
//! # #[cfg(feature = "encryption")]
//! # {
//! use hammerwork::{Job, encryption::{EncryptionConfig, EncryptionAlgorithm, RetentionPolicy}};
//! use serde_json::json;
//! use std::time::Duration;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let job = Job::new("payment_processing".to_string(), json!({
//!     "user_id": "user123",
//!     "credit_card": "4111-1111-1111-1111",
//!     "ssn": "123-45-6789",
//!     "amount": 99.99
//! }))
//! .with_encryption(EncryptionConfig::new(EncryptionAlgorithm::AES256GCM))
//! .with_pii_fields(vec!["credit_card", "ssn"])
//! .with_retention_policy(RetentionPolicy::DeleteAfter(Duration::from_secs(7 * 24 * 60 * 60))); // 7 days
//! # Ok(())
//! # }
//! # }
//! ```
//!
//! ## Custom Key Management
//!
//! ```rust,no_run
//! # #[cfg(feature = "encryption")]
//! # {
//! use hammerwork::encryption::{EncryptionConfig, KeySource, EncryptionAlgorithm};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let config = EncryptionConfig::new(EncryptionAlgorithm::ChaCha20Poly1305)
//!     .with_key_source(KeySource::Environment("HAMMERWORK_ENCRYPTION_KEY".to_string()))
//!     .with_key_rotation_enabled(true);
//! # Ok(())
//! # }
//! # }
//! ```

pub mod engine;
pub mod key_manager;

pub use engine::EncryptionEngine;
pub use key_manager::{
    EncryptionKey, ExternalKmsConfig, KeyAuditRecord, KeyDerivationConfig, KeyManager,
    KeyManagerConfig, KeyManagerStats, KeyOperation, KeyPurpose, KeyStatus, parse_algorithm,
    parse_key_purpose, parse_key_source, parse_key_status,
};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;
use thiserror::Error;

use base64::Engine;

/// Errors that can occur during encryption operations.
#[derive(Error, Debug)]
pub enum EncryptionError {
    /// Key management error (missing, invalid, or rotation failure).
    #[error("Key management error: {0}")]
    KeyManagement(String),

    /// Encryption operation failed.
    #[error("Encryption failed: {0}")]
    EncryptionFailed(String),

    /// Decryption operation failed.
    #[error("Decryption failed: {0}")]
    DecryptionFailed(String),

    /// Invalid algorithm or configuration.
    #[error("Invalid configuration: {0}")]
    InvalidConfiguration(String),

    /// Field processing error (PII detection, field extraction, etc.).
    #[error("Field processing error: {0}")]
    FieldProcessing(String),

    /// Serialization/deserialization error.
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// Base64 encoding/decoding error.
    #[error("Base64 error: {0}")]
    Base64(#[from] base64::DecodeError),

    /// Cryptographic operation error.
    #[error("Cryptographic error: {0}")]
    Cryptographic(String),

    /// Database operation error.
    #[error("Database error: {0}")]
    DatabaseError(String),
}

/// Supported encryption algorithms.
///
/// Each algorithm has different characteristics in terms of performance,
/// security, and compatibility.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum EncryptionAlgorithm {
    /// AES-256 in Galois/Counter Mode (AES-256-GCM).
    ///
    /// Industry standard, widely supported, hardware acceleration available
    /// on most modern processors. Provides both confidentiality and authenticity.
    AES256GCM,

    /// ChaCha20-Poly1305 stream cipher.
    ///
    /// Modern alternative to AES, designed for software implementations.
    /// Resistant to timing attacks and performs well on devices without
    /// AES hardware acceleration.
    ChaCha20Poly1305,
}

impl Default for EncryptionAlgorithm {
    fn default() -> Self {
        Self::AES256GCM
    }
}

/// Source for encryption keys.
///
/// Determines where encryption keys are obtained from, enabling
/// different security models and key management strategies.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum KeySource {
    /// Use a static key provided directly.
    ///
    /// **Security Note**: Only use for development/testing.
    /// Production systems should use environment variables or external key management.
    Static(String),

    /// Load key from an environment variable.
    ///
    /// The environment variable should contain a base64-encoded key
    /// of appropriate length for the selected algorithm.
    Environment(String),

    /// Retrieve key from an external key management service.
    ///
    /// This could be AWS KMS, HashiCorp Vault, Azure Key Vault, etc.
    /// The string contains the key identifier or service configuration.
    External(String),

    /// Generate a random key and store it in the specified location.
    ///
    /// Useful for initial setup or testing scenarios.
    Generated(String),
}

impl Default for KeySource {
    fn default() -> Self {
        Self::Environment("HAMMERWORK_ENCRYPTION_KEY".to_string())
    }
}

/// Configuration for job payload encryption.
///
/// This struct contains all settings needed to encrypt and decrypt job payloads,
/// including algorithm selection, key management, and field-specific encryption rules.
///
/// # Examples
///
/// ```rust,no_run
/// # #[cfg(feature = "encryption")]
/// # {
/// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm, KeySource};
/// use std::time::Duration;
///
/// // Basic configuration
/// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
///
/// // Advanced configuration
/// let config = EncryptionConfig::new(EncryptionAlgorithm::ChaCha20Poly1305)
///     .with_key_source(KeySource::Environment("MY_ENCRYPTION_KEY".to_string()))
///     .with_key_rotation_enabled(true)
///     .with_default_retention(Duration::from_secs(30 * 24 * 60 * 60)); // 30 days
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionConfig {
    /// The encryption algorithm to use.
    pub algorithm: EncryptionAlgorithm,

    /// Source for the encryption key.
    pub key_source: KeySource,

    /// Whether to enable automatic key rotation.
    pub key_rotation_enabled: bool,

    /// How often to rotate keys (if rotation is enabled).
    pub key_rotation_interval: Option<Duration>,

    /// Default retention period for encrypted data.
    pub default_retention: Option<Duration>,

    /// Whether to compress data before encryption.
    ///
    /// Can reduce storage size for large payloads but adds CPU overhead.
    pub compression_enabled: bool,

    /// Key identifier for the current encryption key.
    ///
    /// Used to track which key was used for encryption to support
    /// key rotation and proper decryption.
    pub key_id: Option<String>,

    /// Version of the encryption configuration.
    ///
    /// Incremented when encryption settings change to ensure
    /// backward compatibility during upgrades.
    pub version: u32,
}

impl EncryptionConfig {
    /// Creates a new encryption configuration with the specified algorithm.
    ///
    /// Uses default settings for key source (environment variable),
    /// no key rotation, and no default retention period.
    ///
    /// # Arguments
    ///
    /// * `algorithm` - The encryption algorithm to use
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// assert_eq!(config.algorithm, EncryptionAlgorithm::AES256GCM);
    /// assert!(!config.key_rotation_enabled);
    /// ```
    pub fn new(algorithm: EncryptionAlgorithm) -> Self {
        Self {
            algorithm,
            key_source: KeySource::default(),
            key_rotation_enabled: false,
            key_rotation_interval: None,
            default_retention: None,
            compression_enabled: false,
            key_id: None,
            version: 1,
        }
    }

    /// Sets the key source for this configuration.
    ///
    /// # Arguments
    ///
    /// * `key_source` - Where to obtain the encryption key
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "encryption")]
    /// # {
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm, KeySource};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_key_source(KeySource::Environment("MY_SECRET_KEY".to_string()));
    /// # }
    /// ```
    pub fn with_key_source(mut self, key_source: KeySource) -> Self {
        self.key_source = key_source;
        self
    }

    /// Enables or disables automatic key rotation.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to enable key rotation
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_key_rotation_enabled(true);
    ///
    /// assert!(config.key_rotation_enabled);
    /// ```
    pub fn with_key_rotation_enabled(mut self, enabled: bool) -> Self {
        self.key_rotation_enabled = enabled;
        self
    }

    /// Sets the key rotation interval.
    ///
    /// Only effective if key rotation is enabled.
    ///
    /// # Arguments
    ///
    /// * `interval` - How often to rotate keys
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    /// use std::time::Duration;
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_key_rotation_enabled(true)
    ///     .with_key_rotation_interval(Duration::from_secs(30 * 24 * 60 * 60)); // 30 days
    /// ```
    pub fn with_key_rotation_interval(mut self, interval: Duration) -> Self {
        self.key_rotation_interval = Some(interval);
        self
    }

    /// Sets the default retention period for encrypted data.
    ///
    /// # Arguments
    ///
    /// * `retention` - How long to keep encrypted data before cleanup
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    /// use std::time::Duration;
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_default_retention(Duration::from_secs(7 * 24 * 60 * 60)); // 7 days
    /// ```
    pub fn with_default_retention(mut self, retention: Duration) -> Self {
        self.default_retention = Some(retention);
        self
    }

    /// Enables or disables compression before encryption.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether to compress data before encryption
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_compression_enabled(true);
    ///
    /// assert!(config.compression_enabled);
    /// ```
    pub fn with_compression_enabled(mut self, enabled: bool) -> Self {
        self.compression_enabled = enabled;
        self
    }

    /// Sets the key identifier for this configuration.
    ///
    /// # Arguments
    ///
    /// * `key_id` - Identifier for the encryption key
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_key_id("key-2024-01");
    /// ```
    pub fn with_key_id(mut self, key_id: impl Into<String>) -> Self {
        self.key_id = Some(key_id.into());
        self
    }

    /// Gets the expected key size in bytes for the configured algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// assert_eq!(config.key_size_bytes(), 32); // 256 bits = 32 bytes
    /// ```
    pub fn key_size_bytes(&self) -> usize {
        match self.algorithm {
            EncryptionAlgorithm::AES256GCM => 32,        // 256 bits
            EncryptionAlgorithm::ChaCha20Poly1305 => 32, // 256 bits
        }
    }

    /// Gets the nonce/IV size in bytes for the configured algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// assert_eq!(config.nonce_size_bytes(), 12); // 96 bits for GCM
    /// ```
    pub fn nonce_size_bytes(&self) -> usize {
        match self.algorithm {
            EncryptionAlgorithm::AES256GCM => 12,        // 96 bits for GCM
            EncryptionAlgorithm::ChaCha20Poly1305 => 12, // 96 bits
        }
    }

    /// Gets the authentication tag size in bytes for the configured algorithm.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionConfig, EncryptionAlgorithm};
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// assert_eq!(config.tag_size_bytes(), 16); // 128 bits
    /// ```
    pub fn tag_size_bytes(&self) -> usize {
        match self.algorithm {
            EncryptionAlgorithm::AES256GCM => 16,        // 128 bits
            EncryptionAlgorithm::ChaCha20Poly1305 => 16, // 128 bits
        }
    }
}

impl Default for EncryptionConfig {
    fn default() -> Self {
        Self::new(EncryptionAlgorithm::default())
    }
}

/// Policy for retaining encrypted data.
///
/// Determines how long encrypted job data should be kept before
/// automatic cleanup. Different retention policies can be applied
/// based on data sensitivity and compliance requirements.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum RetentionPolicy {
    /// Keep data for a specific duration from job creation.
    DeleteAfter(Duration),

    /// Keep data until a specific date/time.
    DeleteAt(DateTime<Utc>),

    /// Keep data indefinitely (manual cleanup required).
    KeepIndefinitely,

    /// Delete immediately after job completion.
    DeleteImmediately,

    /// Use the default retention policy from the encryption configuration.
    UseDefault,
}

impl Default for RetentionPolicy {
    fn default() -> Self {
        Self::UseDefault
    }
}

impl RetentionPolicy {
    /// Calculates when the data should be deleted based on the policy.
    ///
    /// # Arguments
    ///
    /// * `created_at` - When the job was created
    /// * `completed_at` - When the job was completed (if applicable)
    /// * `default_retention` - Default retention period to use if policy is UseDefault
    ///
    /// # Returns
    ///
    /// The date/time when the data should be deleted, or None if it should be kept indefinitely.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::RetentionPolicy;
    /// use chrono::Utc;
    /// use std::time::Duration;
    ///
    /// let policy = RetentionPolicy::DeleteAfter(Duration::from_secs(7 * 24 * 60 * 60));
    /// let created_at = Utc::now();
    /// let delete_at = policy.calculate_deletion_time(created_at, None, None);
    ///
    /// assert!(delete_at.is_some());
    /// ```
    pub fn calculate_deletion_time(
        &self,
        created_at: DateTime<Utc>,
        completed_at: Option<DateTime<Utc>>,
        default_retention: Option<Duration>,
    ) -> Option<DateTime<Utc>> {
        match self {
            RetentionPolicy::DeleteAfter(duration) => {
                let duration_chrono = chrono::Duration::from_std(*duration).ok()?;
                Some(created_at + duration_chrono)
            }
            RetentionPolicy::DeleteAt(timestamp) => Some(*timestamp),
            RetentionPolicy::KeepIndefinitely => None,
            RetentionPolicy::DeleteImmediately => completed_at.or(Some(created_at)),
            RetentionPolicy::UseDefault => {
                if let Some(default_duration) = default_retention {
                    let duration_chrono = chrono::Duration::from_std(default_duration).ok()?;
                    Some(created_at + duration_chrono)
                } else {
                    None
                }
            }
        }
    }

    /// Checks if the data should be deleted now based on the policy.
    ///
    /// # Arguments
    ///
    /// * `created_at` - When the job was created
    /// * `completed_at` - When the job was completed (if applicable)
    /// * `default_retention` - Default retention period to use if policy is UseDefault
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::RetentionPolicy;
    /// use chrono::Utc;
    /// use std::time::Duration;
    ///
    /// let policy = RetentionPolicy::DeleteAfter(Duration::from_secs(1));
    /// let created_at = Utc::now() - chrono::Duration::seconds(2);
    ///
    /// assert!(policy.should_delete_now(created_at, None, None));
    /// ```
    pub fn should_delete_now(
        &self,
        created_at: DateTime<Utc>,
        completed_at: Option<DateTime<Utc>>,
        default_retention: Option<Duration>,
    ) -> bool {
        match self.calculate_deletion_time(created_at, completed_at, default_retention) {
            Some(delete_at) => Utc::now() >= delete_at,
            None => false,
        }
    }
}

/// Metadata about an encrypted payload.
///
/// Contains information needed to decrypt the payload and manage
/// its lifecycle according to retention policies.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptionMetadata {
    /// The encryption algorithm used.
    pub algorithm: EncryptionAlgorithm,

    /// Identifier of the key used for encryption.
    pub key_id: String,

    /// Version of the encryption configuration.
    pub config_version: u32,

    /// Whether the data was compressed before encryption.
    pub compressed: bool,

    /// List of field names that contain PII and were encrypted.
    pub encrypted_fields: Vec<String>,

    /// Retention policy for this encrypted data.
    pub retention_policy: RetentionPolicy,

    /// When the data was encrypted.
    pub encrypted_at: DateTime<Utc>,

    /// When the data should be deleted (if applicable).
    pub delete_at: Option<DateTime<Utc>>,

    /// Hash of the original payload for integrity verification.
    pub payload_hash: String,
}

impl EncryptionMetadata {
    /// Creates new encryption metadata.
    ///
    /// # Arguments
    ///
    /// * `config` - The encryption configuration used
    /// * `encrypted_fields` - List of fields that were encrypted
    /// * `retention_policy` - Retention policy for the data
    /// * `payload_hash` - Hash of the original payload
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionMetadata, EncryptionConfig, EncryptionAlgorithm, RetentionPolicy};
    /// use std::time::Duration;
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM)
    ///     .with_key_id("key-123");
    /// let metadata = EncryptionMetadata::new(
    ///     &config,
    ///     vec!["ssn".to_string(), "credit_card".to_string()],
    ///     RetentionPolicy::DeleteAfter(Duration::from_secs(86400)),
    ///     "hash123".to_string(),
    /// );
    ///
    /// assert_eq!(metadata.algorithm, EncryptionAlgorithm::AES256GCM);
    /// assert_eq!(metadata.encrypted_fields.len(), 2);
    /// ```
    pub fn new(
        config: &EncryptionConfig,
        encrypted_fields: Vec<String>,
        retention_policy: RetentionPolicy,
        payload_hash: String,
    ) -> Self {
        let now = Utc::now();
        let delete_at =
            retention_policy.calculate_deletion_time(now, None, config.default_retention);

        Self {
            algorithm: config.algorithm.clone(),
            key_id: config
                .key_id
                .clone()
                .unwrap_or_else(|| "default".to_string()),
            config_version: config.version,
            compressed: config.compression_enabled,
            encrypted_fields,
            retention_policy,
            encrypted_at: now,
            delete_at,
            payload_hash,
        }
    }

    /// Checks if this encrypted data should be deleted now.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::encryption::{EncryptionMetadata, EncryptionConfig, EncryptionAlgorithm, RetentionPolicy};
    /// use std::time::Duration;
    ///
    /// let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
    /// let metadata = EncryptionMetadata::new(
    ///     &config,
    ///     vec![],
    ///     RetentionPolicy::DeleteAfter(Duration::from_secs(1)),
    ///     "hash".to_string(),
    /// );
    ///
    /// // Should not be deleted immediately
    /// assert!(!metadata.should_delete_now());
    /// ```
    pub fn should_delete_now(&self) -> bool {
        match self.delete_at {
            Some(delete_at) => Utc::now() >= delete_at,
            None => false,
        }
    }

    /// Updates the deletion time based on job completion.
    ///
    /// # Arguments
    ///
    /// * `completed_at` - When the job was completed
    /// * `default_retention` - Default retention period from config
    pub fn update_deletion_time(
        &mut self,
        completed_at: DateTime<Utc>,
        default_retention: Option<Duration>,
    ) {
        self.delete_at = self.retention_policy.calculate_deletion_time(
            self.encrypted_at,
            Some(completed_at),
            default_retention,
        );
    }
}

/// Container for encrypted job payload data.
///
/// Contains the encrypted payload along with all metadata needed
/// for decryption and lifecycle management.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncryptedPayload {
    /// Base64-encoded encrypted data.
    pub ciphertext: String,

    /// Base64-encoded nonce/IV used for encryption.
    pub nonce: String,

    /// Base64-encoded authentication tag.
    pub tag: String,

    /// Metadata about the encryption.
    pub metadata: EncryptionMetadata,
}

impl EncryptedPayload {
    /// Creates a new encrypted payload container.
    ///
    /// # Arguments
    ///
    /// * `ciphertext` - The encrypted data
    /// * `nonce` - The nonce/IV used for encryption
    /// * `tag` - The authentication tag
    /// * `metadata` - Encryption metadata
    pub fn new(
        ciphertext: Vec<u8>,
        nonce: Vec<u8>,
        tag: Vec<u8>,
        metadata: EncryptionMetadata,
    ) -> Self {
        Self {
            ciphertext: base64::engine::general_purpose::STANDARD.encode(ciphertext),
            nonce: base64::engine::general_purpose::STANDARD.encode(nonce),
            tag: base64::engine::general_purpose::STANDARD.encode(tag),
            metadata,
        }
    }

    /// Decodes the ciphertext from base64.
    pub fn decode_ciphertext(&self) -> Result<Vec<u8>, EncryptionError> {
        base64::engine::general_purpose::STANDARD
            .decode(&self.ciphertext)
            .map_err(EncryptionError::Base64)
    }

    /// Decodes the nonce from base64.
    pub fn decode_nonce(&self) -> Result<Vec<u8>, EncryptionError> {
        base64::engine::general_purpose::STANDARD
            .decode(&self.nonce)
            .map_err(EncryptionError::Base64)
    }

    /// Decodes the authentication tag from base64.
    pub fn decode_tag(&self) -> Result<Vec<u8>, EncryptionError> {
        base64::engine::general_purpose::STANDARD
            .decode(&self.tag)
            .map_err(EncryptionError::Base64)
    }

    /// Checks if this encrypted payload should be deleted now.
    pub fn should_delete_now(&self) -> bool {
        self.metadata.should_delete_now()
    }

    /// Gets the size of the encrypted payload in bytes.
    pub fn size_bytes(&self) -> usize {
        self.ciphertext.len() + self.nonce.len() + self.tag.len()
    }

    /// Checks if the payload contains specific PII fields.
    pub fn contains_pii_field(&self, field_name: &str) -> bool {
        self.metadata
            .encrypted_fields
            .contains(&field_name.to_string())
    }

    /// Gets all PII fields contained in this payload.
    pub fn pii_fields(&self) -> &[String] {
        &self.metadata.encrypted_fields
    }
}

/// Statistics about encryption operations.
///
/// Provides metrics for monitoring encryption performance and usage.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EncryptionStats {
    /// Total number of jobs encrypted.
    pub jobs_encrypted: u64,

    /// Total number of jobs decrypted.
    pub jobs_decrypted: u64,

    /// Total number of PII fields encrypted.
    pub pii_fields_encrypted: u64,

    /// Total size of data encrypted (in bytes).
    pub total_encrypted_bytes: u64,

    /// Total size of data decrypted (in bytes).
    pub total_decrypted_bytes: u64,

    /// Number of encryption errors.
    pub encryption_errors: u64,

    /// Number of decryption errors.
    pub decryption_errors: u64,

    /// Number of key rotation events.
    pub key_rotations: u64,

    /// Number of retention policy cleanups.
    pub retention_cleanups: u64,

    /// Average encryption time in milliseconds.
    pub avg_encryption_time_ms: f64,

    /// Average decryption time in milliseconds.
    pub avg_decryption_time_ms: f64,

    /// Breakdown by encryption algorithm.
    pub algorithm_usage: HashMap<String, u64>,

    /// When these statistics were last updated.
    pub last_updated: DateTime<Utc>,
}

impl EncryptionStats {
    /// Creates new encryption statistics.
    pub fn new() -> Self {
        Self {
            last_updated: Utc::now(),
            ..Default::default()
        }
    }

    /// Records a successful encryption operation.
    pub fn record_encryption(
        &mut self,
        algorithm: &EncryptionAlgorithm,
        size_bytes: usize,
        duration_ms: f64,
    ) {
        self.jobs_encrypted += 1;
        self.total_encrypted_bytes += size_bytes as u64;

        // Update average encryption time
        if self.jobs_encrypted == 1 {
            self.avg_encryption_time_ms = duration_ms;
        } else {
            let total_time =
                self.avg_encryption_time_ms * (self.jobs_encrypted - 1) as f64 + duration_ms;
            self.avg_encryption_time_ms = total_time / self.jobs_encrypted as f64;
        }

        // Update algorithm usage
        let algo_name = format!("{:?}", algorithm);
        *self.algorithm_usage.entry(algo_name).or_insert(0) += 1;

        self.last_updated = Utc::now();
    }

    /// Records a successful decryption operation.
    pub fn record_decryption(&mut self, size_bytes: usize, duration_ms: f64) {
        self.jobs_decrypted += 1;
        self.total_decrypted_bytes += size_bytes as u64;

        // Update average decryption time
        if self.jobs_decrypted == 1 {
            self.avg_decryption_time_ms = duration_ms;
        } else {
            let total_time =
                self.avg_decryption_time_ms * (self.jobs_decrypted - 1) as f64 + duration_ms;
            self.avg_decryption_time_ms = total_time / self.jobs_decrypted as f64;
        }

        self.last_updated = Utc::now();
    }

    /// Records PII field encryption.
    pub fn record_pii_encryption(&mut self, field_count: usize) {
        self.pii_fields_encrypted += field_count as u64;
        self.last_updated = Utc::now();
    }

    /// Records an encryption error.
    pub fn record_encryption_error(&mut self) {
        self.encryption_errors += 1;
        self.last_updated = Utc::now();
    }

    /// Records a decryption error.
    pub fn record_decryption_error(&mut self) {
        self.decryption_errors += 1;
        self.last_updated = Utc::now();
    }

    /// Records a key rotation event.
    pub fn record_key_rotation(&mut self) {
        self.key_rotations += 1;
        self.last_updated = Utc::now();
    }

    /// Records a retention cleanup operation.
    pub fn record_retention_cleanup(&mut self, jobs_cleaned: u64) {
        self.retention_cleanups += jobs_cleaned;
        self.last_updated = Utc::now();
    }

    /// Calculates the encryption success rate as a percentage.
    pub fn encryption_success_rate(&self) -> f64 {
        let total_attempts = self.jobs_encrypted + self.encryption_errors;
        if total_attempts == 0 {
            100.0
        } else {
            (self.jobs_encrypted as f64 / total_attempts as f64) * 100.0
        }
    }

    /// Calculates the decryption success rate as a percentage.
    pub fn decryption_success_rate(&self) -> f64 {
        let total_attempts = self.jobs_decrypted + self.decryption_errors;
        if total_attempts == 0 {
            100.0
        } else {
            (self.jobs_decrypted as f64 / total_attempts as f64) * 100.0
        }
    }

    /// Gets the most used encryption algorithm.
    pub fn most_used_algorithm(&self) -> Option<String> {
        self.algorithm_usage
            .iter()
            .max_by_key(|(_, count)| *count)
            .map(|(algo, _)| algo.clone())
    }
}

/// Deterministic key generation utility for KMS fallback scenarios
///
/// This utility generates consistent keys for development, testing, and fallback scenarios
/// when external KMS services are unavailable. It uses SHA-256 hashing to create
/// deterministic keys based on the service type and configuration parameters.
///
/// # Arguments
///
/// * `service_prefix` - Service-specific prefix (e.g., "aws-kms-data-key", "azure-kv-master-key")
/// * `inputs` - Variable number of string inputs that will be hashed together
///
/// # Returns
///
/// A `Vec<u8>` containing the generated key material (32 bytes for SHA-256)
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "encryption")]
/// # {
/// use hammerwork::encryption::generate_deterministic_key;
///
/// // Generate a deterministic key for AWS KMS fallback
/// let key = generate_deterministic_key("aws-kms-data-key", &["my-key-id", "us-east-1"]);
/// assert_eq!(key.len(), 32); // SHA-256 produces 32 bytes
///
/// // Generate a deterministic key for Azure Key Vault fallback
/// let key = generate_deterministic_key("azure-kv-master-key", &["vault-url", "key-name"]);
/// assert_eq!(key.len(), 32);
/// # }
/// ```
pub fn generate_deterministic_key(service_prefix: &str, inputs: &[&str]) -> Vec<u8> {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    hasher.update(service_prefix.as_bytes());
    for input in inputs {
        hasher.update(input.as_bytes());
    }
    let hash = hasher.finalize();
    hash[0..32].to_vec()
}

/// Generate a deterministic key with a specific size
///
/// This function extends the basic deterministic key generation to support
/// variable key sizes by repeating the hash pattern as needed.
///
/// # Arguments
///
/// * `service_prefix` - Service-specific prefix
/// * `inputs` - Variable number of string inputs
/// * `key_size` - Desired key size in bytes
///
/// # Returns
///
/// A `Vec<u8>` of the requested size containing the generated key material
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "encryption")]
/// # {
/// use hammerwork::encryption::generate_deterministic_key_with_size;
///
/// // Generate a 64-byte key for a specific use case
/// let key = generate_deterministic_key_with_size("custom-service", &["param1", "param2"], 64);
/// assert_eq!(key.len(), 64);
///
/// // Generate a 16-byte key for AES-128
/// let key = generate_deterministic_key_with_size("aes128-key", &["param1"], 16);
/// assert_eq!(key.len(), 16);
/// # }
/// ```
pub fn generate_deterministic_key_with_size(
    service_prefix: &str,
    inputs: &[&str],
    key_size: usize,
) -> Vec<u8> {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    hasher.update(service_prefix.as_bytes());
    for input in inputs {
        hasher.update(input.as_bytes());
    }
    let hash = hasher.finalize();

    // Generate key of the requested size by repeating the hash pattern
    let mut key = vec![0u8; key_size];
    let hash_bytes = hash.as_slice();
    for (i, byte) in key.iter_mut().enumerate() {
        *byte = hash_bytes[i % hash_bytes.len()];
    }
    key
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_encryption_config_creation() {
        let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
        assert_eq!(config.algorithm, EncryptionAlgorithm::AES256GCM);
        assert!(!config.key_rotation_enabled);
        assert!(!config.compression_enabled);
        assert_eq!(config.version, 1);
    }

    #[test]
    fn test_encryption_config_builder() {
        let config = EncryptionConfig::new(EncryptionAlgorithm::ChaCha20Poly1305)
            .with_key_source(KeySource::Environment("TEST_KEY".to_string()))
            .with_key_rotation_enabled(true)
            .with_compression_enabled(true)
            .with_key_id("test-key-1");

        assert_eq!(config.algorithm, EncryptionAlgorithm::ChaCha20Poly1305);
        assert_eq!(
            config.key_source,
            KeySource::Environment("TEST_KEY".to_string())
        );
        assert!(config.key_rotation_enabled);
        assert!(config.compression_enabled);
        assert_eq!(config.key_id, Some("test-key-1".to_string()));
    }

    #[test]
    fn test_algorithm_key_sizes() {
        let aes_config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
        assert_eq!(aes_config.key_size_bytes(), 32);
        assert_eq!(aes_config.nonce_size_bytes(), 12);
        assert_eq!(aes_config.tag_size_bytes(), 16);

        let chacha_config = EncryptionConfig::new(EncryptionAlgorithm::ChaCha20Poly1305);
        assert_eq!(chacha_config.key_size_bytes(), 32);
        assert_eq!(chacha_config.nonce_size_bytes(), 12);
        assert_eq!(chacha_config.tag_size_bytes(), 16);
    }

    #[test]
    fn test_retention_policy_calculation() {
        let now = Utc::now();
        let one_day = Duration::from_secs(24 * 60 * 60);

        let policy = RetentionPolicy::DeleteAfter(one_day);
        let delete_time = policy.calculate_deletion_time(now, None, None).unwrap();

        let expected = now + chrono::Duration::from_std(one_day).unwrap();
        assert!((delete_time - expected).num_seconds().abs() < 1);
    }

    #[test]
    fn test_retention_policy_should_delete() {
        let past = Utc::now() - chrono::Duration::seconds(2);
        let policy = RetentionPolicy::DeleteAfter(Duration::from_secs(1));

        assert!(policy.should_delete_now(past, None, None));

        let future = Utc::now() + chrono::Duration::seconds(10);
        assert!(!policy.should_delete_now(future, None, None));
    }

    #[test]
    fn test_encryption_metadata_creation() {
        let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM).with_key_id("test-key");

        let fields = vec!["ssn".to_string(), "credit_card".to_string()];
        let policy = RetentionPolicy::DeleteAfter(Duration::from_secs(86400));

        let metadata =
            EncryptionMetadata::new(&config, fields.clone(), policy, "hash123".to_string());

        assert_eq!(metadata.algorithm, EncryptionAlgorithm::AES256GCM);
        assert_eq!(metadata.key_id, "test-key");
        assert_eq!(metadata.encrypted_fields, fields);
        assert_eq!(metadata.payload_hash, "hash123");
        assert!(!metadata.compressed);
    }

    #[test]
    fn test_encrypted_payload_creation() {
        let config = EncryptionConfig::new(EncryptionAlgorithm::AES256GCM);
        let metadata = EncryptionMetadata::new(
            &config,
            vec!["test_field".to_string()],
            RetentionPolicy::KeepIndefinitely,
            "hash".to_string(),
        );

        let payload = EncryptedPayload::new(
            b"encrypted_data".to_vec(),
            b"nonce123".to_vec(),
            b"tag12345".to_vec(),
            metadata,
        );

        assert!(payload.contains_pii_field("test_field"));
        assert!(!payload.contains_pii_field("other_field"));
        assert_eq!(payload.pii_fields().len(), 1);
        assert!(!payload.should_delete_now());
    }

    #[test]
    fn test_encryption_stats() {
        let mut stats = EncryptionStats::new();

        stats.record_encryption(&EncryptionAlgorithm::AES256GCM, 1024, 10.5);
        stats.record_encryption(&EncryptionAlgorithm::AES256GCM, 2048, 15.0);
        stats.record_pii_encryption(2);

        assert_eq!(stats.jobs_encrypted, 2);
        assert_eq!(stats.total_encrypted_bytes, 3072);
        assert_eq!(stats.pii_fields_encrypted, 2);
        assert_eq!(stats.avg_encryption_time_ms, 12.75); // (10.5 + 15.0) / 2
        assert_eq!(stats.encryption_success_rate(), 100.0);

        stats.record_encryption_error();
        assert!(stats.encryption_success_rate() < 100.0);
    }

    #[test]
    fn test_key_source_equality() {
        assert_eq!(
            KeySource::Environment("KEY1".to_string()),
            KeySource::Environment("KEY1".to_string())
        );
        assert_ne!(
            KeySource::Environment("KEY1".to_string()),
            KeySource::Environment("KEY2".to_string())
        );
        assert_ne!(
            KeySource::Environment("KEY1".to_string()),
            KeySource::Static("KEY1".to_string())
        );
    }

    #[test]
    fn test_serialization() {
        let config = EncryptionConfig::new(EncryptionAlgorithm::ChaCha20Poly1305)
            .with_key_rotation_enabled(true)
            .with_compression_enabled(true);

        let serialized = serde_json::to_string(&config).unwrap();
        let deserialized: EncryptionConfig = serde_json::from_str(&serialized).unwrap();

        assert_eq!(config.algorithm, deserialized.algorithm);
        assert_eq!(
            config.key_rotation_enabled,
            deserialized.key_rotation_enabled
        );
        assert_eq!(config.compression_enabled, deserialized.compression_enabled);
    }
}