| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
use std::path::Path; |
| 29 |
|
| 30 |
use chrono::{DateTime, TimeZone, Utc}; |
| 31 |
use rusqlite::{Connection, OpenFlags}; |
| 32 |
use tokio::sync::mpsc; |
| 33 |
|
| 34 |
use crate::config::{Config, Store}; |
| 35 |
|
| 36 |
|
| 37 |
pub(crate) struct Update { |
| 38 |
pub index: usize, |
| 39 |
pub at: DateTime<Utc>, |
| 40 |
pub result: Result<Vec<Reading>, String>, |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
#[derive(Debug, Clone, PartialEq)] |
| 50 |
pub(crate) struct Reading { |
| 51 |
pub series: String, |
| 52 |
pub labels: String, |
| 53 |
pub value: f64, |
| 54 |
pub at: DateTime<Utc>, |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
pub(crate) fn spawn_all(stores: &[Store]) -> mpsc::Receiver<Update> { |
| 59 |
let (tx, rx) = mpsc::channel(stores.len().max(1) * 4); |
| 60 |
for (index, store) in stores.iter().enumerate() { |
| 61 |
tokio::spawn(read_forever(index, store.clone(), tx.clone())); |
| 62 |
} |
| 63 |
rx |
| 64 |
} |
| 65 |
|
| 66 |
async fn read_forever(index: usize, store: Store, tx: mpsc::Sender<Update>) { |
| 67 |
let mut ticker = tokio::time::interval(Config::store_interval(&store)); |
| 68 |
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); |
| 69 |
loop { |
| 70 |
ticker.tick().await; |
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
let store = store.clone(); |
| 77 |
let result = tokio::task::spawn_blocking(move || read(&store)) |
| 78 |
.await |
| 79 |
.unwrap_or_else(|e| Err(format!("read task: {e}"))); |
| 80 |
if tx |
| 81 |
.send(Update { |
| 82 |
index, |
| 83 |
at: Utc::now(), |
| 84 |
result, |
| 85 |
}) |
| 86 |
.await |
| 87 |
.is_err() |
| 88 |
{ |
| 89 |
return; |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
fn read(store: &Store) -> Result<Vec<Reading>, String> { |
| 100 |
let conn = open(&store.path)?; |
| 101 |
let mut readings = Vec::new(); |
| 102 |
for series in &store.series { |
| 103 |
readings.extend(latest_per_labels(&conn, &series.name).map_err(|e| short(&e))?); |
| 104 |
} |
| 105 |
Ok(readings) |
| 106 |
} |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
fn open(path: &Path) -> Result<Connection, String> { |
| 115 |
Connection::open_with_flags( |
| 116 |
path, |
| 117 |
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI, |
| 118 |
) |
| 119 |
.map_err(|e| short(&e)) |
| 120 |
} |
| 121 |
|
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
fn latest_per_labels(conn: &Connection, series: &str) -> rusqlite::Result<Vec<Reading>> { |
| 129 |
let mut stmt = conn.prepare( |
| 130 |
"SELECT labels, value, MAX(at) |
| 131 |
FROM observations |
| 132 |
WHERE series = ?1 |
| 133 |
GROUP BY labels |
| 134 |
ORDER BY labels", |
| 135 |
)?; |
| 136 |
let rows = stmt.query_map([series], |row| { |
| 137 |
Ok(Reading { |
| 138 |
series: series.to_string(), |
| 139 |
labels: row.get(0)?, |
| 140 |
value: row.get(1)?, |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
at: Utc |
| 146 |
.timestamp_opt(row.get::<_, i64>(2)?, 0) |
| 147 |
.single() |
| 148 |
.unwrap_or_else(|| Utc.timestamp_nanos(0)), |
| 149 |
}) |
| 150 |
})?; |
| 151 |
rows.collect() |
| 152 |
} |
| 153 |
|
| 154 |
|
| 155 |
fn short(error: &dyn std::error::Error) -> String { |
| 156 |
let text = error.to_string(); |
| 157 |
match text.split_once('\n') { |
| 158 |
Some((first, _)) => first.to_string(), |
| 159 |
None => text, |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
#[cfg(test)] |
| 164 |
mod tests { |
| 165 |
use super::*; |
| 166 |
use crate::config::Series; |
| 167 |
|
| 168 |
|
| 169 |
fn seeded(rows: &[(&str, &str, f64, i64)]) -> (tempfile::TempDir, std::path::PathBuf) { |
| 170 |
let dir = tempfile::tempdir().unwrap(); |
| 171 |
let path = dir.path().join("observations.db"); |
| 172 |
let conn = Connection::open(&path).unwrap(); |
| 173 |
conn.execute_batch( |
| 174 |
"CREATE TABLE observations ( |
| 175 |
id INTEGER PRIMARY KEY, |
| 176 |
series TEXT NOT NULL, |
| 177 |
labels TEXT NOT NULL, |
| 178 |
value REAL NOT NULL, |
| 179 |
at INTEGER NOT NULL |
| 180 |
);", |
| 181 |
) |
| 182 |
.unwrap(); |
| 183 |
for (series, labels, value, at) in rows { |
| 184 |
conn.execute( |
| 185 |
"INSERT INTO observations (series, labels, value, at) VALUES (?1, ?2, ?3, ?4)", |
| 186 |
rusqlite::params![series, labels, value, at], |
| 187 |
) |
| 188 |
.unwrap(); |
| 189 |
} |
| 190 |
(dir, path) |
| 191 |
} |
| 192 |
|
| 193 |
fn store(path: &Path, series: &[&str]) -> Store { |
| 194 |
Store { |
| 195 |
name: "witchbroom".into(), |
| 196 |
path: path.to_path_buf(), |
| 197 |
poll_secs: 60, |
| 198 |
series: series |
| 199 |
.iter() |
| 200 |
.map(|s| Series { |
| 201 |
name: (*s).to_string(), |
| 202 |
label: format!("label for {s}"), |
| 203 |
unit: Some("edges".into()), |
| 204 |
}) |
| 205 |
.collect(), |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
#[test] |
| 210 |
fn a_series_reads_its_newest_value_per_label_set() { |
| 211 |
let (_dir, path) = seeded(&[ |
| 212 |
("soak.coverage_edges", r#"{"repo":"a"}"#, 100.0, 1_000), |
| 213 |
("soak.coverage_edges", r#"{"repo":"a"}"#, 200.0, 2_000), |
| 214 |
("soak.coverage_edges", r#"{"repo":"b"}"#, 50.0, 1_500), |
| 215 |
]); |
| 216 |
let readings = read(&store(&path, &["soak.coverage_edges"])).unwrap(); |
| 217 |
assert_eq!(readings.len(), 2, "one row per label set, not per sample"); |
| 218 |
assert_eq!(readings[0].labels, r#"{"repo":"a"}"#); |
| 219 |
assert!( |
| 220 |
(readings[0].value - 200.0).abs() < f64::EPSILON, |
| 221 |
"the newest, not the first" |
| 222 |
); |
| 223 |
assert_eq!(readings[0].at.timestamp(), 2_000); |
| 224 |
assert!((readings[1].value - 50.0).abs() < f64::EPSILON); |
| 225 |
} |
| 226 |
|
| 227 |
#[test] |
| 228 |
fn a_series_nobody_named_is_not_read() { |
| 229 |
|
| 230 |
|
| 231 |
let (_dir, path) = seeded(&[ |
| 232 |
("soak.coverage_edges", "{}", 1.0, 10), |
| 233 |
("cache.size_bytes", "{}", 999.0, 10), |
| 234 |
]); |
| 235 |
let readings = read(&store(&path, &["soak.coverage_edges"])).unwrap(); |
| 236 |
assert_eq!(readings.len(), 1); |
| 237 |
assert_eq!(readings[0].series, "soak.coverage_edges"); |
| 238 |
} |
| 239 |
|
| 240 |
#[test] |
| 241 |
fn a_named_series_with_no_observations_reads_as_nothing_not_an_error() { |
| 242 |
let (_dir, path) = seeded(&[("cache.size_bytes", "{}", 1.0, 10)]); |
| 243 |
let readings = read(&store(&path, &["soak.coverage_edges"])).unwrap(); |
| 244 |
assert!(readings.is_empty()); |
| 245 |
} |
| 246 |
|
| 247 |
#[test] |
| 248 |
fn a_missing_store_is_a_short_reason_rather_than_a_panic() { |
| 249 |
let dir = tempfile::tempdir().unwrap(); |
| 250 |
let err = read(&store(&dir.path().join("nope.db"), &["x"])).unwrap_err(); |
| 251 |
assert!(!err.is_empty()); |
| 252 |
assert!(!err.contains('\n'), "one line for one column: {err}"); |
| 253 |
} |
| 254 |
|
| 255 |
#[test] |
| 256 |
fn reading_never_creates_the_file_it_could_not_find() { |
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
let dir = tempfile::tempdir().unwrap(); |
| 261 |
let path = dir.path().join("nope.db"); |
| 262 |
assert!(read(&store(&path, &["x"])).is_err()); |
| 263 |
assert!(!path.exists(), "a read must not create a store"); |
| 264 |
} |
| 265 |
|
| 266 |
#[test] |
| 267 |
fn a_store_missing_the_producers_table_says_so_rather_than_reading_empty() { |
| 268 |
let dir = tempfile::tempdir().unwrap(); |
| 269 |
let path = dir.path().join("wrong.db"); |
| 270 |
Connection::open(&path) |
| 271 |
.unwrap() |
| 272 |
.execute_batch("CREATE TABLE something_else (x INTEGER);") |
| 273 |
.unwrap(); |
| 274 |
let err = read(&store(&path, &["x"])).unwrap_err(); |
| 275 |
assert!(err.contains("observations"), "{err}"); |
| 276 |
} |
| 277 |
|
| 278 |
#[test] |
| 279 |
fn the_series_come_back_in_the_order_the_config_names_them() { |
| 280 |
|
| 281 |
let (_dir, path) = seeded(&[("zzz", "{}", 1.0, 10), ("aaa", "{}", 2.0, 10)]); |
| 282 |
let readings = read(&store(&path, &["zzz", "aaa"])).unwrap(); |
| 283 |
let names: Vec<&str> = readings.iter().map(|r| r.series.as_str()).collect(); |
| 284 |
assert_eq!(names, vec!["zzz", "aaa"]); |
| 285 |
} |
| 286 |
} |
| 287 |
|