Skip to main content

rust_web_server/metrics/
mod.rs

1/// Global server-state metrics — thread-safe counters accessible from all code paths.
2///
3/// All fields are static atomics; no allocation or locking needed.
4
5use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
6
7/// Set to `true` after [`crate::server::Server::setup`] completes.
8/// The `/readyz` controller returns `503` until this is `true`.
9/// Set back to `false` when a shutdown signal is received so that
10/// Kubernetes stops routing traffic before the pod exits.
11pub static SERVER_READY: AtomicBool = AtomicBool::new(false);
12
13/// Total HTTP requests handled across all connections and protocols.
14pub static REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
15
16/// Requests that caused an application-level error (app.execute returned Err).
17pub static ERRORS_TOTAL: AtomicU64 = AtomicU64::new(0);
18
19/// Number of currently open TCP/QUIC connections.
20pub static ACTIVE_CONNECTIONS: AtomicI64 = AtomicI64::new(0);
21
22pub fn record_request() {
23    REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
24}
25
26pub fn record_error() {
27    ERRORS_TOTAL.fetch_add(1, Ordering::Relaxed);
28}
29
30pub fn connection_open() {
31    ACTIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
32}
33
34pub fn connection_close() {
35    ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Relaxed);
36}
37
38#[cfg(test)]
39mod tests;
40
41/// Returns a Prometheus text-format snapshot of all metrics.
42pub fn prometheus_text() -> String {
43    let requests = REQUESTS_TOTAL.load(Ordering::Relaxed);
44    let errors   = ERRORS_TOTAL.load(Ordering::Relaxed);
45    let active   = ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
46
47    format!(
48        "# HELP rws_requests_total Total HTTP requests handled\n\
49         # TYPE rws_requests_total counter\n\
50         rws_requests_total {}\n\n\
51         # HELP rws_errors_total HTTP requests that returned an application error\n\
52         # TYPE rws_errors_total counter\n\
53         rws_errors_total {}\n\n\
54         # HELP rws_active_connections Currently open connections\n\
55         # TYPE rws_active_connections gauge\n\
56         rws_active_connections {}\n",
57        requests, errors, active
58    )
59}