-
Notifications
You must be signed in to change notification settings - Fork 247
Expand file tree
/
Copy pathhandler.rs
More file actions
82 lines (73 loc) · 2.62 KB
/
handler.rs
File metadata and controls
82 lines (73 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use futures_util::future::BoxFuture;
use http::{Request, Response, StatusCode};
use jsonrpsee::server::logger::Body;
use std::task::{Context, Poll};
use tower::{Layer, Service};
/// Layer that intercepts /metrics requests and returns Prometheus metrics directly
#[derive(Clone)]
pub struct MetricsHandlerLayer {
endpoint: String,
}
impl MetricsHandlerLayer {
pub fn new(endpoint: String) -> Self {
Self { endpoint }
}
}
impl Default for MetricsHandlerLayer {
fn default() -> Self {
Self { endpoint: "/metrics".to_string() }
}
}
impl<S> Layer<S> for MetricsHandlerLayer {
type Service = MetricsHandlerService<S>;
fn layer(&self, inner: S) -> Self::Service {
MetricsHandlerService { inner, endpoint: self.endpoint.clone() }
}
}
#[derive(Clone)]
pub struct MetricsHandlerService<S> {
inner: S,
endpoint: String,
}
impl<S> Service<Request<Body>> for MetricsHandlerService<S>
where
S: Service<Request<Body>, Response = Response<Body>> + Clone + Send + 'static,
S::Future: Send + 'static,
{
type Response = Response<Body>;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
// Check if this is a metrics request
let endpoint = self.endpoint.clone();
if req.uri().path() == endpoint && req.method() == http::Method::GET {
// Return metrics directly
Box::pin(async move {
match crate::metrics::gather() {
Ok(metrics) => {
let response = Response::builder()
.status(StatusCode::OK)
.header("content-type", "text/plain; version=0.0.4")
.body(Body::from(metrics))
.expect("Failed to build response");
Ok(response)
}
Err(e) => {
let response = Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::from(format!("Error gathering metrics: {e}")))
.expect("Failed to build response");
Ok(response)
}
}
})
} else {
// Pass through to inner service
let mut inner = self.inner.clone();
Box::pin(async move { inner.call(req).await })
}
}
}