//! The health probe worker (contracts.md 4): every minute it asks each listed service for `GET /healthz` //! and records the answer in that service's row of the `services` table. //! //! - A probe is a plain GET of `/healthz`. Redirects are not followed, so a `301` from a service is //! a failure. The answer is healthy only when its status is `200`. At most [`BODY_LIMIT`] bytes of the //! body are read, and they are discarded. //! - A probe has [`PROBE_TIMEOUT`] to finish, from connect to the end of the body. A service that does not //! answer in time is down. //! - Only `http` and `https` origins are probed. Any other origin is recorded as down. //! - im's own row (key `im`) is not probed: im is answering this very round, so it is recorded as healthy. //! - The rows are probed a few at a time ([`PROBE_CONCURRENCY`]), so one slow service does not hold up the //! others. Each row is recorded as soon as its own probe is done. //! //! The list is read again at every round, so a service the admin adds or removes is picked up within a minute. //! Nothing here fails the server: a store error or a failed probe is logged, and the next round tries again. use std::time::Duration; use futures_util::{StreamExt, stream}; use im_core::model::Service; use im_core::store::Store; use im_core::time::now_stamp; use reqwest::{StatusCode, Url}; use tokio::sync::watch; use tokio::task::JoinHandle; /// The key of im's own row. im is never probed over HTTP: its answer is known. const HOME_KEY: &str = "im"; /// The time between two rounds (contracts.md 4: every 60 seconds). const EVERY: Duration = Duration::from_secs(60); /// How long a service has to answer one probe (contracts.md 4: 2 seconds). pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2); /// The most body bytes read from a probe answer. Only the status decides, so the body is read to drain it /// and then discarded. const BODY_LIMIT: usize = 256; /// How many probes run at once. const PROBE_CONCURRENCY: usize = 8; /// Starts the worker. It runs one round at boot and then every [`EVERY`], until `stop` is set. pub fn spawn(store: Store, mut stop: watch::Receiver) -> JoinHandle<()> { tokio::spawn(async move { let http = probe_client(); loop { round(&store, &http).await; tokio::select! { () = tokio::time::sleep(EVERY) => {} _ = stop.wait_for(|stopped| *stopped) => return, } } }) } /// The HTTP client of the probes: two-second timeouts and no redirects. fn probe_client() -> reqwest::Client { reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .timeout(PROBE_TIMEOUT) .connect_timeout(PROBE_TIMEOUT) .build() .expect("the probe HTTP client can be built with fixed settings") } /// One round: im's own row is recorded as healthy, and every other row is probed and recorded. /// Failures are logged per row. pub async fn round(store: &Store, http: &reqwest::Client) { let services = match store.list_services().await { Ok(services) => services, Err(error) => { tracing::error!(error = %error, "service probes: cannot list the services"); return; } }; if let Err(error) = store.record_health(HOME_KEY, true, &now_stamp()).await { tracing::error!(error = %error, "service probes: cannot record im's own health"); } // The probes are built in a loop and polled `PROBE_CONCURRENCY` at a time, as the back-channel worker does. let mut pending = Vec::with_capacity(services.len()); for service in &services { if service.key != HOME_KEY { pending.push(probe_and_record(store, http, service)); } } stream::iter(pending) .buffer_unordered(PROBE_CONCURRENCY) .collect::>() .await; } /// Probes one row and records the answer with the time it was recorded. async fn probe_and_record(store: &Store, http: &reqwest::Client, service: &Service) { let healthy = probe(http, &service.key, &service.url).await; if let Err(error) = store .record_health(&service.key, healthy, &now_stamp()) .await { tracing::error!(service = %service.key, error = %error, "service probes: cannot record the answer"); } } /// True when `origin` is an http or https origin whose `/healthz` answers `200` within the timeout. async fn probe(http: &reqwest::Client, key: &str, origin: &str) -> bool { let parsed = match Url::parse(origin) { Ok(url) if matches!(url.scheme(), "http" | "https") => url, _ => { tracing::warn!(service = %key, "service probes: the origin is not an http or https address"); return false; } }; let target = format!("{}/healthz", parsed.as_str().trim_end_matches('/')); let mut response = match http.get(&target).send().await { Ok(response) => response, Err(error) => { tracing::warn!(service = %key, error = %error.without_url(), "service probe failed"); return false; } }; let healthy = response.status() == StatusCode::OK; // Drain the body up to the limit so the connection can be reused. The last chunk may pass the limit; // it is discarded either way. let mut read = 0; while read < BODY_LIMIT { match response.chunk().await { Ok(Some(chunk)) => read += chunk.len(), _ => break, } } if !healthy { tracing::warn!(service = %key, status = %response.status(), "service probe answered unhealthy"); } healthy }