about summary refs log tree commit diff
path: root/src/db.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/db.rs')
-rw-r--r--src/db.rs108
1 files changed, 107 insertions, 1 deletions
diff --git a/src/db.rs b/src/db.rs
index 283f4bf..975a821 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -113,7 +113,14 @@ pub fn is_connection_loss(error: &DbError) -> bool {
     let DbError::Query(error) = error else {
         return false;
     };
-    let text = error.to_string().to_lowercase();
+    is_connection_loss_detail(&error.to_string())
+}
+
+/// The same test against a driver message already rendered, so a caller
+/// that has to borrow the text anyway (for the error it returns) can ask
+/// the question without a second copy of the error.
+pub fn is_connection_loss_detail(message: &str) -> bool {
+    let text = message.to_lowercase();
     [
         "broken pipe",
         "connection reset",
@@ -141,6 +148,69 @@ pub fn forget_pool() {
     }
 }
 
+/// The last database failure this process saw, so a caller's report of a
+/// 500 can be matched to a cause even when nobody was watching the log.
+///
+/// Recorded in [`crate::error::ApiError::from_db`], i.e. at the one place
+/// every database error passes through, and read by `/version`: "the API
+/// answers but data endpoints fail" is otherwise indistinguishable from an
+/// authentication problem from the outside, which is exactly the confusion
+/// that sent a user to the wrong conclusion on 2026-11-08.
+static LAST_FAILURE: OnceLock<Mutex<Option<Failure>>> = OnceLock::new();
+
+/// How a database failure happened: what an operator needs to tell "the
+/// server is down" from "a connection died under us" from "the query was
+/// wrong".
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FailureKind {
+    /// Could not build a connection/pool at all: the database is down or
+    /// refuses this configuration.
+    Unavailable,
+    /// The server closed a connection we were using. The pool is rebuilt
+    /// when this is seen, so it is usually recovered-from by the next
+    /// request -- and it is the failure that *looks* like a server fault
+    /// while being a socket-level event.
+    ConnectionLost,
+    /// A query the database rejected.
+    Query,
+}
+
+impl FailureKind {
+    pub fn as_str(self) -> &'static str {
+        match self {
+            FailureKind::Unavailable => "unavailable",
+            FailureKind::ConnectionLost => "connection_lost",
+            FailureKind::Query => "query",
+        }
+    }
+}
+
+/// One recorded failure: when, what kind, and the driver's message.
+#[derive(Debug, Clone)]
+pub struct Failure {
+    pub at: std::time::Instant,
+    pub kind: FailureKind,
+    pub detail: String,
+}
+
+/// Remember `failure` as the last database failure.
+pub fn record_failure(kind: FailureKind, detail: impl Into<String>) {
+    if let Ok(mut slot) = LAST_FAILURE.get_or_init(|| Mutex::new(None)).lock() {
+        *slot = Some(Failure {
+            at: std::time::Instant::now(),
+            kind,
+            detail: detail.into(),
+        });
+    }
+}
+
+/// The last recorded failure, if it was less than `max_age` ago.
+pub fn recent_failure(max_age: std::time::Duration) -> Option<Failure> {
+    let guard = LAST_FAILURE.get_or_init(|| Mutex::new(None)).lock().ok()?;
+    let failure = guard.as_ref()?;
+    (failure.at.elapsed() < max_age).then(|| failure.clone())
+}
+
 /// Database reachability, cached for a few seconds: what `/version`
 /// reports, so "the service answers but nothing behind it works" is
 /// visible without trying a data endpoint.
@@ -1500,3 +1570,39 @@ mod tests {
         )));
     }
 }
+
+#[cfg(test)]
+mod failure_tests {
+    use super::*;
+    use std::time::Duration;
+
+    /// The memory of the last failure is what makes `/version` able to say
+    /// "the data endpoints failed a minute ago" while its own probe is
+    /// healthy -- the exact confusion behind a user reading a database
+    /// fault as an authentication problem.
+    #[test]
+    fn a_recent_failure_is_remembered_and_ages_out() {
+        record_failure(FailureKind::ConnectionLost, "CodecError { IO error: Broken pipe }");
+        let failure = recent_failure(Duration::from_secs(60)).expect("just recorded");
+        assert_eq!(failure.kind, FailureKind::ConnectionLost);
+        assert!(failure.kind.as_str() == "connection_lost");
+        assert!(failure.detail.contains("Broken pipe"));
+        // Aged out: the note must not outlive its usefulness.
+        assert!(recent_failure(Duration::ZERO).is_none());
+    }
+
+    #[test]
+    fn a_driver_message_is_recognised_as_a_connection_loss() {
+        for message in [
+            "CodecError { IO error: Broken pipe }",
+            "server has gone away",
+            "Lost connection to MySQL server during query",
+            "connection reset by peer",
+        ] {
+            assert!(is_connection_loss_detail(message), "{message}");
+        }
+        assert!(!is_connection_loss_detail(
+            "Table 'db_webqtl.Nope' doesn't exist"
+        ));
+    }
+}