cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
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
//! Enhanced tracing configuration for cuenv CLI
//!
//! This module provides structured, contextual tracing with multiple output formats,
//! correlation IDs, performance instrumentation, and structured event capture.

use cuenv_events::{CuenvEventLayer, EventBus, EventReceiver};
use std::io;
use std::sync::OnceLock;
pub use tracing::Level;
use tracing_subscriber::{filter::EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
use uuid::Uuid;

/// Global `EventBus` for the application.
/// Set during initialization and can be accessed from anywhere to subscribe to events.
static GLOBAL_EVENT_BUS: OnceLock<EventBus> = OnceLock::new();

/// Subscribe to the global event bus.
///
/// Returns `None` if the event bus hasn't been initialized yet (e.g., during tests
/// or if called before `init_tracing_with_events`).
#[must_use]
pub fn subscribe_global_events() -> Option<EventReceiver> {
    GLOBAL_EVENT_BUS.get().map(EventBus::subscribe)
}

/// Shut down the global event bus.
///
/// This must be called before the tokio runtime shuts down to prevent deadlocks.
/// After calling this, the forwarding task will exit and no more events can be sent.
///
/// This function is safe to call multiple times or if the event bus was never initialized.
pub fn shutdown_global_events() {
    if let Some(bus) = GLOBAL_EVENT_BUS.get() {
        bus.shutdown();
    }
}

/// Tracing output format options
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum TracingFormat {
    /// Pretty-printed human-readable format
    Pretty,
    /// Compact single-line format
    Compact,
    /// Structured JSON format
    Json,
    /// Development format with extra context
    Dev,
}

/// Log level options for CLI
#[derive(Debug, Clone, clap::ValueEnum)]
pub enum LogLevel {
    /// Show all logs (trace level)
    Trace,
    /// Show debug and above
    Debug,
    /// Show info and above
    Info,
    /// Show warnings and above (default)
    Warn,
    /// Show errors only
    Error,
}

impl From<LogLevel> for Level {
    fn from(level: LogLevel) -> Self {
        match level {
            LogLevel::Trace => Self::TRACE,
            LogLevel::Debug => Self::DEBUG,
            LogLevel::Info => Self::INFO,
            LogLevel::Warn => Self::WARN,
            LogLevel::Error => Self::ERROR,
        }
    }
}

impl std::str::FromStr for TracingFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "pretty" => Ok(Self::Pretty),
            "compact" => Ok(Self::Compact),
            "json" => Ok(Self::Json),
            "dev" => Ok(Self::Dev),
            _ => Err(format!("Unknown tracing format: {s}")),
        }
    }
}

/// Tracing configuration options.
///
/// Controls format, log level, and optional features like correlation IDs
/// and file location tracking.
#[derive(Debug, Clone)]
pub struct TracingConfig {
    /// Output format for log messages.
    pub format: TracingFormat,
    /// Minimum log level to capture.
    pub level: Level,
    /// Whether to include correlation IDs in log output.
    pub enable_correlation_ids: bool,
    /// Whether to include timestamps in log output.
    pub enable_timestamps: bool,
    /// Whether to include file/line location in log output.
    pub enable_file_location: bool,
    /// Optional custom filter string (overrides level-based filtering).
    pub filter: Option<String>,
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            format: TracingFormat::Pretty,
            level: Level::WARN, // Default to quiet operation
            enable_correlation_ids: true,
            enable_timestamps: true,
            enable_file_location: true,
            filter: None,
        }
    }
}

/// Global correlation ID for tracing request correlation
static CORRELATION_ID: std::sync::OnceLock<Uuid> = std::sync::OnceLock::new();

/// Get or create a correlation ID for the current session.
///
/// Returns the same UUID for all calls within a single process execution.
#[must_use]
pub fn correlation_id() -> Uuid {
    *CORRELATION_ID.get_or_init(Uuid::new_v4)
}

/// Initialize tracing with the given configuration.
///
/// Sets up the tracing subscriber with the specified format, level, and filters.
///
/// # Errors
///
/// Returns an error if the tracing filter configuration is invalid.
pub fn init_tracing(config: TracingConfig) -> miette::Result<()> {
    let correlation_id = correlation_id();

    // Create base filter
    let env_filter = if let Some(filter) = config.filter {
        EnvFilter::try_new(filter)
    } else {
        EnvFilter::try_from_default_env().or_else(|_| {
            let level_str = match config.level {
                Level::TRACE => "trace",
                Level::DEBUG => "debug",
                Level::INFO => "info",
                Level::WARN => "warn",
                Level::ERROR => "error",
            };
            EnvFilter::try_new(format!(
                "cuenv={level_str},cuenv_cli={level_str},cuenv_core={level_str},cuengine={level_str}"
            ))
        })
    }
    .map_err(|e| miette::miette!("Failed to create tracing filter: {e}"))?;

    let registry = tracing_subscriber::registry().with(env_filter);

    match config.format {
        TracingFormat::Pretty => {
            let layer = tracing_subscriber::fmt::layer()
                .pretty()
                .with_writer(io::stderr)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true);

            registry.with(layer).init();
        }
        TracingFormat::Compact => {
            let layer = tracing_subscriber::fmt::layer()
                .compact()
                .with_writer(io::stderr)
                .with_target(false)
                .with_thread_ids(false);

            registry.with(layer).init();
        }
        TracingFormat::Json => {
            let layer = tracing_subscriber::fmt::layer()
                .json()
                .with_writer(io::stderr)
                .with_current_span(true)
                .with_span_list(true);

            registry.with(layer).init();
        }
        TracingFormat::Dev => {
            let layer = tracing_subscriber::fmt::layer()
                .with_writer(io::stderr)
                .with_file(config.enable_file_location)
                .with_line_number(config.enable_file_location)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_level(true);

            registry.with(layer).init();
        }
    }

    tracing::info!(
        correlation_id = %correlation_id,
        version = env!("CARGO_PKG_VERSION"),
        format = ?config.format,
        "Tracing initialized for cuenv CLI"
    );

    Ok(())
}

/// Initialize tracing with event capture support.
///
/// Returns an `EventReceiver` for the main renderer (CLI, JSON, etc.).
/// The global `EventBus` is stored internally and can be subscribed to
/// via `subscribe_global_events()` for additional subscribers (like TUI).
///
/// # Errors
///
/// Returns an error if the tracing filter is invalid or the event bus is
/// already initialized.
#[allow(clippy::needless_pass_by_value)] // Config is small and taking by value is more ergonomic
pub fn init_tracing_with_events(config: TracingConfig) -> miette::Result<EventReceiver> {
    // Sync correlation ID with cuenv_events
    let corr_id = correlation_id();
    cuenv_events::set_correlation_id(corr_id);

    // Create event bus and layer
    let event_bus = EventBus::new();
    let sender = event_bus
        .sender()
        .ok_or_else(|| miette::miette!("EventBus sender unavailable"))?;
    let event_layer = CuenvEventLayer::new(sender.into_inner());

    // Get a receiver for the main renderer before storing the bus globally
    let main_receiver = event_bus.subscribe();

    // Store the bus globally for additional subscribers (like TUI)
    if GLOBAL_EVENT_BUS.set(event_bus).is_err() {
        return Err(miette::miette!("Global event bus already initialized"));
    }

    // Create base filter - always capture cuenv events at info level
    let env_filter = if let Some(ref filter) = config.filter {
        EnvFilter::try_new(filter)
    } else {
        EnvFilter::try_from_default_env().or_else(|_| {
            let level_str = match config.level {
                Level::TRACE => "trace",
                Level::DEBUG => "debug",
                Level::INFO => "info",
                Level::WARN => "warn",
                Level::ERROR => "error",
            };
            // Always capture cuenv events at info level for the event system
            EnvFilter::try_new(format!(
                "cuenv=info,cuenv_cli={level_str},cuenv_core={level_str},cuengine={level_str}"
            ))
        })
    }
    .map_err(|e| miette::miette!("Failed to create tracing filter: {e}"))?;

    // Build registry with event layer
    let registry = tracing_subscriber::registry()
        .with(env_filter)
        .with(event_layer);

    // Add format layer based on config
    // Only add verbose output in JSON mode or when explicitly debugging
    let is_verbose = config.level == Level::DEBUG || config.level == Level::TRACE;

    match config.format {
        TracingFormat::Json => {
            // JSON mode: format layer always on for structured logs
            let layer = tracing_subscriber::fmt::layer()
                .json()
                .with_writer(io::stderr)
                .with_current_span(true)
                .with_span_list(true);
            registry.with(layer).init();
        }
        TracingFormat::Pretty if is_verbose => {
            let layer = tracing_subscriber::fmt::layer()
                .pretty()
                .with_writer(io::stderr)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true);
            registry.with(layer).init();
        }
        TracingFormat::Compact if is_verbose => {
            let layer = tracing_subscriber::fmt::layer()
                .compact()
                .with_writer(io::stderr)
                .with_target(false)
                .with_thread_ids(false);
            registry.with(layer).init();
        }
        TracingFormat::Dev if is_verbose => {
            let layer = tracing_subscriber::fmt::layer()
                .with_writer(io::stderr)
                .with_file(config.enable_file_location)
                .with_line_number(config.enable_file_location)
                .with_target(true)
                .with_thread_ids(true)
                .with_thread_names(true)
                .with_level(true);
            registry.with(layer).init();
        }
        _ => {
            // Normal mode: no format layer, events go to renderers only
            registry.init();
        }
    }

    tracing::debug!(
        correlation_id = %corr_id,
        version = env!("CARGO_PKG_VERSION"),
        "Event-based tracing initialized"
    );

    Ok(main_receiver)
}

/// Create a new span for command execution with structured fields
#[macro_export]
macro_rules! command_span {
    ($command:expr) => {
        tracing::info_span!(
            "command",
            command = %$command,
            correlation_id = %$crate::tracing::correlation_id(),
            start_time = %chrono::Utc::now().to_rfc3339(),
        )
    };
    ($command:expr, $($key:expr => $value:expr),+ $(,)?) => {
        tracing::info_span!(
            "command",
            command = %$command,
            correlation_id = %$crate::tracing::correlation_id(),
            start_time = %chrono::Utc::now().to_rfc3339(),
            $($key = $value),+
        )
    };
}

/// Instrument a function with tracing span
pub use tracing::instrument;

/// Create performance measurement span
#[macro_export]
macro_rules! perf_span {
    ($name:expr) => {
        tracing::debug_span!(
            "perf",
            operation = %$name,
            correlation_id = %$crate::tracing::correlation_id(),
        )
    };
}

/// Log performance metrics
#[macro_export]
macro_rules! perf_event {
    ($operation:expr, $duration:expr) => {
        tracing::debug!(
            operation = %$operation,
            duration_ms = $duration.as_millis(),
            correlation_id = %$crate::tracing::correlation_id(),
            "Performance measurement"
        );
    };
    ($operation:expr, $duration:expr, $($key:expr => $value:expr),+ $(,)?) => {
        tracing::debug!(
            operation = %$operation,
            duration_ms = $duration.as_millis(),
            correlation_id = %$crate::tracing::correlation_id(),
            $($key = $value),+
            "Performance measurement"
        );
    };
}

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

    #[test]
    fn test_format_parsing() {
        assert!(matches!(
            "pretty".parse::<TracingFormat>().unwrap(),
            TracingFormat::Pretty
        ));
        assert!(matches!(
            "json".parse::<TracingFormat>().unwrap(),
            TracingFormat::Json
        ));
        assert!("invalid".parse::<TracingFormat>().is_err());
    }

    #[test]
    fn test_format_parsing_all_variants() {
        assert!(matches!(
            "compact".parse::<TracingFormat>().unwrap(),
            TracingFormat::Compact
        ));
        assert!(matches!(
            "dev".parse::<TracingFormat>().unwrap(),
            TracingFormat::Dev
        ));
    }

    #[test]
    fn test_format_parsing_case_insensitive() {
        assert!(matches!(
            "PRETTY".parse::<TracingFormat>().unwrap(),
            TracingFormat::Pretty
        ));
        assert!(matches!(
            "JSON".parse::<TracingFormat>().unwrap(),
            TracingFormat::Json
        ));
        assert!(matches!(
            "Compact".parse::<TracingFormat>().unwrap(),
            TracingFormat::Compact
        ));
    }

    #[test]
    fn test_log_level_conversion() {
        assert_eq!(Level::from(LogLevel::Trace), Level::TRACE);
        assert_eq!(Level::from(LogLevel::Debug), Level::DEBUG);
        assert_eq!(Level::from(LogLevel::Info), Level::INFO);
        assert_eq!(Level::from(LogLevel::Warn), Level::WARN);
        assert_eq!(Level::from(LogLevel::Error), Level::ERROR);
    }

    #[test]
    fn test_tracing_config_default() {
        let config = TracingConfig::default();
        assert!(matches!(config.format, TracingFormat::Pretty));
        assert_eq!(config.level, Level::WARN);
        assert!(config.enable_correlation_ids);
        assert!(config.enable_timestamps);
        assert!(config.enable_file_location);
        assert!(config.filter.is_none());
    }

    #[test]
    fn test_tracing_config_clone() {
        let config = TracingConfig::default();
        let cloned = config.clone();
        assert_eq!(config.level, cloned.level);
        assert_eq!(config.enable_timestamps, cloned.enable_timestamps);
    }

    #[test]
    fn test_tracing_config_debug() {
        let config = TracingConfig::default();
        let debug = format!("{:?}", config);
        assert!(debug.contains("TracingConfig"));
    }

    #[test]
    fn test_tracing_format_debug() {
        let format = TracingFormat::Pretty;
        let debug = format!("{:?}", format);
        assert!(debug.contains("Pretty"));
    }

    #[test]
    fn test_tracing_format_clone() {
        let format = TracingFormat::Json;
        let cloned = format.clone();
        assert!(matches!(cloned, TracingFormat::Json));
    }

    #[test]
    fn test_log_level_debug() {
        let level = LogLevel::Info;
        let debug = format!("{:?}", level);
        assert!(debug.contains("Info"));
    }

    #[test]
    fn test_log_level_clone() {
        let level = LogLevel::Error;
        let cloned = level.clone();
        assert!(matches!(cloned, LogLevel::Error));
    }

    #[test]
    fn test_correlation_id_consistency() {
        let id1 = correlation_id();
        let id2 = correlation_id();
        assert_eq!(id1, id2);
    }

    #[test]
    fn test_tracing_macros_smoke() {
        // command_span should create a span without panicking
        let span = command_span!("unit_test_cmd");
        let _entered = span.enter();

        // perf_span and perf_event should also be safe to call
        let pspan = perf_span!("perf_op");
        let _e2 = pspan.enter();
        let dur = std::time::Duration::from_millis(1);
        // smoke test for macro with required args
        perf_event!("perf_op", dur);
    }

    #[test]
    fn test_subscribe_global_events_before_init() {
        // Before init, subscribe should return None
        // Note: This test may not work if the global is already set by other tests
        // In a fresh run, this should return None
        let result = subscribe_global_events();
        // Result depends on whether other tests have run first
        // We just verify it doesn't panic
        let _ = result;
    }
}