Files
axum/examples/key-value-store/src/main.rs
T

150 lines
4.3 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
//! cargo run -p example-key-value-store
//! ```
2021-07-09 21:36:14 +02:00
use axum::{
body::Bytes,
2021-10-24 19:33:03 +02:00
error_handling::HandleErrorLayer,
2022-09-24 13:29:53 +02:00
extract::{DefaultBodyLimit, Path, State},
handler::Handler,
http::StatusCode,
2021-06-13 11:22:02 +02:00
response::IntoResponse,
routing::{delete, get},
Router,
2021-06-13 11:22:02 +02:00
};
2021-05-30 14:33:20 +02:00
use std::{
borrow::Cow,
2021-05-30 14:33:20 +02:00
collections::HashMap,
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::{
2023-02-24 21:51:30 +01:00
compression::CompressionLayer, limit::RequestBodyLimitLayer, trace::TraceLayer,
validate_request::ValidateRequestHeaderLayer,
2021-05-30 14:33:20 +02:00
};
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-05-30 14:33:20 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()
}),
)
2022-03-06 12:37:00 +01:00
.with(tracing_subscriber::fmt::layer())
.init();
2021-05-30 14:33:20 +02:00
2022-08-17 17:13:31 +02:00
let shared_state = SharedState::default();
// Build our application by composing routes
2022-11-18 12:02:58 +01:00
let app = Router::new()
.route(
2024-10-03 17:46:58 +02:00
"/{key}",
// Add compression to `kv_get`
get(kv_get.layer(CompressionLayer::new()))
// But don't compress `kv_set`
2022-09-24 13:29:53 +02:00
.post_service(
kv_set
.layer((
DefaultBodyLimit::disable(),
RequestBodyLimitLayer::new(1024 * 5_000 /* ~5mb */),
))
.with_state(Arc::clone(&shared_state)),
2022-09-24 13:29:53 +02:00
),
)
.route("/keys", get(list_keys))
// Nest our admin routes under `/admin`
2022-11-18 12:02:58 +01:00
.nest("/admin", admin_routes())
// Add middleware to all routes
.layer(
ServiceBuilder::new()
2021-10-24 19:33:03 +02:00
// Handle errors from middleware
.layer(HandleErrorLayer::new(handle_error))
.load_shed()
.concurrency_limit(1024)
.timeout(Duration::from_secs(10))
2022-11-18 12:02:58 +01:00
.layer(TraceLayer::new_for_http()),
)
.with_state(Arc::clone(&shared_state));
2021-05-30 14:33:20 +02:00
// Run our app with hyper
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
2021-06-19 12:50:33 +02:00
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await.unwrap();
2021-05-30 14:33:20 +02:00
}
2022-08-17 17:13:31 +02:00
type SharedState = Arc<RwLock<AppState>>;
2021-05-30 14:33:20 +02:00
#[derive(Default)]
2022-08-17 17:13:31 +02:00
struct AppState {
2021-05-30 14:33:20 +02:00
db: HashMap<String, Bytes>,
}
2021-06-04 01:00:48 +02:00
async fn kv_get(
2021-08-06 16:17:57 +08:00
Path(key): Path<String>,
2022-08-17 17:13:31 +02:00
State(state): State<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
}
}
2022-09-24 13:29:53 +02:00
async fn kv_set(Path(key): Path<String>, State(state): State<SharedState>, bytes: Bytes) {
2021-06-09 08:14:20 +02:00
state.write().unwrap().db.insert(key, bytes);
}
2022-08-17 17:13:31 +02:00
async fn list_keys(State(state): State<SharedState>) -> String {
let db = &state.read().unwrap().db;
db.keys()
.map(|key| key.to_string())
.collect::<Vec<String>>()
.join("\n")
}
2022-11-18 12:02:58 +01:00
fn admin_routes() -> Router<SharedState> {
2022-08-17 17:13:31 +02:00
async fn delete_all_keys(State(state): State<SharedState>) {
state.write().unwrap().db.clear();
}
2022-08-17 17:13:31 +02:00
async fn remove_key(Path(key): Path<String>, State(state): State<SharedState>) {
state.write().unwrap().db.remove(&key);
}
2022-11-18 12:02:58 +01:00
Router::new()
.route("/keys", delete(delete_all_keys))
2024-10-03 17:46:58 +02:00
.route("/key/{key}", delete(remove_key))
// Require bearer auth for all admin routes
2023-02-24 21:51:30 +01:00
.layer(ValidateRequestHeaderLayer::bearer("secret-token"))
}
async fn handle_error(error: BoxError) -> impl IntoResponse {
if error.is::<tower::timeout::error::Elapsed>() {
2021-10-24 19:33:03 +02:00
return (StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out"));
}
if error.is::<tower::load_shed::error::Overloaded>() {
2021-10-24 19:33:03 +02:00
return (
StatusCode::SERVICE_UNAVAILABLE,
Cow::from("service is overloaded, try again later"),
2021-10-24 19:33:03 +02:00
);
}
2021-10-24 19:33:03 +02:00
(
StatusCode::INTERNAL_SERVER_ERROR,
2023-09-19 02:51:57 -04:00
Cow::from(format!("Unhandled internal error: {error}")),
2021-10-24 19:33:03 +02:00
)
2021-05-30 14:33:20 +02:00
}