use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, Once};
use std::time::Duration;
use metrics::Label;
use oxtel_sdk::KeyValue;
use oxtel_sdk::trace::{EventMapping, MappedSpan, SpanKind, Status};
use tracing_core::field::{Field, Visit};
use tracing_core::{Event, Level, Metadata};
pub(crate) fn built_in() -> Vec<Arc<dyn EventMapping>> {
vec![Arc::new(Sqlx::new())]
}
pub struct Sqlx {
system: Cow<'static, str>,
namespace: Option<String>,
server: Option<(String, u16)>,
described: Once,
cache: Mutex<HashMap<String, Arc<Analysis>>>,
}
struct Analysis {
summary: Option<String>,
text: String,
}
const CACHE_LIMIT: usize = 1024;
impl Sqlx {
pub fn new() -> Self {
Sqlx {
system: Cow::Borrowed("other_sql"),
namespace: None,
server: None,
described: Once::new(),
cache: Mutex::default(),
}
}
pub fn with_system(mut self, system: impl Into<Cow<'static, str>>) -> Self {
self.system = system.into();
self
}
pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
self.namespace = Some(namespace.into());
self
}
pub fn with_server(mut self, address: impl Into<String>, port: u16) -> Self {
self.server = Some((address.into(), port));
self
}
fn analyze(&self, sql: &str) -> Arc<Analysis> {
let mut cache = self.cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some(a) = cache.get(sql) {
return Arc::clone(a);
}
let analysis = Arc::new(Analysis {
summary: oxtel_sql::summarize(sql),
text: oxtel_sql::sanitize(sql),
});
if cache.len() >= CACHE_LIMIT {
cache.clear();
}
cache.insert(sql.to_string(), Arc::clone(&analysis));
analysis
}
fn record_duration(&self, analysis: &Analysis, seconds: f64) {
let mut labels = Vec::with_capacity(5);
labels.push(Label::new("db.system.name", self.system.clone()));
if let Some(namespace) = &self.namespace {
labels.push(Label::new("db.namespace", namespace.clone()));
}
if let Some(summary) = &analysis.summary {
labels.push(Label::new("db.query.summary", summary.clone()));
}
if let Some((address, port)) = &self.server {
labels.push(Label::new("server.address", address.clone()));
labels.push(Label::new("server.port", port.to_string()));
}
metrics::histogram!("db.client.operation.duration", labels).record(seconds);
}
}
impl Default for Sqlx {
fn default() -> Self {
Sqlx::new()
}
}
impl std::fmt::Debug for Sqlx {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sqlx")
.field("system", &self.system)
.field("namespace", &self.namespace)
.field("server", &self.server)
.finish_non_exhaustive()
}
}
#[derive(Default)]
struct QueryFields {
summary: Option<String>,
statement: Option<String>,
rows_returned: Option<u64>,
elapsed_secs: Option<f64>,
}
impl QueryFields {
fn sql(&self) -> Option<&str> {
let statement = self.statement.as_deref().map(str::trim);
let summary = self.summary.as_deref().map(str::trim);
statement
.filter(|s| !s.is_empty())
.or(summary.filter(|s| !s.is_empty() && !s.ends_with('…')))
}
}
impl Visit for QueryFields {
fn record_str(&mut self, field: &Field, value: &str) {
match field.name() {
"summary" => self.summary = Some(value.to_string()),
"db.statement" => self.statement = Some(value.to_string()),
_ => {}
}
}
fn record_u64(&mut self, field: &Field, value: u64) {
if field.name() == "rows_returned" {
self.rows_returned = Some(value);
}
}
fn record_f64(&mut self, field: &Field, value: f64) {
if field.name() == "elapsed_secs" {
self.elapsed_secs = Some(value);
}
}
fn record_debug(&mut self, _: &Field, _: &dyn std::fmt::Debug) {}
}
impl EventMapping for Sqlx {
fn map(
&self,
event: &Event<'_>,
parent: Option<&'static Metadata<'static>>,
) -> Option<MappedSpan> {
if event.metadata().target() != "sqlx::query" {
return None;
}
if parent
.is_some_and(|p| p.target() == "oxtel_sql" || p.target().starts_with("oxtel_sql::"))
{
return None;
}
let mut fields = QueryFields::default();
event.record(&mut fields);
let seconds = fields.elapsed_secs.filter(|s| s.is_finite() && *s >= 0.0)?;
let analysis = self.analyze(fields.sql()?);
self.described.call_once(oxtel_sql::describe_metrics);
self.record_duration(&analysis, seconds);
let mut attributes = vec![KeyValue::new("db.system.name", self.system.to_string())];
if let Some(namespace) = &self.namespace {
attributes.push(KeyValue::new("db.namespace", namespace.clone()));
}
if let Some(summary) = &analysis.summary {
attributes.push(KeyValue::new("db.query.summary", summary.clone()));
}
if oxtel_sql::records_query_text() {
attributes.push(KeyValue::new("db.query.text", analysis.text.clone()));
}
if let Some(rows) = fields.rows_returned {
attributes.push(KeyValue::new(
"db.response.returned_rows",
i64::try_from(rows).unwrap_or(i64::MAX),
));
}
if let Some((address, port)) = &self.server {
attributes.push(KeyValue::new("server.address", address.clone()));
attributes.push(KeyValue::new("server.port", i64::from(*port)));
}
Some(MappedSpan {
name: Cow::Owned(
analysis
.summary
.clone()
.unwrap_or_else(|| self.system.to_string()),
),
kind: SpanKind::Client,
duration: Duration::from_secs_f64(seconds),
attributes,
status: Status::Unset,
scope: Cow::Borrowed("sqlx"),
})
}
fn targets(&self) -> &'static [(&'static str, Level)] {
&[("sqlx::query", Level::DEBUG)]
}
}