1 | #[cfg (any( |
2 | all(any(feature = "client" , feature = "server" ), feature = "http2" ), |
3 | all(feature = "server" , feature = "http1" ), |
4 | ))] |
5 | use std::time::Duration; |
6 | use std::{fmt, sync::Arc}; |
7 | use std::{pin::Pin, time::Instant}; |
8 | |
9 | use crate::rt::Sleep; |
10 | use crate::rt::Timer; |
11 | |
12 | /// A user-provided timer to time background tasks. |
13 | #[derive (Clone)] |
14 | pub(crate) enum Time { |
15 | Timer(Arc<dyn Timer + Send + Sync>), |
16 | Empty, |
17 | } |
18 | |
19 | #[cfg (all(feature = "server" , feature = "http1" ))] |
20 | #[derive (Clone, Copy, Debug)] |
21 | pub(crate) enum Dur { |
22 | Default(Option<Duration>), |
23 | Configured(Option<Duration>), |
24 | } |
25 | |
26 | impl fmt::Debug for Time { |
27 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
28 | f.debug_struct(name:"Time" ).finish() |
29 | } |
30 | } |
31 | |
32 | impl Time { |
33 | #[cfg (all(any(feature = "client" , feature = "server" ), feature = "http2" ))] |
34 | pub(crate) fn sleep(&self, duration: Duration) -> Pin<Box<dyn Sleep>> { |
35 | match *self { |
36 | Time::Empty => { |
37 | panic!("You must supply a timer." ) |
38 | } |
39 | Time::Timer(ref t) => t.sleep(duration), |
40 | } |
41 | } |
42 | |
43 | #[cfg (feature = "http1" )] |
44 | pub(crate) fn sleep_until(&self, deadline: Instant) -> Pin<Box<dyn Sleep>> { |
45 | match *self { |
46 | Time::Empty => { |
47 | panic!("You must supply a timer." ) |
48 | } |
49 | Time::Timer(ref t) => t.sleep_until(deadline), |
50 | } |
51 | } |
52 | |
53 | pub(crate) fn reset(&self, sleep: &mut Pin<Box<dyn Sleep>>, new_deadline: Instant) { |
54 | match *self { |
55 | Time::Empty => { |
56 | panic!("You must supply a timer." ) |
57 | } |
58 | Time::Timer(ref t) => t.reset(sleep, new_deadline), |
59 | } |
60 | } |
61 | |
62 | #[cfg (all(feature = "server" , feature = "http1" ))] |
63 | pub(crate) fn check(&self, dur: Dur, name: &'static str) -> Option<Duration> { |
64 | match dur { |
65 | Dur::Default(Some(dur)) => match self { |
66 | Time::Empty => { |
67 | warn!("timeout `{}` has default, but no timer set" , name,); |
68 | None |
69 | } |
70 | Time::Timer(..) => Some(dur), |
71 | }, |
72 | Dur::Configured(Some(dur)) => match self { |
73 | Time::Empty => panic!("timeout `{}` set, but no timer set" , name,), |
74 | Time::Timer(..) => Some(dur), |
75 | }, |
76 | Dur::Default(None) | Dur::Configured(None) => None, |
77 | } |
78 | } |
79 | } |
80 | |