feat: add telemetry instrumentation
This commit is contained in:
159
src/app.rs
159
src/app.rs
@@ -1,48 +1,102 @@
|
||||
use crate::{
|
||||
config::AppConfig, error::AppError, pokemon::PokeApiClient, service::PokedexService,
|
||||
translation::TranslationClient,
|
||||
telemetry::Telemetry, translation::TranslationClient,
|
||||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Path, State},
|
||||
extract::{MatchedPath, Path, Request, State},
|
||||
http::header,
|
||||
middleware,
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tower::ServiceBuilder;
|
||||
use tower_http::{
|
||||
ServiceBuilderExt,
|
||||
request_id::MakeRequestUuid,
|
||||
trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
service: Arc<PokedexService>,
|
||||
telemetry: Arc<Telemetry>,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
#[must_use]
|
||||
pub fn new(service: PokedexService) -> Self {
|
||||
pub fn new(service: PokedexService, telemetry: Telemetry) -> Self {
|
||||
Self {
|
||||
service: Arc::new(service),
|
||||
telemetry: Arc::new(telemetry),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config(config: &AppConfig) -> Result<Self, AppError> {
|
||||
let telemetry = Telemetry::new(&config.service_name);
|
||||
let pokemon = PokeApiClient::new(&config.pokeapi_base_url, config.request_timeout)?;
|
||||
let translations =
|
||||
TranslationClient::new(&config.translations_base_url, config.request_timeout)?;
|
||||
Ok(Self::new(PokedexService::new(pokemon, translations)))
|
||||
let service = PokedexService::new(pokemon, translations, telemetry.metrics());
|
||||
Ok(Self::new(service, telemetry))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn create_app(state: AppState) -> Router {
|
||||
let tracing_layers = ServiceBuilder::new()
|
||||
.set_x_request_id(MakeRequestUuid)
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
.make_span_with(DefaultMakeSpan::new().include_headers(true))
|
||||
.on_response(DefaultOnResponse::new().include_headers(true)),
|
||||
)
|
||||
.propagate_x_request_id();
|
||||
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/metrics", get(metrics))
|
||||
.route("/pokemon/{name}", get(get_pokemon))
|
||||
.route("/pokemon/translated/{name}", get(get_translated_pokemon))
|
||||
.with_state(state)
|
||||
.with_state(state.clone())
|
||||
.layer(middleware::from_fn_with_state(state, record_http_metrics))
|
||||
.layer(tracing_layers)
|
||||
}
|
||||
|
||||
async fn health() -> Json<HealthResponse> {
|
||||
Json(HealthResponse { status: "ok" })
|
||||
}
|
||||
|
||||
async fn metrics(State(state): State<AppState>) -> Result<impl IntoResponse, AppError> {
|
||||
let body = state.telemetry.render_prometheus()?;
|
||||
Ok(([(header::CONTENT_TYPE, "text/plain; version=0.0.4")], body))
|
||||
}
|
||||
|
||||
async fn record_http_metrics(
|
||||
State(state): State<AppState>,
|
||||
req: Request,
|
||||
next: middleware::Next,
|
||||
) -> Response {
|
||||
let start = Instant::now();
|
||||
let method = req.method().clone();
|
||||
let path = req.extensions().get::<MatchedPath>().map_or_else(
|
||||
|| req.uri().path().to_owned(),
|
||||
|path| path.as_str().to_owned(),
|
||||
);
|
||||
|
||||
let response = next.run(req).await;
|
||||
let status = response.status();
|
||||
state.telemetry.metrics().record_http_request(
|
||||
method.as_str(),
|
||||
&path,
|
||||
status.as_u16(),
|
||||
start.elapsed(),
|
||||
);
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
async fn get_pokemon(
|
||||
State(state): State<AppState>,
|
||||
Path(name): Path<String>,
|
||||
@@ -65,10 +119,13 @@ struct HealthResponse {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{AppState, create_app};
|
||||
use crate::{pokemon::PokeApiClient, service::PokedexService, translation::TranslationClient};
|
||||
use crate::{
|
||||
pokemon::PokeApiClient, service::PokedexService, telemetry::Telemetry,
|
||||
translation::TranslationClient,
|
||||
};
|
||||
use axum::{
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
http::{Request, StatusCode, header::HeaderName},
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::time::Duration;
|
||||
@@ -143,6 +200,62 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_response_has_a_request_id() {
|
||||
let pokeapi = MockServer::start().await;
|
||||
let translations = MockServer::start().await;
|
||||
let app = create_app(state_for(&pokeapi, &translations));
|
||||
|
||||
let response = app
|
||||
.oneshot(request("/health"))
|
||||
.await
|
||||
.expect("request should be handled");
|
||||
|
||||
assert!(response.headers().contains_key("x-request-id"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_incoming_request_id_when_present() {
|
||||
let pokeapi = MockServer::start().await;
|
||||
let translations = MockServer::start().await;
|
||||
let app = create_app(state_for(&pokeapi, &translations));
|
||||
let request = Request::builder()
|
||||
.uri("/health")
|
||||
.header(HeaderName::from_static("x-request-id"), "external-id")
|
||||
.body(Body::empty())
|
||||
.expect("request should build");
|
||||
|
||||
let response = app
|
||||
.oneshot(request)
|
||||
.await
|
||||
.expect("request should be handled");
|
||||
|
||||
assert_eq!(response.headers()["x-request-id"], "external-id");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn metrics_endpoint_exposes_http_and_upstream_otel_metrics() {
|
||||
let pokeapi = MockServer::start().await;
|
||||
let translations = MockServer::start().await;
|
||||
mount_species(&pokeapi, "mewtwo", true, "rare", "Created by science.").await;
|
||||
let app = create_app(state_for(&pokeapi, &translations));
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(request("/pokemon/mewtwo"))
|
||||
.await
|
||||
.expect("request should be handled");
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let response = app
|
||||
.oneshot(request("/metrics"))
|
||||
.await
|
||||
.expect("request should be handled");
|
||||
let body = text_body(response).await;
|
||||
|
||||
assert!(body.contains("http_server_requests"));
|
||||
assert!(body.contains("upstream_client_requests"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pokemon_endpoint_maps_missing_pokemon_to_404() {
|
||||
let pokeapi = MockServer::start().await;
|
||||
@@ -185,11 +298,17 @@ mod tests {
|
||||
}
|
||||
|
||||
fn state_for(pokeapi: &MockServer, translations: &MockServer) -> AppState {
|
||||
AppState::new(PokedexService::new(
|
||||
PokeApiClient::new(pokeapi.uri(), Duration::from_secs(1)).expect("client should build"),
|
||||
TranslationClient::new(translations.uri(), Duration::from_secs(1))
|
||||
.expect("client should build"),
|
||||
))
|
||||
let telemetry = Telemetry::new("test-service");
|
||||
AppState::new(
|
||||
PokedexService::new(
|
||||
PokeApiClient::new(pokeapi.uri(), Duration::from_secs(1))
|
||||
.expect("client should build"),
|
||||
TranslationClient::new(translations.uri(), Duration::from_secs(1))
|
||||
.expect("client should build"),
|
||||
telemetry.metrics(),
|
||||
),
|
||||
telemetry,
|
||||
)
|
||||
}
|
||||
|
||||
fn request(path: &str) -> Request<Body> {
|
||||
@@ -200,9 +319,17 @@ mod tests {
|
||||
}
|
||||
|
||||
async fn json_body(response: axum::response::Response) -> Value {
|
||||
let bytes = to_bytes(response.into_body(), 1024 * 1024)
|
||||
.await
|
||||
.expect("body should be readable");
|
||||
let bytes = body_bytes(response).await;
|
||||
serde_json::from_slice(&bytes).expect("body should be valid JSON")
|
||||
}
|
||||
|
||||
async fn text_body(response: axum::response::Response) -> String {
|
||||
String::from_utf8(body_bytes(response).await.to_vec()).expect("body should be valid UTF-8")
|
||||
}
|
||||
|
||||
async fn body_bytes(response: axum::response::Response) -> axum::body::Bytes {
|
||||
to_bytes(response.into_body(), 1024 * 1024)
|
||||
.await
|
||||
.expect("body should be readable")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user