lemon_bugsnag_rs 0.1.2

A library for interacting with the BugSnag error-reporting and sessions APIs.
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
#![cfg_attr(docsrs, feature(doc_cfg))]

//! The lemon-bugsnag-rs crate offers developers a low-friction way to interface
//! with the BugSnag error-reporting and sessions APIs.
//!
//! # Goals
//! - Low friction and ease of use.
//!     - This crate should offer little resistance to implementation for users
//!     at all skill and experience levels.
//!     - This crate should require no specialized knowledge of Rust, the
//!     BugSnag API, hardware, etc. A user with the ability to write a Hello
//!     World Rust application and skim the BugSnag documentation should be able
//!     to have this crate working and delivering payloads in a matter of
//!     minutes. We've even tried to reduce that second burden as much as possible.
//!     - As part of the above goal, we have created builders that allow the user
//!     to elide the burden of turning their Strings into &strs, explicitly
//!     wrapping arguments in [Option]s, manually creating vectors for single
//!     items, and so on.
//! - Flexibility.
//!     - In addition to some of the ease-of-use considerations which cross
//!     into this domain, we have also done our best to create a structure
//!     of features that allows the user of this library significant control
//!     over which non-critical code is compiled into their final product.
//!     Features such as `optional-builders` and `convenience-intos` allow
//!     users to exchange ease of use and flexibility for tighter control over
//!     this library's footprint.
//! - Thorough documentation. Thoooorough.
//!     - We tested and documented setters and getters. Big whoop. Wanna fight
//!     about it?
//!     - We set a goal of 100% documentation and 100% test coverage. Probably a
//!     bit excessive, but it gave us a quantifiable goal, and we stuck to it.
//! - Code organization tightly coupled with usage.
//!     - We completely restructured the code three or four times. Frankly,
//!     we're still not 100% satisfied with this. We built the structures to
//!     reflect the BugSnag API payload 1:1, but that led to the user having to
//!     write an awful lot of `use` statements, since everything was so
//!     heavily segmented. We tried to alleviate this somewhat by flattening
//!     the larger payload structs, but I personally find this to be
//!     unsatisfying as it breaks the 1:1 relationship between the file
//!     structure and the payload structure.
//! - Consistency.
//!     - Switching from synchronous to asynchronous, from sessions to
//!     error-reporting, or from Reqwest to Ureq, should be as close to
//!     seamless as possible. The APIs for all variations of API, backend,
//!     and blocking/non-blocking should differ only where absolutely
//!     necessary.
//!
//! - Things that still need doing:
//!     - Develop a guide for contributors.
//!     - Audit the constraints on trait inputs.
//!     - We're not entirely thrilled with the `blocking` and `non_blocking`
//!     idioms we used in place of `async,` since `async` is a reserved word in
//!     Rust. This is currently in a mixed state, where the traits and structs
//!     have `Sync` and `Async` in their names, but the functions are using the
//!     `blocking()` and `non_blocking()` names.
//!
//! # Features
#![cfg_attr(
feature = "document-features",
cfg_attr(doc, doc = ::document_features::document_features!(
    feature_label =
        r#"<span class="stab portability"><code>{feature}</code></span>"#
    )
)
)]

#![doc = include_str!("../README.md")]

/// Includes structs and trait common to all builders and clients.
///
/// # Example Imports
/// ```
/// use lemon_bugsnag_rs::common::{
///     builder,
///     client,
/// #    // // Cobbler is relevant for development within the crate, however
/// #    // // users of the library do not need to directly use cobbler.
/// #    // cobbler,
///     error,
///     traits
/// };
/// ```
pub mod common;
#[cfg_attr(docsrs, doc(cfg(feature = "error-client")))]
#[cfg(feature = "error-client")]
/// Contains structs and enums used for BugSnag error-reporting API
/// builders, clients, and payloads.
///
/// # Example Imports
/// ```
/// use lemon_bugsnag_rs::error::{
///     error_client_builder,
///     payload,
///     reqwest,
///     ureq
/// };
/// ```
pub mod error;
#[cfg_attr(docsrs, doc(cfg(feature = "session-client")))]
#[cfg(feature = "session-client")]
/// Contains structs and enums used for BugSnag sessions API builders,
/// clients, and payloads.
///
/// # Example Imports
/// ```
/// use lemon_bugsnag_rs::session::{
///     payload,
///     reqwest,
///     session_client_builder,
///     ureq,
/// };
/// ```
pub mod session;

#[cfg(test)]
mod test {
    pub mod doctest_support {
        #[test]
        #[allow(unused)]
        #[cfg(all(feature = "session-client", feature = "ureq", feature = "sync"))]
        pub fn sessions_synchrous_ureq() {
            use crate::common::builder::client_builder::ClientBuilder;
            use crate::common::traits::backend_builder_trait_sync::BackendBuilderTraitSync;
            // Exposes the `ClientTraitSync::send()` function for synchronous backend clients.
            use crate::common::traits::client_trait_sync::ClientTraitSync;
            // To use the bundle rather than import each item separately:
            // use lemon_bugsnag_rs::common::bundle::*;
            // Start by retrieving a builder for BugSnag error-reporting API clients.
            let mut cb = ClientBuilder::session();
            cb.configure(
                "Your API key goes here",
                // A string to identify the source of the error report. For example,
                // "Company Name mobile app," "web API," or, "lemon-bugsnag-rs," depending
                // on how you want to track errors.
                "A name to identify your application",
                "Notifier version",
                // Release stage of application reporting the error.
                "dev",
                "Application version",
            );
            // Choose the `Ureq` backend.
            let mut client = cb.ureq().build().unwrap();
            #[cfg(norun)]
            let result = client.send();
            #[cfg(norun)]
            if result.is_ok() {
                let response = result.unwrap();
                // Due to the way the Ureq clients are implemented, you will want to
                // check the HTTP response code to ensure you received the expected result.
                if response.status() != 200 {
                    // Looks good. Do stuff.
                } else {
                    // Possible 40x or 50x. Process as appropriate.
                }
            } else {
                // A bummer has happened. Handle it.
            }
        }

        #[test]
        #[allow(unused)]
        #[cfg(all(feature = "session-client", feature = "reqwest", feature = "async"))]
        pub fn sessions_asynchronous_reqwest() {
            use crate::common::bundle::*;
            // Start by retrieving a builder for BugSnag error-reporting API clients.
            let mut cb = ClientBuilder::session();
            cb.configure(
                "Your API key goes here",
                // A string to identify the source of the error report. For example,
                // "Company Name mobile app," "web API," or, "lemon-bugsnag-rs," depending
                // on how you want to track errors.
                "A name to identify your application",
                "Notifier version",
                // Release stage of application reporting the error.
                "dev",
                "Application version",
            );
            // Choose the `Reqwest` backend, which supports asynchronous operations. If
            // additional asynchronous backends are implemented in the future, you could
            // select one of them by replacing reqwest() with the appropriate backend
            // name.
            let mut client = cb.reqwest().non_blocking().build().unwrap();
            #[cfg(norun)]
            match client.send().await {
                Ok(response) => {
                    // Looks good. Do stuff.
                },
                Err(error) => {
                    // A bummer has happened. Handle it.
                },
            }
        }
    }

    #[test]
    #[allow(unused)]
    #[cfg(all(feature = "error-client", feature = "reqwest", feature = "async"))]
    pub fn error_asynchronous_reqwest() {
        // The ClientBuilder is the basis for most operations in this library.
        use crate::common::builder::client_builder::ClientBuilder;
        // This brings the `non_blocking()` function  of DeciderTraitAsync into
        // scope. DeciderTraitSync and DeciderTraitAsync are the functions that
        // allow you to choose whether you want a blocking or non-blocking client.
        // This is required even if your chosen networking backend only offers one
        // or the other.
        use crate::common::traits::decider_trait_async::DeciderTraitAsync;
        // This brings into scope the `build()` function of
        // `BackendBuilderTraitAsync,` which is implemented by the builders that
        // create and configure the asynchronous networking client you will use to
        // send your BugSnag payload.
        use crate::common::traits::backend_builder_trait_async::BackendBuilderTraitAsync;
        // Provides the `send()` function for asynchronous backend clients.
        use crate::common::traits::client_trait_async::ClientTraitAsync;
        
        // To use the bundle rather than import each item separately:
        // use crate::common::bundle::*;
        
        // Start by retrieving a builder for BugSnag error-reporting API clients.
        let mut cb = ClientBuilder::error();
        
        cb.configure(
            "Your API key goes here",
            // An arbitrary string declaring an error class for this payload.
            "An error class for your message",
            "The error message you wish to record",
            // A string to identify the source of the error report. For example,
            // "Company Name mobile app," "web API," or, "lemon-bugsnag-rs," depending
            // on how you want to track errors.
            "Notifier name",
            "Notifier version",
            // Optional. Used to provide information about the language, libraries,
            // and frameworks used by the application reporting the error.
            "Rust 1.82.0 with lemon-bugsnag-rs",
            // Release stage of application reporting the error.
            "dev"
        );
        
        // Choose the `Reqwest` backend, which is the only currently-implemented
        // networking backend that supports asynchronous operations. If additional
        // asynchronous backends are implemented in the future, you would select
        // one of them by replacing reqwest() with the appropriate backend name.
        let mut client = cb.reqwest().non_blocking().build().unwrap();
        
        // Send your payload. This must be done from an async context, such as
        // an async function, or using `block_on()` or the equivalent from an
        // async runtime.
        #[cfg(norun)]
        match client.send().await {
            Ok(response) => {
                // Looks good. Do stuff.
            },
            Err(error) => {
                // A bummer has happened. Handle it.
            },
        }
    }

    #[test]
    #[allow(unused)]
    #[cfg(all(feature = "error-client", feature = "reqwest", feature = "sync"))]
    pub fn error_synchronous_reqwest() {
        use crate::common::bundle::*;

        // Start by retrieving a builder for BugSnag error-reporting API clients.
        let mut cb = ClientBuilder::error();

        cb.configure(
            "Your API key goes here",
            // An arbitrary string declaring an error class for this payload.
            "An error class for your message",
            "The error message you wish to record",
            // A string to identify the source of the error report. For example,
            // "Company Name mobile app," "web API," or, "lemon-bugsnag-rs," depending
            // on how you want to track errors.
            "Notifier name",
            "Notifier version",
            // Optional. Used to provide information about the language, libraries,
            // and frameworks used by the application reporting the error.
            "Rust 1.82.0 with lemon-bugsnag-rs",
            // Release stage of application reporting the error.
            "dev"
        );

        // Choose the `Reqwest` non-blocking backend.
        let mut client = cb.reqwest().blocking().build().unwrap();

        // Send your payload.
        #[cfg(norun)]
        match client.send() {
            Ok(response) => {
                // Looks good. Do stuff.
            },
            Err(error) => {
                // A bummer has happened. Handle it.
            }
        }
    }
    #[cfg(feature = "error-client")]
    pub mod test_error_utility {
        #[cfg(feature = "optional-builders")]
        use crate::error::payload::events::event::EventBuilder;
        use crate::error::{
            error_client_builder::ErrorClientBuilder,
            payload::{
                events::{
                    enums::{BreadcrumbType, RuntimeType, Severity},
                    Breadcrumb, Event, Exception, StackTrace, StackTraceCode,
                },
                notifier::Dependency,
                notifier::Notifier as ErrorNotifier,
            },
        };
        use crate::{
            common::builder::client_builder::ClientBuilder,
            error::payload::events::App,
        };
        pub fn get_error_client_builder() -> ErrorClientBuilder {
            /*
             * API keys
             * API_KEY - MerchantAccess
             * API_KEY - market-information-api-rust
             * API_KEY - lemon-bugsnag-rs, created specifically for this project
             */
            let mut cb = ClientBuilder::error();
            cb.set_host("notify.bugsnag.com")
                .set_scheme("https")
                .set_api_key(std::env::var(
                    "NAB_BUGSNAG_RS_API_KEY"
                ).unwrap_or_else(|_| {
                    assert!(false, "NAB_BUGSNAG_RS_API_KEY not found in environment, or contains invalid unicode");
                    "".to_string()
                }).as_str());
            cb.set_notifier(
                ErrorNotifier {
                    name: "Name".to_string(),
                    version: "Version".to_string(),
                    url: "Url".to_string(),
                    dependencies: Some([
                        Dependency {
                            name: "Dependency 1".to_string(),
                            version: "Dependency 1 version".to_string(),
                            url: "Dependency 1 url".to_string()
                        },
                        Dependency {
                            name: "Dependency 2".to_string(),
                            version: "Dependency 2 Version".to_string(),
                            url: "Dependency 2 Url".to_string()
                        },
                    ].to_vec()),
                }
            )
            .set_events(
                [
                    Event {
                        app: Some(App {
                            id: None
                            , version: Some("1.0.2".to_string())
                            , version_code: Some(1)
                            , bundle_version: None
                            , code_bundle_id: None
                            , build_uuid: None
                            , release_stage: None
                            , app_type: None
                            , dsym_uuids: None
                            , duration: None
                            , duration_in_foreground: None
                            , in_foreground: None
                            , is_launching: None
                            , binary_arch: None
                            , running_on_rosetta: None
                        })
                        , breadcrumbs: Some([Breadcrumb {
                            timestamp: "Right now".to_string()
                            , name: "This is the name of a breadcrumb".to_string()
                            , breadcrumb_type: BreadcrumbType::Navigation
                            , meta_data: Some([
                                ("Metadata key one".to_string()
                                , "Metadata value one".to_string()),
                                ("Metadata key two".to_string()
                                , "Metadata value two".to_string())
                            ].into()) }].to_vec())
                        , context: None
                        , device: None
                        , exceptions: [Exception { error_class: "Exception name goes here".to_string()
                        , message: Some("This is an error message".to_string())
                        , stack_trace: [
                            StackTrace {
                            file: "this is the file the error occurred in".to_string()
                            , line_number: 42
                            , column_number: Some(128)
                            , method: "method_name()".to_string()
                            , in_project: Some(true)
                            , code: Some(StackTraceCode {
                                code: [
                                    (10, "This is the code on line 2".to_string())
                                    , (2, "This is the code on line 2".to_string())
                                    , (6, "This is the code on line 2".to_string())
                                    , (4, "This is the code on line 4".to_string())
                                    , (8, "This is the code on line 4".to_string())
                                    , (12, "This is the code on line 4".to_string())
                                ].into()
                            })
                            , frame_address: Some("0x00BFD60000".to_string())
                            , load_address: Some("0x0000000000".to_string())
                            , is_lr: Some(false)
                            , is_pc: Some(false)
                            , symbol_address: Some("0x00bb00bbdd".to_string())
                            , macho_file: Some("we don't have this nosnense".to_string())
                            , macho_load_address: Some("0x00ffff00dd".to_string())
                            , macho_uuid: Some("asdffdsaqwerrewq".to_string())
                            , macho_vm_address: Some("Come on, now".to_string())
                            , code_identifier: Some("this is probably going to be a hash of the binary or something".to_string())
                        }].to_vec()
                        , runtime_type: Some(RuntimeType::Go) }].to_vec()
                        , feature_flags: None
                        , grouping_hash: None
                        , meta_data: Some([
                            ("Metadata key one".to_string()
                            , "Metadata value one".to_string()),
                            ("Metadata key two".to_string()
                            , "Metadata value two".to_string())
                        ].into())
                        , project_packages: None
                        , request: None
                        , session: None
                        , severity: Some(Severity::Info)
                        , severity_reason: None
                        , threads: None
                        , unhandled: None
                        , user: None
                    }
                ].to_vec()
            );

            cb
        }

        #[cfg(feature = "optional-builders")]
        #[allow(dead_code)]
        pub fn get_event_builder() -> EventBuilder {
            let mut event_builder = EventBuilder::default();
            let mut exception_builder = Exception::builder();
            exception_builder.set_error_class("get_event_builder exception");

            let mut stack_trace_builder = StackTrace::builder();
            stack_trace_builder.set_file("File");
            stack_trace_builder.set_line_number(2);
            stack_trace_builder.set_method("get_event_builder()");
            exception_builder
                .set_stack_trace(stack_trace_builder.build().unwrap());

            event_builder
                .set_exceptions([exception_builder.build().unwrap()].to_vec());

            event_builder
        }

        #[allow(dead_code)]
        pub fn extract_event_at_index(
            client_builder: &ErrorClientBuilder,
            index: usize,
        ) -> Event {
            let events = client_builder.events().unwrap();
            let event = events.get(index).unwrap().to_owned();

            event
        }
    }
}