2021-07-09 21:36:14 +02:00
|
|
|
//! Simple in-memory key/value store showing features of axum.
|
2021-06-08 12:43:16 +02:00
|
|
|
//!
|
|
|
|
//! 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::{
|
2021-07-22 13:23:50 +02:00
|
|
|
async_trait,
|
|
|
|
extract::{extractor_middleware, ContentLengthLimit, Extension, RequestParts, UrlParams},
|
2021-06-13 11:22:02 +02:00
|
|
|
prelude::*,
|
|
|
|
response::IntoResponse,
|
|
|
|
routing::BoxRoute,
|
2021-07-05 16:18:39 +02:00
|
|
|
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::{
|
2021-06-08 12:43:16 +02:00
|
|
|
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,
|
2021-06-08 12:43:16 +02:00
|
|
|
sync::{Arc, RwLock},
|
2021-05-30 14:33:20 +02:00
|
|
|
time::Duration,
|
|
|
|
};
|
2021-06-12 21:44:40 +02:00
|
|
|
use tower::{BoxError, ServiceBuilder};
|
2021-05-30 14:33:20 +02:00
|
|
|
use tower_http::{
|
2021-07-22 13:23:50 +02:00
|
|
|
add_extension::AddExtensionLayer, compression::CompressionLayer, trace::TraceLayer,
|
2021-05-30 14:33:20 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
tracing_subscriber::fmt::init();
|
|
|
|
|
2021-06-08 12:43:16 +02:00
|
|
|
// Build our application by composing routes
|
2021-06-04 01:00:48 +02:00
|
|
|
let app = route(
|
|
|
|
"/:key",
|
2021-06-08 12:43:16 +02:00
|
|
|
// 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
|
2021-07-05 16:18:39 +02:00
|
|
|
.handle_error(handle_error)
|
|
|
|
.check_infallible();
|
2021-05-30 14:33:20 +02:00
|
|
|
|
2021-06-08 12:43:16 +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
|
|
|
}
|
|
|
|
|
2021-06-08 12:43:16 +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> {
|
2021-06-08 12:43:16 +02:00
|
|
|
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-08 12:43:16 +02:00
|
|
|
}
|
|
|
|
|
2021-06-09 09:03:09 +02:00
|
|
|
async fn list_keys(Extension(state): Extension<SharedState>) -> String {
|
2021-06-08 12:43:16 +02:00
|
|
|
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>) {
|
2021-06-08 12:43:16 +02:00
|
|
|
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
|
2021-07-22 13:23:50 +02:00
|
|
|
.layer(extractor_middleware::<RequireAuth>())
|
2021-06-08 12:43:16 +02:00
|
|
|
.boxed()
|
|
|
|
}
|
|
|
|
|
2021-07-22 13:23:50 +02:00
|
|
|
/// 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> {
|
2021-06-08 12:43:16 +02:00
|
|
|
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")));
|
2021-06-08 12:43:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
if error.is::<tower::load_shed::error::Overloaded>() {
|
2021-07-22 15:00:33 +02:00
|
|
|
return Ok((
|
2021-06-08 12:43:16 +02:00
|
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
|
|
Cow::from("service is overloaded, try again later"),
|
2021-07-22 15:00:33 +02:00
|
|
|
));
|
2021-06-08 12:43:16 +02:00
|
|
|
}
|
|
|
|
|
2021-07-22 15:00:33 +02:00
|
|
|
Ok((
|
2021-06-08 12:43:16 +02:00
|
|
|
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
|
|
|
}
|