Skip to main content

ash_log/
context.rs

1//! Fields bound once per request and inherited by every event.
2//!
3//! # Why this exists
4//!
5//! A correlation ID identifies a request across every event it produces, but
6//! passing it explicitly to each call means threading it through every function
7//! that might log. In practice that is not done, and the field ends up missing
8//! from precisely the events that need it.
9//!
10//! A [`Scope`] binds fields for a region of code. Events recorded inside it
11//! inherit them, so the correlation ID is attached once at the edge of the
12//! request rather than at every call site.
13//!
14//! # Threads and tasks
15//!
16//! The active scope is thread-local. A spawned thread starts with no scope,
17//! which is the safe default — inheriting one implicitly would attach a stale
18//! correlation ID to unrelated work. Carry it across a boundary explicitly with
19//! [`Scope::current`] and [`ScopeFields::enter`].
20//!
21//! The same applies to async tasks: an `.await` can resume on another thread,
22//! so a scope held across one is not reliable. Bind fields inside the task, or
23//! capture and re-enter them.
24
25use super::AuditEvent;
26use std::cell::RefCell;
27use std::collections::HashMap;
28use std::sync::Arc;
29
30thread_local! {
31    /// The innermost active scope on this thread.
32    static ACTIVE: RefCell<Option<Arc<ScopeFields>>> = const { RefCell::new(None) };
33}
34
35/// Fields bound by a scope, and whatever its parent bound.
36///
37/// Cheap to clone: the parent chain is shared through [`Arc`].
38#[derive(Debug, Default)]
39pub struct ScopeFields {
40    correlation_id: Option<String>,
41    principal: Option<String>,
42    metadata: HashMap<String, serde_json::Value>,
43    parent: Option<Arc<ScopeFields>>,
44}
45
46impl ScopeFields {
47    /// The correlation ID bound here, or by the nearest enclosing scope.
48    #[must_use]
49    pub fn correlation_id(&self) -> Option<&str> {
50        self.correlation_id.as_deref().or_else(|| {
51            self.parent
52                .as_ref()
53                .and_then(|parent| parent.correlation_id())
54        })
55    }
56
57    /// The principal bound here, or by the nearest enclosing scope.
58    #[must_use]
59    pub fn principal(&self) -> Option<&str> {
60        self.principal
61            .as_deref()
62            .or_else(|| self.parent.as_ref().and_then(|parent| parent.principal()))
63    }
64
65    /// Look up one metadata value, innermost binding first.
66    #[must_use]
67    pub fn get(&self, key: &str) -> Option<&serde_json::Value> {
68        self.metadata
69            .get(key)
70            .or_else(|| self.parent.as_ref().and_then(|parent| parent.get(key)))
71    }
72
73    /// Every metadata key visible here, with inner bindings shadowing outer.
74    #[must_use]
75    pub fn metadata(&self) -> HashMap<String, serde_json::Value> {
76        let mut merged = self
77            .parent
78            .as_ref()
79            .map(|parent| parent.metadata())
80            .unwrap_or_default();
81        for (key, value) in &self.metadata {
82            merged.insert(key.clone(), value.clone());
83        }
84        merged
85    }
86
87    /// Make these fields the active scope for as long as the guard lives.
88    ///
89    /// Used to carry a scope onto another thread:
90    ///
91    /// ```rust
92    /// use ash_log::*;
93    ///
94    /// let _outer = Scope::new().correlation_id("req-1").enter();
95    /// let carried = Scope::current().expect("a scope is active");
96    ///
97    /// std::thread::spawn(move || {
98    ///     let _inner = carried.enter();
99    ///     // Events here carry `req-1`.
100    /// })
101    /// .join()
102    /// .unwrap();
103    /// ```
104    pub fn enter(self: Arc<Self>) -> ScopeGuard {
105        let previous = ACTIVE.with(|active| active.borrow_mut().replace(self));
106        ScopeGuard { previous }
107    }
108
109    /// Fill any field `event` has not set from these bindings.
110    ///
111    /// An explicit value on the event always wins: a scope supplies defaults,
112    /// it does not override what a call site stated.
113    pub fn apply(&self, event: &mut AuditEvent) {
114        if event.correlation_id.is_none()
115            && let Some(id) = self.correlation_id()
116        {
117            event.correlation_id = Some(id.to_string());
118        }
119        if event.principal.is_none()
120            && let Some(principal) = self.principal()
121        {
122            event.principal = Some(principal.to_string());
123        }
124        for (key, value) in self.metadata() {
125            event.metadata.entry(key).or_insert(value);
126        }
127    }
128}
129
130/// Builds a set of scope fields.
131///
132/// # Examples
133///
134/// ```rust
135/// use ash_log::*;
136/// use std::sync::Arc;
137///
138/// let logger = ash_logger!(backend: Arc::new(NoopAuditBackend));
139///
140/// let _scope = Scope::new()
141///     .correlation_id("req-7f3a")
142///     .principal("alice@example.com")
143///     .with("tenant", "acme")
144///     .enter();
145///
146/// // Both events carry the correlation ID, the principal, and `tenant`.
147/// ash_info!(logger, "handling request");
148/// ash_audit!(logger, MethodInvocation, Success, method = "transfer");
149/// ```
150#[derive(Debug, Default)]
151pub struct Scope {
152    fields: ScopeFields,
153}
154
155impl Scope {
156    /// An empty scope. Entering it inherits the enclosing scope's fields.
157    #[must_use]
158    pub fn new() -> Self {
159        Self::default()
160    }
161
162    /// Bind the correlation ID.
163    #[must_use]
164    pub fn correlation_id<S: Into<String>>(mut self, id: S) -> Self {
165        self.fields.correlation_id = Some(id.into());
166        self
167    }
168
169    /// Bind the principal.
170    #[must_use]
171    pub fn principal<S: Into<String>>(mut self, principal: S) -> Self {
172        self.fields.principal = Some(principal.into());
173        self
174    }
175
176    /// Bind one metadata field.
177    #[must_use]
178    pub fn with<K, V>(mut self, key: K, value: V) -> Self
179    where
180        K: Into<String>,
181        V: Into<serde_json::Value>,
182    {
183        self.fields.metadata.insert(key.into(), value.into());
184        self
185    }
186
187    /// Activate this scope until the returned guard is dropped.
188    ///
189    /// The enclosing scope, if any, becomes this one's parent, so its fields
190    /// are still visible unless shadowed.
191    pub fn enter(mut self) -> ScopeGuard {
192        self.fields.parent = Scope::current();
193        Arc::new(self.fields).enter()
194    }
195
196    /// The active scope on this thread, if any.
197    #[must_use]
198    pub fn current() -> Option<Arc<ScopeFields>> {
199        ACTIVE.with(|active| active.borrow().clone())
200    }
201
202    /// Apply the active scope's fields to `event`, if there is one.
203    pub fn apply_current(event: &mut AuditEvent) {
204        if let Some(scope) = Self::current() {
205            scope.apply(event);
206        }
207    }
208
209    /// The active correlation ID, for stamping an outgoing request.
210    #[must_use]
211    pub fn current_correlation_id() -> Option<String> {
212        Self::current().and_then(|scope| scope.correlation_id().map(ToString::to_string))
213    }
214}
215
216/// Restores the previous scope when dropped.
217///
218/// Must be bound to a named variable: `let _guard = ...`. Binding to `_` drops
219/// it immediately and the scope is never active.
220#[must_use = "the scope ends as soon as the guard is dropped"]
221#[derive(Debug)]
222pub struct ScopeGuard {
223    previous: Option<Arc<ScopeFields>>,
224}
225
226impl Drop for ScopeGuard {
227    fn drop(&mut self) {
228        let previous = self.previous.take();
229        ACTIVE.with(|active| {
230            *active.borrow_mut() = previous;
231        });
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use crate::{AuditEventType, AuditResult};
239    use serde_json::json;
240
241    fn event() -> AuditEvent {
242        AuditEvent::builder()
243            .event_type(AuditEventType::MethodInvocation)
244            .result(AuditResult::Success)
245            .build()
246    }
247
248    #[test]
249    fn test_fields_are_inherited_by_events() {
250        let _scope = Scope::new()
251            .correlation_id("req-1")
252            .principal("alice")
253            .with("tenant", "acme")
254            .enter();
255
256        let mut event = event();
257        Scope::apply_current(&mut event);
258
259        assert_eq!(event.correlation_id.as_deref(), Some("req-1"));
260        assert_eq!(event.principal.as_deref(), Some("alice"));
261        assert_eq!(event.metadata["tenant"], json!("acme"));
262    }
263
264    #[test]
265    fn test_an_explicit_value_wins_over_the_scope() {
266        // A scope supplies defaults; it must not overwrite what a call site
267        // stated, or an event could be attributed to the wrong principal.
268        let _scope = Scope::new()
269            .correlation_id("req-1")
270            .principal("alice")
271            .enter();
272
273        let mut event = AuditEvent::builder()
274            .event_type(AuditEventType::MethodInvocation)
275            .result(AuditResult::Success)
276            .principal("bob")
277            .build();
278        Scope::apply_current(&mut event);
279
280        assert_eq!(event.principal.as_deref(), Some("bob"));
281        assert_eq!(
282            event.correlation_id.as_deref(),
283            Some("req-1"),
284            "unset fields still come from the scope"
285        );
286    }
287
288    #[test]
289    fn test_nested_scopes_shadow_and_inherit() {
290        let _outer = Scope::new()
291            .correlation_id("req-1")
292            .with("tenant", "acme")
293            .with("stage", "outer")
294            .enter();
295
296        {
297            let _inner = Scope::new().with("stage", "inner").enter();
298
299            let mut event = event();
300            Scope::apply_current(&mut event);
301
302            assert_eq!(event.correlation_id.as_deref(), Some("req-1"), "inherited");
303            assert_eq!(event.metadata["tenant"], json!("acme"), "inherited");
304            assert_eq!(event.metadata["stage"], json!("inner"), "shadowed");
305        }
306
307        let mut after = event();
308        Scope::apply_current(&mut after);
309        assert_eq!(
310            after.metadata["stage"],
311            json!("outer"),
312            "the inner scope ended with its guard"
313        );
314    }
315
316    #[test]
317    fn test_the_scope_ends_with_its_guard() {
318        {
319            let _scope = Scope::new().correlation_id("req-1").enter();
320            assert!(Scope::current().is_some());
321        }
322        assert!(
323            Scope::current().is_none(),
324            "the guard restored the previous"
325        );
326
327        let mut event = event();
328        Scope::apply_current(&mut event);
329        assert_eq!(event.correlation_id, None);
330    }
331
332    #[test]
333    fn test_a_spawned_thread_starts_with_no_scope() {
334        // Implicit inheritance would attach a stale correlation ID to unrelated
335        // work, so a new thread must start clean.
336        let _scope = Scope::new().correlation_id("req-1").enter();
337
338        let seen = std::thread::spawn(Scope::current_correlation_id)
339            .join()
340            .expect("thread panicked");
341
342        assert_eq!(seen, None, "scopes do not leak across threads");
343    }
344
345    #[test]
346    fn test_a_scope_can_be_carried_across_a_thread_boundary() {
347        let _scope = Scope::new().correlation_id("req-1").enter();
348        let carried = Scope::current().expect("active");
349
350        let seen = std::thread::spawn(move || {
351            let _entered = carried.enter();
352            Scope::current_correlation_id()
353        })
354        .join()
355        .expect("thread panicked");
356
357        assert_eq!(seen.as_deref(), Some("req-1"), "explicitly carried over");
358    }
359
360    #[test]
361    fn test_scopes_on_different_threads_are_independent() {
362        let _scope = Scope::new().correlation_id("main").enter();
363
364        let other = std::thread::spawn(|| {
365            let _scope = Scope::new().correlation_id("worker").enter();
366            Scope::current_correlation_id()
367        })
368        .join()
369        .expect("thread panicked");
370
371        assert_eq!(other.as_deref(), Some("worker"));
372        assert_eq!(
373            Scope::current_correlation_id().as_deref(),
374            Some("main"),
375            "the worker's scope did not disturb this thread"
376        );
377    }
378}