//! HTTP is an adapter: parse a request, call one service method, shape a response. pub(crate) mod auth; mod error; mod oauth; mod observability; pub(crate) mod rate_limit; mod repository; pub(crate) mod request; mod runtime; mod security; mod server; mod subscription; use std::time::Duration; use axum::{ Router, error_handling::HandleErrorLayer, extract::DefaultBodyLimit, http::{ HeaderValue, StatusCode, header::{CONTENT_TYPE, RETRY_AFTER}, }, response::{IntoResponse, Response}, routing::{MethodRouter, get, post}, }; use tower::{ BoxError, ServiceBuilder, limit::GlobalConcurrencyLimitLayer, load_shed::LoadShedLayer, timeout::TimeoutLayer, }; use crate::{ AppState, error::{Error, ErrorContext as _}, repository::MAX_BLOB_BYTES, }; pub use crate::error::Result as ApiResult; pub use runtime::{serve, shutdown_signal}; const STRUCTURED_BODY_LIMIT: usize = 2 * 1024 * 1024; const MAX_IN_FLIGHT_REQUESTS: usize = 64; const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Clone, Copy)] struct AdmissionPolicy { max_in_flight: usize, timeout: Duration, } impl AdmissionPolicy { const fn production() -> Self { Self { max_in_flight: MAX_IN_FLIGHT_REQUESTS, timeout: REQUEST_TIMEOUT, } } fn apply(self, router: Router) -> Router { router.layer( ServiceBuilder::new() .layer(HandleErrorLayer::new(admission_error)) .layer(LoadShedLayer::new()) .layer(GlobalConcurrencyLimitLayer::new(self.max_in_flight)) .layer(TimeoutLayer::new(self.timeout)), ) } } async fn admission_error(error: BoxError) -> axum::response::Response { let (status, name, message) = if error.is::() { ( StatusCode::SERVICE_UNAVAILABLE, "RequestTimeout", "request exceeded the server time limit", ) } else if error.is::() { ( StatusCode::SERVICE_UNAVAILABLE, "ServiceUnavailable", "server is at request capacity", ) } else { ( StatusCode::INTERNAL_SERVER_ERROR, "InternalServerError", "request middleware failed", ) }; let mut response = error::response(status, name, message); if status == StatusCode::SERVICE_UNAVAILABLE { response .headers_mut() .insert(RETRY_AFTER, "1".parse().expect("static header is valid")); } response } pub fn router(state: AppState) -> Router { let router = Router::new() .route("/", get(server::index)) .route("/health", get(server::health)) .route("/ready", get(server::ready)) .route("/.well-known/did.json", get(server::did_document)) .route( "/.well-known/oauth-protected-resource", get(oauth::protected_resource_metadata), ) .route( "/.well-known/oauth-authorization-server", get(oauth::authorization_server_metadata), ) .merge(rate_limit::oauth_routes()) .merge(atproto_routes()) .merge(crate::space::routes::routes()) .layer(DefaultBodyLimit::max(STRUCTURED_BODY_LIMIT)) .with_state(state); let router = AdmissionPolicy::production() .apply(router) .layer(axum::middleware::from_fn( error::normalize_framework_rejections, )) .layer(security::cors()) .layer(axum::middleware::from_fn(security::response_headers)); observability::apply(router) } fn atproto_routes() -> Router { use rate_limit::{expensive, protected}; xrpc_routes([ ("server.describeServer", get(server::describe_server)), ("server.getSession", protected(get(server::get_session))), ( "server.activateAccount", protected(post(server::activate_account)), ), ( "server.deactivateAccount", protected(post(server::deactivate_account)), ), ("identity.resolveHandle", get(server::resolve_handle)), ( "repo.createRecord", protected(post(repository::create_record)), ), ("repo.putRecord", protected(post(repository::put_record))), ( "repo.applyWrites", protected(post(repository::apply_writes)), ), ("repo.getRecord", get(repository::get_record)), ("repo.describeRepo", get(repository::describe_repo)), ("repo.listRecords", get(repository::list_records)), ( "repo.listMissingBlobs", protected(get(repository::list_missing_blobs)), ), ( "repo.deleteRecord", protected(post(repository::delete_record)), ), ( "repo.uploadBlob", protected(post(repository::upload_blob).layer(DefaultBodyLimit::max(MAX_BLOB_BYTES))), ), ("sync.getBlob", expensive(get(repository::get_blob))), ("sync.getLatestCommit", get(repository::get_latest_commit)), ("sync.getRepoStatus", get(repository::get_repo_status)), ("sync.getRepo", expensive(get(repository::get_repo))), ( "sync.getRecord", expensive(get(repository::get_sync_record)), ), ("sync.getBlocks", expensive(get(repository::get_blocks))), ("sync.listBlobs", expensive(get(repository::list_blobs))), ("sync.listRepos", get(repository::list_repos)), ( "sync.listReposByCollection", get(repository::list_repos_by_collection), ), ( "sync.subscribeRepos", expensive(get(subscription::subscribe_repos)), ), ]) } pub(crate) fn xrpc_routes( routes: impl IntoIterator)>, ) -> Router { routes .into_iter() .fold(Router::new(), |router, (name, method)| { router.route(&format!("/xrpc/com.atproto.{name}"), method) }) } pub(crate) fn car_response(bytes: Vec) -> Response { ([(CONTENT_TYPE, "application/vnd.ipld.car")], bytes).into_response() } pub(crate) fn blob_response(media_type: &str, bytes: Vec) -> ApiResult { let content_type = HeaderValue::from_str(media_type).context(Error::Internal, "invalid stored MIME type")?; Ok(([(CONTENT_TYPE, content_type)], bytes).into_response()) } #[cfg(test)] mod tests { use std::{future::pending, sync::Arc, time::Duration}; use axum::{ Router, body::{Body, to_bytes}, extract::State, http::{Request, StatusCode, header::RETRY_AFTER}, routing::get, }; use tokio::sync::Notify; use tower::ServiceExt as _; use super::AdmissionPolicy; #[tokio::test] async fn request_timeout_cancels_a_stalled_handler() { let app = AdmissionPolicy { max_in_flight: 1, timeout: Duration::from_millis(10), } .apply(Router::new().route("/", get(|| async { pending::<()>().await }))); let response = app .oneshot(Request::get("/").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(response.headers()[RETRY_AFTER], "1"); assert_eq!(error_name(response).await, "RequestTimeout"); } #[derive(Clone)] struct Gate { entered: Arc, release: Arc, } #[tokio::test] async fn concurrency_limit_sheds_excess_work_without_queueing() { let gate = Gate { entered: Arc::new(Notify::new()), release: Arc::new(Notify::new()), }; let app = AdmissionPolicy { max_in_flight: 1, timeout: Duration::from_secs(5), } .apply( Router::new() .route( "/", get(|State(gate): State| async move { gate.entered.notify_one(); gate.release.notified().await; }), ) .with_state(gate.clone()), ); let first = tokio::spawn( app.clone() .oneshot(Request::get("/").body(Body::empty()).unwrap()), ); gate.entered.notified().await; let overloaded = app .oneshot(Request::get("/").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(overloaded.status(), StatusCode::SERVICE_UNAVAILABLE); assert_eq!(overloaded.headers()[RETRY_AFTER], "1"); assert_eq!(error_name(overloaded).await, "ServiceUnavailable"); gate.release.notify_one(); assert_eq!(first.await.unwrap().unwrap().status(), StatusCode::OK); } async fn error_name(response: axum::response::Response) -> String { let bytes = to_bytes(response.into_body(), 1024).await.unwrap(); serde_json::from_slice::(&bytes).unwrap()["error"] .as_str() .unwrap() .to_owned() } }