metrique 0.1.12

Library for generating unit of work metrics
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use std::{
    marker::PhantomData,
    ops::AddAssign,
    sync::{Arc, Mutex},
    time::{Duration, UNIX_EPOCH},
};

use metrique_core::CloseValue;
use metrique_timesource::{Instant, SystemTime, TimeSource, time_source};
use metrique_writer_core::{
    Value,
    unit::{Millisecond, Second},
};
use metrique_writer_core::{unit::Microsecond, value::ValueFormatter};
use timestamp_to_str::TimestampToStr;

/// Timestamp of a metric entry
///
/// This type should with `#[metrics(timestamp)]` attribute on the root of your metrics entry.
/// Unless otherwise specified, it will record the time that it was created at. If you need to record a different time,
/// use [`Timestamp::new`].
///
/// When used as a field (without the `#[metrics(timestamp)]` attribute), `Timestamp` will record a `value` field (not a metric)
/// containing the current timestamp. By default, `Timestamp` will report units of [`Millisecond`]. You can control the unit with the `unit` attribute.
#[derive(Debug)]
pub struct Timestamp {
    time: SystemTime,
}

impl Timestamp {
    /// Create a new timestamp at the current time.
    ///
    /// The time will be loaded from [`metrique_timesource::time_source`]
    ///
    /// This is the behavior of `Timestamp::default`
    pub fn now() -> Self {
        Self::new_from_time_source(time_source())
    }

    /// Create a new timestamp at a specific time
    pub fn new(time: SystemTime) -> Self {
        Self { time }
    }

    /// Create a new timestamp at a specific time from an explicit [`TimeSource`]
    ///
    /// # Examples
    /// ```rust
    /// use std::time::UNIX_EPOCH;
    /// use metrique_timesource::{TimeSource, fakes::StaticTimeSource};
    /// use metrique::timers::Timestamp;
    /// let ts = TimeSource::custom(StaticTimeSource::at_time(UNIX_EPOCH));
    /// let timestamp = Timestamp::new_from_time_source(ts);
    /// ```
    pub fn new_from_time_source(ts: TimeSource) -> Self {
        Self {
            time: ts.system_time(),
        }
    }
}

impl CloseValue for &'_ Timestamp {
    type Closed = TimestampValue;

    fn close(self) -> Self::Closed {
        TimestampValue::new(&self.time)
    }
}

impl CloseValue for Timestamp {
    type Closed = TimestampValue;

    fn close(self) -> Self::Closed {
        <&Self>::close(&self)
    }
}

impl Default for Timestamp {
    fn default() -> Self {
        Self::now()
    }
}

/// A `Timestamp` which records the time when the record is closed
///
/// When combined with [`Timestamp`], this is a useful tool for to record when
/// an event starts and stops for post-hoc analysis.
///
/// # Examples
/// ```rust
/// use metrique::unit_of_work::metrics;
/// use metrique::timers::{Timestamp, TimestampOnClose};
///
/// #[metrics]
/// struct TrackStartStop {
///     start: Timestamp,
///     stop: TimestampOnClose
/// }
/// ```
pub struct TimestampOnClose {
    time_source: TimeSource,
}

impl Default for TimestampOnClose {
    fn default() -> Self {
        Self {
            time_source: time_source(),
        }
    }
}

impl CloseValue for TimestampOnClose {
    type Closed = TimestampValue;

    fn close(self) -> Self::Closed {
        TimestampValue::new(&self.time_source.system_time())
    }
}

/// Formats a timestamp in `EpochSeconds` format
pub type EpochSeconds = TimestampFormat<Second>;

/// Formats a timestamp in `EpochMillis` format
pub type EpochMillis = TimestampFormat<Millisecond>;

/// Formats a timestamp in `EpochMicros` format
pub type EpochMicros = TimestampFormat<Microsecond>;

/// The type returned when `Timestamp` types are closed
#[derive(Copy, Clone)]
pub struct TimestampValue {
    duration_since_epoch: Duration,
}

impl Value for TimestampValue {
    fn write(&self, writer: impl metrique_writer_core::ValueWriter) {
        // by default, use the milliseconds format
        <Millisecond as TimestampToStr>::to_str(self.duration_since_epoch, |v| writer.string(v));
    }
}

impl TimestampValue {
    /// Create a new `TimestampValue` from a `SystemTime`
    pub fn new(ts: &SystemTime) -> Self {
        Self {
            duration_since_epoch: ts.duration_since(UNIX_EPOCH).unwrap_or_default(),
        }
    }

    /// Duration since the [`UNIX_EPOCH`] represented by this Timestamp
    pub fn duration_since_epoch(&self) -> Duration {
        self.duration_since_epoch
    }
}

impl From<TimestampValue> for std::time::SystemTime {
    fn from(value: TimestampValue) -> Self {
        UNIX_EPOCH + value.duration_since_epoch
    }
}

#[doc(hidden)]
pub struct TimestampFormat<Unit> {
    u: PhantomData<Unit>,
}

impl<U: TimestampToStr> ValueFormatter<TimestampValue> for TimestampFormat<U> {
    fn format_value(writer: impl metrique_writer_core::ValueWriter, value: &TimestampValue) {
        U::to_str(value.duration_since_epoch, |s| writer.string(s));
    }
}

/// Timestamps must be formatted as strings
mod timestamp_to_str {
    use std::time::Duration;

    use metrique_writer_core::unit::{Microsecond, Millisecond, Second};

    pub(super) trait TimestampToStr {
        fn to_str(value: Duration, f: impl FnOnce(&str));
    }

    impl TimestampToStr for Second {
        fn to_str(value: Duration, f: impl FnOnce(&str)) {
            let mut buf = ryu::Buffer::new();
            let value = buf.format(value.as_secs_f64());
            f(value)
        }
    }

    pub(crate) fn duration_as_millis_with_nano_precision(duration: Duration) -> f64 {
        //         milli
        // unit  * ----- = milli
        //         unit
        duration.as_secs_f64() * 1000.0
    }

    impl TimestampToStr for Millisecond {
        fn to_str(value: Duration, f: impl FnOnce(&str)) {
            let mut buf = ryu::Buffer::new();
            let value = buf.format(duration_as_millis_with_nano_precision(value));
            f(value)
        }
    }

    impl TimestampToStr for Microsecond {
        fn to_str(value: Duration, f: impl FnOnce(&str)) {
            let mut buf = itoa::Buffer::new();
            let value = buf.format(value.as_micros());
            f(value)
        }
    }
}

/// Timers record the time it takes to do a unit of work
///
/// They are started automatically and stop automatically when dropped (unless you call `Timer::stop` first.)
/// If you want a timer you can control explicitly, use [`Stopwatch`]
///
/// Unlike [`Stopwatch`], timer records a single continuous span of time. It cannot be restarted after it is stopped.
#[derive(Debug)]
pub struct Timer {
    start: Instant,
    duration: Option<Duration>,
}

impl Default for Timer {
    fn default() -> Self {
        Self {
            start: time_source().instant(),
            duration: None,
        }
    }
}

impl Timer {
    /// Creates a new timer that starts immediately using the default time source.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Timer;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut timer = Timer::start_now();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = timer.stop();
    /// assert!(elapsed >= Duration::from_millis(10));
    /// ```
    pub fn start_now() -> Self {
        Self::start_now_with_timesource(time_source())
    }

    /// Creates a new timer that starts immediately using the specified time source.
    ///
    /// This is useful for testing with a mock time source.
    ///
    /// # Example
    /// ```
    /// # use metrique::timers::Timer;
    /// # use metrique_timesource::TimeSource;
    /// # use std::time::UNIX_EPOCH;
    /// #
    /// let time_source = TimeSource::tokio(UNIX_EPOCH);
    /// let timer = Timer::start_now_with_timesource(time_source);
    /// ```
    pub fn start_now_with_timesource(timesource: TimeSource) -> Self {
        Self {
            start: timesource.instant(),
            duration: None,
        }
    }

    /// Stops the timer and returns the elapsed duration.
    ///
    /// After calling this method, the timer will no longer update and will report
    /// the same duration when closed.
    ///
    /// Calling `stop` on a stopped timer is idempotent, and returns the
    /// timer's stopped duration.
    ///
    /// **Important Note**: Although this returns the duration for convenience, you don't need to store it yourself. The duration
    /// will be recorded in the parent metric when it is closed.
    ///
    /// # Example
    /// ```no_run
    /// use metrique::timers::Timer;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut timer = Timer::start_now();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = timer.stop();
    /// ```
    pub fn stop(&mut self) -> Duration {
        if let Some(duration) = self.duration {
            return duration;
        }

        let time = self.start.elapsed();
        self.duration = Some(time);
        time
    }
}

impl CloseValue for &'_ Timer {
    type Closed = Duration;

    fn close(self) -> Self::Closed {
        self.duration.unwrap_or_else(|| self.start.elapsed())
    }
}

impl CloseValue for Timer {
    type Closed = Duration;

    fn close(self) -> Self::Closed {
        <&Self>::close(&self)
    }
}
/// A guard that stops a timer when dropped.
///
/// This guard is returned by [`Stopwatch::start()`] and will add the elapsed time
/// to the stopwatch when dropped.
///
/// To customize this behavior, use [`Self::overwrite()`] or
/// [`Self::discard()`].
///
/// To explicitly stop this guard and access the Duration it flushed to the `Stopwatch`,
/// use [`Self::stop()`].
#[must_use]
pub struct TimerGuard<'a> {
    start: Option<Instant>,
    self_time: Option<Duration>,
    timer: &'a mut MaybeGuardedDuration,
}

impl TimerGuard<'_> {
    /// Explicitly stops the timer.
    ///
    /// This is equivalent to dropping the guard, but makes the intention clearer.
    ///
    /// **Important Note**: Although this returns the duration for convenience, you don't need to store it yourself. The duration
    /// will be recorded in the parent metric when it is closed.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// ```
    pub fn stop(mut self) -> Duration {
        // we know that this is not None, since the only way to wipe the stored
        // fields is by calling `Self::clear()`, or `Self::discard()`, which both take self,
        // meaning stop can't be called afterwards
        self.stop_ref().unwrap()
    }

    fn stop_ref(&mut self) -> Option<Duration> {
        match self.self_time {
            Some(time) => Some(time),
            None => {
                let elapsed = self.start.as_ref().map(|start| start.elapsed());
                self.self_time = elapsed;
                elapsed
            }
        }
    }

    /// Flush loaded duration in this guard, overwriting any existing
    /// contents in the underlying [`Stopwatch`].
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// // stopwatch now contains 10 millis
    ///
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(30));
    /// // wipe the existing 10 millis in this guard,
    /// // and replace with 30ms in loaded guard
    /// guard.overwrite();
    /// // stopwatch contains 30ms
    /// ```
    pub fn overwrite(self) {
        self.timer.take();
    }

    /// Discard all loaded duration in this guard,
    /// preventing it from being flushed into the underlying `Stopwatch`.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(20));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// // stopwatch now contains 20 millis
    ///
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// // wipe the new 10 millis in this guard, but not the already-loaded
    /// // 20 millis in the underlying timer
    /// guard.discard();
    /// // stopwatch still contains 20ms
    /// ```
    pub fn discard(mut self) {
        self.self_time.take();
        self.start.take();
    }
}

impl Drop for TimerGuard<'_> {
    fn drop(&mut self) {
        let self_time = self.stop_ref();
        // only update the underlying StopWatch if we haven't called
        // clear() or discard() on the guard explicitly
        if let Some(self_time) = self_time {
            *self.timer += self_time;
        }
    }
}

/// An owned guard that stops a timer when dropped.
///
/// This guard is returned by [`Stopwatch::start_owned()`] and will add the elapsed time
/// to the stopwatch when dropped.
///
/// To customize this behavior, use [`Self::overwrite()`] or
/// [`Self::discard()`].
///
/// To explicitly stop this guard and access the Duration it flushed to the `Stopwatch`,
/// use [`Self::stop()`].
#[must_use]
pub struct OwnedTimerGuard {
    start: Option<Instant>,
    self_time: Option<Duration>,
    timer: MaybeGuardedDuration,
}

impl OwnedTimerGuard {
    /// Explicitly stops the timer.
    ///
    /// This is equivalent to dropping the guard, but makes the intention clearer.
    ///
    /// **Important Note**: Although this returns the duration for convenience, you don't need to store it yourself. The duration
    /// will be recorded in the parent metric when it is closed.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// ```
    pub fn stop(mut self) -> Duration {
        // we know that this is not None, since the only way to wipe the stored
        // fields is by calling `Self::clear()`, or `Self::discard()`, which both take self,
        // meaning stop can't be called afterwards
        self.stop_ref().unwrap()
    }

    fn stop_ref(&mut self) -> Option<Duration> {
        match self.self_time {
            Some(time) => Some(time),
            None => {
                let elapsed = self.start.as_ref().map(|start| start.elapsed());
                self.self_time = elapsed;
                elapsed
            }
        }
    }

    /// Flush loaded duration in this guard, overwriting any existing
    /// contents in the underlying [`Stopwatch`].
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// // stopwatch now contains 10 millis
    ///
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(30));
    /// // wipe the existing 10 millis in this guard,
    /// // and replace with 30ms in loaded guard
    /// guard.overwrite();
    /// // stopwatch contains 30ms
    /// ```
    pub fn overwrite(mut self) {
        self.timer.take();
    }

    /// Discard all loaded duration in this guard,
    /// preventing it from being flushed into the underlying `Stopwatch`.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// // stopwatch now contains 10 millis
    ///
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// // wipe the new 10 millis in this guard, but not the already-loaded
    /// // 10 millis in the underlying timer
    /// guard.discard();
    /// // stopwatch still contains 10ms
    /// ```
    pub fn discard(mut self) {
        self.self_time.take();
        self.start.take();
    }
}

impl Drop for OwnedTimerGuard {
    fn drop(&mut self) {
        let self_time = self.stop_ref();
        // only update the underlying StopWatch if we haven't called
        // clear() or discard() on the guard explicitly
        if let Some(self_time) = self_time {
            self.timer += self_time;
        }
    }
}

/// The internal storage of a duration that might have [`TimerGuard`] or [`SharedTimerGuard`]
/// pointing to it. We default to a Exclusive duration, meaning a guard backed by a mutable pointer
/// can access it ( eg[`Stopwatch::start()`]).
/// We switch to an shared, mutex-backed version if the caller uses eg [`Stopwatch::start_owned()`].
#[derive(Debug)]
enum MaybeGuardedDuration {
    Exclusive(Option<Duration>),
    Shared(SharedDuration),
}

impl MaybeGuardedDuration {
    /// Pull the stored duration out of the state, leaving empty state behind
    fn take(&mut self) -> Option<Duration> {
        match self {
            MaybeGuardedDuration::Exclusive(duration) => duration.take(),
            MaybeGuardedDuration::Shared(shared_duration) => shared_duration
                .0
                .lock()
                .expect("owned timer guard panicked while holding lock")
                .take(),
        }
    }

    /// Converts the the stored duration into the shared variant if needed,
    /// then returns of clone of it
    fn shared_cloned(&mut self) -> SharedDuration {
        match self {
            MaybeGuardedDuration::Exclusive(duration) => {
                let shared_duration = SharedDuration(Arc::new(Mutex::new(duration.take())));
                *self = MaybeGuardedDuration::Shared(shared_duration.clone());
                shared_duration
            }
            MaybeGuardedDuration::Shared(shared_duration) => shared_duration.clone(),
        }
    }
}

impl Default for MaybeGuardedDuration {
    fn default() -> Self {
        MaybeGuardedDuration::Exclusive(Default::default())
    }
}

impl PartialEq<Option<Duration>> for MaybeGuardedDuration {
    fn eq(&self, other: &Option<Duration>) -> bool {
        match self {
            MaybeGuardedDuration::Exclusive(duration) => duration == other,
            MaybeGuardedDuration::Shared(shared_duration) => shared_duration == other,
        }
    }
}

impl AddAssign<Duration> for MaybeGuardedDuration {
    fn add_assign(&mut self, rhs: Duration) {
        match self {
            MaybeGuardedDuration::Exclusive(duration) => {
                *duration = Some(duration.unwrap_or_default() + rhs)
            }
            MaybeGuardedDuration::Shared(shared_duration) => *shared_duration += rhs,
        }
    }
}

/// The internal representation of [`MaybeGuardedDuration::Shared`]
#[derive(Debug, Clone)]
struct SharedDuration(Arc<Mutex<Option<Duration>>>);

impl PartialEq<Option<Duration>> for SharedDuration {
    fn eq(&self, other: &Option<Duration>) -> bool {
        *self
            .0
            .lock()
            .expect("owned timer guard panicked while holding lock")
            == *other
    }
}

impl AddAssign<Duration> for SharedDuration {
    fn add_assign(&mut self, rhs: Duration) {
        let mut guard = self
            .0
            .lock()
            .expect("owned timer guard panicked while holding lock");
        *guard = Some(guard.unwrap_or_default() + rhs);
    }
}

/// Stopwatches allow you to manually measure time
///
/// Stopwatches must be manually started by calling [`Stopwatch::start`]. This will return a guard
/// which you must hold until the measurement is complete.
///
/// A stopwatch MAY be started multiple times—the durations will add. It is impossible to run the stopwatch multiple times concurrently
/// as the `start` method uses `&mut self`.
#[derive(Debug)]
pub struct Stopwatch {
    time_source: TimeSource,
    start: Option<Instant>,
    duration: MaybeGuardedDuration,
}

impl Default for Stopwatch {
    fn default() -> Self {
        Self {
            time_source: time_source(),
            start: None,
            duration: MaybeGuardedDuration::default(),
        }
    }
}

impl Stopwatch {
    /// Creates a new stopwatch that is not yet started.
    ///
    /// The stopwatch must be started by calling `start()` or `start_owned()` before it will measure time.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start(); // Start timing
    /// // Do some work...
    /// drop(guard); // Stop timing
    /// ```
    pub fn new() -> Self {
        Self::new_from_timesource(time_source())
    }

    /// Creates a new stopwatch from an explicit timesource
    ///
    /// The stopwatch must be started by calling `start()` before it will measure time.
    pub fn new_from_timesource(time_source: TimeSource) -> Self {
        Self {
            time_source,
            start: None,
            duration: MaybeGuardedDuration::default(),
        }
    }

    /// Starts the stopwatch and returns a guard that will stop it when dropped.
    ///
    /// The stopwatch will accumulate time until the guard is dropped. Multiple calls
    /// to `start()` or `start_owned()` will add to the total duration.
    ///
    /// Note that the guard will involve a mutable borrow of this [`Stopwatch`].
    /// If you encounter double mutable borrow errors or otherwise need an owned handle,
    /// use [`Stopwatch::start_owned()`] instead.
    ///
    /// # Example
    /// ```
    /// # use metrique::timers::Stopwatch;
    /// # use std::time::Duration;
    /// #
    /// let mut stopwatch = Stopwatch::new();
    ///
    /// // First timing session
    /// let guard = stopwatch.start();
    /// // Do some work...
    /// drop(guard);
    ///
    /// // Second timing session (adds to the first)
    /// let guard = stopwatch.start();
    /// // Do more work...
    /// drop(guard);
    /// ```
    pub fn start(&mut self) -> TimerGuard<'_> {
        let start = self.time_source.instant();
        TimerGuard {
            start: Some(start),
            self_time: None,
            timer: &mut self.duration,
        }
    }

    /// Starts the stopwatch and returns an shared guard that will stop it when dropped.
    ///
    /// The stopwatch will accumulate time until the guard is dropped. Multiple calls
    /// to `start()` or `start_owned()` will add to the total duration.
    ///
    /// The shared guard is backed by a (usually uncontended) `Arc<Mutex>` so this method slightly more overhead than
    /// a simple [`Stopwatch::start()`] call.
    ///
    /// Use this if you specifically are encountering double mutable borrows while passing around the guard.
    /// Or, if you want to stop the stopwatch in another task.
    ///
    /// # Example
    /// ```
    /// # use metrique::timers::Stopwatch;
    /// # use std::time::Duration;
    ///
    /// #[derive(Default, Debug)]
    /// struct DuckTracker {
    ///    total_latency: Stopwatch,
    ///    duck_count: usize
    /// }
    ///
    /// fn process_ducks(tracker: &mut DuckTracker) {
    ///     tracker.duck_count += 1;
    /// }
    ///
    /// let mut tracker = DuckTracker::default();
    /// loop {
    ///     let _timer = tracker.total_latency.start_owned();
    ///     process_ducks(&mut tracker);
    ///     if tracker.duck_count >= 5 {
    ///         break;
    ///     }
    ///     // timer drops, adding to total latency
    /// }
    /// println!("{tracker:#?}")
    /// ```
    pub fn start_owned(&mut self) -> OwnedTimerGuard {
        let shared_duration = self.duration.shared_cloned();
        let start = self.time_source.instant();

        OwnedTimerGuard {
            start: Some(start),
            self_time: None,
            timer: MaybeGuardedDuration::Shared(shared_duration),
        }
    }

    /// Clear all loaded duration in the [`Stopwatch`].
    ///
    /// This will result in no metrics being published on drop,
    /// unless further duration is loaded in.
    ///
    /// This only clears the [`Stopwatch`] for its immediate state.
    ///
    /// Any active [`TimerGuard`]/[`OwnedTimerGuard`]s will continue to tick and write
    /// to this `Stopwatch` when they drop or are stopped explicitly.
    ///
    /// See also: [`TimerGuard::discard()`]/[`OwnedTimerGuard::discard()`] to
    /// drop the guard's state but leave the stopwatch's loaded duration in place.
    ///
    /// And see:
    /// [`TimerGuard::overwrite()`]/[`OwnedTimerGuard::overwrite()`] to overwrite the stopwatch's loaded duration
    /// with the guard's contents.
    ///
    /// # Example
    /// ```
    /// use metrique::timers::Stopwatch;
    /// use std::thread::sleep;
    /// use std::time::Duration;
    ///
    /// let mut stopwatch = Stopwatch::new();
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// guard.stop(); // Explicitly stop timing
    ///
    /// stopwatch.clear();
    /// // stopwatch now contains no stored time
    ///
    /// // start fresh
    /// let guard = stopwatch.start();
    /// sleep(Duration::from_millis(10));
    /// let elapsed = guard.stop(); // Explicitly stop timing
    /// // duration will now be roughly 10 millis
    /// ```
    pub fn clear(&mut self) {
        self.duration.take();
        self.start.take();
    }
}

impl CloseValue for &'_ Stopwatch {
    type Closed = Option<Duration>;

    fn close(self) -> Self::Closed {
        match &self.duration {
            MaybeGuardedDuration::Exclusive(Some(duration)) => Some(*duration),
            MaybeGuardedDuration::Shared(mutex) => {
                let duration = mutex
                    .0
                    .lock()
                    .expect("owned timer guard panicked while holding lock");
                *duration
            }
            _ => self.start.as_ref().map(|start| start.elapsed()),
        }
    }
}
impl CloseValue for Stopwatch {
    type Closed = Option<Duration>;

    fn close(self) -> Self::Closed {
        <&Self>::close(&self)
    }
}

#[cfg(test)]
mod test {
    use std::time::{Duration, UNIX_EPOCH};

    use metrique_core::CloseValue;
    use metrique_timesource::{TimeSource, set_time_source};

    use crate::timers::{Stopwatch, Timer};

    #[tokio::test(start_paused = true)]
    async fn timer_stop_is_idempotent() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut timer = Timer::start_now();

        tokio::time::sleep(Duration::from_millis(1)).await;
        let first_stop = timer.stop();
        tokio::time::sleep(Duration::from_millis(1)).await;
        let second_stop = timer.stop();

        assert_eq!(first_stop, second_stop);
    }

    #[tokio::test(start_paused = true)]
    async fn stopwatch_can_start_multiple_times() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!((&stopwatch).close(), Some(Duration::from_secs(1)));
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(3)).await;
        drop(guard);
        assert_eq!((&stopwatch).close(), Some(Duration::from_secs(4)));
    }

    #[tokio::test(start_paused = true)]
    async fn stopwatch_clear_works() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        stopwatch.clear();
        assert_eq!(stopwatch.duration, None);
        assert!(stopwatch.start.is_none());

        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!((&stopwatch).close(), Some(Duration::from_secs(1)));
    }

    #[tokio::test(start_paused = true)]
    async fn timer_guard_discard_works() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        // load in one second
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(2)).await;
        // discard the guard but leave existing data in place
        guard.discard();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));
    }

    #[tokio::test(start_paused = true)]
    async fn timer_guard_overwrite_works() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        // load in one second
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(2)).await;
        // overwrite existing data iwth new data
        guard.overwrite();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(2)));
    }

    #[tokio::test(start_paused = true)]
    async fn owned_timer_guard_multiple_adds() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        for _ in 0..3 {
            let _guard = stopwatch.start_owned();
            tokio::time::advance(Duration::from_secs(1)).await;
        }

        assert_eq!(stopwatch.duration, Some(Duration::from_secs(3)));
    }

    #[tokio::test(start_paused = true)]
    async fn owned_then_regular_timer_guard() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        let owned_guard = stopwatch.start_owned();
        tokio::time::advance(Duration::from_secs(1)).await;
        owned_guard.stop();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(2)).await;
        guard.stop();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(3)));
    }

    #[tokio::test(start_paused = true)]
    async fn owned_timer_guard_overwrite_works() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        // load in one second
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        guard.stop();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        let guard = stopwatch.start_owned();
        tokio::time::advance(Duration::from_secs(2)).await;
        // overwrite the loaded time with the guard contents
        guard.overwrite();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(2)));
    }

    #[tokio::test(start_paused = true)]
    async fn owned_timer_guard_discard_works() {
        let _ts = set_time_source(TimeSource::tokio(UNIX_EPOCH));
        let mut stopwatch = Stopwatch::new();

        // load in one second
        let guard = stopwatch.start();
        tokio::time::advance(Duration::from_secs(1)).await;
        drop(guard);
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));

        let guard = stopwatch.start_owned();
        tokio::time::advance(Duration::from_secs(2)).await;
        // discard the guard's contents but leave loaded time in place
        guard.discard();
        assert_eq!(stopwatch.duration, Some(Duration::from_secs(1)));
    }
}