Skip to main content

structured_logging/
context_adapter.rs

1//! Advanced context management for structured_logging
2//!
3//! This module provides domain-specific context management capabilities that build on
4//! observability_core's basic trace context foundation. It includes:
5//! - RAII scoped context management
6//! - Domain-specific context managers (LLM, A2A, Request)
7//! - Dependency injection registry
8//! - Advanced correlation features
9
10use crate::convenience::{
11    clear_a2a_context, clear_llm_context, clear_request_context, set_a2a_context, set_llm_context,
12    set_request_context,
13};
14use std::sync::{Arc, OnceLock};
15
16// ==================== ADVANCED CONTEXT MANAGEMENT PORTS ====================
17
18/// Port (trait) for LLM context management
19///
20/// Extensions like structured_logging can implement this trait to provide
21/// concrete context management functionality.
22pub trait LlmContextManager: Send + Sync + std::fmt::Debug {
23    fn set_context(&self, model: &str, component: &str);
24    fn clear_context(&self);
25}
26
27/// Port (trait) for A2A context management
28pub trait A2aContextManager: Send + Sync + std::fmt::Debug {
29    fn set_context(&self, message_type: &str, from_agent: &str, to_agent: &str, component: &str);
30    fn clear_context(&self);
31}
32
33/// Port (trait) for request context management
34pub trait RequestContextManager: Send + Sync + std::fmt::Debug {
35    fn set_context(&self, request_id: &str, user_id: Option<&str>, session_id: Option<&str>);
36    fn clear_context(&self);
37}
38
39/// Combined context manager that coordinates all context types
40pub trait ContextManagerRegistry: Send + Sync + std::fmt::Debug {
41    fn get_llm_manager(&self) -> Option<Arc<dyn LlmContextManager>>;
42    fn get_a2a_manager(&self) -> Option<Arc<dyn A2aContextManager>>;
43    fn get_request_manager(&self) -> Option<Arc<dyn RequestContextManager>>;
44}
45
46// ==================== GLOBAL REGISTRY ====================
47
48/// Global registry for context managers (dependency injection)
49static CONTEXT_REGISTRY: OnceLock<Arc<dyn ContextManagerRegistry>> = OnceLock::new();
50
51/// Register a context manager registry (dependency injection)
52///
53/// This allows structured_logging to register its context managers
54pub fn register_context_managers(registry: Arc<dyn ContextManagerRegistry>) {
55    CONTEXT_REGISTRY.set(registry).ok();
56}
57
58/// Get the current context manager registry
59fn get_context_registry() -> Option<Arc<dyn ContextManagerRegistry>> {
60    CONTEXT_REGISTRY.get().cloned()
61}
62
63// ==================== CONCRETE IMPLEMENTATIONS ====================
64
65/// Adapter implementing LLM context management for structured_logging
66#[derive(Debug)]
67pub struct StructuredLlmContextManager;
68
69impl LlmContextManager for StructuredLlmContextManager {
70    fn set_context(&self, model: &str, component: &str) {
71        set_llm_context(model, component);
72    }
73
74    fn clear_context(&self) {
75        clear_llm_context();
76    }
77}
78
79/// Adapter implementing A2A context management for structured_logging
80#[derive(Debug)]
81pub struct StructuredA2aContextManager;
82
83impl A2aContextManager for StructuredA2aContextManager {
84    fn set_context(&self, message_type: &str, from_agent: &str, to_agent: &str, component: &str) {
85        set_a2a_context(message_type, from_agent, to_agent, component);
86    }
87
88    fn clear_context(&self) {
89        clear_a2a_context();
90    }
91}
92
93/// Adapter implementing request context management for structured_logging
94#[derive(Debug)]
95pub struct StructuredRequestContextManager;
96
97impl RequestContextManager for StructuredRequestContextManager {
98    fn set_context(&self, request_id: &str, user_id: Option<&str>, session_id: Option<&str>) {
99        set_request_context(request_id, user_id, session_id);
100    }
101
102    fn clear_context(&self) {
103        clear_request_context();
104    }
105}
106
107/// Registry coordinating all structured_logging context managers
108#[derive(Debug)]
109pub struct StructuredContextRegistry {
110    llm_manager: Option<Arc<dyn LlmContextManager>>,
111    a2a_manager: Option<Arc<dyn A2aContextManager>>,
112    request_manager: Option<Arc<dyn RequestContextManager>>,
113}
114
115impl StructuredContextRegistry {
116    /// Create a new registry with all structured_logging context managers
117    pub fn new() -> Self {
118        Self {
119            llm_manager: Some(Arc::new(StructuredLlmContextManager)),
120            a2a_manager: Some(Arc::new(StructuredA2aContextManager)),
121            request_manager: Some(Arc::new(StructuredRequestContextManager)),
122        }
123    }
124
125    /// Register this registry with the global context system
126    pub fn register(&self) {
127        let registry = Arc::new(Self {
128            llm_manager: self.llm_manager.clone(),
129            a2a_manager: self.a2a_manager.clone(),
130            request_manager: self.request_manager.clone(),
131        });
132
133        register_context_managers(registry);
134    }
135}
136
137impl Default for StructuredContextRegistry {
138    fn default() -> Self {
139        Self::new()
140    }
141}
142
143impl ContextManagerRegistry for StructuredContextRegistry {
144    fn get_llm_manager(&self) -> Option<Arc<dyn LlmContextManager>> {
145        self.llm_manager.clone()
146    }
147
148    fn get_a2a_manager(&self) -> Option<Arc<dyn A2aContextManager>> {
149        self.a2a_manager.clone()
150    }
151
152    fn get_request_manager(&self) -> Option<Arc<dyn RequestContextManager>> {
153        self.request_manager.clone()
154    }
155}
156
157// ==================== RAII SCOPED CONTEXT MANAGEMENT ====================
158
159/// RAII guard for LLM context
160///
161/// When this guard is dropped, the LLM context is automatically cleared.
162/// This ensures exception-safe cleanup and prevents forgetting to clear context.
163///
164/// # Example
165/// ```rust,ignore
166/// {
167///     let _guard = set_llm_context_scoped("gpt-4", "openai_client");
168///     log::info!("This will have LLM context");
169/// }
170/// log::info!("This will NOT have LLM context");
171/// ```
172pub struct LlmContextGuard {
173    _phantom: std::marker::PhantomData<()>,
174}
175
176impl Drop for LlmContextGuard {
177    fn drop(&mut self) {
178        // Use dependency injection to clear context
179        if let Some(registry) = get_context_registry() {
180            if let Some(manager) = registry.get_llm_manager() {
181                manager.clear_context();
182            }
183        }
184    }
185}
186
187/// RAII guard for A2A context
188///
189/// Automatically clears A2A context when dropped, providing exception-safe cleanup.
190pub struct A2aContextGuard {
191    _phantom: std::marker::PhantomData<()>,
192}
193
194impl Drop for A2aContextGuard {
195    fn drop(&mut self) {
196        // Use dependency injection to clear context
197        if let Some(registry) = get_context_registry() {
198            if let Some(manager) = registry.get_a2a_manager() {
199                manager.clear_context();
200            }
201        }
202    }
203}
204
205/// RAII guard for request context
206///
207/// Automatically clears request context when dropped, providing exception-safe cleanup.
208pub struct RequestContextGuard {
209    _phantom: std::marker::PhantomData<()>,
210}
211
212impl Drop for RequestContextGuard {
213    fn drop(&mut self) {
214        // Use dependency injection to clear context
215        if let Some(registry) = get_context_registry() {
216            if let Some(manager) = registry.get_request_manager() {
217                manager.clear_context();
218            }
219        }
220    }
221}
222
223/// Combined RAII guard for all contexts
224///
225/// When dropped, clears all contexts in the correct order.
226/// This is the safest option for complex operations.
227pub struct AllContextsGuard {
228    _phantom: std::marker::PhantomData<()>,
229}
230
231impl Drop for AllContextsGuard {
232    fn drop(&mut self) {
233        // Use dependency injection to clear all contexts
234        if let Some(registry) = get_context_registry() {
235            // Clear in reverse order (LIFO) for proper cleanup
236            if let Some(manager) = registry.get_request_manager() {
237                manager.clear_context();
238            }
239            if let Some(manager) = registry.get_a2a_manager() {
240                manager.clear_context();
241            }
242            if let Some(manager) = registry.get_llm_manager() {
243                manager.clear_context();
244            }
245        }
246    }
247}
248
249// ==================== SCOPED CONTEXT SETTING APIS ====================
250
251/// Set LLM context with RAII guard
252///
253/// Returns a guard that will automatically clear the context when dropped.
254/// This is the safest way to set LLM context as cleanup is guaranteed.
255///
256/// # Example
257/// ```rust,ignore
258/// let _guard = set_llm_context_scoped("gpt-4", "openai_client");
259/// log::info!("Processing LLM request");
260/// ```
261pub fn set_llm_context_scoped(model: &str, component: &str) -> LlmContextGuard {
262    if let Some(registry) = get_context_registry() {
263        if let Some(manager) = registry.get_llm_manager() {
264            manager.set_context(model, component);
265        }
266    }
267    LlmContextGuard {
268        _phantom: std::marker::PhantomData,
269    }
270}
271
272/// Set A2A context with RAII guard
273///
274/// Returns a guard that will automatically clear the context when dropped.
275pub fn set_a2a_context_scoped(
276    message_type: &str,
277    from_agent: &str,
278    to_agent: &str,
279    component: &str,
280) -> A2aContextGuard {
281    if let Some(registry) = get_context_registry() {
282        if let Some(manager) = registry.get_a2a_manager() {
283            manager.set_context(message_type, from_agent, to_agent, component);
284        }
285    }
286    A2aContextGuard {
287        _phantom: std::marker::PhantomData,
288    }
289}
290
291/// Set request context with RAII guard
292///
293/// Returns a guard that will automatically clear the context when dropped.
294pub fn set_request_context_scoped(
295    request_id: &str,
296    user_id: Option<&str>,
297    session_id: Option<&str>,
298) -> RequestContextGuard {
299    if let Some(registry) = get_context_registry() {
300        if let Some(manager) = registry.get_request_manager() {
301            manager.set_context(request_id, user_id, session_id);
302        }
303    }
304    RequestContextGuard {
305        _phantom: std::marker::PhantomData,
306    }
307}
308
309/// Set all contexts with combined RAII guard
310///
311/// Returns a guard that will automatically clear all contexts when dropped.
312/// This is the most comprehensive option for complex operations.
313pub fn set_all_contexts_scoped(
314    // LLM context
315    model: &str,
316    component: &str,
317    // A2A context
318    message_type: &str,
319    from_agent: &str,
320    to_agent: &str,
321    a2a_component: &str,
322    // Request context
323    request_id: &str,
324    user_id: Option<&str>,
325    session_id: Option<&str>,
326) -> AllContextsGuard {
327    if let Some(registry) = get_context_registry() {
328        if let Some(manager) = registry.get_llm_manager() {
329            manager.set_context(model, component);
330        }
331        if let Some(manager) = registry.get_a2a_manager() {
332            manager.set_context(message_type, from_agent, to_agent, a2a_component);
333        }
334        if let Some(manager) = registry.get_request_manager() {
335            manager.set_context(request_id, user_id, session_id);
336        }
337    }
338
339    AllContextsGuard {
340        _phantom: std::marker::PhantomData,
341    }
342}
343
344// ==================== SCOPED CALLBACK APIS ====================
345
346/// Execute a closure with LLM context, automatically clearing when done
347///
348/// This is the most secure pattern as it guarantees context cleanup
349/// even if the closure panics or returns early.
350///
351/// # Example
352/// ```rust,ignore
353/// let result = with_llm_context("gpt-4", "openai_client", || {
354///     log::info!("This has LLM context");
355///     process_llm_request()
356/// });
357/// ```
358pub fn with_llm_context<F, R>(model: &str, component: &str, f: F) -> R
359where
360    F: FnOnce() -> R,
361{
362    let _guard = set_llm_context_scoped(model, component);
363    f()
364}
365
366/// Execute a closure with A2A context, automatically clearing when done
367pub fn with_a2a_context<F, R>(
368    message_type: &str,
369    from_agent: &str,
370    to_agent: &str,
371    component: &str,
372    f: F,
373) -> R
374where
375    F: FnOnce() -> R,
376{
377    let _guard = set_a2a_context_scoped(message_type, from_agent, to_agent, component);
378    f()
379}
380
381/// Execute a closure with request context, automatically clearing when done  
382pub fn with_request_context<F, R>(
383    request_id: &str,
384    user_id: Option<&str>,
385    session_id: Option<&str>,
386    f: F,
387) -> R
388where
389    F: FnOnce() -> R,
390{
391    let _guard = set_request_context_scoped(request_id, user_id, session_id);
392    f()
393}
394
395/// Execute a closure with all contexts, automatically clearing when done
396///
397/// This is the most comprehensive scoped API that sets all contexts
398/// and guarantees cleanup regardless of how the closure exits.
399pub fn with_all_contexts<F, R>(
400    // LLM context
401    model: &str,
402    component: &str,
403    // A2A context
404    message_type: &str,
405    from_agent: &str,
406    to_agent: &str,
407    a2a_component: &str,
408    // Request context
409    request_id: &str,
410    user_id: Option<&str>,
411    session_id: Option<&str>,
412    // Closure to execute
413    f: F,
414) -> R
415where
416    F: FnOnce() -> R,
417{
418    let _guard = set_all_contexts_scoped(
419        model,
420        component,
421        message_type,
422        from_agent,
423        to_agent,
424        a2a_component,
425        request_id,
426        user_id,
427        session_id,
428    );
429    f()
430}
431
432// ==================== NESTED CONTEXT SUPPORT ====================
433
434/// Scoped context builder for complex nested operations
435///
436/// Allows building up contexts step by step with automatic cleanup.
437/// Each context level gets its own guard for fine-grained control.
438pub struct ScopedContextBuilder {
439    guards: Vec<Box<dyn std::any::Any + Send>>,
440}
441
442impl ScopedContextBuilder {
443    pub fn new() -> Self {
444        Self { guards: Vec::new() }
445    }
446
447    pub fn with_llm_context(mut self, model: &str, component: &str) -> Self {
448        let guard = set_llm_context_scoped(model, component);
449        self.guards.push(Box::new(guard));
450        self
451    }
452
453    pub fn with_a2a_context(
454        mut self,
455        message_type: &str,
456        from_agent: &str,
457        to_agent: &str,
458        component: &str,
459    ) -> Self {
460        let guard = set_a2a_context_scoped(message_type, from_agent, to_agent, component);
461        self.guards.push(Box::new(guard));
462        self
463    }
464
465    pub fn with_request_context(
466        mut self,
467        request_id: &str,
468        user_id: Option<&str>,
469        session_id: Option<&str>,
470    ) -> Self {
471        let guard = set_request_context_scoped(request_id, user_id, session_id);
472        self.guards.push(Box::new(guard));
473        self
474    }
475
476    /// Execute a closure with all built contexts active
477    pub fn execute<F, R>(&self, f: F) -> R
478    where
479        F: FnOnce() -> R,
480    {
481        // All guards are held by self, so contexts remain active
482        // until ScopedContextBuilder is dropped
483        f()
484    }
485}
486
487impl Drop for ScopedContextBuilder {
488    fn drop(&mut self) {
489        // Guards will be dropped in reverse order (LIFO)
490        // which provides correct cleanup semantics
491        self.guards.clear();
492    }
493}
494
495impl Default for ScopedContextBuilder {
496    fn default() -> Self {
497        Self::new()
498    }
499}
500
501// ==================== CONVENIENCE MACROS ====================
502
503/// Macro for easy scoped LLM context
504///
505/// # Example
506/// ```rust,ignore
507/// with_llm_context_scoped!("gpt-4", "openai_client" => {
508///     log::info!("Processing with LLM context");
509/// });
510/// ```
511#[macro_export]
512macro_rules! with_llm_context_scoped {
513    ($model:expr_2021, $component:expr_2021 => $block:block) => {
514        $crate::context_adapter::with_llm_context($model, $component, || $block)
515    };
516}
517
518/// Macro for easy scoped A2A context
519#[macro_export]
520macro_rules! with_a2a_context_scoped {
521    ($message_type:expr_2021, $from_agent:expr_2021, $to_agent:expr_2021, $component:expr_2021 => $block:block) => {
522        $crate::context_adapter::with_a2a_context(
523            $message_type,
524            $from_agent,
525            $to_agent,
526            $component,
527            || $block,
528        )
529    };
530}
531
532/// Macro for easy scoped request context
533#[macro_export]
534macro_rules! with_request_context_scoped {
535    ($request_id:expr_2021, $user_id:expr_2021, $session_id:expr_2021 => $block:block) => {
536        $crate::context_adapter::with_request_context($request_id, $user_id, $session_id, || $block)
537    };
538}
539
540/// Initialize structured_logging context management integration
541///
542/// Call this once during application startup to enable advanced RAII context
543/// management features in structured_logging.
544///
545/// # Example
546/// ```rust,ignore
547/// use structured_logging::context_adapter::init_context_integration;
548/// init_context_integration();
549/// let _guard = set_llm_context_scoped("gpt-4", "my_component");
550/// log::info!("This log will have LLM context automatically");
551/// ```
552pub fn init_context_integration() {
553    let registry = StructuredContextRegistry::new();
554    registry.register();
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    #[test]
562    fn test_context_integration() {
563        init_context_integration();
564
565        // Test that RAII guards work with structured_logging backend
566        {
567            let _guard = set_llm_context_scoped("gpt-4", "test_component");
568            // Context should be set now
569        }
570        // Context should be cleared when guard is dropped
571    }
572
573    #[test]
574    fn test_scoped_callback_integration() {
575        init_context_integration();
576
577        // Test that scoped callbacks work with structured_logging backend
578        let result = with_llm_context("gpt-4", "test_component", || "test_result");
579
580        assert_eq!(result, "test_result");
581        // Context should be cleared automatically
582    }
583
584    #[test]
585    fn test_scoped_builder() {
586        init_context_integration();
587
588        let builder = ScopedContextBuilder::new()
589            .with_llm_context("gpt-4", "test_component")
590            .with_request_context("req-123", Some("user-456"), None);
591
592        let result = builder.execute(|| "builder_test");
593
594        assert_eq!(result, "builder_test");
595    }
596}