volo_http/context/
client.rs

1//! Context and its utilities of client
2
3use std::time::Duration;
4
5use chrono::{DateTime, Local};
6use volo::{
7    context::{Reusable, Role, RpcCx, RpcInfo},
8    newtype_impl_context,
9};
10
11use crate::{
12    client::Target,
13    utils::macros::{impl_deref_and_deref_mut, stat_impl},
14};
15
16/// RPC context of http client
17#[derive(Debug)]
18pub struct ClientContext(pub(crate) RpcCx<ClientCxInner, Config>);
19
20impl ClientContext {
21    /// Create a new [`ClientContext`]
22    pub fn new() -> Self {
23        Self(RpcCx::new(
24            RpcInfo::<Config>::with_role(Role::Client),
25            ClientCxInner {
26                target: Target::None,
27                stats: ClientStats::default(),
28            },
29        ))
30    }
31}
32
33impl Default for ClientContext {
34    fn default() -> Self {
35        Self::new()
36    }
37}
38
39newtype_impl_context!(ClientContext, Config, 0);
40
41impl_deref_and_deref_mut!(ClientContext, RpcCx<ClientCxInner, Config>, 0);
42
43/// Inner details of [`ClientContext`]
44#[derive(Debug)]
45pub struct ClientCxInner {
46    /// Target of the current request
47    target: Target,
48
49    /// Statistics of client
50    ///
51    /// This is unstable now and may be changed in the future.
52    pub stats: ClientStats,
53}
54
55impl ClientCxInner {
56    /// Get [`Target`] of current request context.
57    pub fn target(&self) -> &Target {
58        &self.target
59    }
60
61    pub(crate) fn set_target(&mut self, target: Target) {
62        self.target = target;
63    }
64}
65
66/// Statistics of client
67///
68/// This is unstable now and may be changed in the future.
69#[derive(Debug, Default, Clone)]
70pub struct ClientStats {
71    transport_start_at: Option<DateTime<Local>>,
72    transport_end_at: Option<DateTime<Local>>,
73}
74
75impl ClientStats {
76    stat_impl!(transport_start_at);
77    stat_impl!(transport_end_at);
78}
79
80/// Configuration of the request
81#[derive(Clone, Debug, Default)]
82pub struct Config {
83    /// Timeout of the current request
84    pub timeout: Option<Duration>,
85}
86
87impl Config {
88    /// Create a default [`Config`]
89    #[inline]
90    pub fn new() -> Self {
91        Default::default()
92    }
93
94    /// Get current timeout of the request
95    #[inline]
96    pub fn timeout(&self) -> Option<&Duration> {
97        self.timeout.as_ref()
98    }
99
100    /// Set timeout to the request
101    #[inline]
102    pub fn set_timeout(&mut self, timeout: Option<Duration>) {
103        self.timeout = timeout;
104    }
105}
106
107impl Reusable for Config {
108    fn clear(&mut self) {
109        self.timeout = None;
110    }
111}