-
Notifications
You must be signed in to change notification settings - Fork 70
starknet_transaction_prover: Prometheus /metrics endpoint with build_info #14167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
avi-starkware
wants to merge
1
commit into
avi/prover-v3/panic-shutdown
Choose a base branch
from
avi/prover-v3/metrics
base: avi/prover-v3/panic-shutdown
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
106 changes: 106 additions & 0 deletions
106
crates/starknet_transaction_prover/src/server/metrics.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| //! Prometheus `/metrics` endpoint as a tower middleware layer. | ||
| //! | ||
| //! Short-circuits `GET /metrics` ahead of jsonrpsee so scrapes never run | ||
| //! through the JSON-RPC parser. Label cardinality is bounded by the | ||
| //! enumerations in [`names`] — no user-controlled values become labels. | ||
|
|
||
| use std::task::{Context, Poll}; | ||
|
|
||
| use bytes::Bytes; | ||
| use futures::future::{ready, Either, Ready}; | ||
| use http::{header, Method, Request, Response, StatusCode}; | ||
| use http_body_util::Full; | ||
| use jsonrpsee::server::HttpBody; | ||
| use metrics_exporter_prometheus::{PrometheusBuilder, PrometheusHandle}; | ||
| use tower::{Layer, Service}; | ||
|
|
||
| #[cfg(test)] | ||
| #[path = "metrics_test.rs"] | ||
| mod metrics_test; | ||
|
|
||
| /// Path served by [`MetricsLayer`]. | ||
| pub const METRICS_PATH: &str = "/metrics"; | ||
|
|
||
| /// Metric name constants. Kept here so `metrics!` invocations elsewhere link | ||
| /// to a single definition instead of bare string literals. | ||
| pub mod names { | ||
| /// Build identity. Value is always 1; labels carry version + git_sha. | ||
| pub const BUILD_INFO: &str = "prover_build_info"; | ||
| /// Requests rejected because the concurrency semaphore was full. | ||
| pub const CONCURRENCY_REJECTED_TOTAL: &str = "prover_concurrency_rejected_total"; | ||
| } | ||
|
|
||
| /// Initializes the global Prometheus exporter and emits the `build_info` | ||
| /// gauge. Returns the handle used by [`MetricsLayer`] to render the scrape | ||
| /// response. | ||
| /// | ||
| /// Should be called exactly once at startup. The handle is cheap to clone | ||
| /// (it wraps an `Arc`). | ||
| pub fn install_exporter(version: &str, git_sha: &str) -> anyhow::Result<PrometheusHandle> { | ||
| let handle = PrometheusBuilder::new() | ||
| .install_recorder() | ||
| .map_err(|err| anyhow::anyhow!("failed to install prometheus recorder: {err}"))?; | ||
| metrics::gauge!( | ||
| names::BUILD_INFO, | ||
| "version" => version.to_string(), | ||
| "git_sha" => git_sha.to_string(), | ||
| ) | ||
| .set(1.0); | ||
| // Pre-register the counter at 0 so it shows up in scrapes before the | ||
| // first rejection — dashboards relying on `rate(...) > 0` need the | ||
| // series to exist. | ||
| metrics::counter!(names::CONCURRENCY_REJECTED_TOTAL).increment(0); | ||
| Ok(handle) | ||
| } | ||
|
|
||
| /// tower [`Layer`] that intercepts `GET /metrics`. | ||
| #[derive(Clone)] | ||
| pub struct MetricsLayer { | ||
| handle: PrometheusHandle, | ||
| } | ||
|
|
||
| impl MetricsLayer { | ||
| pub fn new(handle: PrometheusHandle) -> Self { | ||
| Self { handle } | ||
| } | ||
| } | ||
|
|
||
| impl<S> Layer<S> for MetricsLayer { | ||
| type Service = MetricsService<S>; | ||
|
|
||
| fn layer(&self, inner: S) -> Self::Service { | ||
| MetricsService { inner, handle: self.handle.clone() } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone)] | ||
| pub struct MetricsService<S> { | ||
| inner: S, | ||
| handle: PrometheusHandle, | ||
| } | ||
|
|
||
| impl<S, ReqB> Service<Request<ReqB>> for MetricsService<S> | ||
| where | ||
| S: Service<Request<ReqB>, Response = Response<HttpBody>>, | ||
| { | ||
| type Response = Response<HttpBody>; | ||
| type Error = S::Error; | ||
| type Future = Either<Ready<Result<Self::Response, Self::Error>>, S::Future>; | ||
|
|
||
| fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { | ||
| Poll::Ready(Ok(())) | ||
| } | ||
|
|
||
| fn call(&mut self, request: Request<ReqB>) -> Self::Future { | ||
| if request.method() == Method::GET && request.uri().path() == METRICS_PATH { | ||
| let body = Bytes::from(self.handle.render()); | ||
| let response = Response::builder() | ||
| .status(StatusCode::OK) | ||
| .header(header::CONTENT_TYPE, "text/plain; version=0.0.4") | ||
| .body(HttpBody::new(Full::new(body))) | ||
| .expect("response build with a string body is infallible"); | ||
| return Either::Left(ready(Ok(response))); | ||
| } | ||
| Either::Right(self.inner.call(request)) | ||
| } | ||
| } | ||
57 changes: 57 additions & 0 deletions
57
crates/starknet_transaction_prover/src/server/metrics_test.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| use bytes::Bytes; | ||
| use http::{Method, Request, Response, StatusCode}; | ||
| use http_body_util::{BodyExt, Full}; | ||
| use jsonrpsee::server::HttpBody; | ||
| use tower::{Layer, ServiceExt}; | ||
|
|
||
| use crate::server::metrics::{install_exporter, MetricsLayer, METRICS_PATH}; | ||
|
|
||
| fn fallthrough_service() -> impl tower::Service< | ||
| Request<HttpBody>, | ||
| Response = Response<HttpBody>, | ||
| Error = std::convert::Infallible, | ||
| Future = futures::future::Ready<Result<Response<HttpBody>, std::convert::Infallible>>, | ||
| > + Clone { | ||
| tower::service_fn(|_req: Request<HttpBody>| { | ||
| let response = Response::builder() | ||
| .status(StatusCode::IM_A_TEAPOT) | ||
| .body(HttpBody::new(Full::new(Bytes::from_static(b"fallthrough")))) | ||
| .expect("static body is infallible"); | ||
| futures::future::ready(Ok::<_, std::convert::Infallible>(response)) | ||
| }) | ||
| } | ||
|
|
||
| fn empty_request(method: Method, path: &str) -> Request<HttpBody> { | ||
| Request::builder() | ||
| .method(method) | ||
| .uri(path) | ||
| .body(HttpBody::new(Full::new(Bytes::new()))) | ||
| .expect("static body is infallible") | ||
| } | ||
|
|
||
| async fn read_body(response: Response<HttpBody>) -> (StatusCode, Vec<u8>) { | ||
| let (parts, body) = response.into_parts(); | ||
| let bytes = body.collect().await.expect("body collect").to_bytes().to_vec(); | ||
| (parts.status, bytes) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn get_metrics_renders_prometheus_text() { | ||
| // Note: install_exporter installs the global recorder, so this test must | ||
| // be the only one in the crate that calls it. Other metric tests should | ||
| // share this fixture or call install_exporter via `try_install`. | ||
| let handle = install_exporter("0.0.1-test", "deadbeef").expect("install"); | ||
| let svc = MetricsLayer::new(handle).layer(fallthrough_service()); | ||
|
|
||
| let response = svc.oneshot(empty_request(Method::GET, METRICS_PATH)).await.unwrap(); | ||
|
|
||
| let (status, body) = read_body(response).await; | ||
| assert_eq!(status, StatusCode::OK); | ||
| let body_text = String::from_utf8(body).unwrap(); | ||
| assert!( | ||
| body_text.contains("prover_build_info"), | ||
| "scrape should include build_info, got:\n{body_text}" | ||
| ); | ||
| assert!(body_text.contains("version=\"0.0.1-test\"")); | ||
| assert!(body_text.contains("git_sha=\"deadbeef\"")); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.