pf_structured_logging 0.1.0

Enhanced structured logging with performance optimizations and convenience APIs for SpinKube agents
Documentation
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
//! Advanced context management for structured_logging
//!
//! This module provides domain-specific context management capabilities that build on
//! observability_core's basic trace context foundation. It includes:
//! - RAII scoped context management
//! - Domain-specific context managers (LLM, A2A, Request)
//! - Dependency injection registry
//! - Advanced correlation features

use crate::convenience::{
    clear_a2a_context, clear_llm_context, clear_request_context, set_a2a_context, set_llm_context,
    set_request_context,
};
use std::sync::{Arc, OnceLock};

// ==================== ADVANCED CONTEXT MANAGEMENT PORTS ====================

/// Port (trait) for LLM context management
///
/// Extensions like structured_logging can implement this trait to provide
/// concrete context management functionality.
pub trait LlmContextManager: Send + Sync + std::fmt::Debug {
    fn set_context(&self, model: &str, component: &str);
    fn clear_context(&self);
}

/// Port (trait) for A2A context management
pub trait A2aContextManager: Send + Sync + std::fmt::Debug {
    fn set_context(&self, message_type: &str, from_agent: &str, to_agent: &str, component: &str);
    fn clear_context(&self);
}

/// Port (trait) for request context management
pub trait RequestContextManager: Send + Sync + std::fmt::Debug {
    fn set_context(&self, request_id: &str, user_id: Option<&str>, session_id: Option<&str>);
    fn clear_context(&self);
}

/// Combined context manager that coordinates all context types
pub trait ContextManagerRegistry: Send + Sync + std::fmt::Debug {
    fn get_llm_manager(&self) -> Option<Arc<dyn LlmContextManager>>;
    fn get_a2a_manager(&self) -> Option<Arc<dyn A2aContextManager>>;
    fn get_request_manager(&self) -> Option<Arc<dyn RequestContextManager>>;
}

// ==================== GLOBAL REGISTRY ====================

/// Global registry for context managers (dependency injection)
static CONTEXT_REGISTRY: OnceLock<Arc<dyn ContextManagerRegistry>> = OnceLock::new();

/// Register a context manager registry (dependency injection)
///
/// This allows structured_logging to register its context managers
pub fn register_context_managers(registry: Arc<dyn ContextManagerRegistry>) {
    CONTEXT_REGISTRY.set(registry).ok();
}

/// Get the current context manager registry
fn get_context_registry() -> Option<Arc<dyn ContextManagerRegistry>> {
    CONTEXT_REGISTRY.get().cloned()
}

// ==================== CONCRETE IMPLEMENTATIONS ====================

/// Adapter implementing LLM context management for structured_logging
#[derive(Debug)]
pub struct StructuredLlmContextManager;

impl LlmContextManager for StructuredLlmContextManager {
    fn set_context(&self, model: &str, component: &str) {
        set_llm_context(model, component);
    }

    fn clear_context(&self) {
        clear_llm_context();
    }
}

/// Adapter implementing A2A context management for structured_logging
#[derive(Debug)]
pub struct StructuredA2aContextManager;

impl A2aContextManager for StructuredA2aContextManager {
    fn set_context(&self, message_type: &str, from_agent: &str, to_agent: &str, component: &str) {
        set_a2a_context(message_type, from_agent, to_agent, component);
    }

    fn clear_context(&self) {
        clear_a2a_context();
    }
}

/// Adapter implementing request context management for structured_logging
#[derive(Debug)]
pub struct StructuredRequestContextManager;

impl RequestContextManager for StructuredRequestContextManager {
    fn set_context(&self, request_id: &str, user_id: Option<&str>, session_id: Option<&str>) {
        set_request_context(request_id, user_id, session_id);
    }

    fn clear_context(&self) {
        clear_request_context();
    }
}

/// Registry coordinating all structured_logging context managers
#[derive(Debug)]
pub struct StructuredContextRegistry {
    llm_manager: Option<Arc<dyn LlmContextManager>>,
    a2a_manager: Option<Arc<dyn A2aContextManager>>,
    request_manager: Option<Arc<dyn RequestContextManager>>,
}

impl StructuredContextRegistry {
    /// Create a new registry with all structured_logging context managers
    pub fn new() -> Self {
        Self {
            llm_manager: Some(Arc::new(StructuredLlmContextManager)),
            a2a_manager: Some(Arc::new(StructuredA2aContextManager)),
            request_manager: Some(Arc::new(StructuredRequestContextManager)),
        }
    }

    /// Register this registry with the global context system
    pub fn register(&self) {
        let registry = Arc::new(Self {
            llm_manager: self.llm_manager.clone(),
            a2a_manager: self.a2a_manager.clone(),
            request_manager: self.request_manager.clone(),
        });

        register_context_managers(registry);
    }
}

impl Default for StructuredContextRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ContextManagerRegistry for StructuredContextRegistry {
    fn get_llm_manager(&self) -> Option<Arc<dyn LlmContextManager>> {
        self.llm_manager.clone()
    }

    fn get_a2a_manager(&self) -> Option<Arc<dyn A2aContextManager>> {
        self.a2a_manager.clone()
    }

    fn get_request_manager(&self) -> Option<Arc<dyn RequestContextManager>> {
        self.request_manager.clone()
    }
}

// ==================== RAII SCOPED CONTEXT MANAGEMENT ====================

/// RAII guard for LLM context
///
/// When this guard is dropped, the LLM context is automatically cleared.
/// This ensures exception-safe cleanup and prevents forgetting to clear context.
///
/// # Example
/// ```rust,ignore
/// {
///     let _guard = set_llm_context_scoped("gpt-4", "openai_client");
///     log::info!("This will have LLM context");
/// }
/// log::info!("This will NOT have LLM context");
/// ```
pub struct LlmContextGuard {
    _phantom: std::marker::PhantomData<()>,
}

impl Drop for LlmContextGuard {
    fn drop(&mut self) {
        // Use dependency injection to clear context
        if let Some(registry) = get_context_registry() {
            if let Some(manager) = registry.get_llm_manager() {
                manager.clear_context();
            }
        }
    }
}

/// RAII guard for A2A context
///
/// Automatically clears A2A context when dropped, providing exception-safe cleanup.
pub struct A2aContextGuard {
    _phantom: std::marker::PhantomData<()>,
}

impl Drop for A2aContextGuard {
    fn drop(&mut self) {
        // Use dependency injection to clear context
        if let Some(registry) = get_context_registry() {
            if let Some(manager) = registry.get_a2a_manager() {
                manager.clear_context();
            }
        }
    }
}

/// RAII guard for request context
///
/// Automatically clears request context when dropped, providing exception-safe cleanup.
pub struct RequestContextGuard {
    _phantom: std::marker::PhantomData<()>,
}

impl Drop for RequestContextGuard {
    fn drop(&mut self) {
        // Use dependency injection to clear context
        if let Some(registry) = get_context_registry() {
            if let Some(manager) = registry.get_request_manager() {
                manager.clear_context();
            }
        }
    }
}

/// Combined RAII guard for all contexts
///
/// When dropped, clears all contexts in the correct order.
/// This is the safest option for complex operations.
pub struct AllContextsGuard {
    _phantom: std::marker::PhantomData<()>,
}

impl Drop for AllContextsGuard {
    fn drop(&mut self) {
        // Use dependency injection to clear all contexts
        if let Some(registry) = get_context_registry() {
            // Clear in reverse order (LIFO) for proper cleanup
            if let Some(manager) = registry.get_request_manager() {
                manager.clear_context();
            }
            if let Some(manager) = registry.get_a2a_manager() {
                manager.clear_context();
            }
            if let Some(manager) = registry.get_llm_manager() {
                manager.clear_context();
            }
        }
    }
}

// ==================== SCOPED CONTEXT SETTING APIS ====================

/// Set LLM context with RAII guard
///
/// Returns a guard that will automatically clear the context when dropped.
/// This is the safest way to set LLM context as cleanup is guaranteed.
///
/// # Example
/// ```rust,ignore
/// let _guard = set_llm_context_scoped("gpt-4", "openai_client");
/// log::info!("Processing LLM request");
/// ```
pub fn set_llm_context_scoped(model: &str, component: &str) -> LlmContextGuard {
    if let Some(registry) = get_context_registry() {
        if let Some(manager) = registry.get_llm_manager() {
            manager.set_context(model, component);
        }
    }
    LlmContextGuard {
        _phantom: std::marker::PhantomData,
    }
}

/// Set A2A context with RAII guard
///
/// Returns a guard that will automatically clear the context when dropped.
pub fn set_a2a_context_scoped(
    message_type: &str,
    from_agent: &str,
    to_agent: &str,
    component: &str,
) -> A2aContextGuard {
    if let Some(registry) = get_context_registry() {
        if let Some(manager) = registry.get_a2a_manager() {
            manager.set_context(message_type, from_agent, to_agent, component);
        }
    }
    A2aContextGuard {
        _phantom: std::marker::PhantomData,
    }
}

/// Set request context with RAII guard
///
/// Returns a guard that will automatically clear the context when dropped.
pub fn set_request_context_scoped(
    request_id: &str,
    user_id: Option<&str>,
    session_id: Option<&str>,
) -> RequestContextGuard {
    if let Some(registry) = get_context_registry() {
        if let Some(manager) = registry.get_request_manager() {
            manager.set_context(request_id, user_id, session_id);
        }
    }
    RequestContextGuard {
        _phantom: std::marker::PhantomData,
    }
}

/// Set all contexts with combined RAII guard
///
/// Returns a guard that will automatically clear all contexts when dropped.
/// This is the most comprehensive option for complex operations.
pub fn set_all_contexts_scoped(
    // LLM context
    model: &str,
    component: &str,
    // A2A context
    message_type: &str,
    from_agent: &str,
    to_agent: &str,
    a2a_component: &str,
    // Request context
    request_id: &str,
    user_id: Option<&str>,
    session_id: Option<&str>,
) -> AllContextsGuard {
    if let Some(registry) = get_context_registry() {
        if let Some(manager) = registry.get_llm_manager() {
            manager.set_context(model, component);
        }
        if let Some(manager) = registry.get_a2a_manager() {
            manager.set_context(message_type, from_agent, to_agent, a2a_component);
        }
        if let Some(manager) = registry.get_request_manager() {
            manager.set_context(request_id, user_id, session_id);
        }
    }

    AllContextsGuard {
        _phantom: std::marker::PhantomData,
    }
}

// ==================== SCOPED CALLBACK APIS ====================

/// Execute a closure with LLM context, automatically clearing when done
///
/// This is the most secure pattern as it guarantees context cleanup
/// even if the closure panics or returns early.
///
/// # Example
/// ```rust,ignore
/// let result = with_llm_context("gpt-4", "openai_client", || {
///     log::info!("This has LLM context");
///     process_llm_request()
/// });
/// ```
pub fn with_llm_context<F, R>(model: &str, component: &str, f: F) -> R
where
    F: FnOnce() -> R,
{
    let _guard = set_llm_context_scoped(model, component);
    f()
}

/// Execute a closure with A2A context, automatically clearing when done
pub fn with_a2a_context<F, R>(
    message_type: &str,
    from_agent: &str,
    to_agent: &str,
    component: &str,
    f: F,
) -> R
where
    F: FnOnce() -> R,
{
    let _guard = set_a2a_context_scoped(message_type, from_agent, to_agent, component);
    f()
}

/// Execute a closure with request context, automatically clearing when done  
pub fn with_request_context<F, R>(
    request_id: &str,
    user_id: Option<&str>,
    session_id: Option<&str>,
    f: F,
) -> R
where
    F: FnOnce() -> R,
{
    let _guard = set_request_context_scoped(request_id, user_id, session_id);
    f()
}

/// Execute a closure with all contexts, automatically clearing when done
///
/// This is the most comprehensive scoped API that sets all contexts
/// and guarantees cleanup regardless of how the closure exits.
pub fn with_all_contexts<F, R>(
    // LLM context
    model: &str,
    component: &str,
    // A2A context
    message_type: &str,
    from_agent: &str,
    to_agent: &str,
    a2a_component: &str,
    // Request context
    request_id: &str,
    user_id: Option<&str>,
    session_id: Option<&str>,
    // Closure to execute
    f: F,
) -> R
where
    F: FnOnce() -> R,
{
    let _guard = set_all_contexts_scoped(
        model,
        component,
        message_type,
        from_agent,
        to_agent,
        a2a_component,
        request_id,
        user_id,
        session_id,
    );
    f()
}

// ==================== NESTED CONTEXT SUPPORT ====================

/// Scoped context builder for complex nested operations
///
/// Allows building up contexts step by step with automatic cleanup.
/// Each context level gets its own guard for fine-grained control.
pub struct ScopedContextBuilder {
    guards: Vec<Box<dyn std::any::Any + Send>>,
}

impl ScopedContextBuilder {
    pub fn new() -> Self {
        Self { guards: Vec::new() }
    }

    pub fn with_llm_context(mut self, model: &str, component: &str) -> Self {
        let guard = set_llm_context_scoped(model, component);
        self.guards.push(Box::new(guard));
        self
    }

    pub fn with_a2a_context(
        mut self,
        message_type: &str,
        from_agent: &str,
        to_agent: &str,
        component: &str,
    ) -> Self {
        let guard = set_a2a_context_scoped(message_type, from_agent, to_agent, component);
        self.guards.push(Box::new(guard));
        self
    }

    pub fn with_request_context(
        mut self,
        request_id: &str,
        user_id: Option<&str>,
        session_id: Option<&str>,
    ) -> Self {
        let guard = set_request_context_scoped(request_id, user_id, session_id);
        self.guards.push(Box::new(guard));
        self
    }

    /// Execute a closure with all built contexts active
    pub fn execute<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        // All guards are held by self, so contexts remain active
        // until ScopedContextBuilder is dropped
        f()
    }
}

impl Drop for ScopedContextBuilder {
    fn drop(&mut self) {
        // Guards will be dropped in reverse order (LIFO)
        // which provides correct cleanup semantics
        self.guards.clear();
    }
}

impl Default for ScopedContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ==================== CONVENIENCE MACROS ====================

/// Macro for easy scoped LLM context
///
/// # Example
/// ```rust,ignore
/// with_llm_context_scoped!("gpt-4", "openai_client" => {
///     log::info!("Processing with LLM context");
/// });
/// ```
#[macro_export]
macro_rules! with_llm_context_scoped {
    ($model:expr_2021, $component:expr_2021 => $block:block) => {
        $crate::context_adapter::with_llm_context($model, $component, || $block)
    };
}

/// Macro for easy scoped A2A context
#[macro_export]
macro_rules! with_a2a_context_scoped {
    ($message_type:expr_2021, $from_agent:expr_2021, $to_agent:expr_2021, $component:expr_2021 => $block:block) => {
        $crate::context_adapter::with_a2a_context(
            $message_type,
            $from_agent,
            $to_agent,
            $component,
            || $block,
        )
    };
}

/// Macro for easy scoped request context
#[macro_export]
macro_rules! with_request_context_scoped {
    ($request_id:expr_2021, $user_id:expr_2021, $session_id:expr_2021 => $block:block) => {
        $crate::context_adapter::with_request_context($request_id, $user_id, $session_id, || $block)
    };
}

/// Initialize structured_logging context management integration
///
/// Call this once during application startup to enable advanced RAII context
/// management features in structured_logging.
///
/// # Example
/// ```rust,ignore
/// use structured_logging::context_adapter::init_context_integration;
/// init_context_integration();
/// let _guard = set_llm_context_scoped("gpt-4", "my_component");
/// log::info!("This log will have LLM context automatically");
/// ```
pub fn init_context_integration() {
    let registry = StructuredContextRegistry::new();
    registry.register();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_context_integration() {
        init_context_integration();

        // Test that RAII guards work with structured_logging backend
        {
            let _guard = set_llm_context_scoped("gpt-4", "test_component");
            // Context should be set now
        }
        // Context should be cleared when guard is dropped
    }

    #[test]
    fn test_scoped_callback_integration() {
        init_context_integration();

        // Test that scoped callbacks work with structured_logging backend
        let result = with_llm_context("gpt-4", "test_component", || "test_result");

        assert_eq!(result, "test_result");
        // Context should be cleared automatically
    }

    #[test]
    fn test_scoped_builder() {
        init_context_integration();

        let builder = ScopedContextBuilder::new()
            .with_llm_context("gpt-4", "test_component")
            .with_request_context("req-123", Some("user-456"), None);

        let result = builder.execute(|| "builder_test");

        assert_eq!(result, "builder_test");
    }
}