axum/examples/key_value_store.rs

173 lines
4.6 KiB
Rust
Raw Normal View History

2021-07-09 21:36:14 +02:00
//! Simple in-memory key/value store showing features of axum.
//!
//! Run with:
//!
//! ```not_rust
//! RUST_LOG=tower_http=debug,key_value_store=trace cargo run --example key_value_store
//! ```
2021-07-09 21:36:14 +02:00
use axum::{
async_trait,
extract::{extractor_middleware, ContentLengthLimit, Extension, RequestParts, UrlParams},
2021-06-13 11:22:02 +02:00
prelude::*,
response::IntoResponse,
routing::BoxRoute,
service::ServiceExt,
2021-06-13 11:22:02 +02:00
};
2021-05-30 14:33:20 +02:00
use bytes::Bytes;
2021-06-09 09:03:09 +02:00
use http::StatusCode;
2021-05-30 14:33:20 +02:00
use std::{
borrow::Cow,
2021-05-30 14:33:20 +02:00
collections::HashMap,
2021-07-22 15:00:33 +02:00
convert::Infallible,
2021-05-30 14:33:20 +02:00
net::SocketAddr,
sync::{Arc, RwLock},
2021-05-30 14:33:20 +02:00
time::Duration,
};
use tower::{BoxError, ServiceBuilder};
2021-05-30 14:33:20 +02:00
use tower_http::{
add_extension::AddExtensionLayer, compression::CompressionLayer, trace::TraceLayer,
2021-05-30 14:33:20 +02:00
};
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
// Build our application by composing routes
2021-06-04 01:00:48 +02:00
let app = route(
"/:key",
// Add compression to `kv_get`
get(kv_get.layer(CompressionLayer::new()))
// But don't compress `kv_set`
.post(kv_set),
)
.route("/keys", get(list_keys))
// Nest our admin routes under `/admin`
.nest("/admin", admin_routes())
// Add middleware to all routes
.layer(
ServiceBuilder::new()
.load_shed()
.concurrency_limit(1024)
.timeout(Duration::from_secs(10))
.layer(TraceLayer::new_for_http())
.layer(AddExtensionLayer::new(SharedState::default()))
.into_inner(),
)
// Handle errors from middleware
.handle_error(handle_error)
.check_infallible();
2021-05-30 14:33:20 +02:00
// Run our app with hyper
2021-05-30 14:33:20 +02:00
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
2021-06-19 12:50:33 +02:00
hyper::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
2021-05-30 14:33:20 +02:00
}
type SharedState = Arc<RwLock<State>>;
2021-05-30 14:33:20 +02:00
#[derive(Default)]
struct State {
db: HashMap<String, Bytes>,
}
2021-06-04 01:00:48 +02:00
async fn kv_get(
2021-06-01 15:07:16 +02:00
UrlParams((key,)): UrlParams<(String,)>,
Extension(state): Extension<SharedState>,
2021-06-01 00:34:09 +02:00
) -> Result<Bytes, StatusCode> {
let db = &state.read().unwrap().db;
2021-05-30 14:33:20 +02:00
2021-05-30 16:53:27 +02:00
if let Some(value) = db.get(&key) {
2021-05-30 14:33:20 +02:00
Ok(value.clone())
} else {
2021-06-01 00:34:09 +02:00
Err(StatusCode::NOT_FOUND)
2021-05-30 14:33:20 +02:00
}
}
2021-06-04 01:00:48 +02:00
async fn kv_set(
2021-06-01 15:07:16 +02:00
UrlParams((key,)): UrlParams<(String,)>,
2021-06-09 08:14:20 +02:00
ContentLengthLimit(bytes): ContentLengthLimit<Bytes, { 1024 * 5_000 }>, // ~5mb
2021-06-01 15:07:16 +02:00
Extension(state): Extension<SharedState>,
2021-05-31 22:54:21 +02:00
) {
2021-06-09 08:14:20 +02:00
state.write().unwrap().db.insert(key, bytes);
}
2021-06-09 09:03:09 +02:00
async fn list_keys(Extension(state): Extension<SharedState>) -> String {
let db = &state.read().unwrap().db;
db.keys()
.map(|key| key.to_string())
.collect::<Vec<String>>()
.join("\n")
}
2021-06-19 12:50:33 +02:00
fn admin_routes() -> BoxRoute<hyper::Body> {
2021-06-09 09:03:09 +02:00
async fn delete_all_keys(Extension(state): Extension<SharedState>) {
state.write().unwrap().db.clear();
}
async fn remove_key(
UrlParams((key,)): UrlParams<(String,)>,
Extension(state): Extension<SharedState>,
) {
state.write().unwrap().db.remove(&key);
}
route("/keys", delete(delete_all_keys))
.route("/key/:key", delete(remove_key))
// Require beare auth for all admin routes
.layer(extractor_middleware::<RequireAuth>())
.boxed()
}
/// An extractor that performs authorization.
// TODO: when https://github.com/hyperium/http-body/pull/46 is merged we can use
// `tower_http::auth::RequireAuthorization` instead
struct RequireAuth;
#[async_trait]
impl<B> extract::FromRequest<B> for RequireAuth
where
B: Send,
{
type Rejection = StatusCode;
async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let auth_header = req
.headers()
.and_then(|headers| headers.get(http::header::AUTHORIZATION))
.and_then(|value| value.to_str().ok());
if let Some(value) = auth_header {
if let Some(token) = value.strip_prefix("Bearer ") {
if token == "secret-token" {
return Ok(Self);
}
}
}
Err(StatusCode::UNAUTHORIZED)
}
}
2021-07-22 15:00:33 +02:00
fn handle_error(error: BoxError) -> Result<impl IntoResponse, Infallible> {
if error.is::<tower::timeout::error::Elapsed>() {
2021-07-22 15:00:33 +02:00
return Ok((StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out")));
}
if error.is::<tower::load_shed::error::Overloaded>() {
2021-07-22 15:00:33 +02:00
return Ok((
StatusCode::SERVICE_UNAVAILABLE,
Cow::from("service is overloaded, try again later"),
2021-07-22 15:00:33 +02:00
));
}
2021-07-22 15:00:33 +02:00
Ok((
StatusCode::INTERNAL_SERVER_ERROR,
Cow::from(format!("Unhandled internal error: {}", error)),
2021-07-22 15:00:33 +02:00
))
2021-05-30 14:33:20 +02:00
}