forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

services.rs88 lines, 3.1 KiBHistoryRawDownload
1//! The service switcher list (contracts.md 4): one row per family app, plus im's own row.
2//!
3//! im's row is kept at boot from `base_url`, so it cannot drift from the configuration. The other rows
4//! are written by the admin services page. The health worker writes `healthy` and `checked_at` of every row
5//! through [`Store::record_health`].
6
7use crate::error::Result;
8use crate::model::Service;
9use crate::store::{Store, col_opt_int, col_opt_text, col_text, db_err, fetch_all};
10
11impl Store {
12 /// Every service, in the admin's order.
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 /// Creates or updates im's own row (key `im`). Its position and client stay as they are.
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 /// Records the answer of one health probe: whether the service is healthy, and when it was checked.
46 /// Its name, address and position stay as they are. A key that no longer exists is a no-op.
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)]
60mod 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}