bugwatch 0.4.0

Official Rust SDK for Bugwatch - AI-Powered Error Tracking
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Bugwatch client for capturing and sending error events.

use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

use crate::backtrace::capture_backtrace_skip;
use crate::fingerprint::fingerprint_from_exception;
use crate::transport::{HttpTransport, Transport};
use crate::types::{
    Breadcrumb, BugwatchOptions, ErrorEvent, ExceptionInfo, Level, UserContext,
};

/// The main Bugwatch client for error tracking.
#[derive(Clone)]
pub struct BugwatchClient {
    options: Arc<BugwatchOptions>,
    transport: Arc<dyn Transport>,
    state: Arc<RwLock<ClientState>>,
}

struct ClientState {
    breadcrumbs: Vec<Breadcrumb>,
    user: Option<UserContext>,
    tags: HashMap<String, String>,
    extra: HashMap<String, serde_json::Value>,
}

impl BugwatchClient {
    /// Create a new Bugwatch client.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bugwatch::{BugwatchClient, BugwatchOptions};
    ///
    /// let client = BugwatchClient::new(
    ///     BugwatchOptions::new("your-api-key")
    ///         .with_environment("production")
    ///         .with_release("1.0.0")
    /// );
    /// ```
    /// Create a new Bugwatch client.
    ///
    /// # Panics
    ///
    /// Panics if the HTTP transport cannot be created. Use `try_new()` for
    /// a fallible alternative.
    pub fn new(options: BugwatchOptions) -> Self {
        Self::try_new(options).expect("Failed to create Bugwatch client")
    }

    /// Try to create a new Bugwatch client.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP transport cannot be created.
    pub fn try_new(options: BugwatchOptions) -> Result<Self, crate::transport::TransportError> {
        let transport = Box::new(HttpTransport::new(&options)?);
        Ok(Self::with_transport(options, transport))
    }

    /// Create a new client with a custom transport.
    pub fn with_transport(options: BugwatchOptions, transport: Box<dyn Transport>) -> Self {
        let mut tags = HashMap::new();
        tags.insert("runtime".to_string(), "rust".to_string());
        tags.insert("runtime.version".to_string(), rustc_version());
        tags.insert("os.platform".to_string(), std::env::consts::OS.to_string());
        tags.insert("os.arch".to_string(), std::env::consts::ARCH.to_string());

        if let Some(ref env) = options.environment {
            tags.insert("environment".to_string(), env.clone());
        }

        if options.debug {
            tracing::info!("[Bugwatch] Rust SDK initialized");
        }

        Self {
            options: Arc::new(options),
            transport: Arc::from(transport),
            state: Arc::new(RwLock::new(ClientState {
                breadcrumbs: Vec::new(),
                user: None,
                tags,
                extra: HashMap::new(),
            })),
        }
    }

    /// Check if debug mode is enabled.
    pub fn is_debug(&self) -> bool {
        self.options.debug
    }

    /// Capture an error and send it to Bugwatch.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bugwatch::{BugwatchClient, BugwatchOptions};
    ///
    /// let client = BugwatchClient::new(BugwatchOptions::new("your-api-key"));
    ///
    /// let error = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
    /// client.capture_error(&error);
    /// ```
    pub fn capture_error<E: std::error::Error>(&self, error: &E) -> String {
        self.capture_error_with_options(error, Level::Error, None, None)
    }

    /// Capture an error with additional options.
    pub fn capture_error_with_options<E: std::error::Error>(
        &self,
        error: &E,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Apply sample rate
        if !self.should_sample() {
            return String::new();
        }

        // Build stack trace
        let stacktrace = if self.options.attach_stacktrace {
            capture_backtrace_skip(3)
        } else {
            Vec::new()
        };

        // Create exception info
        let exception = ExceptionInfo {
            error_type: std::any::type_name_of_val(error)
                .split("::")
                .last()
                .unwrap_or("Error")
                .to_string(),
            value: error.to_string(),
            stacktrace,
            module: None,
        };

        self.capture_exception_internal(exception, level, tags, extra)
    }

    /// Capture an exception internally.
    pub(crate) fn capture_exception_internal(
        &self,
        exception: ExceptionInfo,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Create event
        let event_id = Uuid::new_v4().to_string().replace("-", "");
        let mut event = ErrorEvent::new(&event_id, level);

        // Generate fingerprint
        event.fingerprint = Some(fingerprint_from_exception(&exception));
        event.exception = Some(exception);

        // Add state
        {
            let state = self.state.read();

            // Merge tags
            event.tags = state.tags.clone();
            if let Some(t) = tags {
                event.tags.extend(t);
            }

            // Merge extra
            event.extra = state.extra.clone();
            if let Some(e) = extra {
                event.extra.extend(e);
            }

            // Add breadcrumbs
            event.breadcrumbs = state.breadcrumbs.clone();

            // Add user
            event.user = state.user.clone();
        }

        // Add options
        event.environment = self.options.environment.clone();
        event.release = self.options.release.clone();
        event.server_name = self.options.server_name.clone().or_else(|| {
            hostname::get().ok().map(|h| h.to_string_lossy().to_string())
        });

        // Send event
        if let Err(e) = self.transport.send(&event) {
            if self.options.debug {
                tracing::error!("Failed to send event: {}", e);
            }
        }

        event_id
    }

    /// Capture an exception internally using async transport.
    #[cfg(feature = "async")]
    pub(crate) async fn capture_exception_internal_async(
        &self,
        exception: ExceptionInfo,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Create event
        let event_id = Uuid::new_v4().to_string().replace("-", "");
        let mut event = ErrorEvent::new(&event_id, level);

        // Generate fingerprint
        event.fingerprint = Some(fingerprint_from_exception(&exception));
        event.exception = Some(exception);

        // Add state
        {
            let state = self.state.read();
            event.tags = state.tags.clone();
            if let Some(t) = tags {
                event.tags.extend(t);
            }
            event.extra = state.extra.clone();
            if let Some(e) = extra {
                event.extra.extend(e);
            }
            event.breadcrumbs = state.breadcrumbs.clone();
            event.user = state.user.clone();
        }

        event.environment = self.options.environment.clone();
        event.release = self.options.release.clone();
        event.server_name = self.options.server_name.clone().or_else(|| {
            hostname::get().ok().map(|h| h.to_string_lossy().to_string())
        });

        // Send via async transport
        if let Some(http) = self.transport.as_any().downcast_ref::<HttpTransport>() {
            if let Err(e) = http.send_async(&event).await {
                if self.options.debug {
                    tracing::error!("Failed to send event async: {}", e);
                }
            }
        } else {
            // Fallback to sync send for non-HTTP transports
            if let Err(e) = self.transport.send(&event) {
                if self.options.debug {
                    tracing::error!("Failed to send event: {}", e);
                }
            }
        }

        event_id
    }

    /// Capture a message and send it to Bugwatch.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bugwatch::{BugwatchClient, BugwatchOptions, Level};
    ///
    /// let client = BugwatchClient::new(BugwatchOptions::new("your-api-key"));
    /// client.capture_message("Something happened", Level::Warning);
    /// ```
    pub fn capture_message(&self, message: &str, level: Level) -> String {
        self.capture_message_with_options(message, level, None, None)
    }

    /// Capture a message with additional options.
    pub fn capture_message_with_options(
        &self,
        message: &str,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Apply sample rate
        if !self.should_sample() {
            return String::new();
        }

        // Create event
        let event_id = Uuid::new_v4().to_string().replace("-", "");
        let mut event = ErrorEvent::new(&event_id, level);
        event.message = Some(message.to_string());

        // Add state
        {
            let state = self.state.read();

            // Merge tags
            event.tags = state.tags.clone();
            if let Some(t) = tags {
                event.tags.extend(t);
            }

            // Merge extra
            event.extra = state.extra.clone();
            if let Some(e) = extra {
                event.extra.extend(e);
            }

            // Add breadcrumbs
            event.breadcrumbs = state.breadcrumbs.clone();

            // Add user
            event.user = state.user.clone();
        }

        // Add options
        event.environment = self.options.environment.clone();
        event.release = self.options.release.clone();
        event.server_name = self.options.server_name.clone();

        // Send event
        if let Err(e) = self.transport.send(&event) {
            if self.options.debug {
                tracing::error!("Failed to send event: {}", e);
            }
        }

        event_id
    }

    /// Add a breadcrumb to the trail.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bugwatch::{BugwatchClient, BugwatchOptions, Breadcrumb, Level};
    ///
    /// let client = BugwatchClient::new(BugwatchOptions::new("your-api-key"));
    /// client.add_breadcrumb(Breadcrumb::new("http", "GET /api/users").with_level(Level::Info));
    /// ```
    pub fn add_breadcrumb(&self, breadcrumb: Breadcrumb) {
        let mut state = self.state.write();
        state.breadcrumbs.push(breadcrumb);

        // Limit breadcrumbs
        let max = self.options.max_breadcrumbs;
        if state.breadcrumbs.len() > max {
            let drain_count = state.breadcrumbs.len() - max;
            state.breadcrumbs.drain(..drain_count);
        }
    }

    /// Set the current user context.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use bugwatch::{BugwatchClient, BugwatchOptions, UserContext};
    ///
    /// let client = BugwatchClient::new(BugwatchOptions::new("your-api-key"));
    /// client.set_user(Some(
    ///     UserContext::new()
    ///         .with_id("user-123")
    ///         .with_email("user@example.com")
    /// ));
    /// ```
    pub fn set_user(&self, user: Option<UserContext>) {
        let mut state = self.state.write();
        state.user = user;
    }

    /// Set a tag for all future events.
    pub fn set_tag(&self, key: impl Into<String>, value: impl Into<String>) {
        let mut state = self.state.write();
        state.tags.insert(key.into(), value.into());
    }

    /// Set extra context for all future events.
    pub fn set_extra(&self, key: impl Into<String>, value: impl Into<serde_json::Value>) {
        let mut state = self.state.write();
        state.extra.insert(key.into(), value.into());
    }

    /// Clear all breadcrumbs.
    pub fn clear_breadcrumbs(&self) {
        let mut state = self.state.write();
        state.breadcrumbs.clear();
    }

    /// Check if this event should be sampled.
    fn should_sample(&self) -> bool {
        if self.options.sample_rate >= 1.0 {
            return true;
        }
        if self.options.sample_rate <= 0.0 {
            return false;
        }
        rand::random::<f64>() <= self.options.sample_rate
    }

    /// Capture an error asynchronously using the async transport.
    #[cfg(feature = "async")]
    pub async fn capture_error_async<E: std::error::Error>(&self, error: &E) -> String {
        self.capture_error_with_options_async(error, Level::Error, None, None)
            .await
    }

    /// Capture an error asynchronously with additional options.
    #[cfg(feature = "async")]
    pub async fn capture_error_with_options_async<E: std::error::Error>(
        &self,
        error: &E,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Apply sample rate
        if !self.should_sample() {
            return String::new();
        }

        // Build stack trace
        let stacktrace = if self.options.attach_stacktrace {
            capture_backtrace_skip(3)
        } else {
            Vec::new()
        };

        // Create exception info
        let exception = ExceptionInfo {
            error_type: std::any::type_name_of_val(error)
                .split("::")
                .last()
                .unwrap_or("Error")
                .to_string(),
            value: error.to_string(),
            stacktrace,
            module: None,
        };

        self.capture_exception_internal_async(exception, level, tags, extra)
            .await
    }

    /// Capture a message asynchronously using the async transport.
    #[cfg(feature = "async")]
    pub async fn capture_message_async(&self, message: &str, level: Level) -> String {
        self.capture_message_with_options_async(message, level, None, None)
            .await
    }

    /// Capture a message asynchronously with additional options.
    #[cfg(feature = "async")]
    pub async fn capture_message_with_options_async(
        &self,
        message: &str,
        level: Level,
        tags: Option<HashMap<String, String>>,
        extra: Option<HashMap<String, serde_json::Value>>,
    ) -> String {
        // Apply sample rate
        if !self.should_sample() {
            return String::new();
        }

        // Create event
        let event_id = Uuid::new_v4().to_string().replace("-", "");
        let mut event = ErrorEvent::new(&event_id, level);
        event.message = Some(message.to_string());

        // Add state
        {
            let state = self.state.read();
            event.tags = state.tags.clone();
            if let Some(t) = tags {
                event.tags.extend(t);
            }
            event.extra = state.extra.clone();
            if let Some(e) = extra {
                event.extra.extend(e);
            }
            event.breadcrumbs = state.breadcrumbs.clone();
            event.user = state.user.clone();
        }

        event.environment = self.options.environment.clone();
        event.release = self.options.release.clone();
        event.server_name = self.options.server_name.clone();

        // Send via async transport
        if let Some(http) = self.transport.as_any().downcast_ref::<HttpTransport>() {
            if let Err(e) = http.send_async(&event).await {
                if self.options.debug {
                    tracing::error!("Failed to send event async: {}", e);
                }
            }
        } else {
            // Fallback to sync send for non-HTTP transports
            if let Err(e) = self.transport.send(&event) {
                if self.options.debug {
                    tracing::error!("Failed to send event: {}", e);
                }
            }
        }

        event_id
    }

    /// Flush any pending events to Bugwatch.
    ///
    /// This ensures all queued events are sent before the method returns.
    /// Call this before process exit to ensure no events are lost.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport fails to flush.
    pub fn flush(&self) -> Result<(), crate::transport::TransportError> {
        self.transport.flush()
    }

    /// Close the client and release any resources.
    ///
    /// This flushes any pending events and closes the transport.
    /// After calling this method, the client should not be used again.
    ///
    /// # Errors
    ///
    /// Returns an error if the transport fails to close.
    pub fn close(&self) -> Result<(), crate::transport::TransportError> {
        self.transport.close()
    }
}

fn rustc_version() -> String {
    option_env!("RUSTC_VERSION")
        .unwrap_or("unknown")
        .to_string()
}

// Simple PRNG for sampling (no external dependency)
mod rand {
    use std::hash::{Hash, Hasher};
    use std::collections::hash_map::DefaultHasher;
    use std::time::{SystemTime, UNIX_EPOCH};

    pub fn random<T>() -> T
    where
        T: RandomValue,
    {
        T::random()
    }

    pub trait RandomValue {
        fn random() -> Self;
    }

    impl RandomValue for f64 {
        fn random() -> Self {
            // Get seed from system time, with fallback to thread-based hash
            let seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_nanos())
                .unwrap_or_else(|_| {
                    // Fallback: use thread ID and a static counter for entropy
                    let mut hasher = DefaultHasher::new();
                    std::thread::current().id().hash(&mut hasher);
                    // Mix in some additional entropy from stack address
                    let stack_var = 0u8;
                    (&stack_var as *const u8).hash(&mut hasher);
                    hasher.finish() as u128
                });

            // Simple xorshift PRNG
            let mut x = seed as u64;
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            (x as f64) / (u64::MAX as f64)
        }
    }
}

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

    #[test]
    fn test_capture_error() {
        let options = BugwatchOptions::new("test-key");
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        let error = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
        let event_id = client.capture_error(&error);

        assert!(!event_id.is_empty());
        assert_eq!(event_id.len(), 32);
    }

    #[test]
    fn test_capture_message() {
        let options = BugwatchOptions::new("test-key");
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        let event_id = client.capture_message("Test message", Level::Info);

        assert!(!event_id.is_empty());
        assert_eq!(event_id.len(), 32);
    }

    #[test]
    fn test_breadcrumbs() {
        let options = BugwatchOptions::new("test-key").with_debug(false);
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        client.add_breadcrumb(Breadcrumb::new("http", "GET /api"));
        client.add_breadcrumb(Breadcrumb::new("ui", "Button clicked"));

        let state = client.state.read();
        assert_eq!(state.breadcrumbs.len(), 2);
    }

    #[test]
    fn test_max_breadcrumbs() {
        let mut options = BugwatchOptions::new("test-key");
        options.max_breadcrumbs = 5;
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        for i in 0..10 {
            client.add_breadcrumb(Breadcrumb::new("test", format!("breadcrumb {}", i)));
        }

        let state = client.state.read();
        assert_eq!(state.breadcrumbs.len(), 5);
        assert_eq!(state.breadcrumbs[0].message, "breadcrumb 5");
    }

    #[test]
    fn test_user_context() {
        let options = BugwatchOptions::new("test-key");
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        client.set_user(Some(
            UserContext::new()
                .with_id("user-123")
                .with_email("test@example.com"),
        ));

        let state = client.state.read();
        assert!(state.user.is_some());
        assert_eq!(state.user.as_ref().unwrap().id, Some("user-123".to_string()));
    }

    #[test]
    fn test_tags() {
        let options = BugwatchOptions::new("test-key");
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        client.set_tag("version", "1.0.0");

        let state = client.state.read();
        assert_eq!(state.tags.get("version"), Some(&"1.0.0".to_string()));
    }

    #[test]
    fn test_sample_rate_zero() {
        let options = BugwatchOptions::new("test-key").with_sample_rate(0.0);
        let client = BugwatchClient::with_transport(options, Box::new(NoopTransport));

        let event_id = client.capture_message("Test", Level::Info);
        assert!(event_id.is_empty());
    }
}