feat: implement pokedex api
This commit is contained in:
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
/target/
|
||||||
|
.env
|
||||||
|
.DS_Store
|
||||||
|
.coding-challenge-plan.md
|
||||||
2111
Cargo.lock
generated
Normal file
2111
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
36
Cargo.toml
Normal file
36
Cargo.toml
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
[package]
|
||||||
|
name = "pokedex-api"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "MIT"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = { version = "0.8", features = ["json", "macros"] }
|
||||||
|
opentelemetry = "0.31"
|
||||||
|
opentelemetry-prometheus-text-exporter = "0.2"
|
||||||
|
opentelemetry_sdk = { version = "0.31", features = ["metrics"] }
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
thiserror = "2"
|
||||||
|
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal"] }
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
|
tower-http = { version = "0.6", features = ["request-id", "trace", "util"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
http-body-util = "0.1"
|
||||||
|
wiremock = "0.6"
|
||||||
|
|
||||||
|
[lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
|
|
||||||
|
[lints.clippy]
|
||||||
|
all = { level = "deny", priority = -1 }
|
||||||
|
pedantic = { level = "deny", priority = -1 }
|
||||||
|
nursery = { level = "deny", priority = -1 }
|
||||||
|
cargo = { level = "deny", priority = -1 }
|
||||||
|
multiple_crate_versions = { level = "allow", priority = 1 }
|
||||||
3
src/application/mod.rs
Normal file
3
src/application/mod.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
mod pokedex;
|
||||||
|
|
||||||
|
pub use pokedex::{PokedexService, translation_kind_for};
|
||||||
115
src/application/pokedex.rs
Normal file
115
src/application/pokedex.rs
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
use crate::{
|
||||||
|
clients::{funtranslations::TranslationClient, pokeapi::PokeApiClient},
|
||||||
|
domain::{PokemonInfo, TranslationKind},
|
||||||
|
error::AppError,
|
||||||
|
telemetry::{AppMetrics, UpstreamRequestOutcome},
|
||||||
|
};
|
||||||
|
use std::time::Instant;
|
||||||
|
use tracing::{debug, instrument};
|
||||||
|
|
||||||
|
// The application service depends on concrete clients to keep this challenge
|
||||||
|
// concise. In a larger enterprise codebase these would become trait-based ports
|
||||||
|
// so adapters could be swapped without touching business logic.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PokedexService {
|
||||||
|
pokemon: PokeApiClient,
|
||||||
|
translations: TranslationClient,
|
||||||
|
metrics: AppMetrics,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PokedexService {
|
||||||
|
#[must_use]
|
||||||
|
pub const fn new(
|
||||||
|
pokemon: PokeApiClient,
|
||||||
|
translations: TranslationClient,
|
||||||
|
metrics: AppMetrics,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
pokemon,
|
||||||
|
translations,
|
||||||
|
metrics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self), fields(pokemon.name = %name))]
|
||||||
|
pub async fn get_basic(&self, name: &str) -> Result<PokemonInfo, AppError> {
|
||||||
|
self.fetch_pokemon(name).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self), fields(pokemon.name = %name))]
|
||||||
|
pub async fn get_translated(&self, name: &str) -> Result<PokemonInfo, AppError> {
|
||||||
|
let mut pokemon = self.fetch_pokemon(name).await?;
|
||||||
|
let translation_kind = translation_kind_for(&pokemon);
|
||||||
|
|
||||||
|
let translation_start = Instant::now();
|
||||||
|
let translation = self
|
||||||
|
.translations
|
||||||
|
.translate(translation_kind, &pokemon.description)
|
||||||
|
.await;
|
||||||
|
self.metrics.record_upstream_request(
|
||||||
|
"funtranslations",
|
||||||
|
translation_operation(translation_kind),
|
||||||
|
if translation.is_ok() {
|
||||||
|
UpstreamRequestOutcome::Success
|
||||||
|
} else {
|
||||||
|
UpstreamRequestOutcome::Error
|
||||||
|
},
|
||||||
|
translation_start.elapsed(),
|
||||||
|
);
|
||||||
|
|
||||||
|
match translation {
|
||||||
|
Ok(translated) => pokemon.description = translated,
|
||||||
|
Err(error) => debug!(%error, "using original description after translation failure"),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(pokemon)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_pokemon(&self, name: &str) -> Result<PokemonInfo, AppError> {
|
||||||
|
// PokéAPI species data changes rarely. In production, cache successful
|
||||||
|
// species responses with a TTL to reduce latency and upstream pressure.
|
||||||
|
let start = Instant::now();
|
||||||
|
let pokemon = self.pokemon.get_pokemon_info(name).await;
|
||||||
|
if !matches!(pokemon, Err(AppError::BadRequest(_))) {
|
||||||
|
self.metrics.record_upstream_request(
|
||||||
|
"pokeapi",
|
||||||
|
"pokemon_species",
|
||||||
|
upstream_outcome_for_pokemon(&pokemon),
|
||||||
|
start.elapsed(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
pokemon
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn upstream_outcome_for_pokemon(
|
||||||
|
result: &Result<PokemonInfo, AppError>,
|
||||||
|
) -> UpstreamRequestOutcome {
|
||||||
|
match result {
|
||||||
|
Ok(_) => UpstreamRequestOutcome::Success,
|
||||||
|
Err(AppError::NotFound) => UpstreamRequestOutcome::NotFound,
|
||||||
|
Err(
|
||||||
|
AppError::BadRequest(_)
|
||||||
|
| AppError::InvalidUpstreamData(_)
|
||||||
|
| AppError::Upstream(_)
|
||||||
|
| AppError::Timeout
|
||||||
|
| AppError::Internal,
|
||||||
|
) => UpstreamRequestOutcome::Error,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn translation_operation(kind: TranslationKind) -> &'static str {
|
||||||
|
match kind {
|
||||||
|
TranslationKind::Shakespeare => "shakespeare",
|
||||||
|
TranslationKind::Yoda => "yoda",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn translation_kind_for(pokemon: &PokemonInfo) -> TranslationKind {
|
||||||
|
if pokemon.needs_yoda_translation() {
|
||||||
|
TranslationKind::Yoda
|
||||||
|
} else {
|
||||||
|
TranslationKind::Shakespeare
|
||||||
|
}
|
||||||
|
}
|
||||||
43
src/bin/pokedex-api.rs
Normal file
43
src/bin/pokedex-api.rs
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
#![deny(warnings)]
|
||||||
|
#![deny(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
|
||||||
|
#![allow(clippy::missing_errors_doc, clippy::multiple_crate_versions)]
|
||||||
|
|
||||||
|
use pokedex_api::{config::AppConfig, http, telemetry};
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
telemetry::init_tracing();
|
||||||
|
let config = AppConfig::from_env()?;
|
||||||
|
let listener = tokio::net::TcpListener::bind(config.bind_addr).await?;
|
||||||
|
let state = http::AppState::from_config(&config)?;
|
||||||
|
|
||||||
|
axum::serve(listener, http::create_app(state))
|
||||||
|
.with_graceful_shutdown(shutdown_signal())
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn shutdown_signal() {
|
||||||
|
let ctrl_c = async {
|
||||||
|
tokio::signal::ctrl_c()
|
||||||
|
.await
|
||||||
|
.expect("failed to install Ctrl+C handler");
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
let terminate = async {
|
||||||
|
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||||
|
.expect("failed to install SIGTERM handler")
|
||||||
|
.recv()
|
||||||
|
.await;
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
let terminate = std::future::pending::<()>();
|
||||||
|
|
||||||
|
tokio::select! {
|
||||||
|
() = ctrl_c => {},
|
||||||
|
() = terminate => {},
|
||||||
|
}
|
||||||
|
}
|
||||||
51
src/clients/body.rs
Normal file
51
src/clients/body.rs
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
use crate::error::AppError;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
|
||||||
|
const MAX_UPSTREAM_BODY_BYTES: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
pub async fn read_json<T>(
|
||||||
|
mut response: reqwest::Response,
|
||||||
|
service: &'static str,
|
||||||
|
) -> Result<T, AppError>
|
||||||
|
where
|
||||||
|
T: DeserializeOwned,
|
||||||
|
{
|
||||||
|
if response
|
||||||
|
.content_length()
|
||||||
|
.is_some_and(|length| length > MAX_UPSTREAM_BODY_BYTES as u64)
|
||||||
|
{
|
||||||
|
return Err(AppError::Upstream(format!(
|
||||||
|
"{service} response body exceeded {MAX_UPSTREAM_BODY_BYTES} bytes"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = Vec::new();
|
||||||
|
while let Some(chunk) = response
|
||||||
|
.chunk()
|
||||||
|
.await
|
||||||
|
.map_err(|error| map_reqwest_error(&error))?
|
||||||
|
{
|
||||||
|
let next_len = body
|
||||||
|
.len()
|
||||||
|
.checked_add(chunk.len())
|
||||||
|
.ok_or(AppError::Internal)?;
|
||||||
|
if next_len > MAX_UPSTREAM_BODY_BYTES {
|
||||||
|
return Err(AppError::Upstream(format!(
|
||||||
|
"{service} response body exceeded {MAX_UPSTREAM_BODY_BYTES} bytes"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
body.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
serde_json::from_slice(&body).map_err(|error| {
|
||||||
|
AppError::InvalidUpstreamData(format!("{service} returned invalid JSON: {error}"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_reqwest_error(error: &reqwest::Error) -> AppError {
|
||||||
|
if error.is_timeout() {
|
||||||
|
AppError::Timeout
|
||||||
|
} else {
|
||||||
|
AppError::Upstream(error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
164
src/clients/funtranslations.rs
Normal file
164
src/clients/funtranslations.rs
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
use crate::{clients::body, domain::TranslationKind, error::AppError};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct TranslationClient {
|
||||||
|
base_url: String,
|
||||||
|
http: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TranslationClient {
|
||||||
|
pub fn new(base_url: impl Into<String>, timeout: Duration) -> Result<Self, AppError> {
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.timeout(timeout)
|
||||||
|
.build()
|
||||||
|
.map_err(|error| AppError::Upstream(error.to_string()))?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
base_url: trim_trailing_slash(&base_url.into()),
|
||||||
|
http,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self, text), fields(translation.kind = ?kind))]
|
||||||
|
pub async fn translate(&self, kind: TranslationKind, text: &str) -> Result<String, AppError> {
|
||||||
|
let url = format!("{}/translate/{}", self.base_url, endpoint_for(kind));
|
||||||
|
let response = self
|
||||||
|
.http
|
||||||
|
.post(url)
|
||||||
|
.json(&TranslationRequest { text })
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|error| map_reqwest_error(&error))?;
|
||||||
|
let status = response.status();
|
||||||
|
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(AppError::Upstream(format!(
|
||||||
|
"FunTranslations returned status {status}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload = body::read_json::<TranslationResponse>(response, "FunTranslations").await?;
|
||||||
|
if payload.contents.translated.trim().is_empty() {
|
||||||
|
Err(AppError::InvalidUpstreamData(
|
||||||
|
"FunTranslations returned an empty translation".to_owned(),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Ok(payload.contents.translated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(serde::Serialize)]
|
||||||
|
struct TranslationRequest<'a> {
|
||||||
|
text: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct TranslationResponse {
|
||||||
|
contents: TranslationContents,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct TranslationContents {
|
||||||
|
translated: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn endpoint_for(kind: TranslationKind) -> &'static str {
|
||||||
|
match kind {
|
||||||
|
TranslationKind::Shakespeare => "shakespeare",
|
||||||
|
TranslationKind::Yoda => "yoda",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim_trailing_slash(value: &str) -> String {
|
||||||
|
value.trim_end_matches('/').to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_reqwest_error(error: &reqwest::Error) -> AppError {
|
||||||
|
if error.is_timeout() {
|
||||||
|
AppError::Timeout
|
||||||
|
} else {
|
||||||
|
AppError::Upstream(error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{TranslationClient, endpoint_for};
|
||||||
|
use crate::domain::TranslationKind;
|
||||||
|
use std::time::Duration;
|
||||||
|
use wiremock::{Mock, MockServer, ResponseTemplate, matchers};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn translation_kind_resolves_funtranslations_endpoint() {
|
||||||
|
assert_eq!(endpoint_for(TranslationKind::Yoda), "yoda");
|
||||||
|
assert_eq!(endpoint_for(TranslationKind::Shakespeare), "shakespeare");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn posts_text_to_the_requested_translation_endpoint() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("POST"))
|
||||||
|
.and(matchers::path("/translate/yoda"))
|
||||||
|
.and(matchers::body_string_contains("Created"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"contents": { "translated": "Created, it was." }
|
||||||
|
})))
|
||||||
|
.expect(1)
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let translated = client
|
||||||
|
.translate(TranslationKind::Yoda, "Created")
|
||||||
|
.await
|
||||||
|
.expect("translation should succeed");
|
||||||
|
|
||||||
|
assert_eq!(translated, "Created, it was.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_empty_translations_so_callers_can_fallback() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("POST"))
|
||||||
|
.and(matchers::path("/translate/yoda"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"contents": { "translated": " " }
|
||||||
|
})))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let error = client
|
||||||
|
.translate(TranslationKind::Yoda, "hello")
|
||||||
|
.await
|
||||||
|
.expect_err("empty translation should fail");
|
||||||
|
|
||||||
|
assert!(error.to_string().contains("empty translation"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn maps_translation_http_failures_to_upstream_errors() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("POST"))
|
||||||
|
.and(matchers::path("/translate/shakespeare"))
|
||||||
|
.respond_with(ResponseTemplate::new(429))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let error = client
|
||||||
|
.translate(TranslationKind::Shakespeare, "hello")
|
||||||
|
.await
|
||||||
|
.expect_err("translation should fail");
|
||||||
|
|
||||||
|
assert!(error.to_string().contains("FunTranslations"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_for(server: &MockServer) -> TranslationClient {
|
||||||
|
TranslationClient::new(server.uri(), Duration::from_secs(1)).expect("client should build")
|
||||||
|
}
|
||||||
|
}
|
||||||
4
src/clients/mod.rs
Normal file
4
src/clients/mod.rs
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
mod body;
|
||||||
|
|
||||||
|
pub mod funtranslations;
|
||||||
|
pub mod pokeapi;
|
||||||
324
src/clients/pokeapi.rs
Normal file
324
src/clients/pokeapi.rs
Normal file
@@ -0,0 +1,324 @@
|
|||||||
|
use crate::{clients::body, domain::PokemonInfo, error::AppError};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tracing::instrument;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PokeApiClient {
|
||||||
|
base_url: String,
|
||||||
|
http: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PokeApiClient {
|
||||||
|
pub fn new(base_url: impl Into<String>, timeout: Duration) -> Result<Self, AppError> {
|
||||||
|
let http = reqwest::Client::builder()
|
||||||
|
.timeout(timeout)
|
||||||
|
.build()
|
||||||
|
.map_err(|error| AppError::Upstream(error.to_string()))?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
base_url: trim_trailing_slash(&base_url.into()),
|
||||||
|
http,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(self), fields(pokemon.name = %name))]
|
||||||
|
pub async fn get_pokemon_info(&self, name: &str) -> Result<PokemonInfo, AppError> {
|
||||||
|
validate_pokemon_name(name)?;
|
||||||
|
let url = format!(
|
||||||
|
"{}/pokemon-species/{}",
|
||||||
|
self.base_url,
|
||||||
|
name.to_ascii_lowercase()
|
||||||
|
);
|
||||||
|
let response = self
|
||||||
|
.http
|
||||||
|
.get(url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|error| map_reqwest_error(&error))?;
|
||||||
|
let status = response.status();
|
||||||
|
|
||||||
|
if status == reqwest::StatusCode::NOT_FOUND {
|
||||||
|
return Err(AppError::NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !status.is_success() {
|
||||||
|
return Err(AppError::Upstream(format!(
|
||||||
|
"PokéAPI returned status {status}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
|
||||||
|
body::read_json::<PokemonSpeciesResponse>(response, "PokéAPI")
|
||||||
|
.await
|
||||||
|
.and_then(TryInto::try_into)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct PokemonSpeciesResponse {
|
||||||
|
name: String,
|
||||||
|
is_legendary: bool,
|
||||||
|
habitat: Option<NamedResource>,
|
||||||
|
flavor_text_entries: Vec<FlavorTextEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct NamedResource {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct FlavorTextEntry {
|
||||||
|
flavor_text: String,
|
||||||
|
language: NamedResource,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TryFrom<PokemonSpeciesResponse> for PokemonInfo {
|
||||||
|
type Error = AppError;
|
||||||
|
|
||||||
|
fn try_from(species: PokemonSpeciesResponse) -> Result<Self, Self::Error> {
|
||||||
|
let description = species
|
||||||
|
.flavor_text_entries
|
||||||
|
.iter()
|
||||||
|
.filter(|entry| entry.language.name == "en")
|
||||||
|
.map(|entry| normalize_description(&entry.flavor_text))
|
||||||
|
.find(|description| !description.is_empty())
|
||||||
|
.ok_or_else(|| {
|
||||||
|
AppError::InvalidUpstreamData("missing English flavor text".to_owned())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
name: species.name,
|
||||||
|
description,
|
||||||
|
habitat: species
|
||||||
|
.habitat
|
||||||
|
.map_or_else(|| "unknown".to_owned(), |habitat| habitat.name),
|
||||||
|
is_legendary: species.is_legendary,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate_pokemon_name(name: &str) -> Result<(), AppError> {
|
||||||
|
let is_valid = !name.is_empty()
|
||||||
|
&& name
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-');
|
||||||
|
|
||||||
|
if is_valid {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(AppError::BadRequest(
|
||||||
|
"pokemon name must contain only ASCII letters, digits, or hyphens".to_owned(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn normalize_description(description: &str) -> String {
|
||||||
|
description.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn trim_trailing_slash(value: &str) -> String {
|
||||||
|
value.trim_end_matches('/').to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn map_reqwest_error(error: &reqwest::Error) -> AppError {
|
||||||
|
if error.is_timeout() {
|
||||||
|
AppError::Timeout
|
||||||
|
} else {
|
||||||
|
AppError::Upstream(error.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{PokeApiClient, normalize_description, validate_pokemon_name};
|
||||||
|
use crate::error::AppError;
|
||||||
|
use std::time::Duration;
|
||||||
|
use wiremock::{Mock, MockServer, ResponseTemplate, matchers};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalizes_pokemon_descriptions_for_api_output() {
|
||||||
|
let normalized = normalize_description("Line one\nline two\u{000c} line three");
|
||||||
|
|
||||||
|
assert_eq!(normalized, "Line one line two line three");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_names_that_could_change_the_upstream_url_shape() {
|
||||||
|
let error = validate_pokemon_name("foo?bar=baz").expect_err("name should be rejected");
|
||||||
|
|
||||||
|
assert!(matches!(error, AppError::BadRequest(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn fetches_basic_pokemon_information_from_species_endpoint() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/mewtwo"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"name": "mewtwo",
|
||||||
|
"is_legendary": true,
|
||||||
|
"habitat": { "name": "rare" },
|
||||||
|
"flavor_text_entries": [
|
||||||
|
{ "flavor_text": "Versione italiana", "language": { "name": "it" } },
|
||||||
|
{ "flavor_text": "It was created\nby science.", "language": { "name": "en" } }
|
||||||
|
]
|
||||||
|
})))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let pokemon = client
|
||||||
|
.get_pokemon_info("mewtwo")
|
||||||
|
.await
|
||||||
|
.expect("pokemon should be parsed");
|
||||||
|
|
||||||
|
assert_eq!(pokemon.name, "mewtwo");
|
||||||
|
assert_eq!(pokemon.description, "It was created by science.");
|
||||||
|
assert_eq!(pokemon.habitat, "rare");
|
||||||
|
assert!(pokemon.is_legendary);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn normalizes_pokemon_names_to_pokeapi_identifiers() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/mewtwo"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"name": "mewtwo",
|
||||||
|
"is_legendary": true,
|
||||||
|
"habitat": { "name": "rare" },
|
||||||
|
"flavor_text_entries": [
|
||||||
|
{ "flavor_text": "Created by science.", "language": { "name": "en" } }
|
||||||
|
]
|
||||||
|
})))
|
||||||
|
.expect(1)
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let pokemon = client
|
||||||
|
.get_pokemon_info("Mewtwo")
|
||||||
|
.await
|
||||||
|
.expect("mixed-case pokemon names should resolve");
|
||||||
|
|
||||||
|
assert_eq!(pokemon.name, "mewtwo");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn uses_unknown_habitat_when_pokeapi_has_no_habitat() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/missingno"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"name": "missingno",
|
||||||
|
"is_legendary": false,
|
||||||
|
"habitat": null,
|
||||||
|
"flavor_text_entries": [
|
||||||
|
{ "flavor_text": "A glitch Pokémon.", "language": { "name": "en" } }
|
||||||
|
]
|
||||||
|
})))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let pokemon = client
|
||||||
|
.get_pokemon_info("missingno")
|
||||||
|
.await
|
||||||
|
.expect("pokemon should be parsed");
|
||||||
|
|
||||||
|
assert_eq!(pokemon.habitat, "unknown");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn maps_missing_pokemon_to_not_found() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/nope"))
|
||||||
|
.respond_with(ResponseTemplate::new(404))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let error = client
|
||||||
|
.get_pokemon_info("nope")
|
||||||
|
.await
|
||||||
|
.expect_err("missing pokemon should fail");
|
||||||
|
|
||||||
|
assert!(matches!(error, AppError::NotFound));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn skips_empty_english_descriptions_until_it_finds_a_non_empty_one() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/eevee"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"name": "eevee",
|
||||||
|
"is_legendary": false,
|
||||||
|
"habitat": { "name": "urban" },
|
||||||
|
"flavor_text_entries": [
|
||||||
|
{ "flavor_text": " \n \t", "language": { "name": "en" } },
|
||||||
|
{ "flavor_text": "Can evolve in many ways.", "language": { "name": "en" } }
|
||||||
|
]
|
||||||
|
})))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let pokemon = client
|
||||||
|
.get_pokemon_info("eevee")
|
||||||
|
.await
|
||||||
|
.expect("second English description should be used");
|
||||||
|
|
||||||
|
assert_eq!(pokemon.description, "Can evolve in many ways.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_species_without_english_description() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/pikachu"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||||
|
"name": "pikachu",
|
||||||
|
"is_legendary": false,
|
||||||
|
"habitat": { "name": "forest" },
|
||||||
|
"flavor_text_entries": [
|
||||||
|
{ "flavor_text": "Souris électrique.", "language": { "name": "fr" } }
|
||||||
|
]
|
||||||
|
})))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let error = client
|
||||||
|
.get_pokemon_info("pikachu")
|
||||||
|
.await
|
||||||
|
.expect_err("missing English entry should fail");
|
||||||
|
|
||||||
|
assert!(matches!(error, AppError::InvalidUpstreamData(_)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_oversized_upstream_bodies() {
|
||||||
|
let server = MockServer::start().await;
|
||||||
|
Mock::given(matchers::method("GET"))
|
||||||
|
.and(matchers::path("/pokemon-species/snorlax"))
|
||||||
|
.respond_with(ResponseTemplate::new(200).set_body_string("x".repeat(1025 * 1024)))
|
||||||
|
.mount(&server)
|
||||||
|
.await;
|
||||||
|
let client = client_for(&server);
|
||||||
|
|
||||||
|
let error = client
|
||||||
|
.get_pokemon_info("snorlax")
|
||||||
|
.await
|
||||||
|
.expect_err("oversized body should fail");
|
||||||
|
|
||||||
|
assert!(error.to_string().contains("exceeded"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_for(server: &MockServer) -> PokeApiClient {
|
||||||
|
PokeApiClient::new(server.uri(), Duration::from_secs(1)).expect("client should build")
|
||||||
|
}
|
||||||
|
}
|
||||||
108
src/config.rs
Normal file
108
src/config.rs
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
use std::{env, net::SocketAddr, time::Duration};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct AppConfig {
|
||||||
|
pub bind_addr: SocketAddr,
|
||||||
|
pub pokeapi_base_url: String,
|
||||||
|
pub translations_base_url: String,
|
||||||
|
pub request_timeout: Duration,
|
||||||
|
pub rate_limit_per_second: f64,
|
||||||
|
pub rate_limit_burst: u32,
|
||||||
|
pub service_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppConfig {
|
||||||
|
#[must_use]
|
||||||
|
pub fn default_local() -> Self {
|
||||||
|
Self {
|
||||||
|
bind_addr: default_bind_addr(),
|
||||||
|
pokeapi_base_url: "https://pokeapi.co/api/v2".to_owned(),
|
||||||
|
translations_base_url: "https://api.funtranslations.mercxry.me/v1".to_owned(),
|
||||||
|
request_timeout: Duration::from_secs(5),
|
||||||
|
rate_limit_per_second: 20.0,
|
||||||
|
rate_limit_burst: 40,
|
||||||
|
service_name: env!("CARGO_PKG_NAME").to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn from_env() -> Result<Self, ConfigError> {
|
||||||
|
let defaults = Self::default_local();
|
||||||
|
let rate_limit_per_second =
|
||||||
|
env_or_parse("RATE_LIMIT_PER_SECOND", defaults.rate_limit_per_second)?;
|
||||||
|
let rate_limit_burst = env_or_parse("RATE_LIMIT_BURST", defaults.rate_limit_burst)?;
|
||||||
|
validate_rate_limit(rate_limit_per_second, rate_limit_burst)?;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
bind_addr: env_or_parse("BIND_ADDR", defaults.bind_addr)?,
|
||||||
|
pokeapi_base_url: env_or_string("POKEAPI_BASE_URL", &defaults.pokeapi_base_url),
|
||||||
|
translations_base_url: env_or_string(
|
||||||
|
"FUN_TRANSLATIONS_BASE_URL",
|
||||||
|
&defaults.translations_base_url,
|
||||||
|
),
|
||||||
|
request_timeout: Duration::from_secs(env_or_parse(
|
||||||
|
"REQUEST_TIMEOUT_SECONDS",
|
||||||
|
defaults.request_timeout.as_secs(),
|
||||||
|
)?),
|
||||||
|
rate_limit_per_second,
|
||||||
|
rate_limit_burst,
|
||||||
|
service_name: env_or_string("OTEL_SERVICE_NAME", &defaults.service_name),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
#[error("rate limit values must be positive")]
|
||||||
|
InvalidRateLimit,
|
||||||
|
#[error("invalid value for {name}: {source}")]
|
||||||
|
InvalidValue {
|
||||||
|
name: &'static str,
|
||||||
|
source: Box<dyn std::error::Error + Send + Sync>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_or_string(name: &'static str, default: &str) -> String {
|
||||||
|
env::var(name).unwrap_or_else(|_| default.to_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_bind_addr() -> SocketAddr {
|
||||||
|
SocketAddr::from(([0, 0, 0, 0], 8000))
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn validate_rate_limit(per_second: f64, burst: u32) -> Result<(), ConfigError> {
|
||||||
|
if per_second.is_finite() && per_second > 0.0 && burst > 0 {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(ConfigError::InvalidRateLimit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env_or_parse<T>(name: &'static str, default: T) -> Result<T, ConfigError>
|
||||||
|
where
|
||||||
|
T: std::str::FromStr,
|
||||||
|
T::Err: std::error::Error + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
env::var(name).map_or_else(
|
||||||
|
|_| Ok(default),
|
||||||
|
|value| {
|
||||||
|
value.parse().map_err(|source| ConfigError::InvalidValue {
|
||||||
|
name,
|
||||||
|
source: Box::new(source),
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::AppConfig;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_config_is_valid_for_local_development() {
|
||||||
|
let config = AppConfig::default_local();
|
||||||
|
|
||||||
|
assert_eq!(config.bind_addr.port(), 8000);
|
||||||
|
assert_eq!(config.pokeapi_base_url, "https://pokeapi.co/api/v2");
|
||||||
|
assert!((config.rate_limit_per_second - 20.0).abs() < f64::EPSILON);
|
||||||
|
}
|
||||||
|
}
|
||||||
23
src/domain/mod.rs
Normal file
23
src/domain/mod.rs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
|
||||||
|
pub struct PokemonInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub description: String,
|
||||||
|
pub habitat: String,
|
||||||
|
#[serde(rename = "isLegendary")]
|
||||||
|
pub is_legendary: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PokemonInfo {
|
||||||
|
#[must_use]
|
||||||
|
pub fn needs_yoda_translation(&self) -> bool {
|
||||||
|
self.is_legendary || self.habitat.eq_ignore_ascii_case("cave")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum TranslationKind {
|
||||||
|
Shakespeare,
|
||||||
|
Yoda,
|
||||||
|
}
|
||||||
120
src/error.rs
Normal file
120
src/error.rs
Normal file
@@ -0,0 +1,120 @@
|
|||||||
|
use axum::{
|
||||||
|
Json,
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum AppError {
|
||||||
|
#[error("bad request: {0}")]
|
||||||
|
BadRequest(String),
|
||||||
|
#[error("pokemon not found")]
|
||||||
|
NotFound,
|
||||||
|
#[error("upstream service returned invalid data: {0}")]
|
||||||
|
InvalidUpstreamData(String),
|
||||||
|
#[error("upstream service failed: {0}")]
|
||||||
|
Upstream(String),
|
||||||
|
#[error("request timed out")]
|
||||||
|
Timeout,
|
||||||
|
#[error("internal server error")]
|
||||||
|
Internal,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppError {
|
||||||
|
#[must_use]
|
||||||
|
pub const fn status_code(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
Self::BadRequest(_) => StatusCode::BAD_REQUEST,
|
||||||
|
Self::NotFound => StatusCode::NOT_FOUND,
|
||||||
|
Self::InvalidUpstreamData(_) | Self::Upstream(_) | Self::Timeout => {
|
||||||
|
StatusCode::BAD_GATEWAY
|
||||||
|
}
|
||||||
|
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub const fn code(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::BadRequest(_) => "bad_request",
|
||||||
|
Self::NotFound => "pokemon_not_found",
|
||||||
|
Self::InvalidUpstreamData(_) => "upstream_invalid_data",
|
||||||
|
Self::Upstream(_) | Self::Timeout => "upstream_unavailable",
|
||||||
|
Self::Internal => "internal_error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn public_message(&self) -> String {
|
||||||
|
match self {
|
||||||
|
Self::BadRequest(message) => message.clone(),
|
||||||
|
Self::NotFound => "pokemon not found".to_owned(),
|
||||||
|
Self::InvalidUpstreamData(_) => "upstream service returned invalid data".to_owned(),
|
||||||
|
Self::Upstream(_) | Self::Timeout => "upstream service failed".to_owned(),
|
||||||
|
Self::Internal => "internal server error".to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for AppError {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
ApiError::new(self, None).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ApiError {
|
||||||
|
source: AppError,
|
||||||
|
request_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ApiError {
|
||||||
|
#[must_use]
|
||||||
|
pub const fn new(source: AppError, request_id: Option<String>) -> Self {
|
||||||
|
Self { source, request_id }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn from_headers(source: AppError, headers: &HeaderMap) -> Self {
|
||||||
|
Self::new(source, request_id_from_headers(headers))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ApiError {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
let status = self.source.status_code();
|
||||||
|
let body = ErrorBody::new(
|
||||||
|
self.source.code(),
|
||||||
|
self.source.public_message(),
|
||||||
|
self.request_id,
|
||||||
|
);
|
||||||
|
(status, Json(body)).into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct ErrorBody {
|
||||||
|
code: &'static str,
|
||||||
|
message: String,
|
||||||
|
#[serde(rename = "requestId", skip_serializing_if = "Option::is_none")]
|
||||||
|
request_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrorBody {
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(code: &'static str, message: impl Into<String>, request_id: Option<String>) -> Self {
|
||||||
|
Self {
|
||||||
|
code,
|
||||||
|
message: message.into(),
|
||||||
|
request_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn request_id_from_headers(headers: &HeaderMap) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get("x-request-id")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.map(str::to_owned)
|
||||||
|
}
|
||||||
55
src/http/handlers.rs
Normal file
55
src/http/handlers.rs
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
use super::AppState;
|
||||||
|
use crate::{domain::PokemonInfo, error::ApiError};
|
||||||
|
use axum::{
|
||||||
|
Json,
|
||||||
|
extract::{Path, State},
|
||||||
|
http::{HeaderMap, header},
|
||||||
|
response::IntoResponse,
|
||||||
|
};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
pub(super) async fn health() -> Json<HealthResponse> {
|
||||||
|
Json(HealthResponse { status: "ok" })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn metrics(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<impl IntoResponse, ApiError> {
|
||||||
|
let body = state
|
||||||
|
.telemetry
|
||||||
|
.render_prometheus()
|
||||||
|
.map_err(|error| ApiError::from_headers(error, &headers))?;
|
||||||
|
Ok(([(header::CONTENT_TYPE, "text/plain; version=0.0.4")], body))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn get_pokemon(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(name): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<PokemonInfo>, ApiError> {
|
||||||
|
state
|
||||||
|
.service
|
||||||
|
.get_basic(&name)
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(|error| ApiError::from_headers(error, &headers))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn get_translated_pokemon(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(name): Path<String>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<PokemonInfo>, ApiError> {
|
||||||
|
state
|
||||||
|
.service
|
||||||
|
.get_translated(&name)
|
||||||
|
.await
|
||||||
|
.map(Json)
|
||||||
|
.map_err(|error| ApiError::from_headers(error, &headers))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub(super) struct HealthResponse {
|
||||||
|
status: &'static str,
|
||||||
|
}
|
||||||
56
src/http/middleware.rs
Normal file
56
src/http/middleware.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
use super::AppState;
|
||||||
|
use crate::error::{ErrorBody, request_id_from_headers};
|
||||||
|
use axum::{
|
||||||
|
Json,
|
||||||
|
extract::{MatchedPath, Request, State},
|
||||||
|
http::StatusCode,
|
||||||
|
middleware,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
pub(super) async fn enforce_rate_limit(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
req: Request,
|
||||||
|
next: middleware::Next,
|
||||||
|
) -> Response {
|
||||||
|
let path = req.uri().path();
|
||||||
|
if matches!(path, "/health" | "/metrics") || state.rate_limiter.try_acquire() {
|
||||||
|
next.run(req).await
|
||||||
|
} else {
|
||||||
|
let request_id = request_id_from_headers(req.headers());
|
||||||
|
(
|
||||||
|
StatusCode::TOO_MANY_REQUESTS,
|
||||||
|
Json(ErrorBody::new(
|
||||||
|
"rate_limit_exceeded",
|
||||||
|
"rate limit exceeded",
|
||||||
|
request_id,
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) 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
|
||||||
|
}
|
||||||
95
src/http/mod.rs
Normal file
95
src/http/mod.rs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
mod handlers;
|
||||||
|
mod middleware;
|
||||||
|
mod rate_limit;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
application::PokedexService,
|
||||||
|
clients::{funtranslations::TranslationClient, pokeapi::PokeApiClient},
|
||||||
|
config::AppConfig,
|
||||||
|
error::AppError,
|
||||||
|
telemetry::Telemetry,
|
||||||
|
};
|
||||||
|
use axum::{Router, extract::Request, middleware as axum_middleware, routing::get};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tower::ServiceBuilder;
|
||||||
|
use tower_http::{
|
||||||
|
ServiceBuilderExt,
|
||||||
|
request_id::MakeRequestUuid,
|
||||||
|
trace::{DefaultOnResponse, TraceLayer},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub use rate_limit::RateLimiter;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AppState {
|
||||||
|
pub(super) service: Arc<PokedexService>,
|
||||||
|
pub(super) telemetry: Arc<Telemetry>,
|
||||||
|
pub(super) rate_limiter: Arc<RateLimiter>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(service: PokedexService, telemetry: Telemetry, rate_limiter: RateLimiter) -> Self {
|
||||||
|
Self {
|
||||||
|
service: Arc::new(service),
|
||||||
|
telemetry: Arc::new(telemetry),
|
||||||
|
rate_limiter: Arc::new(rate_limiter),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)?;
|
||||||
|
let service = PokedexService::new(pokemon, translations, telemetry.metrics());
|
||||||
|
Ok(Self::new(
|
||||||
|
service,
|
||||||
|
telemetry,
|
||||||
|
RateLimiter::new(config.rate_limit_per_second, config.rate_limit_burst)
|
||||||
|
.map_err(|_| AppError::Internal)?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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(|request: &Request| {
|
||||||
|
let request_id = request
|
||||||
|
.headers()
|
||||||
|
.get("x-request-id")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.unwrap_or("unknown");
|
||||||
|
tracing::info_span!(
|
||||||
|
"http.request",
|
||||||
|
method = %request.method(),
|
||||||
|
path = %request.uri().path(),
|
||||||
|
request_id = %request_id,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.on_response(DefaultOnResponse::new()),
|
||||||
|
)
|
||||||
|
.propagate_x_request_id();
|
||||||
|
|
||||||
|
Router::new()
|
||||||
|
.route("/health", get(handlers::health))
|
||||||
|
.route("/metrics", get(handlers::metrics))
|
||||||
|
.route("/pokemon/{name}", get(handlers::get_pokemon))
|
||||||
|
.route(
|
||||||
|
"/pokemon/translated/{name}",
|
||||||
|
get(handlers::get_translated_pokemon),
|
||||||
|
)
|
||||||
|
.with_state(state.clone())
|
||||||
|
.layer(axum_middleware::from_fn_with_state(
|
||||||
|
state.clone(),
|
||||||
|
middleware::enforce_rate_limit,
|
||||||
|
))
|
||||||
|
.layer(axum_middleware::from_fn_with_state(
|
||||||
|
state,
|
||||||
|
middleware::record_http_metrics,
|
||||||
|
))
|
||||||
|
.layer(tracing_layers)
|
||||||
|
}
|
||||||
89
src/http/rate_limit.rs
Normal file
89
src/http/rate_limit.rs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
use std::{sync::Mutex, time::Instant};
|
||||||
|
|
||||||
|
// This challenge uses a simple in-memory global limiter. In production,
|
||||||
|
// prefer API gateway rate limiting so limits are shared across instances and
|
||||||
|
// identity-aware policies can be keyed by API key, user, or client IP.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RateLimiter {
|
||||||
|
bucket: Mutex<TokenBucket>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RateLimiter {
|
||||||
|
pub fn new(refill_per_second: f64, burst: u32) -> Result<Self, RateLimitError> {
|
||||||
|
if !refill_per_second.is_finite() || refill_per_second <= 0.0 || burst == 0 {
|
||||||
|
return Err(RateLimitError::InvalidConfiguration);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
bucket: Mutex::new(TokenBucket {
|
||||||
|
capacity: f64::from(burst),
|
||||||
|
tokens: f64::from(burst),
|
||||||
|
refill_per_second,
|
||||||
|
last_refill: Instant::now(),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn try_acquire(&self) -> bool {
|
||||||
|
self.bucket
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.try_acquire()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum RateLimitError {
|
||||||
|
#[error("rate limit configuration must be positive")]
|
||||||
|
InvalidConfiguration,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct TokenBucket {
|
||||||
|
capacity: f64,
|
||||||
|
tokens: f64,
|
||||||
|
refill_per_second: f64,
|
||||||
|
last_refill: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TokenBucket {
|
||||||
|
fn try_acquire(&mut self) -> bool {
|
||||||
|
self.refill();
|
||||||
|
if self.tokens >= 1.0 {
|
||||||
|
self.tokens -= 1.0;
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refill(&mut self) {
|
||||||
|
let elapsed = self.last_refill.elapsed().as_secs_f64();
|
||||||
|
self.tokens = self
|
||||||
|
.capacity
|
||||||
|
.min(self.tokens + elapsed.mul_add(self.refill_per_second, 0.0));
|
||||||
|
self.last_refill = Instant::now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::RateLimiter;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_non_positive_or_non_finite_configuration() {
|
||||||
|
assert!(RateLimiter::new(0.0, 1).is_err());
|
||||||
|
assert!(RateLimiter::new(f64::INFINITY, 1).is_err());
|
||||||
|
assert!(RateLimiter::new(1.0, 0).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn allows_requests_up_to_the_burst_capacity() {
|
||||||
|
let limiter = RateLimiter::new(100.0, 2).expect("rate limiter should build");
|
||||||
|
|
||||||
|
assert!(limiter.try_acquire());
|
||||||
|
assert!(limiter.try_acquire());
|
||||||
|
assert!(!limiter.try_acquire());
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/lib.rs
Normal file
16
src/lib.rs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
#![deny(warnings)]
|
||||||
|
#![deny(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
|
||||||
|
#![allow(clippy::missing_errors_doc, clippy::multiple_crate_versions)]
|
||||||
|
|
||||||
|
pub mod application;
|
||||||
|
pub mod clients;
|
||||||
|
pub mod config;
|
||||||
|
pub mod domain;
|
||||||
|
pub mod error;
|
||||||
|
pub mod http;
|
||||||
|
pub mod telemetry;
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub const fn crate_name() -> &'static str {
|
||||||
|
env!("CARGO_PKG_NAME")
|
||||||
|
}
|
||||||
112
src/telemetry/metrics.rs
Normal file
112
src/telemetry/metrics.rs
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
use opentelemetry::{KeyValue, metrics::Meter};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct AppMetrics {
|
||||||
|
http_requests: opentelemetry::metrics::Counter<u64>,
|
||||||
|
http_errors: opentelemetry::metrics::Counter<u64>,
|
||||||
|
http_request_duration: opentelemetry::metrics::Histogram<f64>,
|
||||||
|
upstream_requests: opentelemetry::metrics::Counter<u64>,
|
||||||
|
upstream_errors: opentelemetry::metrics::Counter<u64>,
|
||||||
|
upstream_request_duration: opentelemetry::metrics::Histogram<f64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||||
|
pub enum UpstreamRequestOutcome {
|
||||||
|
Success,
|
||||||
|
NotFound,
|
||||||
|
Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UpstreamRequestOutcome {
|
||||||
|
const fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Success => "ok",
|
||||||
|
Self::NotFound => "not_found",
|
||||||
|
Self::Error => "error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn is_error(self) -> bool {
|
||||||
|
matches!(self, Self::Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppMetrics {
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(meter: &Meter) -> Self {
|
||||||
|
Self {
|
||||||
|
http_requests: meter
|
||||||
|
.u64_counter("http.server.requests")
|
||||||
|
.with_description("Total HTTP requests")
|
||||||
|
.with_unit("requests")
|
||||||
|
.build(),
|
||||||
|
http_errors: meter
|
||||||
|
.u64_counter("http.server.errors")
|
||||||
|
.with_description("Total HTTP requests with error status codes")
|
||||||
|
.with_unit("errors")
|
||||||
|
.build(),
|
||||||
|
http_request_duration: meter
|
||||||
|
.f64_histogram("http.server.request.duration")
|
||||||
|
.with_description("HTTP request duration")
|
||||||
|
.with_unit("s")
|
||||||
|
.build(),
|
||||||
|
upstream_requests: meter
|
||||||
|
.u64_counter("upstream.client.requests")
|
||||||
|
.with_description("Total upstream requests")
|
||||||
|
.with_unit("requests")
|
||||||
|
.build(),
|
||||||
|
upstream_errors: meter
|
||||||
|
.u64_counter("upstream.client.errors")
|
||||||
|
.with_description("Total failed upstream requests")
|
||||||
|
.with_unit("errors")
|
||||||
|
.build(),
|
||||||
|
upstream_request_duration: meter
|
||||||
|
.f64_histogram("upstream.client.request.duration")
|
||||||
|
.with_description("Upstream request duration")
|
||||||
|
.with_unit("s")
|
||||||
|
.build(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_http_request(&self, method: &str, path: &str, status: u16, duration: Duration) {
|
||||||
|
let is_error = status_is_error(status);
|
||||||
|
let status = status.to_string();
|
||||||
|
let attributes = [
|
||||||
|
KeyValue::new("method", method.to_owned()),
|
||||||
|
KeyValue::new("path", path.to_owned()),
|
||||||
|
KeyValue::new("status", status),
|
||||||
|
];
|
||||||
|
self.http_requests.add(1, &attributes);
|
||||||
|
self.http_request_duration
|
||||||
|
.record(duration.as_secs_f64(), &attributes);
|
||||||
|
if is_error {
|
||||||
|
self.http_errors.add(1, &attributes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_upstream_request(
|
||||||
|
&self,
|
||||||
|
service: &'static str,
|
||||||
|
operation: &'static str,
|
||||||
|
outcome: UpstreamRequestOutcome,
|
||||||
|
duration: Duration,
|
||||||
|
) {
|
||||||
|
let status = outcome.label();
|
||||||
|
let attributes = [
|
||||||
|
KeyValue::new("service", service),
|
||||||
|
KeyValue::new("operation", operation),
|
||||||
|
KeyValue::new("status", status),
|
||||||
|
];
|
||||||
|
self.upstream_requests.add(1, &attributes);
|
||||||
|
self.upstream_request_duration
|
||||||
|
.record(duration.as_secs_f64(), &attributes);
|
||||||
|
if outcome.is_error() {
|
||||||
|
self.upstream_errors.add(1, &attributes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn status_is_error(status: u16) -> bool {
|
||||||
|
status >= 400
|
||||||
|
}
|
||||||
56
src/telemetry/mod.rs
Normal file
56
src/telemetry/mod.rs
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
mod metrics;
|
||||||
|
mod tracing;
|
||||||
|
|
||||||
|
use crate::error::AppError;
|
||||||
|
use opentelemetry::metrics::MeterProvider;
|
||||||
|
use opentelemetry_prometheus_text_exporter::PrometheusExporter;
|
||||||
|
use opentelemetry_sdk::{Resource, metrics::SdkMeterProvider};
|
||||||
|
|
||||||
|
pub use metrics::{AppMetrics, UpstreamRequestOutcome};
|
||||||
|
pub use tracing::init_tracing;
|
||||||
|
|
||||||
|
pub struct Telemetry {
|
||||||
|
provider: SdkMeterProvider,
|
||||||
|
exporter: PrometheusExporter,
|
||||||
|
metrics: AppMetrics,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Telemetry {
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(service_name: &str) -> Self {
|
||||||
|
let exporter = PrometheusExporter::builder().build();
|
||||||
|
let provider = SdkMeterProvider::builder()
|
||||||
|
.with_reader(exporter.clone())
|
||||||
|
.with_resource(
|
||||||
|
Resource::builder_empty()
|
||||||
|
.with_service_name(service_name.to_owned())
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.build();
|
||||||
|
let meter = provider.meter(env!("CARGO_PKG_NAME"));
|
||||||
|
let metrics = AppMetrics::new(&meter);
|
||||||
|
|
||||||
|
Self {
|
||||||
|
provider,
|
||||||
|
exporter,
|
||||||
|
metrics,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn metrics(&self) -> AppMetrics {
|
||||||
|
self.metrics.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_prometheus(&self) -> Result<String, AppError> {
|
||||||
|
let mut output = Vec::new();
|
||||||
|
self.exporter
|
||||||
|
.export(&mut output)
|
||||||
|
.map_err(|_| AppError::Internal)?;
|
||||||
|
String::from_utf8(output).map_err(|_| AppError::Internal)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shutdown(self) -> Result<(), AppError> {
|
||||||
|
self.provider.shutdown().map_err(|_| AppError::Internal)
|
||||||
|
}
|
||||||
|
}
|
||||||
11
src/telemetry/tracing.rs
Normal file
11
src/telemetry/tracing.rs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
|
||||||
|
|
||||||
|
pub fn init_tracing() {
|
||||||
|
let env_filter = EnvFilter::try_from_default_env()
|
||||||
|
.unwrap_or_else(|_| EnvFilter::new("pokedex_api=info,tower_http=info"));
|
||||||
|
|
||||||
|
tracing_subscriber::registry()
|
||||||
|
.with(env_filter)
|
||||||
|
.with(tracing_subscriber::fmt::layer().json())
|
||||||
|
.init();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user