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
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
//! Advanced retry strategies for job scheduling and backoff patterns.
//!
//! This module provides configurable retry strategies that determine how long to wait
//! before retrying a failed job. Different strategies are suitable for different types
//! of failures and system characteristics.
//!
//! # Retry Strategies
//!
//! - [`Fixed`](RetryStrategy::Fixed) - Constant delay between retries
//! - [`Linear`](RetryStrategy::Linear) - Linearly increasing delays
//! - [`Exponential`](RetryStrategy::Exponential) - Exponentially increasing delays with optional jitter
//! - [`Fibonacci`](RetryStrategy::Fibonacci) - Delays following the Fibonacci sequence
//! - [`Custom`](RetryStrategy::Custom) - User-defined retry logic
//!
//! # Examples
//!
//! ## Basic Usage
//!
//! ```rust
//! use hammerwork::{Job, retry::RetryStrategy};
//! use serde_json::json;
//! use std::time::Duration;
//!
//! // Exponential backoff with jitter
//! let job = Job::new("api_call".to_string(), json!({"url": "https://api.example.com"}))
//!     .with_exponential_backoff(
//!         Duration::from_secs(1),    // base delay
//!         2.0,                       // multiplier
//!         Duration::from_secs(10 * 60) // max delay
//!     );
//! ```
//!
//! ## Advanced Configuration
//!
//! ```rust
//! use hammerwork::{Job, retry::{RetryStrategy, JitterType}};
//! use serde_json::json;
//! use std::time::Duration;
//!
//! // Custom exponential backoff with multiplicative jitter
//! let strategy = RetryStrategy::Exponential {
//!     base: Duration::from_secs(2),
//!     multiplier: 1.5,
//!     max_delay: Some(Duration::from_secs(5 * 60)),
//!     jitter: Some(JitterType::Multiplicative(0.1)), // ±10% jitter
//! };
//!
//! let job = Job::new("data_processing".to_string(), json!({"task": "heavy"}))
//!     .with_retry_strategy(strategy);
//! ```

use rand::Rng;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Types of jitter that can be applied to retry delays.
///
/// Jitter helps prevent the "thundering herd" problem where many failing jobs
/// all retry at exactly the same time, potentially overwhelming downstream systems.
///
/// # Examples
///
/// ```rust
/// use hammerwork::retry::JitterType;
/// use std::time::Duration;
///
/// // Add ±2 seconds of randomness
/// let additive = JitterType::Additive(Duration::from_secs(2));
///
/// // Add ±20% randomness to the delay
/// let multiplicative = JitterType::Multiplicative(0.2);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum JitterType {
    /// Add a random duration between 0 and the specified value.
    ///
    /// The jitter is uniform random: `delay ± rand(0, jitter_amount)`
    Additive(Duration),

    /// Multiply the delay by a random factor.
    ///
    /// The factor is uniform random: `delay * (1 ± rand(0, factor))`
    /// For example, with factor 0.1, the delay will be between 90% and 110% of the original.
    Multiplicative(f64),
}

impl JitterType {
    /// Apply jitter to a given delay duration.
    ///
    /// # Arguments
    ///
    /// * `delay` - The base delay to apply jitter to
    ///
    /// # Returns
    ///
    /// The delay with jitter applied. The result is clamped to ensure it's never negative.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::JitterType;
    /// use std::time::Duration;
    ///
    /// let jitter = JitterType::Additive(Duration::from_secs(5));
    /// let base_delay = Duration::from_secs(30);
    /// let jittered = jitter.apply(base_delay);
    ///
    /// // Result will be between 25 and 35 seconds
    /// assert!(jittered >= Duration::from_secs(25));
    /// assert!(jittered <= Duration::from_secs(35));
    /// ```
    pub fn apply(&self, delay: Duration) -> Duration {
        let mut rng = rand::thread_rng();

        match self {
            JitterType::Additive(jitter_amount) => {
                let jitter_millis = rng.gen_range(0..=jitter_amount.as_millis() as u64);
                let jitter = Duration::from_millis(jitter_millis);

                // Randomly add or subtract jitter
                if rng.gen_bool(0.5) {
                    delay + jitter
                } else {
                    delay.saturating_sub(jitter)
                }
            }
            JitterType::Multiplicative(factor) => {
                let jitter_factor = rng.gen_range((1.0 - factor)..=(1.0 + factor));
                let jittered_millis = (delay.as_millis() as f64 * jitter_factor) as u64;
                Duration::from_millis(jittered_millis)
            }
        }
    }
}

impl Serialize for JitterType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        match self {
            JitterType::Additive(duration) => {
                let mut state = serializer.serialize_struct("JitterType", 2)?;
                state.serialize_field("type", "Additive")?;
                state.serialize_field("duration_ms", &(duration.as_millis() as u64))?;
                state.end()
            }
            JitterType::Multiplicative(factor) => {
                let mut state = serializer.serialize_struct("JitterType", 2)?;
                state.serialize_field("type", "Multiplicative")?;
                state.serialize_field("factor", factor)?;
                state.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for JitterType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "snake_case")]
        enum Field {
            Type,
            DurationMs,
            Factor,
        }

        struct JitterTypeVisitor;

        impl<'de> Visitor<'de> for JitterTypeVisitor {
            type Value = JitterType;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a jitter type")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut jitter_type: Option<String> = None;
                let mut duration_ms: Option<u64> = None;
                let mut factor: Option<f64> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => {
                            if jitter_type.is_some() {
                                return Err(de::Error::duplicate_field("type"));
                            }
                            jitter_type = Some(map.next_value()?);
                        }
                        "duration_ms" => {
                            if duration_ms.is_some() {
                                return Err(de::Error::duplicate_field("duration_ms"));
                            }
                            duration_ms = Some(map.next_value()?);
                        }
                        "factor" => {
                            if factor.is_some() {
                                return Err(de::Error::duplicate_field("factor"));
                            }
                            factor = Some(map.next_value()?);
                        }
                        _ => {
                            let _: serde::de::IgnoredAny = map.next_value()?;
                        }
                    }
                }

                let jitter_type = jitter_type.ok_or_else(|| de::Error::missing_field("type"))?;

                match jitter_type.as_str() {
                    "Additive" => {
                        let duration_ms =
                            duration_ms.ok_or_else(|| de::Error::missing_field("duration_ms"))?;
                        Ok(JitterType::Additive(Duration::from_millis(duration_ms)))
                    }
                    "Multiplicative" => {
                        let factor = factor.ok_or_else(|| de::Error::missing_field("factor"))?;
                        Ok(JitterType::Multiplicative(factor))
                    }
                    _ => Err(de::Error::unknown_variant(
                        &jitter_type,
                        &["Additive", "Multiplicative"],
                    )),
                }
            }
        }

        deserializer.deserialize_struct(
            "JitterType",
            &["type", "duration_ms", "factor"],
            JitterTypeVisitor,
        )
    }
}

/// Advanced retry strategies for determining delay between job retry attempts.
///
/// Each strategy calculates the delay based on the number of previous attempts,
/// allowing for sophisticated backoff patterns that can help reduce system load
/// during failures while ensuring jobs are retried appropriately.
///
/// # Strategy Selection Guidelines
///
/// - **Fixed**: Simple scenarios with predictable failure patterns
/// - **Linear**: When you want gradually increasing delays without explosive growth
/// - **Exponential**: Most common choice for network/API failures; prevents overwhelming downstream
/// - **Fibonacci**: Similar to exponential but with gentler growth
/// - **Custom**: When you need domain-specific retry logic
///
/// # Examples
///
/// ```rust
/// use hammerwork::retry::RetryStrategy;
/// use std::time::Duration;
///
/// // Simple fixed delay
/// let fixed = RetryStrategy::Fixed(Duration::from_secs(30));
///
/// // Linear backoff: 10s, 20s, 30s, 40s...
/// let linear = RetryStrategy::Linear {
///     base: Duration::from_secs(10),
///     increment: Duration::from_secs(10),
///     max_delay: Some(Duration::from_secs(5 * 60)),
/// };
///
/// // Exponential backoff: 1s, 2s, 4s, 8s, 16s...
/// let exponential = RetryStrategy::Exponential {
///     base: Duration::from_secs(1),
///     multiplier: 2.0,
///     max_delay: Some(Duration::from_secs(10 * 60)),
///     jitter: None,
/// };
/// ```
pub enum RetryStrategy {
    /// Fixed delay between all retry attempts.
    ///
    /// This is the simplest strategy and matches the original Hammerwork behavior.
    /// All retries wait the same amount of time regardless of attempt number.
    ///
    /// # Use Cases
    /// - Simple systems with predictable failure patterns
    /// - When you want consistent retry timing
    /// - Testing and development environments
    ///
    /// # Example
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::Fixed(Duration::from_secs(30));
    ///
    /// // All attempts wait 30 seconds: 30s, 30s, 30s...
    /// assert_eq!(strategy.calculate_delay(1), Duration::from_secs(30));
    /// assert_eq!(strategy.calculate_delay(5), Duration::from_secs(30));
    /// ```
    Fixed(Duration),

    /// Linear backoff with configurable increment and optional maximum delay.
    ///
    /// Each retry waits longer than the previous by a fixed increment.
    /// Formula: `base + (attempt * increment)`
    ///
    /// # Use Cases
    /// - When you want gradual backoff without explosive growth
    /// - Resource contention scenarios
    /// - Database lock conflicts
    ///
    /// # Example
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::Linear {
    ///     base: Duration::from_secs(5),
    ///     increment: Duration::from_secs(10),
    ///     max_delay: Some(Duration::from_secs(2 * 60)),
    /// };
    ///
    /// // Delays: 5s, 15s, 25s, 35s, 45s, 55s, 65s, 75s, 85s, 95s, 120s (capped)...
    /// assert_eq!(strategy.calculate_delay(1), Duration::from_secs(15));
    /// assert_eq!(strategy.calculate_delay(10), Duration::from_secs(105));
    /// ```
    Linear {
        /// Base delay for the first retry attempt
        base: Duration,
        /// Amount to add for each subsequent attempt
        increment: Duration,
        /// Optional maximum delay to cap exponential growth
        max_delay: Option<Duration>,
    },

    /// Exponential backoff with configurable base, multiplier, and optional jitter.
    ///
    /// Each retry waits exponentially longer than the previous attempt.
    /// Formula: `base * (multiplier ^ (attempt - 1))`
    ///
    /// # Use Cases
    /// - Network and API failures (most common)
    /// - External service integration
    /// - Rate limiting scenarios
    /// - Any scenario where overwhelming downstream systems is a concern
    ///
    /// # Example
    /// ```rust
    /// use hammerwork::retry::{RetryStrategy, JitterType};
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::Exponential {
    ///     base: Duration::from_secs(1),
    ///     multiplier: 2.0,
    ///     max_delay: Some(Duration::from_secs(10 * 60)),
    ///     jitter: Some(JitterType::Multiplicative(0.1)), // ±10% jitter
    /// };
    ///
    /// // Base delays: 1s, 2s, 4s, 8s, 16s, 32s, 64s, 128s, 256s, 512s (capped at 600s)
    /// // With jitter: each delay is randomly adjusted by ±10%
    /// ```
    Exponential {
        /// Base delay for the first retry attempt
        base: Duration,
        /// Multiplier for exponential growth (typically 2.0)
        multiplier: f64,
        /// Optional maximum delay to cap exponential growth
        max_delay: Option<Duration>,
        /// Optional jitter to prevent thundering herd problems
        jitter: Option<JitterType>,
    },

    /// Fibonacci sequence backoff with configurable base delay.
    ///
    /// Each retry waits according to the Fibonacci sequence multiplied by the base delay.
    /// Sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89...
    /// Formula: `base * fibonacci(attempt)`
    ///
    /// # Use Cases
    /// - When you want growth slower than exponential but faster than linear
    /// - Mathematical elegance in retry patterns
    /// - Systems with moderate failure recovery times
    ///
    /// # Example
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::Fibonacci {
    ///     base: Duration::from_secs(2),
    ///     max_delay: Some(Duration::from_secs(5 * 60)),
    /// };
    ///
    /// // Delays: 2s, 2s, 4s, 6s, 10s, 16s, 26s, 42s, 68s, 110s, 178s, 288s (capped at 300s)...
    /// assert_eq!(strategy.calculate_delay(1), Duration::from_secs(2));
    /// assert_eq!(strategy.calculate_delay(5), Duration::from_secs(10));
    /// ```
    Fibonacci {
        /// Base delay multiplied by the Fibonacci number
        base: Duration,
        /// Optional maximum delay to cap growth
        max_delay: Option<Duration>,
    },

    /// Custom retry strategy using a user-defined function.
    ///
    /// Allows for completely custom retry logic based on attempt number.
    /// The function receives the attempt number (1-based) and returns the delay.
    ///
    /// # Use Cases
    /// - Domain-specific retry patterns
    /// - Complex business logic for retry timing
    /// - Integration with external scheduling systems
    /// - When none of the built-in strategies fit your needs
    ///
    /// # Example
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// // Custom strategy: short delays for first few attempts, then longer
    /// let strategy = RetryStrategy::Custom(Box::new(|attempt| {
    ///     if attempt <= 3 {
    ///         Duration::from_secs(5)  // Quick retries for transient issues
    ///     } else if attempt <= 6 {
    ///         Duration::from_secs(60) // Medium delays for persistent issues
    ///     } else {
    ///         Duration::from_secs(300) // Long delays for severe issues
    ///     }
    /// }));
    ///
    /// assert_eq!(strategy.calculate_delay(1), Duration::from_secs(5));
    /// assert_eq!(strategy.calculate_delay(4), Duration::from_secs(60));
    /// assert_eq!(strategy.calculate_delay(7), Duration::from_secs(300));
    /// ```
    Custom(Box<dyn Fn(u32) -> Duration + Send + Sync>),
}

impl RetryStrategy {
    /// Calculate the delay before the next retry attempt.
    ///
    /// # Arguments
    ///
    /// * `attempt` - The attempt number (1-based). The first retry is attempt 1.
    ///
    /// # Returns
    ///
    /// The duration to wait before the next retry attempt.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::Exponential {
    ///     base: Duration::from_secs(1),
    ///     multiplier: 2.0,
    ///     max_delay: None,
    ///     jitter: None,
    /// };
    ///
    /// assert_eq!(strategy.calculate_delay(1), Duration::from_secs(1));
    /// assert_eq!(strategy.calculate_delay(2), Duration::from_secs(2));
    /// assert_eq!(strategy.calculate_delay(3), Duration::from_secs(4));
    /// assert_eq!(strategy.calculate_delay(4), Duration::from_secs(8));
    /// ```
    pub fn calculate_delay(&self, attempt: u32) -> Duration {
        let base_delay = match self {
            RetryStrategy::Fixed(delay) => *delay,

            RetryStrategy::Linear {
                base,
                increment,
                max_delay,
            } => {
                let delay = *base + increment.mul_f64(attempt as f64);
                if let Some(max) = max_delay {
                    delay.min(*max)
                } else {
                    delay
                }
            }

            RetryStrategy::Exponential {
                base,
                multiplier,
                max_delay,
                jitter,
            } => {
                let delay_multiplier = multiplier.powi((attempt.saturating_sub(1)) as i32);
                let delay = base.mul_f64(delay_multiplier);

                let capped_delay = if let Some(max) = max_delay {
                    delay.min(*max)
                } else {
                    delay
                };

                if let Some(jitter_type) = jitter {
                    return jitter_type.apply(capped_delay);
                }

                capped_delay
            }

            RetryStrategy::Fibonacci { base, max_delay } => {
                let fib_number = fibonacci(attempt);
                let delay = base.mul_f64(fib_number as f64);

                if let Some(max) = max_delay {
                    delay.min(*max)
                } else {
                    delay
                }
            }

            RetryStrategy::Custom(func) => func(attempt),
        };

        // Ensure delay is never zero (minimum 1ms)
        base_delay.max(Duration::from_millis(1))
    }

    /// Create a fixed delay retry strategy.
    ///
    /// # Arguments
    ///
    /// * `delay` - The fixed delay between retry attempts
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::fixed(Duration::from_secs(30));
    /// ```
    pub fn fixed(delay: Duration) -> Self {
        RetryStrategy::Fixed(delay)
    }

    /// Create a linear backoff retry strategy.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay for the first attempt
    /// * `increment` - Amount to add for each subsequent attempt
    /// * `max_delay` - Optional maximum delay cap
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::linear(
    ///     Duration::from_secs(10),
    ///     Duration::from_secs(5),
    ///     Some(Duration::from_secs(2 * 60))
    /// );
    /// ```
    pub fn linear(base: Duration, increment: Duration, max_delay: Option<Duration>) -> Self {
        RetryStrategy::Linear {
            base,
            increment,
            max_delay,
        }
    }

    /// Create an exponential backoff retry strategy.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay for the first attempt
    /// * `multiplier` - Exponential growth multiplier
    /// * `max_delay` - Optional maximum delay cap
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::exponential(
    ///     Duration::from_secs(1),
    ///     2.0,
    ///     Some(Duration::from_secs(10 * 60))
    /// );
    /// ```
    pub fn exponential(base: Duration, multiplier: f64, max_delay: Option<Duration>) -> Self {
        RetryStrategy::Exponential {
            base,
            multiplier,
            max_delay,
            jitter: None,
        }
    }

    /// Create an exponential backoff retry strategy with jitter.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay for the first attempt
    /// * `multiplier` - Exponential growth multiplier
    /// * `max_delay` - Optional maximum delay cap
    /// * `jitter` - Jitter type to apply
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::{RetryStrategy, JitterType};
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::exponential_with_jitter(
    ///     Duration::from_secs(1),
    ///     2.0,
    ///     Some(Duration::from_secs(10 * 60)),
    ///     JitterType::Multiplicative(0.1)
    /// );
    /// ```
    pub fn exponential_with_jitter(
        base: Duration,
        multiplier: f64,
        max_delay: Option<Duration>,
        jitter: JitterType,
    ) -> Self {
        RetryStrategy::Exponential {
            base,
            multiplier,
            max_delay,
            jitter: Some(jitter),
        }
    }

    /// Create a Fibonacci sequence retry strategy.
    ///
    /// # Arguments
    ///
    /// * `base` - Base delay multiplied by Fibonacci numbers
    /// * `max_delay` - Optional maximum delay cap
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::fibonacci(
    ///     Duration::from_secs(2),
    ///     Some(Duration::from_secs(5 * 60))
    /// );
    /// ```
    pub fn fibonacci(base: Duration, max_delay: Option<Duration>) -> Self {
        RetryStrategy::Fibonacci { base, max_delay }
    }

    /// Create a custom retry strategy using a user-defined function.
    ///
    /// # Arguments
    ///
    /// * `func` - Function that takes attempt number and returns delay
    ///
    /// # Examples
    ///
    /// ```rust
    /// use hammerwork::retry::RetryStrategy;
    /// use std::time::Duration;
    ///
    /// let strategy = RetryStrategy::custom(|attempt| {
    ///     match attempt {
    ///         1..=3 => Duration::from_secs(5),
    ///         4..=6 => Duration::from_secs(30),
    ///         _ => Duration::from_secs(300),
    ///     }
    /// });
    /// ```
    pub fn custom<F>(func: F) -> Self
    where
        F: Fn(u32) -> Duration + Send + Sync + 'static,
    {
        RetryStrategy::Custom(Box::new(func))
    }
}

/// Calculate the nth Fibonacci number efficiently.
///
/// Uses an iterative approach to avoid recursion overhead and stack overflow
/// for large attempt numbers.
///
/// # Arguments
///
/// * `n` - The position in the Fibonacci sequence (1-based)
///
/// # Returns
///
/// The nth Fibonacci number
///
/// # Examples
///
/// ```rust
/// use hammerwork::retry::fibonacci;
///
/// assert_eq!(fibonacci(1), 1);
/// assert_eq!(fibonacci(2), 1);
/// assert_eq!(fibonacci(3), 2);
/// assert_eq!(fibonacci(4), 3);
/// assert_eq!(fibonacci(5), 5);
/// assert_eq!(fibonacci(6), 8);
/// ```
pub fn fibonacci(n: u32) -> u64 {
    if n == 0 {
        return 0;
    }
    if n <= 2 {
        return 1;
    }

    let mut prev = 1u64;
    let mut curr = 1u64;

    for _ in 3..=n {
        let next = prev.saturating_add(curr);
        prev = curr;
        curr = next;
    }

    curr
}

// Manual implementations for RetryStrategy to handle the Custom variant

impl std::fmt::Debug for RetryStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RetryStrategy::Fixed(duration) => f.debug_tuple("Fixed").field(duration).finish(),
            RetryStrategy::Linear {
                base,
                increment,
                max_delay,
            } => f
                .debug_struct("Linear")
                .field("base", base)
                .field("increment", increment)
                .field("max_delay", max_delay)
                .finish(),
            RetryStrategy::Exponential {
                base,
                multiplier,
                max_delay,
                jitter,
            } => f
                .debug_struct("Exponential")
                .field("base", base)
                .field("multiplier", multiplier)
                .field("max_delay", max_delay)
                .field("jitter", jitter)
                .finish(),
            RetryStrategy::Fibonacci { base, max_delay } => f
                .debug_struct("Fibonacci")
                .field("base", base)
                .field("max_delay", max_delay)
                .finish(),
            RetryStrategy::Custom(_) => f.write_str("Custom(<function>)"),
        }
    }
}

impl Clone for RetryStrategy {
    fn clone(&self) -> Self {
        match self {
            RetryStrategy::Fixed(duration) => RetryStrategy::Fixed(*duration),
            RetryStrategy::Linear {
                base,
                increment,
                max_delay,
            } => RetryStrategy::Linear {
                base: *base,
                increment: *increment,
                max_delay: *max_delay,
            },
            RetryStrategy::Exponential {
                base,
                multiplier,
                max_delay,
                jitter,
            } => RetryStrategy::Exponential {
                base: *base,
                multiplier: *multiplier,
                max_delay: *max_delay,
                jitter: jitter.clone(),
            },
            RetryStrategy::Fibonacci { base, max_delay } => RetryStrategy::Fibonacci {
                base: *base,
                max_delay: *max_delay,
            },
            RetryStrategy::Custom(_) => {
                panic!("Cannot clone custom retry strategy functions")
            }
        }
    }
}

impl PartialEq for RetryStrategy {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (RetryStrategy::Fixed(a), RetryStrategy::Fixed(b)) => a == b,
            (
                RetryStrategy::Linear {
                    base: a_base,
                    increment: a_inc,
                    max_delay: a_max,
                },
                RetryStrategy::Linear {
                    base: b_base,
                    increment: b_inc,
                    max_delay: b_max,
                },
            ) => a_base == b_base && a_inc == b_inc && a_max == b_max,
            (
                RetryStrategy::Exponential {
                    base: a_base,
                    multiplier: a_mult,
                    max_delay: a_max,
                    jitter: a_jitter,
                },
                RetryStrategy::Exponential {
                    base: b_base,
                    multiplier: b_mult,
                    max_delay: b_max,
                    jitter: b_jitter,
                },
            ) => a_base == b_base && a_mult == b_mult && a_max == b_max && a_jitter == b_jitter,
            (
                RetryStrategy::Fibonacci {
                    base: a_base,
                    max_delay: a_max,
                },
                RetryStrategy::Fibonacci {
                    base: b_base,
                    max_delay: b_max,
                },
            ) => a_base == b_base && a_max == b_max,
            (RetryStrategy::Custom(_), RetryStrategy::Custom(_)) => false, // Custom functions can't be compared
            _ => false,
        }
    }
}

impl Serialize for RetryStrategy {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;

        match self {
            RetryStrategy::Fixed(duration) => {
                let mut state = serializer.serialize_struct("RetryStrategy", 2)?;
                state.serialize_field("type", "Fixed")?;
                state.serialize_field("duration_ms", &(duration.as_millis() as u64))?;
                state.end()
            }
            RetryStrategy::Linear {
                base,
                increment,
                max_delay,
            } => {
                let mut state = serializer.serialize_struct("RetryStrategy", 4)?;
                state.serialize_field("type", "Linear")?;
                state.serialize_field("base_ms", &(base.as_millis() as u64))?;
                state.serialize_field("increment_ms", &(increment.as_millis() as u64))?;
                state.serialize_field("max_delay_ms", &max_delay.map(|d| d.as_millis() as u64))?;
                state.end()
            }
            RetryStrategy::Exponential {
                base,
                multiplier,
                max_delay,
                jitter,
            } => {
                let mut state = serializer.serialize_struct("RetryStrategy", 5)?;
                state.serialize_field("type", "Exponential")?;
                state.serialize_field("base_ms", &(base.as_millis() as u64))?;
                state.serialize_field("multiplier", multiplier)?;
                state.serialize_field("max_delay_ms", &max_delay.map(|d| d.as_millis() as u64))?;
                state.serialize_field("jitter", jitter)?;
                state.end()
            }
            RetryStrategy::Fibonacci { base, max_delay } => {
                let mut state = serializer.serialize_struct("RetryStrategy", 3)?;
                state.serialize_field("type", "Fibonacci")?;
                state.serialize_field("base_ms", &(base.as_millis() as u64))?;
                state.serialize_field("max_delay_ms", &max_delay.map(|d| d.as_millis() as u64))?;
                state.end()
            }
            RetryStrategy::Custom(_) => Err(serde::ser::Error::custom(
                "Cannot serialize custom retry strategy functions",
            )),
        }
    }
}

impl<'de> Deserialize<'de> for RetryStrategy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        struct RetryStrategyVisitor;

        impl<'de> Visitor<'de> for RetryStrategyVisitor {
            type Value = RetryStrategy;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a retry strategy")
            }

            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
            where
                M: MapAccess<'de>,
            {
                let mut strategy_type: Option<String> = None;
                let mut duration_ms: Option<u64> = None;
                let mut base_ms: Option<u64> = None;
                let mut increment_ms: Option<u64> = None;
                let mut max_delay_ms: Option<Option<u64>> = None;
                let mut multiplier: Option<f64> = None;
                let mut jitter: Option<Option<JitterType>> = None;

                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => {
                            if strategy_type.is_some() {
                                return Err(de::Error::duplicate_field("type"));
                            }
                            strategy_type = Some(map.next_value()?);
                        }
                        "duration_ms" => {
                            if duration_ms.is_some() {
                                return Err(de::Error::duplicate_field("duration_ms"));
                            }
                            duration_ms = Some(map.next_value()?);
                        }
                        "base_ms" => {
                            if base_ms.is_some() {
                                return Err(de::Error::duplicate_field("base_ms"));
                            }
                            base_ms = Some(map.next_value()?);
                        }
                        "increment_ms" => {
                            if increment_ms.is_some() {
                                return Err(de::Error::duplicate_field("increment_ms"));
                            }
                            increment_ms = Some(map.next_value()?);
                        }
                        "max_delay_ms" => {
                            if max_delay_ms.is_some() {
                                return Err(de::Error::duplicate_field("max_delay_ms"));
                            }
                            max_delay_ms = Some(map.next_value()?);
                        }
                        "multiplier" => {
                            if multiplier.is_some() {
                                return Err(de::Error::duplicate_field("multiplier"));
                            }
                            multiplier = Some(map.next_value()?);
                        }
                        "jitter" => {
                            if jitter.is_some() {
                                return Err(de::Error::duplicate_field("jitter"));
                            }
                            jitter = Some(map.next_value()?);
                        }
                        _ => {
                            let _: serde::de::IgnoredAny = map.next_value()?;
                        }
                    }
                }

                let strategy_type =
                    strategy_type.ok_or_else(|| de::Error::missing_field("type"))?;

                match strategy_type.as_str() {
                    "Fixed" => {
                        let duration_ms =
                            duration_ms.ok_or_else(|| de::Error::missing_field("duration_ms"))?;
                        Ok(RetryStrategy::Fixed(Duration::from_millis(duration_ms)))
                    }
                    "Linear" => {
                        let base_ms = base_ms.ok_or_else(|| de::Error::missing_field("base_ms"))?;
                        let increment_ms =
                            increment_ms.ok_or_else(|| de::Error::missing_field("increment_ms"))?;
                        let max_delay_ms =
                            max_delay_ms.ok_or_else(|| de::Error::missing_field("max_delay_ms"))?;
                        Ok(RetryStrategy::Linear {
                            base: Duration::from_millis(base_ms),
                            increment: Duration::from_millis(increment_ms),
                            max_delay: max_delay_ms.map(Duration::from_millis),
                        })
                    }
                    "Exponential" => {
                        let base_ms = base_ms.ok_or_else(|| de::Error::missing_field("base_ms"))?;
                        let multiplier =
                            multiplier.ok_or_else(|| de::Error::missing_field("multiplier"))?;
                        let max_delay_ms =
                            max_delay_ms.ok_or_else(|| de::Error::missing_field("max_delay_ms"))?;
                        let jitter = jitter.unwrap_or(None);
                        Ok(RetryStrategy::Exponential {
                            base: Duration::from_millis(base_ms),
                            multiplier,
                            max_delay: max_delay_ms.map(Duration::from_millis),
                            jitter,
                        })
                    }
                    "Fibonacci" => {
                        let base_ms = base_ms.ok_or_else(|| de::Error::missing_field("base_ms"))?;
                        let max_delay_ms =
                            max_delay_ms.ok_or_else(|| de::Error::missing_field("max_delay_ms"))?;
                        Ok(RetryStrategy::Fibonacci {
                            base: Duration::from_millis(base_ms),
                            max_delay: max_delay_ms.map(Duration::from_millis),
                        })
                    }
                    _ => Err(de::Error::unknown_variant(
                        &strategy_type,
                        &["Fixed", "Linear", "Exponential", "Fibonacci"],
                    )),
                }
            }
        }

        deserializer.deserialize_struct(
            "RetryStrategy",
            &[
                "type",
                "duration_ms",
                "base_ms",
                "increment_ms",
                "max_delay_ms",
                "multiplier",
                "jitter",
            ],
            RetryStrategyVisitor,
        )
    }
}

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

    #[test]
    fn test_fibonacci_sequence() {
        assert_eq!(fibonacci(0), 0);
        assert_eq!(fibonacci(1), 1);
        assert_eq!(fibonacci(2), 1);
        assert_eq!(fibonacci(3), 2);
        assert_eq!(fibonacci(4), 3);
        assert_eq!(fibonacci(5), 5);
        assert_eq!(fibonacci(6), 8);
        assert_eq!(fibonacci(7), 13);
        assert_eq!(fibonacci(8), 21);
        assert_eq!(fibonacci(9), 34);
        assert_eq!(fibonacci(10), 55);
    }

    #[test]
    fn test_fixed_retry_strategy() {
        let strategy = RetryStrategy::Fixed(Duration::from_secs(30));

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(30));
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(30));
        assert_eq!(strategy.calculate_delay(10), Duration::from_secs(30));
    }

    #[test]
    fn test_linear_retry_strategy() {
        let strategy = RetryStrategy::Linear {
            base: Duration::from_secs(10),
            increment: Duration::from_secs(5),
            max_delay: Some(Duration::from_secs(40)),
        };

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(15)); // 10 + (1 * 5)
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(20)); // 10 + (2 * 5)
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(25)); // 10 + (3 * 5)
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(40)); // Capped at max_delay
        assert_eq!(strategy.calculate_delay(10), Duration::from_secs(40)); // Still capped
    }

    #[test]
    fn test_exponential_retry_strategy() {
        let strategy = RetryStrategy::Exponential {
            base: Duration::from_secs(1),
            multiplier: 2.0,
            max_delay: Some(Duration::from_secs(60)),
            jitter: None,
        };

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(1)); // 1 * 2^0 = 1
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(2)); // 1 * 2^1 = 2
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(4)); // 1 * 2^2 = 4
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(8)); // 1 * 2^3 = 8
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(16)); // 1 * 2^4 = 16
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(32)); // 1 * 2^5 = 32
        assert_eq!(strategy.calculate_delay(7), Duration::from_secs(60)); // Capped at max_delay
        assert_eq!(strategy.calculate_delay(10), Duration::from_secs(60)); // Still capped
    }

    #[test]
    fn test_fibonacci_retry_strategy() {
        let strategy = RetryStrategy::Fibonacci {
            base: Duration::from_secs(2),
            max_delay: Some(Duration::from_secs(100)),
        };

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(2)); // 2 * 1 = 2
        assert_eq!(strategy.calculate_delay(2), Duration::from_secs(2)); // 2 * 1 = 2  
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(4)); // 2 * 2 = 4
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(6)); // 2 * 3 = 6
        assert_eq!(strategy.calculate_delay(5), Duration::from_secs(10)); // 2 * 5 = 10
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(16)); // 2 * 8 = 16
        assert_eq!(strategy.calculate_delay(7), Duration::from_secs(26)); // 2 * 13 = 26
    }

    #[test]
    fn test_custom_retry_strategy() {
        let strategy = RetryStrategy::Custom(Box::new(|attempt| match attempt {
            1..=3 => Duration::from_secs(5),
            4..=6 => Duration::from_secs(30),
            _ => Duration::from_secs(300),
        }));

        assert_eq!(strategy.calculate_delay(1), Duration::from_secs(5));
        assert_eq!(strategy.calculate_delay(3), Duration::from_secs(5));
        assert_eq!(strategy.calculate_delay(4), Duration::from_secs(30));
        assert_eq!(strategy.calculate_delay(6), Duration::from_secs(30));
        assert_eq!(strategy.calculate_delay(7), Duration::from_secs(300));
        assert_eq!(strategy.calculate_delay(100), Duration::from_secs(300));
    }

    #[test]
    fn test_additive_jitter() {
        let jitter = JitterType::Additive(Duration::from_secs(10));
        let base_delay = Duration::from_secs(60);

        // Test multiple applications to ensure it's within range
        for _ in 0..100 {
            let jittered = jitter.apply(base_delay);
            assert!(jittered >= Duration::from_secs(50)); // 60 - 10
            assert!(jittered <= Duration::from_secs(70)); // 60 + 10
        }
    }

    #[test]
    fn test_multiplicative_jitter() {
        let jitter = JitterType::Multiplicative(0.2); // ±20%
        let base_delay = Duration::from_secs(100);

        // Test multiple applications to ensure it's within range
        for _ in 0..100 {
            let jittered = jitter.apply(base_delay);
            assert!(jittered >= Duration::from_secs(80)); // 100 * 0.8
            assert!(jittered <= Duration::from_secs(120)); // 100 * 1.2
        }
    }

    #[test]
    fn test_exponential_with_jitter() {
        let strategy = RetryStrategy::Exponential {
            base: Duration::from_secs(1),
            multiplier: 2.0,
            max_delay: None,
            jitter: Some(JitterType::Multiplicative(0.1)), // ±10%
        };

        // Test first attempt (should be around 1 second ±10%)
        let delay = strategy.calculate_delay(1);
        assert!(delay >= Duration::from_millis(900)); // 1000ms * 0.9
        assert!(delay <= Duration::from_millis(1100)); // 1000ms * 1.1

        // Test third attempt (should be around 4 seconds ±10%)
        let delay = strategy.calculate_delay(3);
        assert!(delay >= Duration::from_millis(3600)); // 4000ms * 0.9
        assert!(delay <= Duration::from_millis(4400)); // 4000ms * 1.1
    }

    #[test]
    fn test_strategy_builder_methods() {
        let fixed = RetryStrategy::fixed(Duration::from_secs(30));
        assert_eq!(fixed.calculate_delay(1), Duration::from_secs(30));

        let linear = RetryStrategy::linear(
            Duration::from_secs(5),
            Duration::from_secs(10),
            Some(Duration::from_secs(120)),
        );
        assert_eq!(linear.calculate_delay(1), Duration::from_secs(15));

        let exponential =
            RetryStrategy::exponential(Duration::from_secs(1), 2.0, Some(Duration::from_secs(600)));
        assert_eq!(exponential.calculate_delay(1), Duration::from_secs(1));

        let fibonacci =
            RetryStrategy::fibonacci(Duration::from_secs(2), Some(Duration::from_secs(300)));
        assert_eq!(fibonacci.calculate_delay(1), Duration::from_secs(2));
    }

    #[test]
    fn test_minimum_delay_enforcement() {
        // Test that zero delays are converted to 1ms minimum
        let strategy = RetryStrategy::Custom(Box::new(|_| Duration::from_millis(0)));
        assert_eq!(strategy.calculate_delay(1), Duration::from_millis(1));
    }

    #[test]
    fn test_serialization() {
        let strategies = vec![
            RetryStrategy::Fixed(Duration::from_secs(30)),
            RetryStrategy::Linear {
                base: Duration::from_secs(10),
                increment: Duration::from_secs(5),
                max_delay: Some(Duration::from_secs(60)),
            },
            RetryStrategy::Exponential {
                base: Duration::from_secs(1),
                multiplier: 2.0,
                max_delay: Some(Duration::from_secs(600)),
                jitter: None, // No jitter for serialization test to avoid randomness
            },
            RetryStrategy::Fibonacci {
                base: Duration::from_secs(2),
                max_delay: Some(Duration::from_secs(300)),
            },
        ];

        for strategy in strategies {
            // Test that we can serialize and deserialize
            let serialized = serde_json::to_string(&strategy).unwrap();
            let deserialized: RetryStrategy = serde_json::from_str(&serialized).unwrap();

            // Test that behavior is preserved (except for Custom which can't be serialized)
            if !matches!(strategy, RetryStrategy::Custom(_)) {
                assert_eq!(strategy.calculate_delay(1), deserialized.calculate_delay(1));
                assert_eq!(strategy.calculate_delay(3), deserialized.calculate_delay(3));
            }
        }
    }
}