use std::borrow::Cow;
use std::collections::BTreeMap;
use serde::Serialize;
use serde_json::{Map, Number, Value};
use flareapp_otlp::{AnyValue, KeyValue, Resource};
use super::{DebugImage, FALLBACK_EXCEPTION_CLASS, Frame, Report, ResolvedReport};
use crate::entry_point::EntryPoint;
use crate::level::Level;
use crate::scope::{Breadcrumb, Glow, User};
const MAX_REPORT_BYTES: usize = 512 * 1024;
const MAX_TRIMMED_FRAMES: usize = 50;
const MAX_TRIMMED_MESSAGE: usize = 10_000;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ReportPayload<'a> {
exception_class: &'a str,
message: Cow<'a, str>,
seen_at_unix_nano: u64,
stacktrace: Vec<FramePayload<'a>>,
events: Vec<EventPayload>,
attributes: Map<String, Value>,
handled: bool,
tracking_uuid: String,
#[serde(skip_serializing_if = "Option::is_none")]
level: Option<&'static str>,
#[serde(skip_serializing_if = "std::ops::Not::not")]
is_log: bool,
#[serde(skip_serializing_if = "Option::is_none")]
application_path: Option<&'a str>,
#[serde(skip_serializing_if = "Vec::is_empty")]
debug_images: Vec<DebugImagePayload<'a>>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct DebugImagePayload<'a> {
debug_id: &'a str,
image_addr: String,
image_size: usize,
#[serde(skip_serializing_if = "Option::is_none")]
code_file: Option<&'a str>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct FramePayload<'a> {
file: &'a str,
line_number: u32,
#[serde(skip_serializing_if = "Option::is_none")]
column_number: Option<u32>,
method: Option<&'a str>,
class: Option<&'a str>,
code_snippet: (),
arguments: (),
is_application_frame: bool,
#[serde(skip_serializing_if = "Option::is_none")]
instruction_addr: Option<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct EventPayload {
#[serde(rename = "type")]
kind: &'static str,
start_time_unix_nano: u64,
end_time_unix_nano: Option<u64>,
attributes: Map<String, Value>,
}
impl ResolvedReport {
pub(crate) fn encode(&self, resource: &Resource) -> serde_json::Result<Vec<u8>> {
let report = &self.report;
let mut payload = ReportPayload {
exception_class: exception_class_or_fallback(&report.exception_class),
message: Cow::Borrowed(&report.message),
seen_at_unix_nano: report.seen_at_unix_nano,
stacktrace: self.frames().iter().map(frame_payload).collect(),
events: events(report),
attributes: attributes(report, resource),
handled: report.handled,
tracking_uuid: report.id.to_string(),
level: report.level.map(Level::as_str),
is_log: report.level.is_some(),
application_path: report.application_path.as_deref(),
debug_images: self
.debug_images()
.iter()
.map(debug_image_payload)
.collect(),
};
let body = serde_json::to_vec(&payload)?;
if body.len() <= MAX_REPORT_BYTES {
return Ok(body);
}
payload.stacktrace.truncate(MAX_TRIMMED_FRAMES);
payload.message = Cow::Owned(report.message.chars().take(MAX_TRIMMED_MESSAGE).collect());
let body = serde_json::to_vec(&payload)?;
if body.len() <= MAX_REPORT_BYTES {
return Ok(body);
}
payload.events.clear();
serde_json::to_vec(&payload)
}
}
fn frame_payload(frame: &Frame) -> FramePayload<'_> {
FramePayload {
file: &frame.file,
line_number: frame.line_number,
column_number: frame.column_number,
method: frame.method.as_deref(),
class: frame.class.as_deref(),
code_snippet: (),
arguments: (),
is_application_frame: frame.is_application_frame,
instruction_addr: frame.instruction_addr.map(hex_address),
}
}
fn debug_image_payload(image: &DebugImage) -> DebugImagePayload<'_> {
DebugImagePayload {
debug_id: &image.debug_id,
image_addr: hex_address(image.image_addr),
image_size: image.image_size,
code_file: image.code_file.as_deref(),
}
}
fn hex_address(address: usize) -> String {
format!("{address:#x}")
}
fn events(report: &Report) -> Vec<EventPayload> {
let mut events: Vec<EventPayload> = report
.scope
.glows
.iter()
.map(glow_event)
.chain(report.scope.breadcrumbs.iter().map(breadcrumb_event))
.collect();
events.sort_by_key(|event| event.start_time_unix_nano);
events
}
fn breadcrumb_event(breadcrumb: &Breadcrumb) -> EventPayload {
let mut attributes = Map::new();
attributes.insert(
"log.message".to_owned(),
Value::from(breadcrumb.message.clone()),
);
attributes.insert(
"log.level".to_owned(),
Value::from(breadcrumb.level.as_str()),
);
attributes.insert(
"log.context".to_owned(),
to_object(fields_to_json(&breadcrumb.fields)),
);
EventPayload {
kind: "log",
start_time_unix_nano: breadcrumb.time_unix_nano,
end_time_unix_nano: None,
attributes,
}
}
fn glow_event(glow: &Glow) -> EventPayload {
let mut attributes = Map::new();
attributes.insert("glow.name".to_owned(), Value::from(glow.name.clone()));
attributes.insert("glow.level".to_owned(), Value::from(glow.level.as_str()));
attributes.insert("glow.context".to_owned(), glow.context.clone());
EventPayload {
kind: "glow",
start_time_unix_nano: glow.time_unix_nano,
end_time_unix_nano: None,
attributes,
}
}
fn exception_class_or_fallback(class: &str) -> &str {
if class.trim().is_empty() {
FALLBACK_EXCEPTION_CLASS
} else {
class
}
}
fn attributes(report: &Report, resource: &Resource) -> Map<String, Value> {
let mut attributes: Map<String, Value> = resource
.attributes
.iter()
.map(|attribute| (attribute.key.to_string(), to_json(&attribute.value)))
.collect();
let entry_point = report
.entry_point
.as_ref()
.map_or_else(|| Cow::Owned(EntryPoint::current_process()), Cow::Borrowed);
for (key, value) in entry_point.attributes() {
attributes.insert(key.to_owned(), Value::from(value));
}
attributes.extend(report.scope.attributes.clone());
if let Some(user) = &report.scope.user {
insert_user_attributes(&mut attributes, user);
}
let mut context = report.scope.context.clone();
context.extend(report.context.clone());
if !context.is_empty() {
attributes.insert("context.custom".to_owned(), to_object(context));
}
attributes.extend(report.attributes.clone());
attributes
}
fn insert_user_attributes(attributes: &mut Map<String, Value>, user: &User) {
attributes.insert("user.id".to_owned(), Value::from(user.id.as_str()));
if let Some(email) = &user.email {
attributes.insert("user.email".to_owned(), Value::from(email.as_str()));
}
if let Some(name) = &user.name {
attributes.insert("user.full_name".to_owned(), Value::from(name.as_str()));
}
if !user.attributes.is_empty() {
attributes.insert(
"user.attributes".to_owned(),
to_object(user.attributes.clone()),
);
}
}
fn to_object(map: BTreeMap<String, Value>) -> Value {
Value::Object(map.into_iter().collect())
}
pub(crate) fn fields_to_json(fields: &[KeyValue]) -> BTreeMap<String, Value> {
fields
.iter()
.map(|field| (field.key.to_string(), to_json(&field.value)))
.collect()
}
pub(crate) fn to_json(value: &AnyValue) -> Value {
match value {
AnyValue::String(text) => Value::from(text.clone()),
AnyValue::Bool(flag) => Value::from(*flag),
AnyValue::Int(number) => Value::from(*number),
AnyValue::Double(number) => Number::from_f64(*number).map_or(Value::Null, Value::Number),
AnyValue::Array(array) => Value::Array(array.values.iter().map(to_json).collect()),
AnyValue::Kvlist(list) => Value::Object(
list.values
.iter()
.map(|entry| (entry.key.to_string(), to_json(&entry.value)))
.collect(),
),
}
}
#[cfg(test)]
mod tests {
use std::collections::VecDeque;
use std::panic::Location;
use serde_json::json;
use flareapp_otlp::KeyValue;
use super::*;
use crate::report::{ResolveFrames, StackTrace};
use crate::scope::{Breadcrumb, Glow, Scope, User};
use crate::test_support::{global_entry_point, in_queue_span, serial};
fn resource() -> Resource {
Resource::new(vec![
KeyValue::new("service.name", "shop"),
KeyValue::new("process.pid", 42_i64),
KeyValue::new("flare.language.name", "rust"),
])
}
fn report() -> Report {
let mut report = Report::new("my_app::OrderFailed", "order 7 failed", Location::caller());
report.set_location(Frame {
file: "/app/src/orders.rs".to_owned(),
line_number: 12,
column_number: Some(5),
method: Some("create".to_owned()),
class: Some("my_app::orders::OrderService".to_owned()),
is_application_frame: true,
instruction_addr: None,
});
let mut scope = Scope::default();
scope.set_user(User::new("42").email("a@b.c").name("Ada"));
scope.set_context("order", json!({ "id": 7 }));
report.attach(scope, Some("/app".to_owned()), None);
report
}
fn encode(report: Report) -> Value {
let body = report.resolve_frames(false).encode(&resource()).unwrap();
serde_json::from_slice(&body).unwrap()
}
#[test]
fn reports_match_the_snapshot() {
let mut json = encode(report());
for (pointer, placeholder) in [
("/seenAtUnixNano", "[time]"),
("/trackingUuid", "[uuid]"),
("/attributes/flare.entry_point.value", "[command line]"),
(
"/attributes/flare.entry_point.handler.identifier",
"[executable]",
),
] {
let value = json
.pointer_mut(pointer)
.unwrap_or_else(|| panic!("the report has no `{pointer}` field"));
*value = json!(placeholder);
}
insta::assert_snapshot!(crate::test_support::snapshot_json(&json));
}
#[test]
fn sends_what_the_backend_requires() {
let json = encode(report());
assert_eq!(json["exceptionClass"], "my_app::OrderFailed");
assert_eq!(json["message"], "order 7 failed");
assert!(json["seenAtUnixNano"].is_u64());
assert_eq!(json["events"], json!([]));
assert_eq!(json["handled"], true);
assert_eq!(json["applicationPath"], "/app");
assert_eq!(json["trackingUuid"].as_str().map(str::len), Some(36));
assert_eq!(json.get("level"), None);
assert_eq!(json.get("isLog"), None);
assert_eq!(json.get("debugImages"), None);
}
#[test]
fn frames_use_flare_field_names() {
let frame = &encode(report())["stacktrace"][0];
assert_eq!(
*frame,
json!({
"file": "/app/src/orders.rs",
"lineNumber": 12,
"columnNumber": 5,
"method": "create",
"class": "my_app::orders::OrderService",
"codeSnippet": null,
"arguments": null,
"isApplicationFrame": true,
})
);
}
#[derive(Debug)]
struct StrippedStack;
impl ResolveFrames for StrippedStack {
fn resolve(self: Box<Self>, location: &Frame) -> StackTrace {
StackTrace {
frames: vec![Frame {
instruction_addr: Some(0x1_00bb_1070),
..location.clone()
}],
debug_images: vec![DebugImage {
debug_id: "f12a7db2-03d7-370d-a820-107402c0c6e7".to_owned(),
image_addr: 0x1_00b9_8000,
image_size: 557_056,
code_file: Some("/app/target/release/shop".to_owned()),
}],
}
}
}
fn stripped_report() -> Value {
let mut report = report();
report.set_frames(StrippedStack);
encode(report)
}
#[test]
fn frames_send_their_address_as_hex() {
assert_eq!(
stripped_report()["stacktrace"][0]["instructionAddr"],
"0x100bb1070"
);
}
#[test]
fn debug_images_use_flare_field_names() {
assert_eq!(
stripped_report()["debugImages"],
json!([{
"debugId": "f12a7db2-03d7-370d-a820-107402c0c6e7",
"imageAddr": "0x100b98000",
"imageSize": 557_056,
"codeFile": "/app/target/release/shop",
}])
);
}
#[test]
fn the_context_of_a_report_joins_the_context_of_the_scope() {
let mut report = report();
report.set_context("payment", "mollie");
let attributes = &encode(report)["attributes"];
assert_eq!(
attributes["context.custom"],
json!({ "order": { "id": 7 }, "payment": "mollie" })
);
}
#[test]
fn the_attributes_of_a_report_are_sent() {
let mut report = report();
report.set_attribute("thread.name", "main");
let attributes = &encode(report)["attributes"];
assert_eq!(attributes["thread.name"], "main");
}
#[test]
fn the_scope_sets_the_attributes() {
let mut scope = Scope::default();
scope.set_attribute("http.request.method", "GET");
let mut report = report();
report.attach(scope, None, None);
let attributes = &encode(report)["attributes"];
assert_eq!(attributes["http.request.method"], "GET");
}
#[test]
fn the_resolved_entry_point_is_encoded() {
let mut report = report();
report.entry_point = Some(
EntryPoint::web("https://shop.test/users/7")
.handler_identifier("GET /users/{id}")
.handler_type("axum_route"),
);
let attributes = &encode(report)["attributes"];
assert_eq!(attributes["flare.entry_point.type"], "web");
assert_eq!(
attributes["flare.entry_point.value"],
"https://shop.test/users/7"
);
assert_eq!(
attributes["flare.entry_point.handler.identifier"],
"GET /users/{id}"
);
assert_eq!(attributes["flare.entry_point.handler.type"], "axum_route");
assert_eq!(attributes.get("flare.entry_point.handler.name"), None);
}
#[test]
fn a_span_entry_point_wins_over_the_global_scope_in_a_report() {
let _serial = serial();
let _global = global_entry_point(EntryPoint::cli("my-app worker"));
let mut report = report();
in_queue_span(|| report.resolve_entry_point());
let attributes = &encode(report)["attributes"];
assert_eq!(attributes["flare.entry_point.type"], "queue");
assert_eq!(attributes["flare.entry_point.value"], "send-invoice");
}
#[test]
fn messages_have_a_level() {
let report = Report::from_message("Stock low", Level::Warning, Location::caller());
let json = encode(report);
assert_eq!(json["exceptionClass"], "Log");
assert_eq!(json["isLog"], true);
assert_eq!(json["level"], "warning");
}
#[test]
fn glows_become_glow_events() {
let scope = Scope {
glows: VecDeque::from([Glow {
name: "cart updated".to_owned(),
level: Level::Info,
context: json!({ "items": 3 }),
time_unix_nano: 1,
}]),
..Scope::default()
};
let mut report = report();
report.attach(scope, None, None);
let event = &encode(report)["events"][0];
assert_eq!(
*event,
json!({
"type": "glow",
"startTimeUnixNano": 1,
"endTimeUnixNano": null,
"attributes": {
"glow.name": "cart updated",
"glow.level": "info",
"glow.context": { "items": 3 },
},
})
);
}
#[test]
fn breadcrumbs_become_log_events_after_older_glows() {
let scope = Scope {
glows: VecDeque::from([Glow {
name: "checkout started".to_owned(),
level: Level::Info,
context: Value::Null,
time_unix_nano: 1,
}]),
breadcrumbs: VecDeque::from([Breadcrumb {
message: "payment declined".to_owned(),
level: Level::Warning,
fields: vec![KeyValue::new("order_id", 7_i64)],
time_unix_nano: 2,
}]),
..Scope::default()
};
let mut report = report();
report.attach(scope, None, None);
let events = &encode(report)["events"];
assert_eq!(events[0]["type"], "glow");
assert_eq!(events[1]["type"], "log");
assert_eq!(events[1]["attributes"]["log.message"], "payment declined");
assert_eq!(events[1]["attributes"]["log.level"], "warning");
assert_eq!(
events[1]["attributes"]["log.context"],
json!({ "order_id": 7 })
);
}
#[test]
fn empty_exception_classes_get_the_fallback() {
let mut report = report();
report.set_exception_class("");
assert_eq!(encode(report)["exceptionClass"], "Error");
}
#[test]
fn blank_exception_classes_get_the_fallback() {
let mut report = report();
report.set_exception_class(" ");
assert_eq!(encode(report)["exceptionClass"], "Error");
}
#[test]
fn trims_large_reports() {
#[derive(Debug)]
struct ManyFrames;
impl ResolveFrames for ManyFrames {
fn resolve(self: Box<Self>, location: &Frame) -> StackTrace {
let frame = Frame {
method: Some("x".repeat(10_000)),
..location.clone()
};
StackTrace {
frames: vec![frame; 200],
debug_images: Vec::new(),
}
}
}
let mut report = report();
report.set_frames(ManyFrames);
let body = report.resolve_frames(false).encode(&resource()).unwrap();
let json: Value = serde_json::from_slice(&body).unwrap();
assert!(body.len() <= MAX_REPORT_BYTES);
assert_eq!(
json["stacktrace"].as_array().map(Vec::len),
Some(MAX_TRIMMED_FRAMES)
);
}
#[test]
fn drops_the_timeline_when_nothing_else_helps() {
let breadcrumb = Breadcrumb {
message: "x".repeat(10_000),
level: Level::Info,
fields: Vec::new(),
time_unix_nano: 1,
};
let scope = Scope {
breadcrumbs: vec![breadcrumb; 100].into(),
..Scope::default()
};
let mut report = report();
report.attach(scope, None, None);
let body = report.resolve_frames(false).encode(&resource()).unwrap();
let json: Value = serde_json::from_slice(&body).unwrap();
assert!(body.len() <= MAX_REPORT_BYTES);
assert_eq!(json["events"], json!([]));
}
}