| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | use crate::error::Result; |
| 8 | use crate::model::Service; |
| 9 | use crate::store::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all}; |
| 10 | |
| 11 | impl Store { |
| 12 | |
| 13 | pub async fn list_services(&self) -> Result<Vec<Service>> { |
| 14 | let conn = self.read_conn().await; |
| 15 | fetch_all( |
| 16 | &conn, |
| 17 | "SELECT key, name, url, healthy, checked_at FROM services ORDER BY position, key", |
| 18 | (), |
| 19 | |row| { |
| 20 | Ok(Service { |
| 21 | key: col_text(row, 0)?, |
| 22 | name: col_text(row, 1)?, |
| 23 | url: col_text(row, 2)?, |
| 24 | healthy: col_opt_int(row, 3)?.map(|value| value != 0), |
| 25 | checked_at: col_opt_text(row, 4)?, |
| 26 | }) |
| 27 | }, |
| 28 | ) |
| 29 | .await |
| 30 | } |
| 31 | |
| 32 | |
| 33 | pub async fn upsert_home_service(&self, name: &str, url: &str) -> Result<()> { |
| 34 | let conn = self.inner.conn.lock().await; |
| 35 | conn.execute( |
| 36 | "INSERT INTO services (key, name, url, position, client_id) VALUES ('im', ?1, ?2, 0, NULL) \ |
| 37 | ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url", |
| 38 | (name.to_string(), url.to_string()), |
| 39 | ) |
| 40 | .await |
| 41 | .map_err(db_err)?; |
| 42 | Ok(()) |
| 43 | } |
| 44 | |
| 45 | |
| 46 | |
| 47 | pub async fn record_health(&self, key: &str, healthy: bool, checked_at: &str) -> Result<()> { |
| 48 | let conn = self.inner.conn.lock().await; |
| 49 | conn.execute( |
| 50 | "UPDATE services SET healthy = ?2, checked_at = ?3 WHERE key = ?1", |
| 51 | (key.to_string(), i64::from(healthy), checked_at.to_string()), |
| 52 | ) |
| 53 | .await |
| 54 | .map_err(db_err)?; |
| 55 | Ok(()) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | #[cfg(test)] |
| 60 | mod tests { |
| 61 | use super::*; |
| 62 | |
| 63 | #[tokio::test] |
| 64 | async fn a_health_answer_is_stored_on_the_row() { |
| 65 | let dir = tempfile::tempdir().unwrap(); |
| 66 | let store = Store::open(&dir.path().join("im.db")).await.unwrap(); |
| 67 | store |
| 68 | .upsert_home_service("Account", "https://im.example.com") |
| 69 | .await |
| 70 | .unwrap(); |
| 71 | store |
| 72 | .record_health("im", false, "2026-10-28T09:00:00.000000000Z") |
| 73 | .await |
| 74 | .unwrap(); |
| 75 | let home = store |
| 76 | .list_services() |
| 77 | .await |
| 78 | .unwrap() |
| 79 | .into_iter() |
| 80 | .find(|service| service.key == "im") |
| 81 | .unwrap(); |
| 82 | assert_eq!(home.healthy, Some(false)); |
| 83 | assert_eq!( |
| 84 | home.checked_at.as_deref(), |
| 85 | Some("2026-10-28T09:00:00.000000000Z") |
| 86 | ); |
| 87 | } |
| 88 | } |