3dd7293feat: ship Steid as an installable binary8d | 1 | |
| 2 | |
| 3 | use sqlx::SqlitePool; |
| 4 | use topcoat::{ |
| 5 | Result, |
| 6 | context::Cx, |
| 7 | router::{StatusCode, route}, |
| 8 | }; |
| 9 | |
| 10 | use super::context::pool; |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | #[route(GET "/healthz")] |
| 24 | async fn healthz(cx: &Cx) -> Result<(StatusCode, &'static str)> { |
| 25 | Ok(match reachable(pool(cx)).await { |
| 26 | Ok(()) => (StatusCode::OK, "ok\n"), |
| 27 | Err(error) => { |
| 28 | |
| 29 | |
| 30 | eprintln!("steid: health check failed: {error}"); |
| 31 | (StatusCode::SERVICE_UNAVAILABLE, "unavailable\n") |
| 32 | } |
| 33 | }) |
| 34 | } |
| 35 | |
| 36 | async fn reachable(pool: &SqlitePool) -> Result<(), sqlx::Error> { |
| 37 | sqlx::query("SELECT 1").fetch_one(pool).await.map(|_| ()) |
| 38 | } |
| 39 | |
| 40 | #[cfg(test)] |
| 41 | mod tests { |
| 42 | use std::str::FromStr; |
| 43 | |
| 44 | use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; |
| 45 | |
| 46 | use super::*; |
| 47 | use crate::infrastructure::database::test_support::test_pool; |
| 48 | |
| 49 | #[tokio::test] |
| 50 | async fn a_working_pool_is_reachable() { |
| 51 | let pool = test_pool().await; |
| 52 | |
| 53 | assert!(reachable(&pool).await.is_ok()); |
| 54 | } |
| 55 | |
| 56 | #[tokio::test] |
| 57 | async fn a_broken_pool_is_not_reachable() { |
| 58 | |
| 59 | |
| 60 | |
| 61 | let options = SqliteConnectOptions::from_str("sqlite:/nonexistent/steid.db") |
| 62 | .expect("the url should parse"); |
| 63 | let pool = SqlitePoolOptions::new().connect_lazy_with(options); |
| 64 | |
| 65 | assert!( |
| 66 | reachable(&pool).await.is_err(), |
| 67 | "a database that cannot be opened must fail the check" |
| 68 | ); |
| 69 | } |
| 70 | } |