1#![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
26pub fn record_query_text(enabled: bool) {
30 QUERY_TEXT.store(enabled, Ordering::Relaxed);
31}
32
33pub fn records_query_text() -> bool {
36 QUERY_TEXT.load(Ordering::Relaxed)
37}
38
39pub(crate) struct Analysis {
41 pub(crate) summary: Option<String>,
42 pub(crate) text: String,
43}
44
45#[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
53const 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
74pub(crate) struct Failure<'a> {
76 pub(crate) error_type: &'a str,
79 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 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
96pub(crate) struct Call<'a> {
98 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 #[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 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
140pub(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
178pub(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
190pub fn describe_metrics() {
194 metrics::describe_histogram!(
195 "db.client.operation.duration",
196 metrics::Unit::Seconds,
197 "Duration of database client operations."
198 );
199}