Skip to main content

leyline/core/config/
timeout.rs

1use std::time::Duration;
2
3const DEFAULT_TOTAL: Option<Duration> = Some(Duration::from_secs(300));
4const DEFAULT_CONNECT: Option<Duration> = Some(Duration::from_secs(10));
5const DEFAULT_ERROR_BODY: Option<Duration> = Some(Duration::from_secs(10));
6
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
8#[non_exhaustive]
9pub struct TimeoutConfig {
10    total: Option<Option<Duration>>,
11    connect: Option<Option<Duration>>,
12    read: Option<Option<Duration>>,
13    response_header: Option<Option<Duration>>,
14    body: Option<Option<Duration>>,
15    error_body: Option<Option<Duration>>,
16}
17
18impl TimeoutConfig {
19    pub fn new() -> Self {
20        Self::default()
21    }
22
23    pub fn total(mut self, d: impl Into<Option<Duration>>) -> Self {
24        self.total = Some(d.into());
25        self
26    }
27
28    pub fn connect(mut self, d: impl Into<Option<Duration>>) -> Self {
29        self.connect = Some(d.into());
30        self
31    }
32
33    pub fn read(mut self, d: impl Into<Option<Duration>>) -> Self {
34        self.read = Some(d.into());
35        self
36    }
37
38    pub fn response_header(mut self, d: impl Into<Option<Duration>>) -> Self {
39        self.response_header = Some(d.into());
40        self
41    }
42
43    pub fn body(mut self, d: impl Into<Option<Duration>>) -> Self {
44        self.body = Some(d.into());
45        self
46    }
47
48    pub fn error_body(mut self, d: impl Into<Option<Duration>>) -> Self {
49        self.error_body = Some(d.into());
50        self
51    }
52
53    pub(crate) fn over(self, base: &TimeoutConfig) -> TimeoutConfig {
54        TimeoutConfig {
55            total: self.total.or(base.total),
56            connect: self.connect.or(base.connect),
57            read: self.read.or(base.read),
58            response_header: self.response_header.or(base.response_header),
59            body: self.body.or(base.body),
60            error_body: self.error_body.or(base.error_body),
61        }
62    }
63
64    pub(crate) fn body_limit(&self) -> Option<Duration> {
65        self.body.flatten()
66    }
67
68    pub(crate) fn error_body_limit(&self) -> Option<Duration> {
69        self.error_body.unwrap_or(DEFAULT_ERROR_BODY)
70    }
71
72    pub(crate) fn total_limit(&self) -> Option<Duration> {
73        self.total.unwrap_or(DEFAULT_TOTAL)
74    }
75
76    pub(crate) fn connect_limit(&self) -> Option<Duration> {
77        self.connect.unwrap_or(DEFAULT_CONNECT)
78    }
79
80    pub(crate) fn read_limit(&self) -> Option<Duration> {
81        self.read.flatten()
82    }
83
84    pub(crate) fn response_header_limit(&self) -> Option<Duration> {
85        self.response_header.flatten()
86    }
87}
88
89impl From<Duration> for TimeoutConfig {
90    fn from(total: Duration) -> Self {
91        Self::new().total(total)
92    }
93}