use serde_json::{Map, Value};
use std::backtrace::{Backtrace, BacktraceStatus};
use std::error::Error;
use tracing::Metadata;
use super::format::{as_i64, KEY_HTTP_REQUEST, KEY_MESSAGE};
const KEY_TYPE: &str = "@type";
const REPORTED_ERROR_EVENT_TYPE: &str =
"type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent";
const KEY_SERVICE_CONTEXT: &str = "serviceContext";
const KEY_CONTEXT: &str = "context";
const KEY_REPORT_LOCATION: &str = "reportLocation";
const KEY_CONTEXT_HTTP_REQUEST: &str = "httpRequest";
const FIELD_EXCEPTION_TYPE: &str = "exception.type";
const FIELD_PANIC_LOCATION: &str = "panic.location";
const HTTP_REQUEST_CONTEXT_KEYS: [(&str, &str); 6] = [
("requestMethod", "method"),
("requestUrl", "url"),
("userAgent", "userAgent"),
("referer", "referrer"),
("status", "responseStatusCode"),
("remoteIp", "remoteIp"),
];
#[derive(Debug, Clone)]
pub struct ServiceContext {
service: String,
version: Option<String>,
}
impl ServiceContext {
pub fn new(service: impl Into<String>) -> Self {
Self {
service: service.into(),
version: None,
}
}
pub fn with_version(mut self, version: impl Into<String>) -> Self {
self.version = Some(version.into());
self
}
pub(crate) fn report(
&self,
record: &mut Map<String, Value>,
metadata: &Metadata<'_>,
error_chain: Option<&[String]>,
) -> ExceptionDetails {
let event_message = match record.get(KEY_MESSAGE) {
Some(Value::String(message)) => message.clone(),
Some(other) => other.to_string(),
None => String::new(),
};
let exception_message = match error_chain {
Some(chain) => chain.join(": "),
None => event_message.clone(),
};
let stacktrace = capture_backtrace();
let mut message = match error_chain {
Some(_) => format!("{event_message}: {exception_message}"),
None => event_message,
};
if let Some(stacktrace) = &stacktrace {
message.push_str("\n\n");
message.push_str(stacktrace);
}
record.insert(KEY_MESSAGE.to_string(), Value::from(message));
record.insert(KEY_TYPE.to_string(), Value::from(REPORTED_ERROR_EVENT_TYPE));
let mut service = Map::new();
service.insert("service".to_string(), Value::from(self.service.clone()));
if let Some(version) = &self.version {
service.insert("version".to_string(), Value::from(version.clone()));
}
record.insert(KEY_SERVICE_CONTEXT.to_string(), Value::Object(service));
let mut context = Map::new();
let location = report_location(record, metadata);
if !location.is_empty() {
context.insert(KEY_REPORT_LOCATION.to_string(), Value::Object(location));
}
if let Some(Value::Object(request)) = record.get(KEY_HTTP_REQUEST) {
let request = http_request_context(request);
if !request.is_empty() {
context.insert(KEY_CONTEXT_HTTP_REQUEST.to_string(), Value::Object(request));
}
}
if !context.is_empty() {
record.insert(KEY_CONTEXT.to_string(), Value::Object(context));
}
ExceptionDetails {
kind: match record.get(FIELD_EXCEPTION_TYPE) {
Some(Value::String(kind)) => Some(kind.clone()),
_ => None,
},
message: exception_message,
}
}
}
fn report_location(record: &Map<String, Value>, metadata: &Metadata<'_>) -> Map<String, Value> {
let mut location = Map::new();
let panic_location = record
.get(FIELD_PANIC_LOCATION)
.and_then(Value::as_str)
.and_then(|text| {
let (file_and_line, _column) = text.rsplit_once(':')?;
let (file, line) = file_and_line.rsplit_once(':')?;
Some((file, line.parse::<u32>().ok()?))
});
match panic_location {
Some((file, line)) => {
location.insert("filePath".to_string(), Value::from(file));
location.insert("lineNumber".to_string(), Value::from(line));
}
None => {
if let Some(file) = metadata.file() {
location.insert("filePath".to_string(), Value::from(file));
}
if let Some(line) = metadata.line() {
location.insert("lineNumber".to_string(), Value::from(line));
}
if let Some(module_path) = metadata.module_path() {
location.insert("functionName".to_string(), Value::from(module_path));
}
}
}
location
}
fn http_request_context(request: &Map<String, Value>) -> Map<String, Value> {
HTTP_REQUEST_CONTEXT_KEYS
.iter()
.filter_map(|(logging_key, context_key)| {
let value = request.get(*logging_key)?;
let value = if *logging_key == "status" {
as_i64(value).map_or_else(|| value.clone(), Value::from)
} else {
value.clone()
};
Some((context_key.to_string(), value))
})
.collect()
}
fn capture_backtrace() -> Option<String> {
let backtrace = Backtrace::capture();
(backtrace.status() == BacktraceStatus::Captured).then(|| backtrace.to_string())
}
#[cfg_attr(not(feature = "logs-otlp"), allow(dead_code))]
pub(crate) struct ExceptionDetails {
pub(crate) kind: Option<String>,
pub(crate) message: String,
}
pub(crate) fn error_chain(error: &(dyn Error + 'static)) -> Vec<String> {
std::iter::successors(Some(error), |cause| (*cause).source())
.map(ToString::to_string)
.collect()
}
pub fn install_panic_hook() {
let previous_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let message = info
.payload_as_str()
.unwrap_or("panic with a non-string payload");
match info.location() {
Some(location) => tracing::error!(
"exception.type" = "panic",
"panic.location" = %location,
"{message}"
),
None => tracing::error!("exception.type" = "panic", "{message}"),
}
previous_hook(info);
}));
}