Merge pull request '在单个 Axum 进程提供 Bedrock 业务与管理 API' (#26) from codex/backend-admin-architecture into main
Deploy Rust Bedrock / deploy (push) Has been cancelled
Deploy Rust Bedrock / deploy (push) Has been cancelled
Reviewed-on: #26 Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
This commit was merged in pull request #26.
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "admin_backend"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
clusters.workspace = true
|
||||
serde.workspace = true
|
||||
subtle.workspace = true
|
||||
@@ -0,0 +1,101 @@
|
||||
use std::{io, sync::Arc};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{Request, State},
|
||||
http::{HeaderMap, StatusCode, header},
|
||||
middleware::{self, Next},
|
||||
response::{IntoResponse, Response},
|
||||
routing::get,
|
||||
};
|
||||
use clusters::{Driver, ResolvedDeployment};
|
||||
use serde::Serialize;
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AdminState {
|
||||
config: Arc<ResolvedDeployment>,
|
||||
config_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct DeploymentStatus<'a> {
|
||||
deployment: &'a str,
|
||||
config_version: Option<&'a str>,
|
||||
storage_driver: &'static str,
|
||||
read_only: bool,
|
||||
}
|
||||
|
||||
impl AdminState {
|
||||
fn status(&self) -> DeploymentStatus<'_> {
|
||||
let config = &self.config;
|
||||
DeploymentStatus {
|
||||
deployment: &config.deployment,
|
||||
config_version: self.config_version.as_deref(),
|
||||
storage_driver: match config.driver {
|
||||
Driver::Sqlite => "sqlite",
|
||||
Driver::Postgres => "postgres",
|
||||
Driver::Mysql => "mysql",
|
||||
},
|
||||
read_only: config.read_only,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router(
|
||||
config: Arc<ResolvedDeployment>,
|
||||
config_version: Option<String>,
|
||||
token: String,
|
||||
) -> io::Result<Router> {
|
||||
if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"BEDROCK_ADMIN_TOKEN must contain visible ASCII characters without spaces",
|
||||
));
|
||||
}
|
||||
|
||||
let admin = Router::new()
|
||||
.route("/status", get(deployment_status))
|
||||
.route_layer(middleware::from_fn_with_state(
|
||||
Arc::<str>::from(token),
|
||||
require_admin,
|
||||
));
|
||||
Ok(Router::new()
|
||||
.route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
|
||||
.route("/readyz", get(|| async { StatusCode::NO_CONTENT }))
|
||||
.nest("/admin/v1", admin)
|
||||
.with_state(AdminState {
|
||||
config,
|
||||
config_version,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn deployment_status(State(state): State<AdminState>) -> Response {
|
||||
([(header::CACHE_CONTROL, "no-store")], Json(state.status())).into_response()
|
||||
}
|
||||
|
||||
async fn require_admin(State(token): State<Arc<str>>, request: Request, next: Next) -> Response {
|
||||
if authorized(request.headers(), &token) {
|
||||
next.run(request).await
|
||||
} else {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, "Bearer")],
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
fn authorized(headers: &HeaderMap, token: &str) -> bool {
|
||||
let mut values = headers.get_all(header::AUTHORIZATION).iter();
|
||||
let Some(value) = values.next().and_then(|value| value.to_str().ok()) else {
|
||||
return false;
|
||||
};
|
||||
if values.next().is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some((scheme, supplied)) = value.split_once(' ') else {
|
||||
return false;
|
||||
};
|
||||
scheme.eq_ignore_ascii_case("Bearer") && bool::from(supplied.as_bytes().ct_eq(token.as_bytes()))
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "backend"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
admin_backend = { path = "../admin_backend" }
|
||||
axum.workspace = true
|
||||
db.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "signal", "sync", "time"] }
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::{env, error::Error, fs, io, net::SocketAddr, sync::Arc};
|
||||
|
||||
use axum::Router;
|
||||
use db::{DeploymentConfig, connect_resolved};
|
||||
use tokio::{net::TcpListener, sync::watch};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")?
|
||||
.as_deref()
|
||||
.unwrap_or("127.0.0.1:8080")
|
||||
.parse()?;
|
||||
let config = match env::var_os("BEDROCK_DB_CONFIG") {
|
||||
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
|
||||
None => DeploymentConfig::default(),
|
||||
};
|
||||
let config = Arc::new(config.resolve()?);
|
||||
|
||||
let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?;
|
||||
let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? {
|
||||
Some(token) => {
|
||||
let address: SocketAddr = admin_address
|
||||
.as_deref()
|
||||
.unwrap_or("127.0.0.1:8081")
|
||||
.parse()?;
|
||||
let router = admin_backend::router(
|
||||
Arc::clone(&config),
|
||||
optional_env("BEDROCK_CONFIG_VERSION")?,
|
||||
token,
|
||||
)?;
|
||||
Some((TcpListener::bind(address).await?, router))
|
||||
}
|
||||
None if admin_address.is_some() => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"BEDROCK_ADMIN_LISTEN requires BEDROCK_ADMIN_TOKEN",
|
||||
)
|
||||
.into());
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let listener = TcpListener::bind(address).await?;
|
||||
let db = connect_resolved(&config).await?;
|
||||
println!("Bedrock backend listening on {}", listener.local_addr()?);
|
||||
|
||||
let (stop, shutdown_signal) = watch::channel(false);
|
||||
tokio::spawn(async move {
|
||||
shutdown().await;
|
||||
stop.send_replace(true);
|
||||
});
|
||||
|
||||
if let Some((admin_listener, admin_router)) = admin {
|
||||
println!("Bedrock admin listener on {}", admin_listener.local_addr()?);
|
||||
tokio::try_join!(
|
||||
serve(listener, backend::router(db), shutdown_signal.clone()),
|
||||
serve(admin_listener, admin_router, shutdown_signal),
|
||||
)?;
|
||||
} else {
|
||||
serve(listener, backend::router(db), shutdown_signal).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
|
||||
match env::var(name) {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(env::VarError::NotPresent) => Ok(None),
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
listener: TcpListener,
|
||||
router: Router,
|
||||
mut shutdown_signal: watch::Receiver<bool>,
|
||||
) -> io::Result<()> {
|
||||
axum::serve(listener, router)
|
||||
.with_graceful_shutdown(async move {
|
||||
let _ = shutdown_signal.wait_for(|stop| *stop).await;
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -44,6 +44,10 @@ pub struct Connection {
|
||||
|
||||
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
|
||||
let config = config.resolve()?;
|
||||
Ok(connect_resolved(&config).await?)
|
||||
}
|
||||
|
||||
pub async fn connect_resolved(config: &ResolvedDeployment) -> Result<Connection, StorageError> {
|
||||
let writer = if config.read_only {
|
||||
None
|
||||
} else {
|
||||
@@ -60,7 +64,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
Some(Writer::Sql(store)) => store.reader(),
|
||||
Some(Writer::MySql(store)) => store.reader(),
|
||||
None => {
|
||||
let reader = reader(&config, &config.primary)?;
|
||||
let reader = reader(config, &config.primary)?;
|
||||
reader.revision().await?;
|
||||
reader
|
||||
}
|
||||
@@ -68,7 +72,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
|
||||
let replicas = config
|
||||
.replicas
|
||||
.iter()
|
||||
.map(|address| reader(&config, address))
|
||||
.map(|address| reader(config, address))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(Connection {
|
||||
driver: config.driver,
|
||||
|
||||
@@ -9,7 +9,7 @@ pub mod sqlite;
|
||||
|
||||
pub use self::documents::StoredDocument;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, connect};
|
||||
pub use connection::{ConnectError, Connection, ReadPreference, connect, connect_resolved};
|
||||
pub use mysql::{Lease, MySql};
|
||||
|
||||
pub use common::Error as StorageError;
|
||||
|
||||
Reference in New Issue
Block a user