eyes-subscriber 0.1.3

Tracing subscriber for sending traces to Eyes (eyes.coreyja.com)
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//! # Eyes Subscriber
//!
//! A tracing subscriber for sending structured trace data to Eyes (eyes.coreyja.com).
//!
//! ## Quick Start
//!
//! ```no_run
//! use eyes_subscriber::EyesSubscriberBuilder;
//! use tracing_subscriber::prelude::*;
//! use uuid::Uuid;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let org_id = Uuid::parse_str("your-org-id")?;
//! let app_id = Uuid::parse_str("your-app-id")?;
//!
//! // Simplest: auto-configure from environment variables
//! let (eyes_layer, shutdown_handle) = EyesSubscriberBuilder::build_from_env(org_id, app_id)?;
//!
//! tracing_subscriber::registry()
//!     .with(eyes_layer)
//!     .init();
//!
//! // Your application code here
//! tracing::info!("Application started");
//!
//! // Graceful shutdown
//! shutdown_handle.shutdown().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Configuration
//!
//! The subscriber can be configured in several ways:
//!
//! 1. **Environment variables** (recommended):
//!    - `EYES_URL`: Override the default URL (defaults to https://eyes.coreyja.com)
//!    - `EYES_TRANSPORT`: Set to "websocket" or "ws" for WebSocket, defaults to HTTP
//! 2. **Default production**: Use `new_with_default()` for https://eyes.coreyja.com
//! 3. **Custom URL**: Use `new()` with any URL for self-hosted instances
//!
//! ## Transports
//!
//! Three transport methods are available:
//! - **HTTP** (default): Reliable, request/response based
//! - **BatchingHttp**: HTTP with client-side batching for high-volume use cases
//! - **WebSocket**: Lower latency, persistent connection

mod batching_http_transport;
mod http_transport;
mod transport;
mod websocket_transport;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::{mpsc, oneshot};
use tracing::{field::Visit, span, Event, Id, Subscriber};
use tracing_subscriber::{layer::Context, registry::LookupSpan, Layer};
use url::Url;
use uuid::Uuid;

pub use batching_http_transport::{BatchConfig, BatchingHttpTransport};
pub use http_transport::HttpTransport;
pub use transport::TransportError;
pub use websocket_transport::WebSocketTransport;

use transport::Transport;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EventData {
    event_type: String,
    event_data: Value,
    event_timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone)]
pub struct EyesLayer {
    sender: mpsc::UnboundedSender<EventData>,
}

#[derive(Debug)]
pub struct EyesShutdownHandle {
    shutdown_tx: oneshot::Sender<()>,
    completion_rx: oneshot::Receiver<()>,
}

impl EyesShutdownHandle {
    pub async fn shutdown(self) -> Result<(), Box<dyn std::error::Error>> {
        let _ = self.shutdown_tx.send(());
        self.completion_rx.await?;
        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct EyesSubscriberBuilder {
    base_url: Url,
    org_id: Uuid,
    app_id: Uuid,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransportType {
    /// Standard HTTP transport - one request per event
    Http,
    /// Batching HTTP transport - buffers events and sends in batches
    BatchingHttp,
    /// WebSocket transport - persistent connection
    WebSocket,
}

impl EyesSubscriberBuilder {
    pub fn new(
        base_url: impl Into<String>,
        org_id: Uuid,
        app_id: Uuid,
    ) -> Result<Self, url::ParseError> {
        Ok(Self {
            base_url: Url::parse(&base_url.into())?,
            org_id,
            app_id,
        })
    }

    /// Create a new builder with the default production URL (eyes.coreyja.com)
    pub fn new_with_default(org_id: Uuid, app_id: Uuid) -> Result<Self, url::ParseError> {
        Self::new("https://eyes.coreyja.com", org_id, app_id)
    }

    /// Create a new builder, checking environment variables for configuration
    ///
    /// Checks the following environment variables:
    /// - `EYES_URL`: Base URL for the Eyes server (defaults to https://eyes.coreyja.com)
    /// - `EYES_TRANSPORT`: Transport type - "http", "batching" or "websocket" (defaults to "http")
    ///
    /// Returns a tuple of (builder, transport_type) to allow customization
    pub fn from_env_with_transport(
        org_id: Uuid,
        app_id: Uuid,
    ) -> Result<(Self, TransportType), url::ParseError> {
        let base_url =
            std::env::var("EYES_URL").unwrap_or_else(|_| "https://eyes.coreyja.com".to_string());

        let transport = match std::env::var("EYES_TRANSPORT")
            .unwrap_or_else(|_| "http".to_string())
            .to_lowercase()
            .as_str()
        {
            "websocket" | "ws" => TransportType::WebSocket,
            "batching" | "batch" | "batching_http" => TransportType::BatchingHttp,
            _ => TransportType::Http,
        };

        Ok((Self::new(base_url, org_id, app_id)?, transport))
    }

    /// Create a new builder, checking environment variables for configuration
    ///
    /// Checks the following in order:
    /// 1. EYES_URL environment variable
    /// 2. Falls back to https://eyes.coreyja.com
    ///
    /// Uses HTTP transport by default. For transport configuration, use `from_env_with_transport`
    pub fn from_env(org_id: Uuid, app_id: Uuid) -> Result<Self, url::ParseError> {
        let base_url =
            std::env::var("EYES_URL").unwrap_or_else(|_| "https://eyes.coreyja.com".to_string());
        Self::new(base_url, org_id, app_id)
    }

    pub fn build(self) -> (EyesLayer, EyesShutdownHandle) {
        self.build_with_transport(TransportType::Http)
    }

    /// Build directly from environment variables in one step
    ///
    /// This is a convenience method that combines `from_env_with_transport` and `build_with_transport`.
    ///
    /// Environment variables:
    /// - `EYES_URL`: Base URL (defaults to https://eyes.coreyja.com)
    /// - `EYES_TRANSPORT`: Transport type - "http" or "websocket" (defaults to "http")
    pub fn build_from_env(
        org_id: Uuid,
        app_id: Uuid,
    ) -> Result<(EyesLayer, EyesShutdownHandle), url::ParseError> {
        let (builder, transport) = Self::from_env_with_transport(org_id, app_id)?;
        Ok(builder.build_with_transport(transport))
    }

    pub fn build_with_transport(
        self,
        transport_type: TransportType,
    ) -> (EyesLayer, EyesShutdownHandle) {
        self.build_with_transport_and_config(transport_type, BatchConfig::default())
    }

    /// Build with a specific transport type and batch configuration
    ///
    /// The batch config is only used when `transport_type` is `BatchingHttp`.
    pub fn build_with_transport_and_config(
        self,
        transport_type: TransportType,
        batch_config: BatchConfig,
    ) -> (EyesLayer, EyesShutdownHandle) {
        let (sender, receiver) = mpsc::unbounded_channel::<EventData>();
        let (shutdown_tx, shutdown_rx) = oneshot::channel();
        let (completion_tx, completion_rx) = oneshot::channel();

        let transport: Box<dyn Transport> = match transport_type {
            TransportType::Http => Box::new(
                HttpTransport::new(self.base_url.clone(), self.org_id, self.app_id)
                    .expect("Failed to create HTTP transport"),
            ),
            TransportType::BatchingHttp => Box::new(
                BatchingHttpTransport::new(
                    self.base_url.clone(),
                    self.org_id,
                    self.app_id,
                    batch_config,
                )
                .expect("Failed to create batching HTTP transport"),
            ),
            TransportType::WebSocket => Box::new(
                WebSocketTransport::new(self.base_url.clone(), self.org_id, self.app_id)
                    .expect("Failed to create WebSocket transport"),
            ),
        };

        // Spawn background task to send events
        tokio::spawn(transport::run_transport_loop(
            transport,
            receiver,
            shutdown_rx,
            completion_tx,
        ));

        let layer = EyesLayer { sender };
        let handle = EyesShutdownHandle {
            shutdown_tx,
            completion_rx,
        };

        (layer, handle)
    }
}

impl<S> Layer<S> for EyesLayer
where
    S: Subscriber + for<'a> LookupSpan<'a>,
{
    fn on_new_span(&self, attrs: &span::Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
        let span = ctx.span(id).expect("Span not found");

        let mut visitor = JsonVisitor::default();
        attrs.record(&mut visitor);

        let mut event_data = serde_json::json!({
            "span_id": format!("{:?}", id),
            "name": span.metadata().name(),
            "target": span.metadata().target(),
            "level": format!("{:?}", span.metadata().level()),
            "fields": visitor.fields,
        });

        if let Some(parent) = span.parent() {
            event_data["parent_id"] = serde_json::json!(format!("{:?}", parent.id()));
        }

        let event = EventData {
            event_type: "span_new".to_string(),
            event_data,
            event_timestamp: Utc::now(),
        };

        let _ = self.sender.send(event);
    }

    fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
        let mut visitor = JsonVisitor::default();
        event.record(&mut visitor);

        let mut event_data = serde_json::json!({
            "level": format!("{:?}", event.metadata().level()),
            "target": event.metadata().target(),
            "fields": visitor.fields,
        });

        if let Some(span) = ctx.event_span(event) {
            event_data["span_id"] = serde_json::json!(format!("{:?}", span.id()));
        }

        let event_msg = EventData {
            event_type: "event".to_string(),
            event_data,
            event_timestamp: Utc::now(),
        };

        let _ = self.sender.send(event_msg);
    }

    fn on_enter(&self, id: &Id, _ctx: Context<'_, S>) {
        let event = EventData {
            event_type: "span_enter".to_string(),
            event_data: serde_json::json!({
                "span_id": format!("{:?}", id),
            }),
            event_timestamp: Utc::now(),
        };

        let _ = self.sender.send(event);
    }

    fn on_exit(&self, id: &Id, _ctx: Context<'_, S>) {
        let event = EventData {
            event_type: "span_exit".to_string(),
            event_data: serde_json::json!({
                "span_id": format!("{:?}", id),
            }),
            event_timestamp: Utc::now(),
        };

        let _ = self.sender.send(event);
    }

    fn on_close(&self, id: Id, ctx: Context<'_, S>) {
        let span = ctx.span(&id).expect("Span not found");

        let event = EventData {
            event_type: "span_close".to_string(),
            event_data: serde_json::json!({
                "span_id": format!("{:?}", id),
                "name": span.metadata().name(),
            }),
            event_timestamp: Utc::now(),
        };

        let _ = self.sender.send(event);
    }
}

#[derive(Default)]
struct JsonVisitor {
    fields: serde_json::Map<String, Value>,
}

impl Visit for JsonVisitor {
    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
        self.fields.insert(
            field.name().to_string(),
            Value::String(format!("{:?}", value)),
        );
    }

    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        self.fields
            .insert(field.name().to_string(), Value::String(value.to_string()));
    }

    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
        self.fields
            .insert(field.name().to_string(), Value::Number(value.into()));
    }

    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
        self.fields
            .insert(field.name().to_string(), Value::Number(value.into()));
    }

    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
        self.fields
            .insert(field.name().to_string(), Value::Bool(value));
    }

    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
        self.fields.insert(
            field.name().to_string(),
            serde_json::Number::from_f64(value)
                .map(Value::Number)
                .unwrap_or(Value::Null),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tracing::{info, span, Level};
    use tracing_subscriber::layer::SubscriberExt;

    #[test]
    fn test_builder_creation() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let builder = EyesSubscriberBuilder::new("http://localhost:4318", org_id, app_id).unwrap();
        assert_eq!(builder.app_id, app_id);
        assert_eq!(builder.org_id, org_id);
    }

    #[test]
    fn test_builder_invalid_url() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let result = EyesSubscriberBuilder::new("invalid-url", org_id, app_id);
        assert!(result.is_err());
    }

    #[test]
    fn test_builder_new_with_default() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let builder = EyesSubscriberBuilder::new_with_default(org_id, app_id).unwrap();
        assert_eq!(builder.app_id, app_id);
        assert_eq!(builder.org_id, org_id);
        // URL should be set to production default
        assert_eq!(builder.base_url.as_str(), "https://eyes.coreyja.com/");
    }

    #[test]
    fn test_http_transport_creation() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let transport = HttpTransport::new(base_url, org_id, app_id);
        assert!(transport.is_ok());
    }

    #[test]
    fn test_websocket_transport_creation() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let base_url = Url::parse("http://localhost:4318").unwrap();
        let transport = WebSocketTransport::new(base_url, org_id, app_id);
        assert!(transport.is_ok());
    }

    #[test]
    fn test_websocket_url_conversion() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let https_url = Url::parse("https://example.com").unwrap();
        let _transport = WebSocketTransport::new(https_url, org_id, app_id).unwrap();
        // The URL should be converted internally to wss://
    }

    #[test]
    fn test_event_data_serialization() {
        let event = EventData {
            event_type: "test_event".to_string(),
            event_data: serde_json::json!({"key": "value", "number": 42}),
            event_timestamp: Utc::now(),
        };

        let serialized = serde_json::to_string(&event).unwrap();
        let deserialized: EventData = serde_json::from_str(&serialized).unwrap();

        assert_eq!(event.event_type, deserialized.event_type);
        assert_eq!(event.event_data, deserialized.event_data);
    }

    #[test]
    fn test_json_visitor_basic_functionality() {
        let mut visitor = JsonVisitor::default();

        // Test that visitor starts empty
        assert_eq!(visitor.fields.len(), 0);

        // Test that we can add fields
        visitor.fields.insert(
            "test_key".to_string(),
            Value::String("test_value".to_string()),
        );
        assert_eq!(visitor.fields.len(), 1);
        assert_eq!(
            visitor.fields.get("test_key"),
            Some(&Value::String("test_value".to_string()))
        );
    }

    #[test]
    fn test_transport_type_debug() {
        let http = TransportType::Http;
        let ws = TransportType::WebSocket;

        assert_eq!(format!("{:?}", http), "Http");
        assert_eq!(format!("{:?}", ws), "WebSocket");
    }

    #[test]
    fn test_transport_type_equality() {
        assert_eq!(TransportType::Http, TransportType::Http);
        assert_eq!(TransportType::WebSocket, TransportType::WebSocket);
        assert_ne!(TransportType::Http, TransportType::WebSocket);
    }

    #[tokio::test]
    async fn test_layer_integration() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        // Create a builder and build the layer
        let (layer, shutdown_handle) =
            EyesSubscriberBuilder::new("http://localhost:4318", org_id, app_id)
                .unwrap()
                .build();

        // Set up tracing with our layer
        let subscriber = tracing_subscriber::registry().with(layer);

        // Use the subscriber in a limited scope
        tracing::subscriber::with_default(subscriber, || {
            let span = span!(Level::INFO, "test_span", user_id = 123);
            let _enter = span.enter();
            info!("Test message in span");
        });

        // Shutdown gracefully
        shutdown_handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_layer_with_websocket_transport() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let (layer, shutdown_handle) =
            EyesSubscriberBuilder::new("http://localhost:4318", org_id, app_id)
                .unwrap()
                .build_with_transport(TransportType::WebSocket);

        // Test that the layer was created successfully
        let subscriber = tracing_subscriber::registry().with(layer);

        tracing::subscriber::with_default(subscriber, || {
            info!("Test WebSocket transport");
        });

        shutdown_handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_build_from_env_with_defaults() {
        // Clear environment
        std::env::remove_var("EYES_URL");
        std::env::remove_var("EYES_TRANSPORT");

        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let result = EyesSubscriberBuilder::build_from_env(org_id, app_id);
        assert!(result.is_ok());

        // Test shutdown
        if let Ok((_, shutdown_handle)) = result {
            shutdown_handle.shutdown().await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_build_from_env_with_custom_values() {
        std::env::set_var("EYES_URL", "http://custom.example.com");
        std::env::set_var("EYES_TRANSPORT", "websocket");

        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let result = EyesSubscriberBuilder::build_from_env(org_id, app_id);
        assert!(result.is_ok());

        // Test shutdown
        if let Ok((_, shutdown_handle)) = result {
            shutdown_handle.shutdown().await.unwrap();
        }

        // Clean up
        std::env::remove_var("EYES_URL");
        std::env::remove_var("EYES_TRANSPORT");
    }

    #[tokio::test]
    async fn test_layer_with_batching_transport() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let (layer, shutdown_handle) =
            EyesSubscriberBuilder::new("http://localhost:4318", org_id, app_id)
                .unwrap()
                .build_with_transport(TransportType::BatchingHttp);

        // Test that the layer was created successfully
        let subscriber = tracing_subscriber::registry().with(layer);

        tracing::subscriber::with_default(subscriber, || {
            info!("Test batching HTTP transport");
        });

        shutdown_handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_layer_with_batching_transport_custom_config() {
        use std::time::Duration;

        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();

        let custom_config = BatchConfig::new(50, Duration::from_millis(100));

        let (layer, shutdown_handle) =
            EyesSubscriberBuilder::new("http://localhost:4318", org_id, app_id)
                .unwrap()
                .build_with_transport_and_config(TransportType::BatchingHttp, custom_config);

        let subscriber = tracing_subscriber::registry().with(layer);

        tracing::subscriber::with_default(subscriber, || {
            info!("Test batching HTTP transport with custom config");
        });

        shutdown_handle.shutdown().await.unwrap();
    }

    #[test]
    fn test_batching_transport_creation() {
        let org_id = Uuid::new_v4();
        let app_id = Uuid::new_v4();
        let base_url = Url::parse("http://localhost:4318").unwrap();

        let transport =
            BatchingHttpTransport::with_default_config(base_url.clone(), org_id, app_id);
        assert!(transport.is_ok());

        use std::time::Duration;
        let custom_config = BatchConfig::new(50, Duration::from_millis(100));
        let transport = BatchingHttpTransport::new(base_url, org_id, app_id, custom_config);
        assert!(transport.is_ok());
    }

    #[test]
    fn test_transport_type_batching_http() {
        assert_eq!(TransportType::BatchingHttp, TransportType::BatchingHttp);
        assert_ne!(TransportType::BatchingHttp, TransportType::Http);
        assert_ne!(TransportType::BatchingHttp, TransportType::WebSocket);
    }
}