//! The service switcher list (contracts.md 4): one row per family app, plus im's own row. //! //! im's row is kept at boot from `base_url`, so it cannot drift from the configuration. The other rows //! are written by the admin services page. The health worker writes `healthy` and `checked_at` of every row //! through [`Store::record_health`]. use crate::error::Result; use crate::model::Service; use crate::store::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all}; impl Store { /// Every service, in the admin's order. pub async fn list_services(&self) -> Result> { let conn = self.read_conn().await; fetch_all( &conn, "SELECT key, name, url, healthy, checked_at FROM services ORDER BY position, key", (), |row| { Ok(Service { key: col_text(row, 0)?, name: col_text(row, 1)?, url: col_text(row, 2)?, healthy: col_opt_int(row, 3)?.map(|value| value != 0), checked_at: col_opt_text(row, 4)?, }) }, ) .await } /// Creates or updates im's own row (key `im`). Its position and client stay as they are. pub async fn upsert_home_service(&self, name: &str, url: &str) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( "INSERT INTO services (key, name, url, position, client_id) VALUES ('im', ?1, ?2, 0, NULL) \ ON CONFLICT(key) DO UPDATE SET name = excluded.name, url = excluded.url", (name.to_string(), url.to_string()), ) .await .map_err(db_err)?; Ok(()) } /// Records the answer of one health probe: whether the service is healthy, and when it was checked. /// Its name, address and position stay as they are. A key that no longer exists is a no-op. pub async fn record_health(&self, key: &str, healthy: bool, checked_at: &str) -> Result<()> { let conn = self.inner.conn.lock().await; conn.execute( "UPDATE services SET healthy = ?2, checked_at = ?3 WHERE key = ?1", (key.to_string(), i64::from(healthy), checked_at.to_string()), ) .await .map_err(db_err)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn a_health_answer_is_stored_on_the_row() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("im.db")).await.unwrap(); store .upsert_home_service("Account", "https://im.example.com") .await .unwrap(); store .record_health("im", false, "2026-10-28T09:00:00.000000000Z") .await .unwrap(); let home = store .list_services() .await .unwrap() .into_iter() .find(|service| service.key == "im") .unwrap(); assert_eq!(home.healthy, Some(false)); assert_eq!( home.checked_at.as_deref(), Some("2026-10-28T09:00:00.000000000Z") ); } }