flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
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
//! One log line from a logging integration, and what the Flare client makes of
//! it: an OTLP log record, a breadcrumb, or an error report.
//!
//! The `tracing` and `log` integrations both turn their log lines into a
//! [`LogLine`], so the conversion lives in one place.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::error::Error;
use std::iter;
use std::mem;
use std::panic::Location;
use std::path::Path;
use std::thread;

use serde_json::{Value, json};

use flareapp_otlp::{KeyValue, LogRecord, Severity, SpanId, TraceId};

use crate::client::Client;
use crate::entry_point::{EntryPoint, resolve_entry_point};
use crate::level::Level;
use crate::report::{
    FALLBACK_EXCEPTION_CLASS, Frame, Report, erased_exception_class, fields_to_json,
};
use crate::scope::{add_log_breadcrumb, has_nested_entry_point};
use crate::source_path::is_application_file;

/// The trace and span a log line belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceContext {
    /// The trace the line happened in.
    pub trace_id: TraceId,
    /// The span the line happened in.
    pub span_id: SpanId,
    /// Whether the trace is sampled.
    pub sampled: bool,
}

/// Where [`LogLine::send`] delivers a line.
#[derive(Debug, Clone, Copy, Default)]
pub struct Targets {
    /// Send the line to Flare as an OTLP log record.
    pub log: bool,
    /// Send the line as an error report.
    pub report: bool,
    /// Keep the line as a breadcrumb in the current scope.
    pub breadcrumb: bool,
}

impl Targets {
    /// Returns `true` when at least one target is on.
    pub fn any(self) -> bool {
        self.log || self.report || self.breadcrumb
    }
}

/// An error that a log line carries, like the `error` field of a `tracing` event.
///
/// A logging integration only borrows the error while it reads the line, so the
/// line keeps a copy of what an error report needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoggedError {
    /// The exception class. A `&dyn Error` has no type name, so this is the name
    /// that [`erased_exception_class`] reads from the `Debug` output, like
    /// `RowNotFound` or `reqwest::Error`.
    class: String,
    /// The `Display` output of the error.
    message: String,
    /// The class and message of each error in the [`Error::source`] chain, the
    /// direct cause first.
    sources: Vec<(String, String)>,
}

impl LoggedError {
    /// Copies the class, the message and the causes of `error`.
    pub fn new(error: &(dyn Error + 'static)) -> Self {
        let sources = iter::successors(error.source(), |&source| source.source())
            .map(|source| (logged_class(source), source.to_string()))
            .collect();

        Self {
            class: logged_class(error),
            message: error.to_string(),
            sources,
        }
    }

    /// Returns a report of the error: its class and its message, and its causes
    /// in the `error` context. The location of the report is a placeholder.
    fn to_report(&self) -> Report {
        let mut report = Report::new(self.class.clone(), self.message.clone(), Location::caller());
        if !self.sources.is_empty() {
            report.set_context("error", json!({ "sources": self.sources_json() }));
        }

        report
    }

    /// Returns the causes as JSON, for the context of a report.
    fn sources_json(&self) -> Value {
        self.sources
            .iter()
            .map(|(class, message)| json!({ "class": class, "message": message }))
            .collect()
    }
}

/// Returns the exception class of an error behind a `&dyn Error`, or a fallback
/// when its `Debug` output has no name.
fn logged_class(error: &(dyn Error + 'static)) -> String {
    erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
}

/// A log line, in the shape every logging integration can produce.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct LogLine {
    /// The `tracing` or `log` target that wrote the line, like `my_app::billing`.
    /// It is the module path, unless the code sets another target. Flare shows it
    /// as the target of the log.
    pub target: Cow<'static, str>,
    /// The message, like `order placed`.
    pub message: String,
    /// The severity. Flare's [`Level`] is derived from it.
    pub severity: Severity,
    /// The structured fields of the line, like `order_id = 7`.
    pub fields: Vec<KeyValue>,
    /// The source file that wrote the line, when known.
    pub file: Option<String>,
    /// The line number in the source file, when known.
    pub line: Option<u32>,
    /// The trace and span the line happened in, when there is one.
    pub trace: Option<TraceContext>,
    /// The entry point of the closest `tracing` span around the line that has an
    /// entry point, like the `server` span of a request. `None` means that no
    /// span around the line has one.
    ///
    /// Integrations must set this field when they send the line as a log record
    /// or as a report. The log record and the report do not search the spans
    /// again, because the current span can differ from the span of the line, for
    /// example for an event with `parent: None`. An integration can leave this
    /// field `None` when a nested scope has an entry point, because that entry
    /// point wins over every span. [`LogLine::search_entry_point`] sets this field
    /// and skips the search in that case.
    pub entry_point: Option<EntryPoint>,
    /// The error the line logs, like the `error` field of a `tracing` event. When
    /// the line is sent as an error report, the report shows this error instead of
    /// the message.
    pub error: Option<LoggedError>,
}

impl LogLine {
    /// Creates a line with a target, a message and a severity. The other fields
    /// start empty, and integrations set them afterwards. For a log record or a
    /// report, integrations must also set [`LogLine::entry_point`].
    pub fn new<T, M>(target: T, message: M, severity: Severity) -> Self
    where
        T: Into<Cow<'static, str>>,
        M: Into<String>,
    {
        Self {
            target: target.into(),
            message: message.into(),
            severity,
            fields: Vec::new(),
            file: None,
            line: None,
            trace: None,
            entry_point: None,
            error: None,
        }
    }

    /// Sets [`LogLine::entry_point`] to the result of `search_spans`, which finds
    /// the entry point of the closest `tracing` span around the line. This function
    /// does not call `search_spans` when a nested scope has an entry point,
    /// because that entry point wins over every span.
    ///
    /// Integrations call this function on the thread that made the line, for a
    /// line that they send as a log record or as a report.
    pub fn search_entry_point<F>(&mut self, search_spans: F)
    where
        F: FnOnce() -> Option<EntryPoint>,
    {
        if !has_nested_entry_point() {
            self.entry_point = search_spans();
        }
    }

    /// Returns the level of the line, as a Flare [`Level`].
    pub fn level(&self) -> Level {
        self.severity.into()
    }

    /// Delivers the line to the given `targets`.
    ///
    /// This function sends the report before it records the breadcrumb. That way,
    /// the timeline of the report shows what happened before this line, and not
    /// this line itself. The log record comes last, because it takes the message
    /// and the fields of the line instead of a copy.
    pub fn send(mut self, client: &Client, targets: Targets) {
        if targets.report {
            client.send_report(self.to_report(client.app_crates()));
        }
        if targets.breadcrumb {
            let (message, fields) = if targets.log {
                (self.message.clone(), self.fields.clone())
            } else {
                (mem::take(&mut self.message), mem::take(&mut self.fields))
            };
            add_log_breadcrumb(message, self.level(), fields);
        }
        if targets.log {
            // Only the log record needs the target, so it can move out of the line.
            let target = mem::take(&mut self.target);
            client.send_log(target, self.into_log_record());
        }
    }

    /// Turns a copy of the line into an OTLP log record. Only the tests call this
    /// function. [`LogLine::send`] moves the line into the record instead.
    #[cfg(test)]
    fn to_log_record(&self) -> LogRecord {
        self.clone().into_log_record()
    }

    /// Turns the line into an OTLP log record, with the trace context, the source
    /// location, the thread name and the entry point of the work. This function
    /// moves the message, the fields, the file and the entry point into the record
    /// instead of copying them.
    fn into_log_record(self) -> LogRecord {
        let mut record = LogRecord::new(self.severity, self.message);
        record.attributes = self.fields;

        if let Some(trace) = self.trace {
            record.trace_id = Some(trace.trace_id);
            record.span_id = Some(trace.span_id);
            record.flags = u32::from(trace.sampled);
        }

        if let Some(file) = self.file {
            record
                .attributes
                .push(KeyValue::new("code.file.path", file));
        }
        if let Some(line) = self.line {
            record
                .attributes
                .push(KeyValue::new("code.line.number", i64::from(line)));
        }
        if let Some(name) = thread::current().name() {
            record
                .attributes
                .push(KeyValue::new("thread.name", name.to_owned()));
        }
        // Flare lists a log under the handler of its entry point, like the route
        // `GET /users/{id}`.
        record.attributes.extend(
            resolve_entry_point(|| self.entry_point)
                .into_attributes()
                .into_iter()
                .map(|(key, value)| KeyValue::new(key, value)),
        );

        record
    }

    /// Turns the line into an error report. The fields go into the report's context
    /// under `log`, and the source location becomes its only frame.
    ///
    /// A line with an [`error`](LogLine::error) reports that error: its class and
    /// message. The message of the line goes into the `log` context, unless the
    /// message is empty or the same as the message of the error. The causes of the
    /// error go into the `error` context. Flare drops causes without frames, and
    /// Rust causes have none. A line without an error is reported like
    /// [`Report::from_message`].
    ///
    /// The report does not search the spans for an entry point. It uses
    /// [`LogLine::entry_point`].
    ///
    /// `app_crates` are the dependencies that count as application code. Pass
    /// [`Client::app_crates`].
    pub(crate) fn to_report(&self, app_crates: &[String]) -> Report {
        // `Location::caller()` is only a placeholder. `set_location` replaces it
        // with the place that wrote the line.
        let mut report = match &self.error {
            Some(error) => error.to_report(),
            None => Report::from_message(self.message.clone(), self.level(), Location::caller()),
        };
        report.set_location(self.location_frame(app_crates));

        let context = self.report_context();
        if !context.is_empty() {
            report.set_context("log", Value::Object(context.into_iter().collect()));
        }
        report.entry_point = Some(resolve_entry_point(|| self.entry_point.clone()));

        report
    }

    /// Returns the place that wrote the line, as the frame of a report. Flare
    /// needs at least one frame, also when the source file is unknown.
    fn location_frame(&self, app_crates: &[String]) -> Frame {
        Frame {
            file: self.file.clone().unwrap_or_else(|| "<unknown>".to_owned()),
            line_number: self.line.unwrap_or(0),
            column_number: None,
            method: None,
            class: None,
            is_application_frame: self
                .file
                .as_deref()
                .is_some_and(|file| is_application_file(Path::new(file), app_crates)),
            instruction_addr: None,
        }
    }

    /// Returns the `log` context of a report: the fields of the line. When the
    /// report shows the error of the line, the context also gets the message of
    /// the line, unless it is empty or the same as the message of the error.
    fn report_context(&self) -> BTreeMap<String, Value> {
        let mut context = fields_to_json(&self.fields);
        if let Some(error) = &self.error
            && !self.message.is_empty()
            && self.message != error.message
        {
            context.insert("message".to_owned(), Value::from(self.message.clone()));
        }

        context
    }
}

#[cfg(test)]
mod tests {
    use std::fmt;

    use flareapp_otlp::{AnyValue, Resource};

    use super::*;
    use crate::scope::with_scope;
    use crate::test_support::{attribute, in_queue_span, serial};

    fn line() -> LogLine {
        let mut line = LogLine::new("shop::checkout", "payment declined", Severity::Warn);
        line.fields = vec![KeyValue::new("order_id", 7_i64)];
        line.file = Some("src/checkout.rs".to_owned());
        line.line = Some(42);

        line
    }

    /// Turns the line into an error report, and returns the JSON that Flare gets.
    fn report_json(line: &LogLine) -> Value {
        let mut report = line.to_report(&[]);
        report.resolve_entry_point();
        let resource = Resource::new(Vec::new());

        let body = report.resolve_frames(false).encode(&resource).unwrap();

        serde_json::from_slice(&body).unwrap()
    }

    #[test]
    fn log_records_have_the_message_and_severity() {
        let record = line().to_log_record();

        assert_eq!(record.severity_number, Severity::Warn);
        assert_eq!(record.body, "payment declined");
    }

    #[test]
    fn log_records_have_the_fields() {
        let record = line().to_log_record();

        assert_eq!(
            attribute(&record.attributes, "order_id"),
            Some(&AnyValue::Int(7))
        );
    }

    #[test]
    fn log_records_have_the_source_location() {
        let record = line().to_log_record();

        assert_eq!(
            attribute(&record.attributes, "code.file.path"),
            Some(&AnyValue::String("src/checkout.rs".to_owned()))
        );
        assert_eq!(
            attribute(&record.attributes, "code.line.number"),
            Some(&AnyValue::Int(42))
        );
    }

    #[test]
    fn log_records_have_the_trace_context() {
        let mut line = line();
        line.trace = Some(TraceContext {
            trace_id: TraceId::random(),
            span_id: SpanId::random(),
            sampled: true,
        });

        let record = line.to_log_record();

        assert_eq!(record.trace_id, line.trace.map(|trace| trace.trace_id));
        assert_eq!(record.span_id, line.trace.map(|trace| trace.span_id));
        assert_eq!(record.flags, 1);
    }

    fn log_record_in_a_web_scope() -> LogRecord {
        let entry_point =
            EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}");

        with_scope(
            |scope| scope.set_entry_point(entry_point),
            || line().to_log_record(),
        )
    }

    #[test]
    fn log_records_have_the_entry_point_type_of_the_scope() {
        let record = log_record_in_a_web_scope();

        assert_eq!(
            attribute(&record.attributes, "flare.entry_point.type"),
            Some(&AnyValue::String("web".to_owned()))
        );
    }

    #[test]
    fn log_records_have_the_handler_identifier_of_the_scope() {
        let record = log_record_in_a_web_scope();

        assert_eq!(
            attribute(&record.attributes, "flare.entry_point.handler.identifier"),
            Some(&AnyValue::String("GET /users/{id}".to_owned()))
        );
    }

    #[test]
    fn log_records_have_the_entry_point_of_their_span() {
        let mut line = line();
        line.entry_point = Some(EntryPoint::queue("send-invoice"));

        let record = line.to_log_record();

        assert_eq!(
            attribute(&record.attributes, "flare.entry_point.type"),
            Some(&AnyValue::String("queue".to_owned()))
        );
    }

    #[test]
    fn log_records_outside_any_work_are_commands() {
        let _serial = serial();
        let record = line().to_log_record();

        assert_eq!(
            attribute(&record.attributes, "flare.entry_point.type"),
            Some(&AnyValue::String("cli".to_owned()))
        );
    }

    #[test]
    fn log_records_outside_any_work_are_rust_binaries() {
        let _serial = serial();
        let record = line().to_log_record();

        assert_eq!(
            attribute(&record.attributes, "flare.entry_point.handler.type"),
            Some(&AnyValue::String("rust_binary".to_owned()))
        );
    }

    #[test]
    fn reports_from_log_lines_get_the_entry_point_of_their_span() {
        let mut line = line();
        line.entry_point = Some(EntryPoint::queue("send-invoice"));

        let json = report_json(&line);

        assert_eq!(json["attributes"]["flare.entry_point.type"], "queue");
    }

    #[test]
    fn reports_from_log_lines_without_a_span_entry_point_ignore_the_current_span() {
        let _serial = serial();

        let json = in_queue_span(|| report_json(&line()));

        assert_eq!(json["attributes"]["flare.entry_point.type"], "cli");
    }

    #[test]
    fn reports_that_never_looked_for_a_span_use_the_current_span() {
        let _serial = serial();

        let entry_point = in_queue_span(|| {
            let mut report = Report::from_message("x".to_owned(), Level::Error, Location::caller());
            report.resolve_entry_point();

            report.entry_point
        });

        assert_eq!(entry_point, Some(EntryPoint::queue("send-invoice")));
    }

    #[test]
    fn reports_have_the_message_and_level() {
        let json = report_json(&line());

        assert_eq!(json["exceptionClass"], "Log");
        assert_eq!(json["message"], "payment declined");
        assert_eq!(json["level"], "warning");
    }

    #[test]
    fn reports_use_the_log_location_as_their_frame() {
        let json = report_json(&line());

        assert_eq!(json["stacktrace"][0]["file"], "src/checkout.rs");
        assert_eq!(json["stacktrace"][0]["lineNumber"], 42);
    }

    #[test]
    fn reports_have_the_fields_as_context() {
        let json = report_json(&line());

        assert_eq!(
            json["attributes"]["context.custom"]["log"],
            json!({ "order_id": 7 })
        );
    }

    #[derive(Debug)]
    struct ForeignKeyViolation;

    impl fmt::Display for ForeignKeyViolation {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("insert violates foreign key constraint")
        }
    }

    impl Error for ForeignKeyViolation {}

    #[derive(Debug)]
    enum QueryFailed {
        Database(ForeignKeyViolation),
    }

    impl fmt::Display for QueryFailed {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("error returned from database")
        }
    }

    impl Error for QueryFailed {
        fn source(&self) -> Option<&(dyn Error + 'static)> {
            let Self::Database(violation) = self;

            Some(violation)
        }
    }

    fn line_with_error() -> LogLine {
        let mut line = line();
        line.error = Some(LoggedError::new(&QueryFailed::Database(
            ForeignKeyViolation,
        )));

        line
    }

    #[test]
    fn reports_of_lines_with_an_error_report_the_error() {
        let json = report_json(&line_with_error());

        assert_eq!(
            (&json["exceptionClass"], &json["message"], &json["level"]),
            (
                &json!("Database"),
                &json!("error returned from database"),
                &Value::Null
            )
        );
    }

    #[test]
    fn reports_of_lines_with_an_error_keep_the_message_as_context() {
        let json = report_json(&line_with_error());

        assert_eq!(
            json["attributes"]["context.custom"]["log"],
            json!({ "message": "payment declined", "order_id": 7 })
        );
    }

    #[test]
    fn reports_of_lines_with_an_error_list_its_causes_as_context() {
        let json = report_json(&line_with_error());

        assert_eq!(
            json["attributes"]["context.custom"]["error"],
            json!({ "sources": [{
                "class": "ForeignKeyViolation",
                "message": "insert violates foreign key constraint",
            }] })
        );
    }

    #[test]
    fn reports_of_lines_with_an_error_without_causes_have_no_error_context() {
        let mut line = line();
        line.error = Some(LoggedError::new(&ForeignKeyViolation));

        let json = report_json(&line);

        assert_eq!(json["attributes"]["context.custom"]["error"], Value::Null);
    }

    /// Like the panic message that `tracing-panic` logs from its own file.
    #[test]
    fn reports_of_lines_from_a_dependency_have_no_application_frame() {
        let mut line = line();
        line.file = Some(
            "/home/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-panic-0.1.2/src/lib.rs"
                .to_owned(),
        );

        let json = report_json(&line);

        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
    }

    #[test]
    fn reports_of_lines_from_the_app_have_an_application_frame() {
        let json = report_json(&line());

        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], true);
    }

    #[test]
    fn reports_without_a_file_have_no_application_frame() {
        let mut line = line();
        line.file = None;

        let json = report_json(&line);

        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
    }
}