1use std::collections::HashMap;
29use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
30use std::sync::{Mutex, OnceLock};
31use std::time::Instant;
32
33use crate::application::Application;
34use crate::middleware::Middleware;
35use crate::request::Request;
36use crate::response::Response;
37use crate::server::ConnectionInfo;
38
39pub static SERVER_READY: AtomicBool = AtomicBool::new(false);
46
47pub static REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
49
50pub static ERRORS_TOTAL: AtomicU64 = AtomicU64::new(0);
52
53pub static ACTIVE_CONNECTIONS: AtomicI64 = AtomicI64::new(0);
55
56pub static THREAD_POOL_QUEUED: AtomicI64 = AtomicI64::new(0);
58
59pub fn record_request() {
60 REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
61}
62
63pub fn record_error() {
64 ERRORS_TOTAL.fetch_add(1, Ordering::Relaxed);
65}
66
67pub fn connection_open() {
68 ACTIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
69}
70
71pub fn connection_close() {
72 ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Relaxed);
73}
74
75const BUCKET_BOUNDS: [f64; 11] = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0];
80
81struct HistogramEntry {
82 buckets: [u64; 11],
84 sum: f64,
85 count: u64,
86}
87
88impl HistogramEntry {
89 fn new() -> Self {
90 HistogramEntry { buckets: [0; 11], sum: 0.0, count: 0 }
91 }
92
93 fn observe(&mut self, secs: f64) {
94 for (i, &upper) in BUCKET_BOUNDS.iter().enumerate() {
95 if secs <= upper {
96 self.buckets[i] += 1;
97 }
98 }
99 self.sum += secs;
100 self.count += 1;
101 }
102}
103
104struct RouteEntry {
105 counts: HashMap<i16, u64>,
106 latency: HistogramEntry,
107}
108
109impl RouteEntry {
110 fn new() -> Self {
111 RouteEntry { counts: HashMap::new(), latency: HistogramEntry::new() }
112 }
113}
114
115struct RouteStore {
116 entries: HashMap<(String, String), RouteEntry>,
118}
119
120static ROUTE_STORE: OnceLock<Mutex<RouteStore>> = OnceLock::new();
121
122fn route_store() -> &'static Mutex<RouteStore> {
123 ROUTE_STORE.get_or_init(|| Mutex::new(RouteStore { entries: HashMap::new() }))
124}
125
126pub fn record_route(method: &str, path: &str, status: i16, elapsed_secs: f64) {
131 let key = (method.to_string(), path.to_string());
132 let mut guard = route_store().lock().unwrap();
133 let entry = guard.entries.entry(key).or_insert_with(RouteEntry::new);
134 *entry.counts.entry(status).or_insert(0) += 1;
135 entry.latency.observe(elapsed_secs);
136}
137
138fn strip_query(uri: &str) -> &str {
140 match uri.find('?') {
141 Some(i) => &uri[..i],
142 None => uri,
143 }
144}
145
146pub struct MetricsLayer;
161
162impl Middleware for MetricsLayer {
163 fn handle(
164 &self,
165 request: &Request,
166 connection: &ConnectionInfo,
167 next: &dyn Application,
168 ) -> Result<Response, String> {
169 let start = Instant::now();
170 let result = next.execute(request, connection);
171 let elapsed = start.elapsed().as_secs_f64();
172
173 let path = strip_query(&request.request_uri).to_string();
174 let status = match &result {
175 Ok(r) => r.status_code,
176 Err(_) => 500,
177 };
178 record_route(&request.method, &path, status, elapsed);
179
180 result
181 }
182
183 fn runs_inline(&self, _request: &Request, _connection: &ConnectionInfo) -> bool {
185 true
186 }
187}
188
189#[cfg(test)]
192mod tests;
193
194pub fn prometheus_text() -> String {
196 let requests = REQUESTS_TOTAL.load(Ordering::Relaxed);
197 let errors = ERRORS_TOTAL.load(Ordering::Relaxed);
198 let active = ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
199
200 let mut out = format!(
201 "# HELP rws_requests_total Total HTTP requests handled\n\
202 # TYPE rws_requests_total counter\n\
203 rws_requests_total {}\n\n\
204 # HELP rws_errors_total HTTP requests that returned an application error\n\
205 # TYPE rws_errors_total counter\n\
206 rws_errors_total {}\n\n\
207 # HELP rws_active_connections Currently open connections\n\
208 # TYPE rws_active_connections gauge\n\
209 rws_active_connections {}\n",
210 requests, errors, active
211 );
212
213 let route_text = route_prometheus_text();
214 if !route_text.is_empty() {
215 out.push('\n');
216 out.push_str(&route_text);
217 }
218
219 let breaker_text = circuit_breaker_prometheus_text();
220 if !breaker_text.is_empty() {
221 out.push('\n');
222 out.push_str(&breaker_text);
223 }
224
225 out
226}
227
228#[cfg(target_arch = "wasm32")]
241fn circuit_breaker_prometheus_text() -> String {
242 String::new()
243}
244
245#[cfg(not(target_arch = "wasm32"))]
246fn circuit_breaker_prometheus_text() -> String {
247 let mut states = crate::circuit_breaker::global().lock().unwrap().all_states();
248 if states.is_empty() {
249 return String::new();
250 }
251 states.sort_by(|a, b| a.0.cmp(&b.0));
252
253 let mut out = String::new();
254 out.push_str("# HELP rws_circuit_breaker_state Circuit breaker state per backend (0=closed, 1=half_open, 2=open)\n");
255 out.push_str("# TYPE rws_circuit_breaker_state gauge\n");
256 for (backend, state) in states {
257 let value = match state {
258 crate::circuit_breaker::BreakerState::Closed => 0,
259 crate::circuit_breaker::BreakerState::HalfOpen => 1,
260 crate::circuit_breaker::BreakerState::Open => 2,
261 };
262 out.push_str(&format!("rws_circuit_breaker_state{{backend=\"{}\"}} {}\n", backend, value));
263 }
264 out
265}
266
267fn route_prometheus_text() -> String {
268 let guard = route_store().lock().unwrap();
269 if guard.entries.is_empty() {
270 return String::new();
271 }
272
273 let mut keys: Vec<&(String, String)> = guard.entries.keys().collect();
275 keys.sort();
276
277 let mut out = String::new();
278
279 out.push_str("# HELP rws_route_requests_total Total requests handled per route\n");
281 out.push_str("# TYPE rws_route_requests_total counter\n");
282 for key in &keys {
283 let entry = &guard.entries[key];
284 let (method, path) = key;
285 let mut statuses: Vec<i16> = entry.counts.keys().cloned().collect();
286 statuses.sort();
287 for status in statuses {
288 let count = entry.counts[&status];
289 out.push_str(&format!(
290 "rws_route_requests_total{{method=\"{}\",path=\"{}\",status=\"{}\"}} {}\n",
291 method, path, status, count,
292 ));
293 }
294 }
295
296 out.push('\n');
298 out.push_str("# HELP rws_route_duration_seconds Request duration in seconds per route\n");
299 out.push_str("# TYPE rws_route_duration_seconds histogram\n");
300 for key in &keys {
301 let entry = &guard.entries[key];
302 let (method, path) = key;
303 let lat = &entry.latency;
304
305 for (i, &upper) in BUCKET_BOUNDS.iter().enumerate() {
306 out.push_str(&format!(
307 "rws_route_duration_seconds_bucket{{method=\"{}\",path=\"{}\",le=\"{}\"}} {}\n",
308 method, path, upper, lat.buckets[i],
309 ));
310 }
311 out.push_str(&format!(
312 "rws_route_duration_seconds_bucket{{method=\"{}\",path=\"{}\",le=\"+Inf\"}} {}\n",
313 method, path, lat.count,
314 ));
315 out.push_str(&format!(
316 "rws_route_duration_seconds_sum{{method=\"{}\",path=\"{}\"}} {:.9}\n",
317 method, path, lat.sum,
318 ));
319 out.push_str(&format!(
320 "rws_route_duration_seconds_count{{method=\"{}\",path=\"{}\"}} {}\n",
321 method, path, lat.count,
322 ));
323 }
324
325 out
326}