Add initial Axum application and admin backends

This commit is contained in:
2026-11-30 18:02:10 +08:00
parent 698f126033
commit 296fb9b1b7
9 changed files with 465 additions and 0 deletions
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "backend"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
axum.workspace = true
db.workspace = true
serde_json.workspace = true
tokio = { workspace = true, features = ["net", "signal", "time"] }
+17
View File
@@ -0,0 +1,17 @@
use std::{sync::Arc, time::Duration};
use axum::{Router, extract::State, http::StatusCode, routing::get};
pub fn router(db: db::Connection) -> Router {
Router::new()
.route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
.route("/readyz", get(readiness))
.with_state(Arc::new(db))
}
async fn readiness(State(db): State<Arc<db::Connection>>) -> StatusCode {
match tokio::time::timeout(Duration::from_secs(2), db.revision()).await {
Ok(Ok(_)) => StatusCode::NO_CONTENT,
_ => StatusCode::SERVICE_UNAVAILABLE,
}
}
+41
View File
@@ -0,0 +1,41 @@
use std::{env, error::Error, fs, net::SocketAddr};
use db::{DeploymentConfig, connect};
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let address: SocketAddr = env::var("BEDROCK_BACKEND_LISTEN")
.or_else(|error| match error {
env::VarError::NotPresent => Ok("127.0.0.1:8080".to_owned()),
error => Err(error),
})?
.parse()?;
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
None => DeploymentConfig::default(),
};
let db = connect(&config).await?;
let listener = TcpListener::bind(address).await?;
println!("Bedrock backend listening on {}", listener.local_addr()?);
axum::serve(listener, backend::router(db))
.with_graceful_shutdown(shutdown())
.await?;
Ok(())
}
async fn shutdown() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
if let Ok(mut terminate) = signal(SignalKind::terminate()) {
tokio::select! {
_ = terminate.recv() => {},
_ = tokio::signal::ctrl_c() => {},
}
return;
}
}
let _ = tokio::signal::ctrl_c().await;
}