use std::borrow::Cow;
use flareapp_otlp::{AnyValue, KeyValue, Span, SpanKind, StatusCode, find_attribute};
use crate::entry_point::{EntryPoint, WebRequest, web_entry_point};
pub const MAX_SPANS_PER_TRACE: usize = 1024;
pub const MAX_ATTRIBUTES: usize = 128;
pub const MAX_EVENTS: usize = 128;
const FLAG_SAMPLED: u32 = 0x01;
const FLAG_HAS_IS_REMOTE: u32 = 0x100;
const FLAG_IS_REMOTE: u32 = 0x200;
pub fn sampled_span_flags(parent_is_remote: bool) -> u32 {
let flags = FLAG_SAMPLED | FLAG_HAS_IS_REMOTE;
if parent_is_remote {
flags | FLAG_IS_REMOTE
} else {
flags
}
}
pub fn is_local_root(span: &Span) -> bool {
let remote_parent = FLAG_HAS_IS_REMOTE | FLAG_IS_REMOTE;
span.parent_span_id.is_none() || span.flags & remote_parent == remote_parent
}
pub fn set_span_attribute<K, V>(span: &mut Span, key: K, value: V)
where
K: Into<Cow<'static, str>>,
V: Into<AnyValue>,
{
let attribute = KeyValue::new(key, value);
if let Some(existing) = span
.attributes
.iter_mut()
.find(|existing| existing.key == attribute.key)
{
existing.value = attribute.value;
} else if span.attributes.len() < MAX_ATTRIBUTES {
span.attributes.push(attribute);
} else {
span.dropped_attributes_count += 1;
}
}
pub fn finish_span(span: &mut Span, is_local_root: bool, entry_point: Option<&EntryPoint>) {
if !has_attribute(span, "flare.span_type")
&& let Some(span_type) = mapped_span_type(span, is_local_root)
{
set_span_attribute(span, "flare.span_type", span_type);
}
if let Some(entry_point) = entry_point {
for (key, value) in entry_point.attributes() {
if !has_attribute(span, key) {
set_span_attribute(span, key, value);
}
}
}
if string_attribute(span, "flare.span_type") == Some("command")
&& !has_attribute(span, "process.command")
{
let name = span.name.to_string();
set_span_attribute(span, "process.command", name);
}
clear_status_message_unless_error(span);
}
pub fn clear_status_message_unless_error(span: &mut Span) {
if span.status.code != StatusCode::Error {
span.status.message = None;
}
}
fn mapped_span_type(span: &Span, is_local_root: bool) -> Option<&'static str> {
let has_method = has_attribute(span, "http.request.method");
if has_attribute(span, "db.system.name")
|| has_attribute(span, "db.query.text")
|| has_attribute(span, "db.statement")
{
Some("query")
} else if span.kind == SpanKind::Server && has_method {
Some("request")
} else if span.kind == SpanKind::Client && has_method {
Some("http_client")
} else if is_local_root && span.kind == SpanKind::Internal {
Some("operation")
} else {
None
}
}
fn has_attribute(span: &Span, key: &str) -> bool {
find_attribute(&span.attributes, key).is_some()
}
fn string_attribute<'a>(span: &'a Span, key: &str) -> Option<&'a str> {
find_attribute(&span.attributes, key)?.as_str()
}
pub fn parse_kind(kind: &str) -> Option<SpanKind> {
const KINDS: [(&str, SpanKind); 5] = [
("internal", SpanKind::Internal),
("server", SpanKind::Server),
("client", SpanKind::Client),
("producer", SpanKind::Producer),
("consumer", SpanKind::Consumer),
];
KINDS
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case(kind))
.map(|&(_, span_kind)| span_kind)
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct EntryFields {
name: Cow<'static, str>,
otel_name: Option<String>,
kind: Option<String>,
span_type: Option<String>,
method: Option<String>,
route: Option<String>,
url: Option<String>,
path: Option<String>,
framework: Option<String>,
destination: Option<String>,
}
impl EntryFields {
pub fn new<N: Into<Cow<'static, str>>>(name: N) -> Self {
Self {
name: name.into(),
..Self::default()
}
}
fn slots(&mut self) -> [(&'static str, &mut Option<String>); 9] {
[
("otel.name", &mut self.otel_name),
("otel.kind", &mut self.kind),
("flare.span_type", &mut self.span_type),
("http.request.method", &mut self.method),
("http.route", &mut self.route),
("url.full", &mut self.url),
("url.path", &mut self.path),
("flare.framework.name", &mut self.framework),
("messaging.destination.name", &mut self.destination),
]
}
pub fn set<F: FnOnce() -> String>(&mut self, field: &str, value: F) {
if let Some((_, slot)) = self.slots().into_iter().find(|(name, _)| *name == field) {
*slot = Some(value());
}
}
pub fn is_empty(&self) -> bool {
let empty = Self {
name: self.name.clone(),
..Self::default()
};
*self == empty
}
pub fn merge(&mut self, mut other: Self) {
for ((_, slot), (_, value)) in self.slots().into_iter().zip(other.slots()) {
if value.is_some() {
*slot = value.take();
}
}
}
pub fn entry_point(&self) -> Option<EntryPoint> {
if self.span_type.as_deref() == Some("command") {
return Some(self.command());
}
match parse_kind(self.kind.as_deref()?)? {
SpanKind::Server => self.web(),
SpanKind::Consumer => Some(self.queue()),
_ => None,
}
}
fn command(&self) -> EntryPoint {
EntryPoint::current_process().handler_identifier(self.span_name())
}
fn web(&self) -> Option<EntryPoint> {
let url = self.url.as_deref().or(self.path.as_deref())?;
Some(web_entry_point(&WebRequest {
url,
method: self.method.as_deref(),
route: self.route.as_deref(),
path: self.path.as_deref(),
framework: self.framework.as_deref(),
}))
}
fn queue(&self) -> EntryPoint {
let name = self.span_name();
let queue = self.destination.as_deref().unwrap_or(name);
EntryPoint::queue(queue).handler_identifier(name)
}
fn span_name(&self) -> &str {
self.otel_name.as_deref().unwrap_or(&self.name)
}
}
#[cfg(test)]
mod tests {
use flareapp_otlp::{SpanId, TraceId};
use super::*;
fn span(kind: SpanKind) -> Span {
Span::new(TraceId::random(), SpanId::random(), "checkout", kind)
}
fn span_type(span: &Span) -> Option<&str> {
string_attribute(span, "flare.span_type")
}
#[test]
fn parses_kinds_in_any_case() {
assert_eq!(parse_kind("server"), Some(SpanKind::Server));
assert_eq!(parse_kind("CLIENT"), Some(SpanKind::Client));
}
#[test]
fn ignores_unknown_kinds() {
assert_eq!(parse_kind("sideways"), None);
}
#[test]
fn a_span_without_a_parent_is_a_local_root() {
assert!(is_local_root(&span(SpanKind::Internal)));
}
#[test]
fn a_span_with_a_remote_parent_is_a_local_root() {
let span = Span {
parent_span_id: Some(SpanId::random()),
flags: sampled_span_flags(true),
..span(SpanKind::Server)
};
assert!(is_local_root(&span));
}
#[test]
fn a_span_with_a_parent_in_this_process_is_not_a_local_root() {
let span = Span {
parent_span_id: Some(SpanId::random()),
flags: sampled_span_flags(false),
..span(SpanKind::Internal)
};
assert!(!is_local_root(&span));
}
#[test]
fn counts_the_attributes_above_the_limit() {
let mut span = span(SpanKind::Internal);
for index in 0..MAX_ATTRIBUTES + 2 {
set_span_attribute(&mut span, format!("field_{index}"), 1_i64);
}
assert_eq!(
(span.attributes.len(), span.dropped_attributes_count),
(MAX_ATTRIBUTES, 2)
);
}
#[test]
fn replacing_an_attribute_keeps_room_for_others() {
let mut span = span(SpanKind::Internal);
set_span_attribute(&mut span, "status", 200_i64);
set_span_attribute(&mut span, "status", 500_i64);
assert_eq!(span.attributes.len(), 1);
}
#[test]
fn an_internal_root_span_is_an_operation() {
let mut span = span(SpanKind::Internal);
finish_span(&mut span, true, None);
assert_eq!(span_type(&span), Some("operation"));
}
#[test]
fn an_internal_child_span_gets_no_type() {
let mut span = span(SpanKind::Internal);
finish_span(&mut span, false, None);
assert_eq!(span_type(&span), None);
}
#[test]
fn a_span_with_a_query_is_a_query() {
let mut span = span(SpanKind::Client);
set_span_attribute(&mut span, "db.query.text", "select 1");
finish_span(&mut span, false, None);
assert_eq!(span_type(&span), Some("query"));
}
#[test]
fn a_span_type_of_the_span_wins() {
let mut span = span(SpanKind::Internal);
set_span_attribute(&mut span, "flare.span_type", "job");
finish_span(&mut span, true, None);
assert_eq!(span_type(&span), Some("job"));
}
#[test]
fn a_command_span_gets_its_name_as_the_process_command() {
let mut span = span(SpanKind::Internal);
set_span_attribute(&mut span, "flare.span_type", "command");
finish_span(&mut span, true, None);
assert_eq!(string_attribute(&span, "process.command"), Some("checkout"));
}
#[test]
fn only_an_error_status_keeps_its_message() {
let mut span = span(SpanKind::Internal);
span.status.message = Some("it went fine".to_owned());
finish_span(&mut span, true, None);
assert_eq!(span.status.message, None);
}
#[test]
fn entry_point_attributes_of_the_span_win() {
let mut span = span(SpanKind::Internal);
set_span_attribute(&mut span, "flare.entry_point.type", "queue");
finish_span(&mut span, true, Some(&EntryPoint::cli("app import")));
assert_eq!(
string_attribute(&span, "flare.entry_point.type"),
Some("queue")
);
}
#[test]
fn a_server_span_with_a_path_is_a_web_entry_point() {
let mut fields = EntryFields::new("request");
fields.set("otel.kind", || "server".to_owned());
fields.set("http.request.method", || "GET".to_owned());
fields.set("url.path", || "/users/7".to_owned());
let attributes = fields.entry_point().map(|entry| entry.attributes());
assert!(attributes.is_some_and(|attributes| {
attributes.contains(&("flare.entry_point.type", "web".to_owned()))
&& attributes.contains(&(
"flare.entry_point.handler.identifier",
"GET /users/7".to_owned(),
))
}));
}
#[test]
fn a_server_span_without_a_url_has_no_entry_point() {
let mut fields = EntryFields::new("grpc");
fields.set("otel.kind", || "server".to_owned());
assert_eq!(fields.entry_point(), None);
}
#[test]
fn merging_keeps_the_fields_that_the_other_value_did_not_set() {
let mut fields = EntryFields::new("job");
fields.set("otel.kind", || "consumer".to_owned());
let mut later = EntryFields::default();
later.set("messaging.destination.name", || "orders".to_owned());
fields.merge(later);
assert_eq!(fields.kind.as_deref(), Some("consumer"));
assert_eq!(fields.destination.as_deref(), Some("orders"));
}
}