use tracing_subscriber::Registry;
use tracing_subscriber::registry::LookupSpan;
use crate::process::executable_name;
use crate::scope::{app_entry_point, nested_entry_point};
const BINARY_HANDLER_TYPE: &str = "rust_binary";
pub(crate) const COMMAND_HANDLER_TYPE: &str = "rust_command";
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct EntryPoint {
kind: EntryPointKind,
value: String,
handler_identifier: Option<String>,
handler_name: Option<String>,
handler_type: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EntryPointKind {
Web,
Cli,
Queue,
}
impl EntryPointKind {
fn as_str(self) -> &'static str {
match self {
Self::Web => "web",
Self::Cli => "cli",
Self::Queue => "queue",
}
}
}
impl EntryPoint {
pub fn web<S: Into<String>>(url: S) -> Self {
Self::new(EntryPointKind::Web, url.into())
}
pub fn cli<S: Into<String>>(command_line: S) -> Self {
Self::new(EntryPointKind::Cli, command_line.into())
}
pub fn queue<S: Into<String>>(job: S) -> Self {
Self::new(EntryPointKind::Queue, job.into())
}
pub fn current_process() -> Self {
Self::cli(crate::command_line())
}
fn new(kind: EntryPointKind, value: String) -> Self {
Self {
kind,
value,
handler_identifier: None,
handler_name: None,
handler_type: None,
}
}
pub fn handler_identifier<S: Into<String>>(mut self, identifier: S) -> Self {
self.handler_identifier = Some(identifier.into());
self
}
pub fn handler_name<S: Into<String>>(mut self, name: S) -> Self {
self.handler_name = Some(name.into());
self
}
pub fn handler_type<S: Into<String>>(mut self, handler_type: S) -> Self {
self.handler_type = Some(handler_type.into());
self
}
#[doc(hidden)]
pub fn attributes(&self) -> Vec<(&'static str, String)> {
self.clone().into_attributes()
}
pub(crate) fn into_attributes(mut self) -> Vec<(&'static str, String)> {
let handler_type = self
.handler_type
.take()
.or_else(|| self.default_handler_type());
let handler_identifier = self
.handler_identifier
.take()
.or_else(|| self.default_handler_identifier());
let mut attributes = vec![
("flare.entry_point.type", self.kind.as_str().to_owned()),
("flare.entry_point.value", self.value),
];
let handler = [
("flare.entry_point.handler.identifier", handler_identifier),
("flare.entry_point.handler.name", self.handler_name),
("flare.entry_point.handler.type", handler_type),
];
attributes.extend(
handler
.into_iter()
.filter_map(|(key, value)| value.map(|value| (key, value))),
);
attributes
}
fn default_handler_identifier(&self) -> Option<String> {
match self.kind {
EntryPointKind::Web => Some(url_path(&self.value).to_owned()),
EntryPointKind::Cli => executable_name().map(str::to_owned),
EntryPointKind::Queue => Some(self.value.clone()),
}
}
fn default_handler_type(&self) -> Option<String> {
if self.kind != EntryPointKind::Cli {
return None;
}
if self.handler_identifier.is_some() {
return Some(COMMAND_HANDLER_TYPE.to_owned());
}
executable_name().map(|_| BINARY_HANDLER_TYPE.to_owned())
}
}
#[doc(hidden)]
#[derive(Debug, Clone, Copy)]
pub struct WebRequest<'a> {
pub url: &'a str,
pub method: Option<&'a str>,
pub route: Option<&'a str>,
pub path: Option<&'a str>,
pub framework: Option<&'a str>,
}
#[doc(hidden)]
pub fn web_entry_point(request: &WebRequest<'_>) -> EntryPoint {
let target = request
.route
.or(request.path)
.unwrap_or_else(|| url_path(request.url));
let identifier = match request.method {
Some(method) => format!("{method} {target}"),
None => target.to_owned(),
};
let entry_point = EntryPoint::web(request.url).handler_identifier(identifier);
match (request.route, request.framework) {
(Some(_), Some(framework)) => entry_point.handler_type(format!("{framework}_route")),
_ => entry_point,
}
}
fn url_path(url: &str) -> &str {
let path = match url.split_once("://") {
Some((_, rest)) => rest.find('/').and_then(|start| rest.get(start..)),
None => Some(url),
};
let path = path.unwrap_or("/");
path.split(['?', '#']).next().unwrap_or(path)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpanEntryPoint(pub EntryPoint);
pub fn current_span_entry_point() -> Option<EntryPoint> {
tracing::Span::current()
.with_subscriber(|(id, dispatch)| {
let registry = dispatch.downcast_ref::<Registry>()?;
registry.span(id)?.scope().find_map(|span| {
span.extensions()
.get::<SpanEntryPoint>()
.map(|entry_point| entry_point.0.clone())
})
})
.flatten()
}
pub fn resolve_entry_point<F>(search_spans: F) -> EntryPoint
where
F: FnOnce() -> Option<EntryPoint>,
{
nested_entry_point()
.or_else(search_spans)
.or_else(app_entry_point)
.unwrap_or_else(EntryPoint::current_process)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scope::with_scope;
use crate::test_support::{global_entry_point, serial};
fn attribute(entry_point: &EntryPoint, key: &str) -> Option<String> {
entry_point
.attributes()
.into_iter()
.find(|(name, _)| *name == key)
.map(|(_, value)| value)
}
#[test]
fn a_set_identifier_wins() {
let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
Some("import")
);
}
#[test]
fn commands_with_an_identifier_are_rust_commands() {
let entry_point = EntryPoint::cli("my-app import").handler_identifier("import");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
Some("rust_command")
);
}
#[test]
fn a_set_handler_type_wins_for_commands() {
let entry_point = EntryPoint::cli("my-app import")
.handler_identifier("import")
.handler_type("clap_command");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
Some("clap_command")
);
}
#[test]
fn jobs_with_an_identifier_have_no_handler_type() {
let entry_point = EntryPoint::queue("send-invoice").handler_identifier("invoices");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.type"),
None
);
}
#[test]
fn commands_default_to_the_executable_name() {
let entry_point = EntryPoint::cli("my-app import");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
executable_name()
);
}
#[test]
fn commands_without_an_identifier_are_rust_binaries() {
let entry_point = EntryPoint::cli("my-app import");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.type").as_deref(),
Some("rust_binary")
);
}
#[test]
fn jobs_default_to_the_job_name() {
let entry_point = EntryPoint::queue("send-invoice");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
Some("send-invoice")
);
}
#[test]
fn web_requests_default_to_the_path() {
let entry_point = EntryPoint::web("https://shop.test/users/7?tab=orders");
assert_eq!(
attribute(&entry_point, "flare.entry_point.handler.identifier").as_deref(),
Some("/users/7")
);
}
#[test]
fn the_path_of_a_url_has_no_query_or_fragment() {
assert_eq!(
url_path("https://shop.test/users/7?tab=orders#top"),
"/users/7"
);
}
#[test]
fn the_path_of_a_url_without_a_path_is_the_root() {
assert_eq!(url_path("https://shop.test"), "/");
}
#[test]
fn the_path_of_a_path_is_the_path() {
assert_eq!(url_path("/users/7?tab=orders"), "/users/7");
}
fn nested() -> EntryPoint {
EntryPoint::web("https://shop.test/users/7")
}
fn span() -> EntryPoint {
EntryPoint::queue("send-invoice")
}
fn global() -> EntryPoint {
EntryPoint::cli("my-app worker")
}
#[test]
fn a_nested_scope_wins_over_a_span() {
let _serial = serial();
let _global = global_entry_point(global());
let resolved = with_scope(
|scope| scope.set_entry_point(nested()),
|| resolve_entry_point(|| Some(span())),
);
assert_eq!(resolved, nested());
}
#[test]
fn a_nested_scope_skips_the_span_search() {
let searched = with_scope(
|scope| scope.set_entry_point(nested()),
|| {
let mut searched = false;
let _ = resolve_entry_point(|| {
searched = true;
None
});
searched
},
);
assert!(!searched);
}
#[test]
fn a_span_wins_over_the_global_scope() {
let _serial = serial();
let _global = global_entry_point(global());
assert_eq!(resolve_entry_point(|| Some(span())), span());
}
#[test]
fn the_global_scope_wins_over_the_process() {
let _serial = serial();
let _global = global_entry_point(global());
assert_eq!(resolve_entry_point(|| None), global());
}
#[test]
fn the_process_is_the_fallback() {
let _serial = serial();
assert_eq!(resolve_entry_point(|| None), EntryPoint::current_process());
}
#[test]
fn a_web_entry_point_with_a_route_and_framework_has_a_route_handler() {
let entry_point = web_entry_point(&WebRequest {
url: "https://shop.test/users/7",
method: Some("GET"),
route: Some("/users/{id}"),
path: Some("/users/7"),
framework: Some("axum"),
});
assert_eq!(
entry_point,
EntryPoint::web("https://shop.test/users/7")
.handler_identifier("GET /users/{id}")
.handler_type("axum_route")
);
}
#[test]
fn a_web_entry_point_with_a_route_but_no_framework_has_no_handler_type() {
let entry_point = web_entry_point(&WebRequest {
url: "https://shop.test/users/7",
method: Some("GET"),
route: Some("/users/{id}"),
path: Some("/users/7"),
framework: None,
});
assert_eq!(
entry_point,
EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}")
);
}
#[test]
fn a_web_entry_point_without_a_route_uses_the_given_path() {
let entry_point = web_entry_point(&WebRequest {
url: "https://shop.test/users/7?tab=orders",
method: Some("GET"),
route: None,
path: Some("/users/7"),
framework: Some("axum"),
});
assert_eq!(
entry_point,
EntryPoint::web("https://shop.test/users/7?tab=orders")
.handler_identifier("GET /users/7")
);
}
#[test]
fn a_web_entry_point_with_only_a_url_uses_the_path_of_the_url() {
let entry_point = web_entry_point(&WebRequest {
url: "https://shop.test/users/7?tab=orders",
method: Some("GET"),
route: None,
path: None,
framework: None,
});
assert_eq!(
entry_point,
EntryPoint::web("https://shop.test/users/7?tab=orders")
.handler_identifier("GET /users/7")
);
}
#[test]
fn a_web_entry_point_without_a_method_has_only_the_path() {
let entry_point = web_entry_point(&WebRequest {
url: "https://shop.test/users/7",
method: None,
route: None,
path: None,
framework: None,
});
assert_eq!(
entry_point,
EntryPoint::web("https://shop.test/users/7").handler_identifier("/users/7")
);
}
}