forge
Explore
Log in

Don't you dare go Hollow

Service health probe every 60 s

Browse files at this commit

243c4e4e642c6c1200f4a8c76e01f4c659fec5bdAhmet Kaan GümüşParent: 1fb6cc2
  • feat
    • service health probe every 60 s
    • oversized pictures get their own message
Show full message
✨ feat: service health probe every 60 s; oversized pictures get their own message
crates/im-core/src/error.rsmodified+3 -0
@@ -33,6 +33,9 @@ pub enum Error {
3333 /// The input is malformed or breaks a policy. Shown to the user.
3434 #[error("invalid value: {0}")]
3535 Invalid(String),
36+ /// A picture has a side longer than the decoder accepts. The web layer shows its own message for it.
37+ #[error("picture too large")]
38+ PictureTooLarge,
3639 }
3740
3841 /// `Result` with the crate error.
crates/im-core/src/photo.rsmodified+12 -8
@@ -55,9 +55,10 @@ fn refused() -> Error {
5555
5656 /// Turns an upload into the stored picture: a square WebP of at most [`MAX_SIDE`] pixels.
5757 ///
58-/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says, and any
59-/// image that is larger than the input limits or cannot be decoded. Only the first frame of an
60-/// animated GIF is kept.
58+/// Refuses anything whose bytes are not PNG, JPEG, WebP or GIF, whatever its name says. A picture with a side
59+/// longer than [`MAX_INPUT_SIDE`] is refused with [`Error::PictureTooLarge`], so the uploader sees the size
60+/// as the reason. Any other image that is larger than the input limits or cannot be decoded is refused too.
61+/// Only the first frame of an animated GIF is kept.
6162 pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> {
6263 let format = image::guess_format(input).map_err(|_| refused())?;
6364 let accepted = matches!(
@@ -72,14 +73,17 @@ pub fn normalize_photo(input: &[u8]) -> Result<Vec<u8>> {
7273 limits.max_image_width = Some(MAX_INPUT_SIDE);
7374 limits.max_image_height = Some(MAX_INPUT_SIDE);
7475 limits.max_alloc = Some(MAX_DECODE_ALLOC);
76+ // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded. The
77+ // size is checked before the decoder limits, so an oversized picture gets its own answer.
78+ let (declared_width, declared_height) = ImageReader::with_format(Cursor::new(input), format)
79+ .into_dimensions()
80+ .map_err(decode_error)?;
81+ if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE {
82+ return Err(Error::PictureTooLarge);
83+ }
7584 let mut reader = ImageReader::with_format(Cursor::new(input), format);
7685 reader.limits(limits);
77- // Reading the header is cheap; the dimensions are checked here, before any pixel is decoded.
7886 let mut decoder = reader.into_decoder().map_err(decode_error)?;
79- let (declared_width, declared_height) = decoder.dimensions();
80- if declared_width > MAX_INPUT_SIDE || declared_height > MAX_INPUT_SIDE {
81- return Err(refused());
82- }
8387 // Phones store the rotation in EXIF and leave the pixels sideways; apply it before cropping.
8488 let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
8589 let mut image = DynamicImage::from_decoder(decoder).map_err(decode_error)?;
crates/im-core/src/store/services.rsmodified+46 -1
@@ -1,7 +1,8 @@
11 //! The service switcher list (contracts.md 4): one row per family app, plus im's own row.
22 //!
33 //! 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 pages, which are not built yet.
4+//! are written by the admin services page. The health worker writes `healthy` and `checked_at` of every row
5+//! through [`Store::record_health`].
56
67 use crate::error::Result;
78 use crate::model::Service;
@@ -40,4 +41,48 @@ impl Store {
4041 .map_err(db_err)?;
4142 Ok(())
4243 }
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)]
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+ }
4388 }
crates/im-web/src/boot.rsmodified+3 -0
@@ -28,6 +28,7 @@ use crate::oidc::signing;
2828 use crate::pages::not_found::NotFoundLayer;
2929 use crate::pages::profile::PHOTO_ROUTE;
3030 use crate::security::{self, SecurityHeaders};
31+use crate::service_probe;
3132 use crate::state::AppState;
3233 use crate::sweeper;
3334 use crate::throttle::Throttle;
@@ -97,6 +98,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
9798 stop_rx.clone(),
9899 );
99100 let sweeper_task = sweeper::spawn(state.store.clone(), stop_rx.clone());
101+ let probe_worker = service_probe::spawn(state.store.clone(), stop_rx.clone());
100102 let mail_worker = mail::worker::spawn(
101103 state.store.clone(),
102104 state.key.clone(),
@@ -113,6 +115,7 @@ pub async fn serve(config_path: &Path) -> im_core::Result<()> {
113115 let _ = signing_worker.await;
114116 let _ = backchannel_worker.await;
115117 let _ = sweeper_task.await;
118+ let _ = probe_worker.await;
116119 let _ = mail_worker.await;
117120 if let Some(task) = backup_task {
118121 let _ = task.await;
crates/im-web/src/i18n/account.rsmodified+8 -0
@@ -208,6 +208,8 @@ pub enum Txt {
208208 ErrPhotoType,
209209 /// Shown when the upload is over the size limit.
210210 ErrPhotoTooLarge,
211+ /// Shown when the picture has a side longer than the decoder accepts (4096 pixels).
212+ ErrPhotoDimensions,
211213 /// Shown when the upload form was sent without a file.
212214 ErrPhotoMissing,
213215 /// Shown when the account has used its photo uploads for the hour.
@@ -501,6 +503,12 @@ pub fn text(lang: Lang, key: Txt) -> &'static str {
501503 (Txt::ErrPhotoType, Lang::Tr) => "Lütfen bir PNG, JPEG, WebP veya GIF resmi seçin.",
502504 (Txt::ErrPhotoTooLarge, Lang::En) => "The photo is larger than 5 MB.",
503505 (Txt::ErrPhotoTooLarge, Lang::Tr) => "Fotoğraf 5 MB'tan büyük.",
506+ (Txt::ErrPhotoDimensions, Lang::En) => {
507+ "The picture is too large; use one at most 4096 pixels on each side."
508+ }
509+ (Txt::ErrPhotoDimensions, Lang::Tr) => {
510+ "Resim çok büyük; en fazla her kenarı 4096 piksel olan bir resim kullanın."
511+ }
504512 (Txt::ErrPhotoRateLimited, Lang::En) => {
505513 "Too many photos were uploaded. Try again in an hour."
506514 }
crates/im-web/src/main.rsmodified+1 -0
@@ -20,6 +20,7 @@ mod mail;
2020 mod oidc;
2121 mod pages;
2222 mod security;
23+mod service_probe;
2324 mod state;
2425 mod sweeper;
2526 mod throttle;
crates/im-web/src/pages/profile.rsmodified+8 -0
@@ -199,6 +199,14 @@ async fn upload_photo(cx: &Cx, mut multipart: Multipart) -> Result<impl View> {
199199 text(lang, Txt::ErrPhotoType),
200200 ));
201201 }
202+ Err(im_core::Error::PictureTooLarge) => {
203+ return Ok(upload_problem(
204+ cx,
205+ lang,
206+ viewer,
207+ text(lang, Txt::ErrPhotoDimensions),
208+ ));
209+ }
202210 Err(error) => return Err(error.into()),
203211 };
204212
crates/im-web/src/service_probe.rsadded+135 -0
@@ -0,0 +1,135 @@
1+//! The health probe worker (contracts.md 4): every minute it asks each listed service for `GET /healthz`
2+//! and records the answer in that service's row of the `services` table.
3+//!
4+//! - A probe is a plain GET of `<origin>/healthz`. Redirects are not followed, so a `301` from a service is
5+//! a failure. The answer is healthy only when its status is `200`. At most [`BODY_LIMIT`] bytes of the
6+//! body are read, and they are discarded.
7+//! - A probe has [`PROBE_TIMEOUT`] to finish, from connect to the end of the body. A service that does not
8+//! answer in time is down.
9+//! - Only `http` and `https` origins are probed. Any other origin is recorded as down.
10+//! - im's own row (key `im`) is not probed: im is answering this very round, so it is recorded as healthy.
11+//! - The rows are probed a few at a time ([`PROBE_CONCURRENCY`]), so one slow service does not hold up the
12+//! others. Each row is recorded as soon as its own probe is done.
13+//!
14+//! The list is read again at every round, so a service the admin adds or removes is picked up within a minute.
15+//! Nothing here fails the server: a store error or a failed probe is logged, and the next round tries again.
16+
17+use std::time::Duration;
18+
19+use futures_util::{StreamExt, stream};
20+use im_core::model::Service;
21+use im_core::store::Store;
22+use im_core::time::now_stamp;
23+use reqwest::{StatusCode, Url};
24+use tokio::sync::watch;
25+use tokio::task::JoinHandle;
26+
27+/// The key of im's own row. im is never probed over HTTP: its answer is known.
28+const HOME_KEY: &str = "im";
29+
30+/// The time between two rounds (contracts.md 4: every 60 seconds).
31+const EVERY: Duration = Duration::from_secs(60);
32+
33+/// How long a service has to answer one probe (contracts.md 4: 2 seconds).
34+pub const PROBE_TIMEOUT: Duration = Duration::from_secs(2);
35+
36+/// The most body bytes read from a probe answer. Only the status decides, so the body is read to drain it
37+/// and then discarded.
38+const BODY_LIMIT: usize = 256;
39+
40+/// How many probes run at once.
41+const PROBE_CONCURRENCY: usize = 8;
42+
43+/// Starts the worker. It runs one round at boot and then every [`EVERY`], until `stop` is set.
44+pub fn spawn(store: Store, mut stop: watch::Receiver<bool>) -> JoinHandle<()> {
45+ tokio::spawn(async move {
46+ let http = probe_client();
47+ loop {
48+ round(&store, &http).await;
49+ tokio::select! {
50+ () = tokio::time::sleep(EVERY) => {}
51+ _ = stop.wait_for(|stopped| *stopped) => return,
52+ }
53+ }
54+ })
55+}
56+
57+/// The HTTP client of the probes: two-second timeouts and no redirects.
58+fn probe_client() -> reqwest::Client {
59+ reqwest::Client::builder()
60+ .redirect(reqwest::redirect::Policy::none())
61+ .timeout(PROBE_TIMEOUT)
62+ .connect_timeout(PROBE_TIMEOUT)
63+ .build()
64+ .expect("the probe HTTP client can be built with fixed settings")
65+}
66+
67+/// One round: im's own row is recorded as healthy, and every other row is probed and recorded.
68+/// Failures are logged per row.
69+pub async fn round(store: &Store, http: &reqwest::Client) {
70+ let services = match store.list_services().await {
71+ Ok(services) => services,
72+ Err(error) => {
73+ tracing::error!(error = %error, "service probes: cannot list the services");
74+ return;
75+ }
76+ };
77+ if let Err(error) = store.record_health(HOME_KEY, true, &now_stamp()).await {
78+ tracing::error!(error = %error, "service probes: cannot record im's own health");
79+ }
80+ // The probes are built in a loop and polled `PROBE_CONCURRENCY` at a time, as the back-channel worker does.
81+ let mut pending = Vec::with_capacity(services.len());
82+ for service in &services {
83+ if service.key != HOME_KEY {
84+ pending.push(probe_and_record(store, http, service));
85+ }
86+ }
87+ stream::iter(pending)
88+ .buffer_unordered(PROBE_CONCURRENCY)
89+ .collect::<Vec<()>>()
90+ .await;
91+}
92+
93+/// Probes one row and records the answer with the time it was recorded.
94+async fn probe_and_record(store: &Store, http: &reqwest::Client, service: &Service) {
95+ let healthy = probe(http, &service.key, &service.url).await;
96+ if let Err(error) = store
97+ .record_health(&service.key, healthy, &now_stamp())
98+ .await
99+ {
100+ tracing::error!(service = %service.key, error = %error, "service probes: cannot record the answer");
101+ }
102+}
103+
104+/// True when `origin` is an http or https origin whose `/healthz` answers `200` within the timeout.
105+async fn probe(http: &reqwest::Client, key: &str, origin: &str) -> bool {
106+ let parsed = match Url::parse(origin) {
107+ Ok(url) if matches!(url.scheme(), "http" | "https") => url,
108+ _ => {
109+ tracing::warn!(service = %key, "service probes: the origin is not an http or https address");
110+ return false;
111+ }
112+ };
113+ let target = format!("{}/healthz", parsed.as_str().trim_end_matches('/'));
114+ let mut response = match http.get(&target).send().await {
115+ Ok(response) => response,
116+ Err(error) => {
117+ tracing::warn!(service = %key, error = %error, "service probe failed");
118+ return false;
119+ }
120+ };
121+ let healthy = response.status() == StatusCode::OK;
122+ // Drain the body up to the limit so the connection can be reused. The last chunk may pass the limit;
123+ // it is discarded either way.
124+ let mut read = 0;
125+ while read < BODY_LIMIT {
126+ match response.chunk().await {
127+ Ok(Some(chunk)) => read += chunk.len(),
128+ _ => break,
129+ }
130+ }
131+ if !healthy {
132+ tracing::warn!(service = %key, status = %response.status(), "service probe answered unhealthy");
133+ }
134+ healthy
135+}