1use super::AuditEvent;
26use std::cell::RefCell;
27use std::collections::HashMap;
28use std::sync::Arc;
29
30thread_local! {
31 static ACTIVE: RefCell<Option<Arc<ScopeFields>>> = const { RefCell::new(None) };
33}
34
35#[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 #[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 #[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 #[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 #[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 pub fn enter(self: Arc<Self>) -> ScopeGuard {
105 let previous = ACTIVE.with(|active| active.borrow_mut().replace(self));
106 ScopeGuard { previous }
107 }
108
109 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#[derive(Debug, Default)]
151pub struct Scope {
152 fields: ScopeFields,
153}
154
155impl Scope {
156 #[must_use]
158 pub fn new() -> Self {
159 Self::default()
160 }
161
162 #[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 #[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 #[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 pub fn enter(mut self) -> ScopeGuard {
192 self.fields.parent = Scope::current();
193 Arc::new(self.fields).enter()
194 }
195
196 #[must_use]
198 pub fn current() -> Option<Arc<ScopeFields>> {
199 ACTIVE.with(|active| active.borrow().clone())
200 }
201
202 pub fn apply_current(event: &mut AuditEvent) {
204 if let Some(scope) = Self::current() {
205 scope.apply(event);
206 }
207 }
208
209 #[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#[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 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 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}