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: String) {
42        self.instance = instance;
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: LanguageIdentifier) {
61        self.locale = Some(locale);
62    }
63
64    /// Returns the start time.
65    #[inline]
66    pub fn start_time(&self) -> Instant {
67        self.start_time
68    }
69
70    /// Returns the instance.
71    #[inline]
72    pub fn instance(&self) -> &str {
73        &self.instance
74    }
75
76    /// Returns the request ID.
77    #[inline]
78    pub fn request_id(&self) -> Uuid {
79        self.request_id
80    }
81
82    /// Returns the trace ID.
83    #[inline]
84    pub fn trace_id(&self) -> Uuid {
85        self.trace_id
86    }
87
88    /// Returns the session ID.
89    #[inline]
90    pub fn session_id(&self) -> Option<&str> {
91        self.session_id.as_deref()
92    }
93
94    /// Returns the locale.
95    #[cfg(feature = "i18n")]
96    pub fn locale(&self) -> Option<&LanguageIdentifier> {
97        self.locale.as_ref()
98    }
99}