about summary refs log tree commit diff
path: root/tests
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-08 12:29:22 +0000
committerPjotr <wrk@bosa.lan>2026-11-08 12:29:22 +0000
commitc008bdeca126062b2ab87bb82e7fc9ae05060e5f (patch)
tree329b595a9e18733ac559c446c11d3b320c7a31b2 /tests
parentee939a246a5b67f6650e0759e23fe2731124f8c3 (diff)
downloadgenenetwork4-c008bdeca126062b2ab87bb82e7fc9ae05060e5f.tar.gz
db: recover from a connection the server closed, and report the database
Every database-backed endpoint 500'd with `CodecError { IO error: Broken
pipe }` while the process answered /version quite happily. The cause was
ours: `pool()` turns off the driver's `check_health` (a ping at checkout,
dead connections replaced) to save a round trip -- sound against a
database 130 ms away, worth nothing against loopback, and it costs the
pool its self-healing. One server-side close of an idle session then
becomes one failed request per dead socket: ten in a row, until a
restart.

* src/db.rs: `SQL_CHECK_HEALTH` (default true) decides the ping;
`is_connection_loss` recognises the errors that mean the peer went away
(broken pipe, reset, went away, lost connection, closed);
`forget_pool` drops the cached pool so the next call rebuilds it;
`health` probes reachability, cached ten seconds. One pool static shared
by pool()/forget_pool (they had drifted into two).
* src/error.rs (ApiError::from_db): on a connection loss, forget the pool
-- the one place every database error passes through, so recovery does
not depend on each caller.
* src/lib.rs (/version): `"database": "reachable" | "unreachable"`; a
service that answers while nothing behind it works is now visible.
* src/config.rs: the switch, with the trade written down.
* tests/db_recovery.rs: kills every pooled session from a second
connection, then asserts the next twelve requests all succeed -- the
scenario that produced the outage, now a regression test.
* tests/...: unit test for the classifier (its own IO error text and the
"this is a bad query, do not retry" cases).
* README.md ("Database connections"), docs/www/operator-checklist.md:
the knob, why it defaults on, and what /version reports.
Diffstat (limited to 'tests')
-rw-r--r--tests/db_recovery.rs75
1 files changed, 75 insertions, 0 deletions
diff --git a/tests/db_recovery.rs b/tests/db_recovery.rs
new file mode 100644
index 0000000..7a24a0e
--- /dev/null
+++ b/tests/db_recovery.rs
@@ -0,0 +1,75 @@
+//! The database pool survives a connection that goes away under it.
+//!
+//! Requires a live MariaDB reachable with the configured `SQL_URI` (and a
+//! token for the route); skips without them. The test asks the database to
+//! `KILL` every session this process holds, which is the same situation as
+//! a server-side close of an idle pooled connection -- the one that made
+//! every database-backed request 500 with `CodecError { IO error: Broken
+//! pipe }` until the process was restarted.
+
+use axum::http::StatusCode;
+use http_body_util::BodyExt;
+use mysql::prelude::Queryable;
+use serde_json::Value;
+
+mod common;
+
+use common::{auth_token, db_available, get_with_token};
+
+#[tokio::test]
+async fn a_killed_pooled_connection_does_not_take_the_service_with_it() {
+    if !db_available() {
+        eprintln!("skipping a_killed_pooled_connection_does_not_take_the_service_with_it: no usable database (check SQL_URI credentials)");
+        return;
+    }
+    let Some(token) = auth_token().await else {
+        eprintln!("skipping a_killed_pooled_connection_does_not_take_the_service_with_it: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
+        return;
+    };
+
+    // Warm the pool and prove the route works.
+    let response = get_with_token("GET /groups/BXD", "/groups/BXD", &token).await;
+    assert_eq!(response.status(), StatusCode::OK);
+
+    // Kill this process's sessions from a separate connection, the way a
+    // server-side timeout or an administrator would.
+    let config = genenetwork4::config::Config::load();
+    let opts = mysql::Opts::from_url(&config.sql_uri).expect("SQL_URI parses");
+    let mut killer = mysql::Conn::new(opts).expect("a second connection");
+    let ids: Vec<u64> = killer
+        .query("SELECT Id FROM information_schema.processlist \
+                WHERE User = SUBSTRING_INDEX(SUBSTRING_INDEX(USER(), '@', 1), '@', 1) \
+                  AND Id <> CONNECTION_ID()")
+        .expect("reading the process list");
+    assert!(!ids.is_empty(), "the pool should hold connections by now");
+    for id in ids {
+        // Ignore failures: a session may already be gone.
+        let _ = killer.query_drop(format!("KILL {id}"));
+    }
+
+    // The next requests must recover: `check_health` replaces a dead
+    // pooled connection at checkout, and if one slips through, the pool is
+    // forgotten rather than drawn from again.
+    let mut failures = Vec::new();
+    for attempt in 1..=12 {
+        let response = get_with_token(
+            &format!("GET /groups/BXD (after a kill, attempt {attempt})"),
+            "/groups/BXD",
+            &token,
+        )
+        .await;
+        let status = response.status();
+        let body = response.into_body().collect().await.unwrap().to_bytes();
+        if status != StatusCode::OK {
+            let error: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);
+            failures.push(format!(
+                "attempt {attempt}: {status} {}",
+                error["detail"].as_str().unwrap_or("")
+            ));
+        }
+    }
+    assert!(
+        failures.is_empty(),
+        "every request after the kill must succeed, got: {failures:?}"
+    );
+}