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
184#[cfg(test)]
187mod tests;
188
189pub fn prometheus_text() -> String {
191 let requests = REQUESTS_TOTAL.load(Ordering::Relaxed);
192 let errors = ERRORS_TOTAL.load(Ordering::Relaxed);
193 let active = ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
194
195 let mut out = format!(
196 "# HELP rws_requests_total Total HTTP requests handled\n\
197 # TYPE rws_requests_total counter\n\
198 rws_requests_total {}\n\n\
199 # HELP rws_errors_total HTTP requests that returned an application error\n\
200 # TYPE rws_errors_total counter\n\
201 rws_errors_total {}\n\n\
202 # HELP rws_active_connections Currently open connections\n\
203 # TYPE rws_active_connections gauge\n\
204 rws_active_connections {}\n",
205 requests, errors, active
206 );
207
208 let route_text = route_prometheus_text();
209 if !route_text.is_empty() {
210 out.push('\n');
211 out.push_str(&route_text);
212 }
213
214 let breaker_text = circuit_breaker_prometheus_text();
215 if !breaker_text.is_empty() {
216 out.push('\n');
217 out.push_str(&breaker_text);
218 }
219
220 out
221}
222
223fn circuit_breaker_prometheus_text() -> String {
234 let mut states = crate::circuit_breaker::global().lock().unwrap().all_states();
235 if states.is_empty() {
236 return String::new();
237 }
238 states.sort_by(|a, b| a.0.cmp(&b.0));
239
240 let mut out = String::new();
241 out.push_str("# HELP rws_circuit_breaker_state Circuit breaker state per backend (0=closed, 1=half_open, 2=open)\n");
242 out.push_str("# TYPE rws_circuit_breaker_state gauge\n");
243 for (backend, state) in states {
244 let value = match state {
245 crate::circuit_breaker::BreakerState::Closed => 0,
246 crate::circuit_breaker::BreakerState::HalfOpen => 1,
247 crate::circuit_breaker::BreakerState::Open => 2,
248 };
249 out.push_str(&format!("rws_circuit_breaker_state{{backend=\"{}\"}} {}\n", backend, value));
250 }
251 out
252}
253
254fn route_prometheus_text() -> String {
255 let guard = route_store().lock().unwrap();
256 if guard.entries.is_empty() {
257 return String::new();
258 }
259
260 let mut keys: Vec<&(String, String)> = guard.entries.keys().collect();
262 keys.sort();
263
264 let mut out = String::new();
265
266 out.push_str("# HELP rws_route_requests_total Total requests handled per route\n");
268 out.push_str("# TYPE rws_route_requests_total counter\n");
269 for key in &keys {
270 let entry = &guard.entries[key];
271 let (method, path) = key;
272 let mut statuses: Vec<i16> = entry.counts.keys().cloned().collect();
273 statuses.sort();
274 for status in statuses {
275 let count = entry.counts[&status];
276 out.push_str(&format!(
277 "rws_route_requests_total{{method=\"{}\",path=\"{}\",status=\"{}\"}} {}\n",
278 method, path, status, count,
279 ));
280 }
281 }
282
283 out.push('\n');
285 out.push_str("# HELP rws_route_duration_seconds Request duration in seconds per route\n");
286 out.push_str("# TYPE rws_route_duration_seconds histogram\n");
287 for key in &keys {
288 let entry = &guard.entries[key];
289 let (method, path) = key;
290 let lat = &entry.latency;
291
292 for (i, &upper) in BUCKET_BOUNDS.iter().enumerate() {
293 out.push_str(&format!(
294 "rws_route_duration_seconds_bucket{{method=\"{}\",path=\"{}\",le=\"{}\"}} {}\n",
295 method, path, upper, lat.buckets[i],
296 ));
297 }
298 out.push_str(&format!(
299 "rws_route_duration_seconds_bucket{{method=\"{}\",path=\"{}\",le=\"+Inf\"}} {}\n",
300 method, path, lat.count,
301 ));
302 out.push_str(&format!(
303 "rws_route_duration_seconds_sum{{method=\"{}\",path=\"{}\"}} {:.9}\n",
304 method, path, lat.sum,
305 ));
306 out.push_str(&format!(
307 "rws_route_duration_seconds_count{{method=\"{}\",path=\"{}\"}} {}\n",
308 method, path, lat.count,
309 ));
310 }
311
312 out
313}