|
1 | 1 | use std::{ |
| 2 | + collections::HashMap, |
2 | 3 | ops::{Deref, DerefMut}, |
3 | 4 | time::{Duration, Instant}, |
4 | 5 | }; |
5 | 6 |
|
| 7 | +use metrics::counter; |
6 | 8 | use once_cell::sync::Lazy; |
7 | | -use rusqlite::types::{ToSql, ToSqlOutput, Value}; |
| 9 | +use parking_lot::Mutex; |
8 | 10 | use rusqlite::{ |
9 | 11 | params, trace::TraceEventCodes, vtab::eponymous_only_module, Connection, Transaction, |
10 | 12 | }; |
| 13 | +use rusqlite::{ |
| 14 | + types::{ToSql, ToSqlOutput, Value}, |
| 15 | + DatabaseName, |
| 16 | +}; |
11 | 17 | use sqlite_pool::{Committable, SqliteConn}; |
12 | 18 | use std::rc::Rc; |
13 | 19 | use tempfile::TempDir; |
| 20 | +use thread_local::ThreadLocal; |
14 | 21 | use tracing::{error, info, trace, warn}; |
| 22 | +use tripwire::Tripwire; |
15 | 23 |
|
16 | 24 | use crate::vtab::unnest::UnnestTab; |
17 | 25 |
|
18 | 26 | pub type SqlitePool = sqlite_pool::Pool<CrConn>; |
19 | 27 | pub type SqlitePoolError = sqlite_pool::PoolError; |
20 | 28 |
|
| 29 | +// Global registry for query stats |
| 30 | +// (sql, readonly) => (total_count, total_nanos) |
| 31 | +type QueryStats = HashMap<(String, bool), (u64, u128)>; |
| 32 | +static QUERY_STATS: ThreadLocal<Mutex<QueryStats>> = ThreadLocal::new(); |
| 33 | +pub async fn query_metrics_loop(mut tripwire: Tripwire) { |
| 34 | + let mut interval = tokio::time::interval(Duration::from_secs(10)); |
| 35 | + let mut prev_tick = interval.tick().await; |
| 36 | + loop { |
| 37 | + tokio::select! { |
| 38 | + t = interval.tick() => { |
| 39 | + let elapsed = t.duration_since(prev_tick); |
| 40 | + prev_tick = t; |
| 41 | + handle_query_metrics(elapsed); |
| 42 | + }, |
| 43 | + _ = &mut tripwire => break, |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// Log to stdout queries taking more than 1 second |
| 49 | +const SLOW_QUERY_THRESHOLD: Duration = Duration::from_secs(1); |
| 50 | +// Send utilization metrics for queries taking more than 10ms per second on average |
| 51 | +const IMPACTFUL_QUERY_THRESHOLD_MS_PER_SECOND: f64 = 10.0; |
| 52 | +// The default length in prometheus is 4kb but 1kb is more than enough |
| 53 | +const MAX_QUERY_LABEL_LENGTH: usize = 1024; |
| 54 | +fn handle_query_metrics(elapsed: Duration) { |
| 55 | + // Aggregate and drain stats from all threads into a single map |
| 56 | + let mut aggregated: QueryStats = Default::default(); |
| 57 | + |
| 58 | + for stats_mutex in QUERY_STATS.iter() { |
| 59 | + let mut stats = stats_mutex.lock(); |
| 60 | + for (key, (count, nanos)) in stats.drain() { |
| 61 | + let entry = aggregated.entry(key).or_insert((0u64, 0u128)); |
| 62 | + entry.0 += count; |
| 63 | + entry.1 += nanos; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + for ((query_raw, readonly), (total_count, total_nanos)) in aggregated.into_iter() { |
| 68 | + let total_ms = (total_nanos / 1_000_000) as u64; |
| 69 | + let ms_per_second = total_ms as f64 / elapsed.as_secs_f64(); |
| 70 | + if ms_per_second > IMPACTFUL_QUERY_THRESHOLD_MS_PER_SECOND { |
| 71 | + // For too long queries, truncate them to cap the label length |
| 72 | + // and append a hash to avoid collisions |
| 73 | + let query = if query_raw.len() > MAX_QUERY_LABEL_LENGTH { |
| 74 | + use std::collections::hash_map::DefaultHasher; |
| 75 | + use std::hash::Hash; |
| 76 | + use std::hash::Hasher; |
| 77 | + let mut h = DefaultHasher::new(); |
| 78 | + query_raw.hash(&mut h); |
| 79 | + format!( |
| 80 | + "{}_{:x}", |
| 81 | + query_raw.chars().take(1024 - 16 - 1).collect::<String>(), |
| 82 | + h.finish() |
| 83 | + ) |
| 84 | + } else { |
| 85 | + query_raw.clone() |
| 86 | + }; |
| 87 | + counter!("corro.db.query.ms", "query" => query.clone() , "readonly" => readonly.to_string()).increment(total_ms); |
| 88 | + counter!("corro.db.query.count", "query" => query.clone(), "readonly" => readonly.to_string()).increment(total_count); |
| 89 | + } |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +fn tracing_callback_ro(ev: rusqlite::trace::TraceEvent) { |
| 94 | + handle_sql_tracing_event(ev, true); |
| 95 | +} |
| 96 | + |
| 97 | +fn tracing_callback_rw(ev: rusqlite::trace::TraceEvent) { |
| 98 | + handle_sql_tracing_event(ev, false); |
| 99 | +} |
| 100 | + |
| 101 | +fn handle_sql_tracing_event(ev: rusqlite::trace::TraceEvent, readonly: bool) { |
| 102 | + if let rusqlite::trace::TraceEvent::Profile(stmt_ref, duration) = ev { |
| 103 | + let dur = duration.as_nanos(); |
| 104 | + let sql = stmt_ref.sql().to_string(); |
| 105 | + |
| 106 | + // Update per-thread stats to avoid contention on hot path |
| 107 | + let stats_mutex = QUERY_STATS.get_or_default(); |
| 108 | + let mut stats = stats_mutex.lock(); |
| 109 | + let entry = stats |
| 110 | + .entry((sql.clone(), readonly)) |
| 111 | + .or_insert((0u64, 0u128)); |
| 112 | + entry.0 += 1; |
| 113 | + entry.1 += dur; |
| 114 | + drop(stats); // Release lock quickly |
| 115 | + |
| 116 | + if duration >= SLOW_QUERY_THRESHOLD { |
| 117 | + warn!( |
| 118 | + "SLOW {} query {duration:?} => {}", |
| 119 | + if readonly { "RO" } else { "RW" }, |
| 120 | + sql |
| 121 | + ); |
| 122 | + } |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +pub fn trace_heavy_queries(conn: &Connection) -> rusqlite::Result<()> { |
| 127 | + let readonly = conn.is_readonly(DatabaseName::Main)?; |
| 128 | + conn.trace_v2( |
| 129 | + TraceEventCodes::SQLITE_TRACE_PROFILE, |
| 130 | + Some(if readonly { |
| 131 | + tracing_callback_ro |
| 132 | + } else { |
| 133 | + tracing_callback_rw |
| 134 | + }), |
| 135 | + ); |
| 136 | + Ok(()) |
| 137 | +} |
| 138 | + |
21 | 139 | const CRSQL_EXT_GENERIC_NAME: &str = "crsqlite"; |
22 | 140 |
|
23 | 141 | #[cfg(target_os = "macos")] |
@@ -71,17 +189,7 @@ pub fn rusqlite_to_crsqlite(mut conn: rusqlite::Connection) -> rusqlite::Result< |
71 | 189 | // I spent too much time debugging, it looks like a real bug in sqlite .-. |
72 | 190 | let _ = conn.prepare_cached(INSERT_CRSQL_CHANGES_QUERY)?; |
73 | 191 |
|
74 | | - const SLOW_THRESHOLD: Duration = Duration::from_secs(1); |
75 | | - conn.trace_v2( |
76 | | - TraceEventCodes::SQLITE_TRACE_PROFILE, |
77 | | - Some(|event| { |
78 | | - if let rusqlite::trace::TraceEvent::Profile(stmt_ref, duration) = event { |
79 | | - if duration >= SLOW_THRESHOLD { |
80 | | - warn!("SLOW query {duration:?} => {}", stmt_ref.sql()); |
81 | | - } |
82 | | - } |
83 | | - }), |
84 | | - ); |
| 192 | + trace_heavy_queries(&conn)?; |
85 | 193 |
|
86 | 194 | Ok(CrConn(conn)) |
87 | 195 | } |
|
0 commit comments