zino_http/request/
context.rs

1use std::time::Instant;
2use zino_core::Uuid;
3
4#[cfg(feature = "i18n")]
5use unic_langid::LanguageIdentifier;
6
7/// Data associated with a request-response lifecycle.
8#[derive(Debug, Clone)]
9pub struct Context {
10    /// Start time.
11    start_time: Instant,
12    /// Instance.
13    instance: String,
14    /// Request ID.
15    request_id: Uuid,
16    /// Trace ID.
17    trace_id: Uuid,
18    /// Session ID.
19    session_id: Option<String>,
20    /// Locale.
21    #[cfg(feature = "i18n")]
22    locale: Option<LanguageIdentifier>,
23}
24
25impl Context {
26    /// Creates a new instance.
27    pub fn new(request_id: Uuid) -> Self {
28        Self {
29            start_time: Instant::now(),
30            instance: String::new(),
31            request_id,
32            trace_id: Uuid::nil(),
33            session_id: None,
34            #[cfg(feature = "i18n")]
35            locale: None,
36        }
37    }
38
39    /// Sets the instance.
40    #[inline]
41    pub fn set_instance(&mut self, instance: impl ToString) {
42        self.instance = instance.to_string();
43    }
44
45    /// Sets the trace ID.
46    #[inline]
47    pub fn set_trace_id(&mut self, trace_id: Uuid) {
48        self.trace_id = trace_id;
49    }
50
51    /// Sets the session ID.
52    #[inline]
53    pub fn set_session_id(&mut self, session_id: Option<String>) {
54        self.session_id = session_id;
55    }
56
57    /// Sets the locale.
58    #[cfg(feature = "i18n")]
59    #[inline]
60    pub fn set_locale(&mut self, locale: &str) {
61        match locale.parse() {
62            Ok(locale) => self.locale = Some(locale),
63            Err(err) => tracing::error!("{err}: `{locale}`"),
64        }
65    }
66
67    /// Returns the start time.
68    #[inline]
69    pub fn start_time(&self) -> Instant {
70        self.start_time
71    }
72
73    /// Returns the instance.
74    #[inline]
75    pub fn instance(&self) -> &str {
76        &self.instance
77    }
78
79    /// Returns the request ID.
80    #[inline]
81    pub fn request_id(&self) -> Uuid {
82        self.request_id
83    }
84
85    /// Returns the trace ID.
86    #[inline]
87    pub fn trace_id(&self) -> Uuid {
88        self.trace_id
89    }
90
91    /// Returns the session ID.
92    #[inline]
93    pub fn session_id(&self) -> Option<&str> {
94        self.session_id.as_deref()
95    }
96
97    /// Returns the locale.
98    #[cfg(feature = "i18n")]
99    pub fn locale(&self) -> Option<&LanguageIdentifier> {
100        self.locale.as_ref()
101    }
102}