#![cfg_attr(
not(any(
feature = "rusqlite",
feature = "postgres",
feature = "sqlx-0.8",
feature = "sqlx-0.9"
)),
allow(dead_code)
)]
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use metrics::Label;
use tracing::field::Empty;
use crate::query;
static QUERY_TEXT: AtomicBool = AtomicBool::new(true);
pub fn record_query_text(enabled: bool) {
QUERY_TEXT.store(enabled, Ordering::Relaxed);
}
pub fn records_query_text() -> bool {
QUERY_TEXT.load(Ordering::Relaxed)
}
pub(crate) struct Analysis {
pub(crate) summary: Option<String>,
pub(crate) text: String,
}
#[cfg(any(feature = "postgres", feature = "sqlx-0.8", feature = "sqlx-0.9"))]
pub(crate) static UNKNOWN: Analysis = Analysis {
summary: None,
text: String::new(),
};
const CACHE_LIMIT: usize = 1024;
pub(crate) fn analyze(sql: &str) -> Arc<Analysis> {
static CACHE: OnceLock<Mutex<HashMap<String, Arc<Analysis>>>> = OnceLock::new();
let cache = CACHE.get_or_init(Mutex::default);
if let Some(a) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(sql) {
return Arc::clone(a);
}
let analysis = Arc::new(Analysis {
summary: query::summarize(sql),
text: query::sanitize(sql),
});
let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
if cache.len() >= CACHE_LIMIT {
cache.clear();
}
cache.insert(sql.to_string(), Arc::clone(&analysis));
analysis
}
pub(crate) struct Failure<'a> {
pub(crate) error_type: &'a str,
pub(crate) status_code: Option<&'a str>,
}
#[cfg(any(feature = "postgres", feature = "sqlx-0.8", feature = "sqlx-0.9"))]
impl Failure<'_> {
pub(crate) fn record(&self, span: &tracing::Span) {
span.record("error.type", self.error_type);
if let Some(code) = self.status_code {
span.record("db.response.status_code", code);
}
span.record("otel.status_code", "error");
}
}
pub(crate) struct Call<'a> {
pub(crate) system: &'static str,
pub(crate) namespace: Option<&'a str>,
pub(crate) server: Option<(&'a str, u16)>,
pub(crate) analysis: &'a Analysis,
}
impl Call<'_> {
#[cfg(any(feature = "rusqlite", feature = "postgres"))]
pub(crate) fn span(&self) -> tracing::Span {
let span = open_span(self.system, self.namespace, self.server);
describe(&span, self.analysis);
span
}
pub(crate) fn record_duration(&self, seconds: f64, failure: Option<&Failure<'_>>) {
let mut labels = Vec::with_capacity(8);
labels.push(Label::new("db.system.name", self.system));
if let Some(namespace) = self.namespace {
labels.push(Label::new("db.namespace", namespace.to_string()));
}
if let Some(summary) = &self.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.to_string()));
labels.push(Label::new("server.port", port.to_string()));
}
if let Some(failure) = failure {
labels.push(Label::new("error.type", failure.error_type.to_string()));
if let Some(code) = failure.status_code {
labels.push(Label::new("db.response.status_code", code.to_string()));
}
}
metrics::histogram!("db.client.operation.duration", labels).record(seconds);
}
}
pub(crate) fn open_span(
system: &'static str,
namespace: Option<&str>,
server: Option<(&str, u16)>,
) -> tracing::Span {
let span = tracing::info_span!(
target: "oxtel_sql",
"database call",
otel.name = system,
otel.kind = "client",
db.system.name = system,
db.namespace = Empty,
db.query.summary = Empty,
db.query.text = Empty,
db.response.returned_rows = Empty,
server.address = Empty,
server.port = Empty,
error.type = Empty,
db.response.status_code = Empty,
otel.status_code = Empty,
);
if span.is_disabled() {
return span;
}
if let Some(namespace) = namespace {
span.record("db.namespace", namespace);
}
if let Some((address, port)) = server {
span.record("server.address", address);
span.record("server.port", port);
}
span
}
pub(crate) fn describe(span: &tracing::Span, analysis: &Analysis) {
if let Some(summary) = &analysis.summary {
span.record("otel.name", summary.as_str());
span.record("db.query.summary", summary.as_str());
}
if QUERY_TEXT.load(Ordering::Relaxed) && !analysis.text.is_empty() {
span.record("db.query.text", analysis.text.as_str());
}
}
pub fn describe_metrics() {
metrics::describe_histogram!(
"db.client.operation.duration",
metrics::Unit::Seconds,
"Duration of database client operations."
);
}