Skip to main content

oxtel_sql/
record.rs

1//! Recording one database call: a client span, and the
2//! `db.client.operation.duration` histogram.
3
4// The clients are features; without one, only the public pieces are used.
5#![cfg_attr(
6    not(any(
7        feature = "rusqlite",
8        feature = "postgres",
9        feature = "sqlx-0.8",
10        feature = "sqlx-0.9"
11    )),
12    allow(dead_code)
13)]
14
15use std::collections::HashMap;
16use std::sync::atomic::{AtomicBool, Ordering};
17use std::sync::{Arc, Mutex, OnceLock};
18
19use metrics::Label;
20use tracing::field::Empty;
21
22use crate::query;
23
24static QUERY_TEXT: AtomicBool = AtomicBool::new(true);
25
26/// Record `db.query.text` on spans: the statement's text with every literal
27/// replaced by `?`. Default: true, as the conventions advise for text
28/// without values. It applies to the whole process.
29pub fn record_query_text(enabled: bool) {
30    QUERY_TEXT.store(enabled, Ordering::Relaxed);
31}
32
33/// Whether `db.query.text` is recorded; see [`record_query_text`]. For
34/// instrumentation outside this crate that follows the same setting.
35pub fn records_query_text() -> bool {
36    QUERY_TEXT.load(Ordering::Relaxed)
37}
38
39/// What a statement's text says, worked out once per distinct text.
40pub(crate) struct Analysis {
41    pub(crate) summary: Option<String>,
42    pub(crate) text: String,
43}
44
45/// What a statement whose text isn't known is recorded as: no summary, so
46/// the span is named by the database system, and no text.
47#[cfg(any(feature = "postgres", feature = "sqlx-0.8", feature = "sqlx-0.9"))]
48pub(crate) static UNKNOWN: Analysis = Analysis {
49    summary: None,
50    text: String::new(),
51};
52
53/// Distinct statement texts remembered; the cache starts over past this.
54const CACHE_LIMIT: usize = 1024;
55
56pub(crate) fn analyze(sql: &str) -> Arc<Analysis> {
57    static CACHE: OnceLock<Mutex<HashMap<String, Arc<Analysis>>>> = OnceLock::new();
58    let cache = CACHE.get_or_init(Mutex::default);
59    if let Some(a) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(sql) {
60        return Arc::clone(a);
61    }
62    let analysis = Arc::new(Analysis {
63        summary: query::summarize(sql),
64        text: query::sanitize(sql),
65    });
66    let mut cache = cache.lock().unwrap_or_else(|e| e.into_inner());
67    if cache.len() >= CACHE_LIMIT {
68        cache.clear();
69    }
70    cache.insert(sql.to_string(), Arc::clone(&analysis));
71    analysis
72}
73
74/// Why a call failed.
75pub(crate) struct Failure<'a> {
76    /// `error.type`: the database's code for the error when it gave one,
77    /// otherwise the client library's error type.
78    pub(crate) error_type: &'a str,
79    /// `db.response.status_code`: the database's own code, such as a
80    /// PostgreSQL SQLSTATE.
81    pub(crate) status_code: Option<&'a str>,
82}
83
84#[cfg(any(feature = "postgres", feature = "sqlx-0.8", feature = "sqlx-0.9"))]
85impl Failure<'_> {
86    /// Mark a call's span as failed.
87    pub(crate) fn record(&self, span: &tracing::Span) {
88        span.record("error.type", self.error_type);
89        if let Some(code) = self.status_code {
90            span.record("db.response.status_code", code);
91        }
92        span.record("otel.status_code", "error");
93    }
94}
95
96/// One call to a database.
97pub(crate) struct Call<'a> {
98    /// `db.system.name`, such as `sqlite` or `postgresql`.
99    pub(crate) system: &'static str,
100    pub(crate) namespace: Option<&'a str>,
101    pub(crate) server: Option<(&'a str, u16)>,
102    pub(crate) analysis: &'a Analysis,
103}
104
105impl Call<'_> {
106    /// A client span for the call, named by its query summary, or the
107    /// database system when there's none.
108    #[cfg(any(feature = "rusqlite", feature = "postgres"))]
109    pub(crate) fn span(&self) -> tracing::Span {
110        let span = open_span(self.system, self.namespace, self.server);
111        describe(&span, self.analysis);
112        span
113    }
114
115    /// Record `db.client.operation.duration`, with why the call failed if
116    /// it did.
117    pub(crate) fn record_duration(&self, seconds: f64, failure: Option<&Failure<'_>>) {
118        let mut labels = Vec::with_capacity(8);
119        labels.push(Label::new("db.system.name", self.system));
120        if let Some(namespace) = self.namespace {
121            labels.push(Label::new("db.namespace", namespace.to_string()));
122        }
123        if let Some(summary) = &self.analysis.summary {
124            labels.push(Label::new("db.query.summary", summary.clone()));
125        }
126        if let Some((address, port)) = self.server {
127            labels.push(Label::new("server.address", address.to_string()));
128            labels.push(Label::new("server.port", port.to_string()));
129        }
130        if let Some(failure) = failure {
131            labels.push(Label::new("error.type", failure.error_type.to_string()));
132            if let Some(code) = failure.status_code {
133                labels.push(Label::new("db.response.status_code", code.to_string()));
134            }
135        }
136        metrics::histogram!("db.client.operation.duration", labels).record(seconds);
137    }
138}
139
140/// A client span for a call to `system`, before its statement is known:
141/// named by the system until [`describe`] names it by the statement. The
142/// target is `oxtel_sql`, which oxtel's sqlx mapping looks for so that it
143/// doesn't record a query a second time.
144pub(crate) fn open_span(
145    system: &'static str,
146    namespace: Option<&str>,
147    server: Option<(&str, u16)>,
148) -> tracing::Span {
149    let span = tracing::info_span!(
150        target: "oxtel_sql",
151        "database call",
152        otel.name = system,
153        otel.kind = "client",
154        db.system.name = system,
155        db.namespace = Empty,
156        db.query.summary = Empty,
157        db.query.text = Empty,
158        db.response.returned_rows = Empty,
159        server.address = Empty,
160        server.port = Empty,
161        error.type = Empty,
162        db.response.status_code = Empty,
163        otel.status_code = Empty,
164    );
165    if span.is_disabled() {
166        return span;
167    }
168    if let Some(namespace) = namespace {
169        span.record("db.namespace", namespace);
170    }
171    if let Some((address, port)) = server {
172        span.record("server.address", address);
173        span.record("server.port", port);
174    }
175    span
176}
177
178/// Name a call's span by its statement, and record the statement's summary
179/// and text.
180pub(crate) fn describe(span: &tracing::Span, analysis: &Analysis) {
181    if let Some(summary) = &analysis.summary {
182        span.record("otel.name", summary.as_str());
183        span.record("db.query.summary", summary.as_str());
184    }
185    if QUERY_TEXT.load(Ordering::Relaxed) && !analysis.text.is_empty() {
186        span.record("db.query.text", analysis.text.as_str());
187    }
188}
189
190/// Describe the metrics this crate records (their units and descriptions)
191/// to the current `metrics` recorder. The instrumentation entry points call
192/// it, so it only matters for a recorder installed after them.
193pub fn describe_metrics() {
194    metrics::describe_histogram!(
195        "db.client.operation.duration",
196        metrics::Unit::Seconds,
197        "Duration of database client operations."
198    );
199}