timer-lib 0.4.0

A feature-rich Rust library for creating and managing timers.
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
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
use async_trait::async_trait;
use std::collections::BTreeMap;
use std::future::Future;
use std::sync::{
    atomic::{AtomicBool, AtomicU64, Ordering},
    Arc,
};
use std::time::Duration;
use tokio::sync::{broadcast, mpsc, watch, Mutex};
use tokio::task::JoinHandle;
use tokio::time::Instant;

#[cfg(feature = "logging")]
use log::debug;

use crate::errors::TimerError;

pub(crate) mod driver;
mod runtime;

#[cfg(test)]
mod tests;

#[cfg(feature = "test-util")]
pub use driver::MockRuntime;

const TIMER_EVENT_BUFFER: usize = 64;

fn saturating_mul_duration(duration: Duration, multiplier: u32) -> Duration {
    let nanos = duration.as_nanos();
    let scaled = nanos.saturating_mul(multiplier as u128);
    let capped = scaled.min(u64::MAX as u128) as u64;
    Duration::from_nanos(capped)
}

/// Represents the state of a timer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimerState {
    Running,
    Paused,
    Stopped,
}

/// Indicates how a timer run ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimerFinishReason {
    Completed,
    Stopped,
    Cancelled,
    Replaced,
}

/// Statistics for a timer run.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TimerStatistics {
    /// Number of callback executions attempted during the current run.
    pub execution_count: usize,
    /// Number of successful callback executions.
    pub successful_executions: usize,
    /// Number of failed callback executions.
    pub failed_executions: usize,
    /// Total elapsed time since the current run started.
    pub elapsed_time: Duration,
    /// The most recent callback error observed in the current run.
    pub last_error: Option<TimerError>,
}

/// Describes the result of a completed timer run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimerOutcome {
    /// The completed run identifier.
    pub run_id: u64,
    /// The reason the run ended.
    pub reason: TimerFinishReason,
    /// Final run statistics.
    pub statistics: TimerStatistics,
}

/// Metadata attached to a timer for observability.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TimerMetadata {
    /// Optional human-readable label for the timer.
    pub label: Option<String>,
    /// Arbitrary key-value metadata associated with the timer.
    pub tags: BTreeMap<String, String>,
}

/// Snapshot of the current or most recent timer state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimerSnapshot {
    /// The timer state observed for the snapshot.
    pub state: TimerState,
    /// The effective interval configured for the timer.
    pub interval: Duration,
    /// The optional recurring execution limit.
    pub expiration_count: Option<usize>,
    /// Statistics for the current or most recent run.
    pub statistics: TimerStatistics,
    /// The most recent completed outcome, if any.
    pub last_outcome: Option<TimerOutcome>,
    /// Metadata associated with the timer.
    pub metadata: TimerMetadata,
}

/// Defines how recurring timers schedule the next execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RecurringCadence {
    FixedDelay,
    FixedRate,
}

/// Configures the schedule for a recurring timer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecurringSchedule {
    interval: Duration,
    initial_delay: Option<Duration>,
    cadence: RecurringCadence,
    expiration_count: Option<usize>,
    jitter: Option<Duration>,
}

impl RecurringSchedule {
    /// Creates a recurring schedule from a fixed interval.
    pub fn new(interval: Duration) -> Self {
        Self {
            interval,
            initial_delay: None,
            cadence: RecurringCadence::FixedDelay,
            expiration_count: None,
            jitter: None,
        }
    }

    /// Returns the recurring interval.
    pub fn interval(self) -> Duration {
        self.interval
    }

    /// Returns the initial delay before the first execution.
    pub fn initial_delay(self) -> Option<Duration> {
        self.initial_delay
    }

    /// Returns the cadence used for the recurring schedule.
    pub fn cadence(self) -> RecurringCadence {
        self.cadence
    }

    /// Returns the optional execution limit.
    pub fn expiration_count(self) -> Option<usize> {
        self.expiration_count
    }

    /// Returns the optional jitter applied to recurring sleeps.
    pub fn jitter(self) -> Option<Duration> {
        self.jitter
    }

    /// Sets an initial delay before the first recurring execution.
    pub fn with_initial_delay(mut self, initial_delay: Duration) -> Self {
        self.initial_delay = Some(initial_delay);
        self
    }

    /// Sets the cadence used for subsequent executions.
    pub fn with_cadence(mut self, cadence: RecurringCadence) -> Self {
        self.cadence = cadence;
        self
    }

    /// Uses fixed-delay cadence semantics.
    pub fn fixed_delay(mut self) -> Self {
        self.cadence = RecurringCadence::FixedDelay;
        self
    }

    /// Uses fixed-rate cadence semantics.
    pub fn fixed_rate(mut self) -> Self {
        self.cadence = RecurringCadence::FixedRate;
        self
    }

    /// Limits the number of recurring executions.
    pub fn with_expiration_count(mut self, expiration_count: usize) -> Self {
        self.expiration_count = Some(expiration_count);
        self
    }

    /// Adds bounded jitter to recurring delays.
    pub fn with_jitter(mut self, jitter: Duration) -> Self {
        self.jitter = Some(jitter);
        self
    }
}

/// Configures retry behavior for failed callback executions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryPolicy {
    max_retries: usize,
    backoff: RetryBackoff,
}

impl RetryPolicy {
    /// Creates a retry policy with the provided retry limit.
    pub fn new(max_retries: usize) -> Self {
        Self {
            max_retries,
            backoff: RetryBackoff::Immediate,
        }
    }

    /// Returns the maximum number of retry attempts after the first failure.
    pub fn max_retries(self) -> usize {
        self.max_retries
    }

    /// Returns the configured retry backoff strategy.
    pub fn backoff(self) -> RetryBackoff {
        self.backoff
    }

    /// Sets the backoff strategy used between retry attempts.
    pub fn with_backoff(mut self, backoff: RetryBackoff) -> Self {
        self.backoff = backoff;
        self
    }

    fn delay_for_retry(self, retry_number: usize) -> Duration {
        self.backoff.delay_for_retry(retry_number)
    }
}

/// Defines how retries should back off after callback failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryBackoff {
    Immediate,
    Fixed(Duration),
    Linear(Duration),
    Exponential(Duration),
}

impl RetryBackoff {
    fn delay_for_retry(self, retry_number: usize) -> Duration {
        match self {
            Self::Immediate => Duration::ZERO,
            Self::Fixed(delay) => delay,
            Self::Linear(step) => saturating_mul_duration(step, retry_number as u32),
            Self::Exponential(base) => {
                let exponent = retry_number.saturating_sub(1) as u32;
                let multiplier = 1_u32.checked_shl(exponent.min(31)).unwrap_or(u32::MAX);
                saturating_mul_duration(base, multiplier)
            }
        }
    }
}

/// Event stream item produced by a timer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimerEvent {
    Started {
        run_id: u64,
        interval: Duration,
        recurring: bool,
        expiration_count: Option<usize>,
        metadata: TimerMetadata,
    },
    Paused {
        run_id: u64,
    },
    Resumed {
        run_id: u64,
    },
    IntervalAdjusted {
        run_id: u64,
        interval: Duration,
    },
    Tick {
        run_id: u64,
        statistics: TimerStatistics,
    },
    CallbackFailed {
        run_id: u64,
        error: TimerError,
        statistics: TimerStatistics,
    },
    Finished(TimerOutcome),
}

/// Subscription handle for timer events.
pub struct TimerEvents {
    receiver: broadcast::Receiver<TimerEvent>,
}

impl TimerEvents {
    /// Attempts to receive the next timer event without waiting.
    pub fn try_recv(&mut self) -> Option<TimerEvent> {
        loop {
            match self.receiver.try_recv() {
                Ok(event) => return Some(event),
                Err(broadcast::error::TryRecvError::Lagged(_)) => continue,
                Err(broadcast::error::TryRecvError::Empty)
                | Err(broadcast::error::TryRecvError::Closed) => return None,
            }
        }
    }

    /// Waits for the next timer event.
    pub async fn recv(&mut self) -> Option<TimerEvent> {
        loop {
            match self.receiver.recv().await {
                Ok(event) => return Some(event),
                Err(broadcast::error::RecvError::Lagged(_)) => continue,
                Err(broadcast::error::RecvError::Closed) => return None,
            }
        }
    }

    /// Waits for the next start event.
    pub async fn wait_started(&mut self) -> Option<TimerEvent> {
        loop {
            if let event @ TimerEvent::Started { .. } = self.recv().await? {
                return Some(event);
            }
        }
    }

    /// Waits for the next tick event.
    pub async fn wait_tick(&mut self) -> Option<TimerEvent> {
        loop {
            if let event @ TimerEvent::Tick { .. } = self.recv().await? {
                return Some(event);
            }
        }
    }

    /// Waits for the next paused event.
    pub async fn wait_paused(&mut self) -> Option<TimerEvent> {
        loop {
            if let event @ TimerEvent::Paused { .. } = self.recv().await? {
                return Some(event);
            }
        }
    }

    /// Waits for the next resumed event.
    pub async fn wait_resumed(&mut self) -> Option<TimerEvent> {
        loop {
            if let event @ TimerEvent::Resumed { .. } = self.recv().await? {
                return Some(event);
            }
        }
    }

    /// Waits for the next finished event.
    pub async fn wait_finished(&mut self) -> Option<TimerOutcome> {
        loop {
            if let TimerEvent::Finished(outcome) = self.recv().await? {
                return Some(outcome);
            }
        }
    }

    /// Waits for the next finished event with a stopped outcome.
    pub async fn wait_stopped(&mut self) -> Option<TimerOutcome> {
        self.wait_finished_reason(TimerFinishReason::Stopped).await
    }

    /// Waits for the next finished event with a cancelled outcome.
    pub async fn wait_cancelled(&mut self) -> Option<TimerOutcome> {
        self.wait_finished_reason(TimerFinishReason::Cancelled)
            .await
    }

    async fn wait_finished_reason(&mut self, reason: TimerFinishReason) -> Option<TimerOutcome> {
        loop {
            let outcome = self.wait_finished().await?;
            if outcome.reason == reason {
                return Some(outcome);
            }
        }
    }
}

/// Lossless subscription handle for completed timer runs.
pub struct TimerCompletion {
    receiver: watch::Receiver<Option<TimerOutcome>>,
}

impl TimerCompletion {
    /// Returns the latest completed outcome, if one has been observed.
    pub fn latest(&self) -> Option<TimerOutcome> {
        self.receiver.borrow().clone()
    }

    /// Waits for the next unseen completed outcome.
    pub async fn wait(&mut self) -> Option<TimerOutcome> {
        loop {
            if let Some(outcome) = self.receiver.borrow_and_update().clone() {
                return Some(outcome);
            }

            if self.receiver.changed().await.is_err() {
                return self.receiver.borrow_and_update().clone();
            }
        }
    }

    /// Waits for a specific run to complete.
    pub async fn wait_for_run(&mut self, run_id: u64) -> Option<TimerOutcome> {
        loop {
            let outcome = self.wait().await?;
            if outcome.run_id == run_id {
                return Some(outcome);
            }
        }
    }
}

/// A trait for timer callbacks.
#[async_trait]
pub trait TimerCallback: Send + Sync {
    /// The function to execute when the timer triggers.
    async fn execute(&self) -> Result<(), TimerError>;
}

#[async_trait]
impl<F, Fut> TimerCallback for F
where
    F: Fn() -> Fut + Send + Sync,
    Fut: Future<Output = Result<(), TimerError>> + Send,
{
    async fn execute(&self) -> Result<(), TimerError> {
        (self)().await
    }
}

pub(super) enum TimerCommand {
    Pause,
    Resume,
    Stop,
    Cancel,
    SetInterval(Duration),
}

pub(super) struct TimerInner {
    pub(super) state: Mutex<TimerState>,
    pub(super) handle: Mutex<Option<JoinHandle<()>>>,
    pub(super) command_tx: Mutex<Option<mpsc::UnboundedSender<TimerCommand>>>,
    pub(super) interval: Mutex<Duration>,
    pub(super) expiration_count: Mutex<Option<usize>>,
    pub(super) metadata: Mutex<TimerMetadata>,
    pub(super) statistics: Mutex<TimerStatistics>,
    pub(super) last_outcome: Mutex<Option<TimerOutcome>>,
    pub(super) completion_tx: watch::Sender<Option<TimerOutcome>>,
    pub(super) event_tx: broadcast::Sender<TimerEvent>,
    pub(super) events_enabled: AtomicBool,
    pub(super) runtime: driver::RuntimeHandle,
    pub(super) next_run_id: AtomicU64,
    pub(super) active_run_id: AtomicU64,
}

#[derive(Debug, Clone)]
pub(super) struct RunConfig {
    pub(super) interval: Duration,
    pub(super) start_deadline: Option<Instant>,
    pub(super) initial_delay: Option<Duration>,
    pub(super) jitter: Option<Duration>,
    pub(super) callback_timeout: Option<Duration>,
    pub(super) retry_policy: Option<RetryPolicy>,
    pub(super) recurring: bool,
    pub(super) cadence: RecurringCadence,
    pub(super) expiration_count: Option<usize>,
    pub(super) metadata: TimerMetadata,
}

#[derive(Debug, Clone, Copy)]
enum TimerKind {
    Once(Duration),
    At(Instant),
    Recurring(RecurringSchedule),
}

/// Builds and starts a timer with less boilerplate.
pub struct TimerBuilder {
    kind: TimerKind,
    callback_timeout: Option<Duration>,
    retry_policy: Option<RetryPolicy>,
    start_paused: bool,
    events_enabled: bool,
    metadata: TimerMetadata,
}

#[derive(Clone)]
/// Timer handle for managing one-time and recurring tasks.
pub struct Timer {
    inner: Arc<TimerInner>,
}

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

impl Timer {
    /// Creates a new timer.
    pub fn new() -> Self {
        Self::new_with_runtime(driver::RuntimeHandle::default(), true)
    }

    /// Creates a new timer with broadcast events disabled.
    pub fn new_silent() -> Self {
        Self::new_with_runtime(driver::RuntimeHandle::default(), false)
    }

    pub(crate) fn new_with_runtime(runtime: driver::RuntimeHandle, events_enabled: bool) -> Self {
        let (completion_tx, _completion_rx) = watch::channel(None);
        let (event_tx, _event_rx) = broadcast::channel(TIMER_EVENT_BUFFER);

        Self {
            inner: Arc::new(TimerInner {
                state: Mutex::new(TimerState::Stopped),
                handle: Mutex::new(None),
                command_tx: Mutex::new(None),
                interval: Mutex::new(Duration::ZERO),
                expiration_count: Mutex::new(None),
                metadata: Mutex::new(TimerMetadata::default()),
                statistics: Mutex::new(TimerStatistics::default()),
                last_outcome: Mutex::new(None),
                completion_tx,
                event_tx,
                events_enabled: AtomicBool::new(events_enabled),
                runtime,
                next_run_id: AtomicU64::new(1),
                active_run_id: AtomicU64::new(0),
            }),
        }
    }

    /// Creates a timer builder configured for a one-time run.
    pub fn once(delay: Duration) -> TimerBuilder {
        TimerBuilder::once(delay)
    }

    /// Creates a timer builder configured for a one-time run at a deadline.
    pub fn at(deadline: Instant) -> TimerBuilder {
        TimerBuilder::at(deadline)
    }

    /// Creates a timer builder configured for a recurring schedule.
    pub fn recurring(schedule: RecurringSchedule) -> TimerBuilder {
        TimerBuilder::recurring(schedule)
    }

    /// Subscribes to future timer events.
    pub fn subscribe(&self) -> TimerEvents {
        TimerEvents {
            receiver: self.inner.event_tx.subscribe(),
        }
    }

    /// Subscribes to completed runs without loss.
    pub fn completion(&self) -> TimerCompletion {
        TimerCompletion {
            receiver: self.inner.completion_tx.subscribe(),
        }
    }

    /// Creates a new timer backed by a manually-driven test runtime.
    #[cfg(feature = "test-util")]
    pub fn new_mocked() -> (Self, MockRuntime) {
        let runtime = MockRuntime::new();
        (Self::new_with_runtime(runtime.handle(), true), runtime)
    }

    /// Starts a one-time timer.
    pub async fn start_once<F>(&self, delay: Duration, callback: F) -> Result<u64, TimerError>
    where
        F: TimerCallback + 'static,
    {
        let metadata = self.inner.metadata.lock().await.clone();
        self.start_internal(
            RunConfig {
                interval: delay,
                start_deadline: None,
                initial_delay: None,
                jitter: None,
                callback_timeout: None,
                retry_policy: None,
                recurring: false,
                cadence: RecurringCadence::FixedDelay,
                expiration_count: None,
                metadata,
            },
            callback,
            false,
        )
        .await
    }

    /// Starts a one-time timer from an async closure.
    pub async fn start_once_fn<F, Fut>(
        &self,
        delay: Duration,
        callback: F,
    ) -> Result<u64, TimerError>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), TimerError>> + Send + 'static,
    {
        self.start_once(delay, callback).await
    }

    /// Starts a one-time timer that fires at the provided deadline.
    pub async fn start_at<F>(&self, deadline: Instant, callback: F) -> Result<u64, TimerError>
    where
        F: TimerCallback + 'static,
    {
        let now = self.inner.runtime.now();
        let metadata = self.inner.metadata.lock().await.clone();
        self.start_internal(
            RunConfig {
                interval: deadline.saturating_duration_since(now),
                start_deadline: Some(deadline),
                initial_delay: None,
                jitter: None,
                callback_timeout: None,
                retry_policy: None,
                recurring: false,
                cadence: RecurringCadence::FixedDelay,
                expiration_count: None,
                metadata,
            },
            callback,
            false,
        )
        .await
    }

    /// Starts a one-time timer from an async closure at the provided deadline.
    pub async fn start_at_fn<F, Fut>(
        &self,
        deadline: Instant,
        callback: F,
    ) -> Result<u64, TimerError>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), TimerError>> + Send + 'static,
    {
        self.start_at(deadline, callback).await
    }

    /// Starts a recurring timer with the provided schedule.
    pub async fn start_recurring<F>(
        &self,
        schedule: RecurringSchedule,
        callback: F,
    ) -> Result<u64, TimerError>
    where
        F: TimerCallback + 'static,
    {
        let metadata = self.inner.metadata.lock().await.clone();
        self.start_internal(
            RunConfig {
                interval: schedule.interval,
                start_deadline: None,
                initial_delay: schedule.initial_delay,
                jitter: schedule.jitter,
                callback_timeout: None,
                retry_policy: None,
                recurring: true,
                cadence: schedule.cadence,
                expiration_count: schedule.expiration_count,
                metadata,
            },
            callback,
            false,
        )
        .await
    }

    /// Starts a recurring timer from an async closure.
    pub async fn start_recurring_fn<F, Fut>(
        &self,
        schedule: RecurringSchedule,
        callback: F,
    ) -> Result<u64, TimerError>
    where
        F: Fn() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<(), TimerError>> + Send + 'static,
    {
        self.start_recurring(schedule, callback).await
    }

    /// Pauses a running timer.
    pub async fn pause(&self) -> Result<(), TimerError> {
        self.ensure_not_reentrant(
            "pause() cannot be awaited from the timer's active callback; use request_pause().",
        )?;
        self.request_pause().await
    }

    /// Requests that the current run pause after the current callback or sleep edge.
    pub async fn request_pause(&self) -> Result<(), TimerError> {
        let _run_id = self
            .active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;
        let mut state = self.inner.state.lock().await;
        if *state != TimerState::Running {
            return Err(TimerError::not_running());
        }

        *state = TimerState::Paused;
        drop(state);

        self.send_command(TimerCommand::Pause).await;

        #[cfg(feature = "logging")]
        debug!("Timer paused.");

        Ok(())
    }

    /// Resumes a paused timer.
    pub async fn resume(&self) -> Result<(), TimerError> {
        self.ensure_not_reentrant(
            "resume() cannot be awaited from the timer's active callback; use request_resume().",
        )?;
        self.request_resume().await
    }

    /// Requests that a paused timer resume.
    pub async fn request_resume(&self) -> Result<(), TimerError> {
        let _run_id = self
            .active_run_id()
            .await
            .ok_or_else(TimerError::not_paused)?;
        let mut state = self.inner.state.lock().await;
        if *state != TimerState::Paused {
            return Err(TimerError::not_paused());
        }

        *state = TimerState::Running;
        drop(state);

        self.send_command(TimerCommand::Resume).await;

        #[cfg(feature = "logging")]
        debug!("Timer resumed.");

        Ok(())
    }

    /// Stops the timer after the current callback finishes.
    pub async fn stop(&self) -> Result<TimerOutcome, TimerError> {
        self.ensure_not_reentrant(
            "stop() cannot be awaited from the timer's active callback; use request_stop().",
        )?;
        let run_id = self
            .active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;
        self.request_stop().await?;
        self.join_run(run_id).await
    }

    /// Requests a graceful stop without waiting for the outcome.
    pub async fn request_stop(&self) -> Result<(), TimerError> {
        self.active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;
        self.send_command(TimerCommand::Stop).await;
        Ok(())
    }

    /// Cancels the timer immediately and aborts the callback task.
    pub async fn cancel(&self) -> Result<TimerOutcome, TimerError> {
        self.ensure_not_reentrant(
            "cancel() cannot be awaited from the timer's active callback; use request_cancel().",
        )?;
        self.cancel_with_reason(TimerFinishReason::Cancelled).await
    }

    /// Requests cancellation without aborting the active callback task.
    pub async fn request_cancel(&self) -> Result<(), TimerError> {
        self.active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;
        self.send_command(TimerCommand::Cancel).await;
        Ok(())
    }

    /// Adjusts the interval of a running or paused timer.
    pub async fn adjust_interval(&self, new_interval: Duration) -> Result<(), TimerError> {
        self.ensure_not_reentrant(
            "adjust_interval() cannot be awaited from the timer's active callback; use request_adjust_interval().",
        )?;
        self.request_adjust_interval(new_interval).await
    }

    /// Requests an interval adjustment for the current run.
    pub async fn request_adjust_interval(&self, new_interval: Duration) -> Result<(), TimerError> {
        if new_interval.is_zero() {
            return Err(TimerError::invalid_parameter(
                "Interval must be greater than zero.",
            ));
        }

        let run_id = self
            .active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;
        *self.inner.interval.lock().await = new_interval;
        self.send_command(TimerCommand::SetInterval(new_interval))
            .await;
        runtime::emit_event(
            &self.inner,
            TimerEvent::IntervalAdjusted {
                run_id,
                interval: new_interval,
            },
        );

        #[cfg(feature = "logging")]
        debug!("Timer interval adjusted.");

        Ok(())
    }

    /// Waits for the current run and returns the completed outcome.
    pub async fn join(&self) -> Result<TimerOutcome, TimerError> {
        self.ensure_not_reentrant(
            "join() cannot be awaited from the timer's active callback; use completion().wait() from another task instead.",
        )?;
        if let Some(run_id) = self.active_run_id().await {
            return self.join_run(run_id).await;
        }

        self.inner
            .last_outcome
            .lock()
            .await
            .clone()
            .ok_or_else(TimerError::not_running)
    }

    /// Waits until the current run has completed or been stopped.
    pub async fn wait(&self) {
        let _ = self.join().await;
    }

    /// Gets the timer's statistics for the current or most recent run.
    pub async fn get_statistics(&self) -> TimerStatistics {
        self.inner.statistics.lock().await.clone()
    }

    /// Gets the current state of the timer.
    pub async fn get_state(&self) -> TimerState {
        *self.inner.state.lock().await
    }

    /// Gets the timer interval for the current or next run.
    pub async fn get_interval(&self) -> Duration {
        *self.inner.interval.lock().await
    }

    /// Gets the configured expiration count for the current or next run.
    pub async fn get_expiration_count(&self) -> Option<usize> {
        *self.inner.expiration_count.lock().await
    }

    /// Gets the most recent callback error observed for the current or most recent run.
    pub async fn get_last_error(&self) -> Option<TimerError> {
        self.inner.statistics.lock().await.last_error.clone()
    }

    /// Returns the metadata currently associated with the timer.
    pub async fn metadata(&self) -> TimerMetadata {
        self.inner.metadata.lock().await.clone()
    }

    /// Returns the current label, if one has been assigned.
    pub async fn label(&self) -> Option<String> {
        self.inner.metadata.lock().await.label.clone()
    }

    /// Sets the timer label used for diagnostics and registry introspection.
    pub async fn set_label(&self, label: impl Into<String>) {
        self.inner.metadata.lock().await.label = Some(label.into());
    }

    /// Sets or replaces a metadata tag on the timer.
    pub async fn set_tag(&self, key: impl Into<String>, value: impl Into<String>) {
        self.inner
            .metadata
            .lock()
            .await
            .tags
            .insert(key.into(), value.into());
    }

    /// Captures a snapshot of the timer's current observable state.
    pub async fn snapshot(&self) -> TimerSnapshot {
        TimerSnapshot {
            state: self.get_state().await,
            interval: self.get_interval().await,
            expiration_count: self.get_expiration_count().await,
            statistics: self.get_statistics().await,
            last_outcome: self.last_outcome().await,
            metadata: self.metadata().await,
        }
    }

    /// Gets the most recent completed run outcome.
    pub async fn last_outcome(&self) -> Option<TimerOutcome> {
        self.inner.last_outcome.lock().await.clone()
    }

    /// Enables or disables broadcast event emission for future runtime events.
    pub fn set_events_enabled(&self, enabled: bool) {
        self.inner.events_enabled.store(enabled, Ordering::SeqCst);
    }

    async fn start_internal<F>(
        &self,
        config: RunConfig,
        callback: F,
        start_paused: bool,
    ) -> Result<u64, TimerError>
    where
        F: TimerCallback + 'static,
    {
        if config.interval.is_zero() && config.start_deadline.is_none() {
            return Err(TimerError::invalid_parameter(
                "Interval must be greater than zero.",
            ));
        }

        if config.recurring && matches!(config.expiration_count, Some(0)) {
            return Err(TimerError::invalid_parameter(
                "Expiration count must be greater than zero.",
            ));
        }

        if config.initial_delay.is_some_and(|delay| delay.is_zero()) {
            return Err(TimerError::invalid_parameter(
                "Initial delay must be greater than zero.",
            ));
        }

        if config.jitter.is_some_and(|jitter| jitter.is_zero()) {
            return Err(TimerError::invalid_parameter(
                "Jitter must be greater than zero.",
            ));
        }

        if config
            .callback_timeout
            .is_some_and(|timeout| timeout.is_zero())
        {
            return Err(TimerError::invalid_parameter(
                "Callback timeout must be greater than zero.",
            ));
        }

        if config.retry_policy.is_some_and(|policy| {
            matches!(
                policy.backoff(),
                RetryBackoff::Fixed(duration)
                    | RetryBackoff::Linear(duration)
                    | RetryBackoff::Exponential(duration) if duration.is_zero()
            )
        }) {
            return Err(TimerError::invalid_parameter(
                "Retry backoff must be greater than zero.",
            ));
        }

        self.ensure_not_reentrant(
            "starting a new run from the timer's active callback is not supported; spawn a separate task instead.",
        )?;

        let _ = self.cancel_with_reason(TimerFinishReason::Replaced).await;

        let run_id = self.inner.next_run_id.fetch_add(1, Ordering::SeqCst);
        let (tx, rx) = mpsc::unbounded_channel();

        {
            *self.inner.state.lock().await = if start_paused {
                TimerState::Paused
            } else {
                TimerState::Running
            };
            *self.inner.command_tx.lock().await = Some(tx);
            *self.inner.interval.lock().await = config.interval;
            *self.inner.expiration_count.lock().await = config.expiration_count;
            *self.inner.metadata.lock().await = config.metadata.clone();
            *self.inner.statistics.lock().await = TimerStatistics::default();
            *self.inner.last_outcome.lock().await = None;
            self.inner.completion_tx.send_replace(None);
        }
        self.inner.active_run_id.store(run_id, Ordering::SeqCst);

        runtime::emit_event(
            &self.inner,
            TimerEvent::Started {
                run_id,
                interval: config.interval,
                recurring: config.recurring,
                expiration_count: config.expiration_count,
                metadata: config.metadata.clone(),
            },
        );

        let inner = Arc::clone(&self.inner);
        let handle = self.inner.runtime.spawn(async move {
            let scoped_inner = Arc::clone(&inner);
            runtime::with_run_context(&scoped_inner, run_id, async move {
                runtime::run_timer(inner, run_id, config, callback, rx).await;
            })
            .await;
        });

        *self.inner.handle.lock().await = Some(handle);

        #[cfg(feature = "logging")]
        debug!("Timer started.");

        Ok(run_id)
    }

    async fn active_run_id(&self) -> Option<u64> {
        match self.inner.active_run_id.load(Ordering::SeqCst) {
            0 => None,
            run_id => Some(run_id),
        }
    }

    async fn send_command(&self, command: TimerCommand) {
        if let Some(tx) = self.inner.command_tx.lock().await.as_ref() {
            let _ = tx.send(command);
        }
    }

    fn ensure_not_reentrant(&self, message: &'static str) -> Result<(), TimerError> {
        if runtime::is_current_run(&self.inner) {
            return Err(TimerError::reentrant_operation(message));
        }

        Ok(())
    }

    async fn cancel_with_reason(
        &self,
        reason: TimerFinishReason,
    ) -> Result<TimerOutcome, TimerError> {
        let run_id = self
            .active_run_id()
            .await
            .ok_or_else(TimerError::not_running)?;

        let _ = self.inner.command_tx.lock().await.take();
        let handle = self.inner.handle.lock().await.take();
        *self.inner.state.lock().await = TimerState::Stopped;

        if let Some(handle) = handle {
            handle.abort();
            let _ = handle.await;
        }

        let statistics = self.get_statistics().await;
        let outcome = TimerOutcome {
            run_id,
            reason,
            statistics,
        };

        runtime::finish_run(&self.inner, outcome.clone()).await;
        Ok(outcome)
    }

    async fn join_run(&self, run_id: u64) -> Result<TimerOutcome, TimerError> {
        let mut completion_rx = self.inner.completion_tx.subscribe();

        loop {
            if let Some(outcome) = completion_rx.borrow().clone() {
                if outcome.run_id == run_id {
                    return Ok(outcome);
                }
            }

            if completion_rx.changed().await.is_err() {
                return completion_rx
                    .borrow()
                    .clone()
                    .ok_or_else(TimerError::not_running);
            }
        }
    }
}

impl TimerBuilder {
    /// Creates a builder for a one-time timer.
    pub fn once(delay: Duration) -> Self {
        Self {
            kind: TimerKind::Once(delay),
            callback_timeout: None,
            retry_policy: None,
            start_paused: false,
            events_enabled: true,
            metadata: TimerMetadata::default(),
        }
    }

    /// Creates a builder for a one-time timer at a deadline.
    pub fn at(deadline: Instant) -> Self {
        Self {
            kind: TimerKind::At(deadline),
            callback_timeout: None,
            retry_policy: None,
            start_paused: false,
            events_enabled: true,
            metadata: TimerMetadata::default(),
        }
    }

    /// Creates a builder for a recurring schedule.
    pub fn recurring(schedule: RecurringSchedule) -> Self {
        Self {
            kind: TimerKind::Recurring(schedule),
            callback_timeout: None,
            retry_policy: None,
            start_paused: false,
            events_enabled: true,
            metadata: TimerMetadata::default(),
        }
    }

    /// Sets a timeout for each callback execution.
    pub fn callback_timeout(mut self, callback_timeout: Duration) -> Self {
        self.callback_timeout = Some(callback_timeout);
        self
    }

    /// Retries failed callback executions according to the provided policy.
    pub fn retry_policy(mut self, retry_policy: RetryPolicy) -> Self {
        self.retry_policy = Some(retry_policy);
        self
    }

    /// Retries failed callback executions up to `max_retries` times.
    pub fn max_retries(mut self, max_retries: usize) -> Self {
        self.retry_policy = Some(RetryPolicy::new(max_retries));
        self
    }

    /// Applies a fixed delay between retry attempts.
    pub fn fixed_backoff(mut self, delay: Duration) -> Self {
        self.retry_policy = Some(
            self.retry_policy
                .unwrap_or_else(|| RetryPolicy::new(0))
                .with_backoff(RetryBackoff::Fixed(delay)),
        );
        self
    }

    /// Applies a linearly increasing delay between retry attempts.
    pub fn linear_backoff(mut self, step: Duration) -> Self {
        self.retry_policy = Some(
            self.retry_policy
                .unwrap_or_else(|| RetryPolicy::new(0))
                .with_backoff(RetryBackoff::Linear(step)),
        );
        self
    }

    /// Applies an exponentially increasing delay between retry attempts.
    pub fn exponential_backoff(mut self, base: Duration) -> Self {
        self.retry_policy = Some(
            self.retry_policy
                .unwrap_or_else(|| RetryPolicy::new(0))
                .with_backoff(RetryBackoff::Exponential(base)),
        );
        self
    }

    /// Starts the timer in the paused state.
    pub fn paused_start(mut self) -> Self {
        self.start_paused = true;
        self
    }

    /// Disables broadcast event emission for the timer.
    pub fn with_events_disabled(mut self) -> Self {
        self.events_enabled = false;
        self
    }

    /// Sets a label for the started timer.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.metadata.label = Some(label.into());
        self
    }

    /// Adds a metadata tag for the started timer.
    pub fn tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.tags.insert(key.into(), value.into());
        self
    }

    /// Starts the configured timer and returns the handle.
    pub async fn start<F>(self, callback: F) -> Result<Timer, TimerError>
    where
        F: TimerCallback + 'static,
    {
        let Self {
            kind,
            callback_timeout,
            retry_policy,
            start_paused,
            events_enabled,
            metadata,
        } = self;

        let timer = Timer::new_with_runtime(driver::RuntimeHandle::default(), events_enabled);
        if start_paused {
            *timer.inner.state.lock().await = TimerState::Paused;
        }

        match kind {
            TimerKind::Once(delay) => {
                let _ = timer
                    .start_internal(
                        RunConfig {
                            interval: delay,
                            start_deadline: None,
                            initial_delay: None,
                            jitter: None,
                            callback_timeout,
                            retry_policy,
                            recurring: false,
                            cadence: RecurringCadence::FixedDelay,
                            expiration_count: None,
                            metadata: metadata.clone(),
                        },
                        callback,
                        start_paused,
                    )
                    .await?;
            }
            TimerKind::At(deadline) => {
                let now = timer.inner.runtime.now();
                let _ = timer
                    .start_internal(
                        RunConfig {
                            interval: deadline.saturating_duration_since(now),
                            start_deadline: Some(deadline),
                            initial_delay: None,
                            jitter: None,
                            callback_timeout,
                            retry_policy,
                            recurring: false,
                            cadence: RecurringCadence::FixedDelay,
                            expiration_count: None,
                            metadata: metadata.clone(),
                        },
                        callback,
                        start_paused,
                    )
                    .await?;
            }
            TimerKind::Recurring(schedule) => {
                let _ = timer
                    .start_internal(
                        RunConfig {
                            interval: schedule.interval,
                            start_deadline: None,
                            initial_delay: schedule.initial_delay,
                            jitter: schedule.jitter,
                            callback_timeout,
                            retry_policy,
                            recurring: true,
                            cadence: schedule.cadence,
                            expiration_count: schedule.expiration_count,
                            metadata,
                        },
                        callback,
                        start_paused,
                    )
                    .await?;
            }
        }
        Ok(timer)
    }
}