Skip to content
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

chore(examples): add axum example #219

Merged
merged 1 commit into from
Aug 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ prost-types = { version = "0.12.0", optional = true }

[dev-dependencies]
async-std = { version = "1", features = ["attributes"] }
axum = "0.7"
criterion = "0.5"
http-types = "2"
pyo3 = "0.21"
Expand Down
88 changes: 88 additions & 0 deletions examples/axum.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use axum::body::Body;
use axum::extract::State;
use axum::http::header::CONTENT_TYPE;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use prometheus_client::encoding::text::encode;
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::registry::Registry;
use prometheus_client_derive_encode::{EncodeLabelSet, EncodeLabelValue};
use std::sync::Arc;
use tokio::sync::Mutex;

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelValue)]
pub enum Method {
Get,
Post,
}

#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct MethodLabels {
pub method: Method,
}

#[derive(Debug)]
pub struct Metrics {
requests: Family<MethodLabels, Counter>,
}

impl Metrics {
pub fn inc_requests(&self, method: Method) {
self.requests.get_or_create(&MethodLabels { method }).inc();
}
}

#[derive(Debug)]
pub struct AppState {
pub registry: Registry,
}

pub async fn metrics_handler(State(state): State<Arc<Mutex<AppState>>>) -> impl IntoResponse {
let state = state.lock().await;
let mut buffer = String::new();
encode(&mut buffer, &state.registry).unwrap();

Response::builder()
.status(StatusCode::OK)
.header(
CONTENT_TYPE,
"application/openmetrics-text; version=1.0.0; charset=utf-8",
)
.body(Body::from(buffer))
.unwrap()
}

pub async fn some_handler(State(metrics): State<Arc<Mutex<Metrics>>>) -> impl IntoResponse {
metrics.lock().await.inc_requests(Method::Get);
"okay".to_string()
}

#[tokio::main]
async fn main() {
let metrics = Metrics {
requests: Family::default(),
};
let mut state = AppState {
registry: Registry::default(),
};
state
.registry
.register("requests", "Count of requests", metrics.requests.clone());
let metrics = Arc::new(Mutex::new(metrics));
let state = Arc::new(Mutex::new(state));

let router = Router::new()
.route("/metrics", get(metrics_handler))
.with_state(state)
.route("/handler", get(some_handler))
.with_state(metrics);
let port = 8080;
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
.await
.unwrap();

axum::serve(listener, router).await.unwrap();
}
Loading