zino_http/request/
context.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::time::Instant;
use zino_core::Uuid;

#[cfg(feature = "i18n")]
use unic_langid::LanguageIdentifier;

/// Data associated with a request-response lifecycle.
#[derive(Debug, Clone)]
pub struct Context {
    /// Start time.
    start_time: Instant,
    /// Instance.
    instance: String,
    /// Request ID.
    request_id: Uuid,
    /// Trace ID.
    trace_id: Uuid,
    /// Session ID.
    session_id: Option<String>,
    /// Locale.
    #[cfg(feature = "i18n")]
    locale: Option<LanguageIdentifier>,
}

impl Context {
    /// Creates a new instance.
    pub fn new(request_id: Uuid) -> Self {
        Self {
            start_time: Instant::now(),
            instance: String::new(),
            request_id,
            trace_id: Uuid::nil(),
            session_id: None,
            #[cfg(feature = "i18n")]
            locale: None,
        }
    }

    /// Sets the instance.
    #[inline]
    pub fn set_instance(&mut self, instance: impl ToString) {
        self.instance = instance.to_string();
    }

    /// Sets the trace ID.
    #[inline]
    pub fn set_trace_id(&mut self, trace_id: Uuid) {
        self.trace_id = trace_id;
    }

    /// Sets the session ID.
    #[inline]
    pub fn set_session_id(&mut self, session_id: Option<String>) {
        self.session_id = session_id;
    }

    /// Sets the locale.
    #[cfg(feature = "i18n")]
    #[inline]
    pub fn set_locale(&mut self, locale: &str) {
        match locale.parse() {
            Ok(locale) => self.locale = Some(locale),
            Err(err) => tracing::error!("{err}: `{locale}`"),
        }
    }

    /// Returns the start time.
    #[inline]
    pub fn start_time(&self) -> Instant {
        self.start_time
    }

    /// Returns the instance.
    #[inline]
    pub fn instance(&self) -> &str {
        &self.instance
    }

    /// Returns the request ID.
    #[inline]
    pub fn request_id(&self) -> Uuid {
        self.request_id
    }

    /// Returns the trace ID.
    #[inline]
    pub fn trace_id(&self) -> Uuid {
        self.trace_id
    }

    /// Returns the session ID.
    #[inline]
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Returns the locale.
    #[cfg(feature = "i18n")]
    pub fn locale(&self) -> Option<&LanguageIdentifier> {
        self.locale.as_ref()
    }
}