Serve business and admin routes from one backend process

This commit is contained in:
2026-11-30 18:24:21 +08:00
parent 296fb9b1b7
commit 6469d3aad6
9 changed files with 122 additions and 98 deletions
Generated
+1 -2
View File
@@ -9,9 +9,7 @@ dependencies = [
"axum", "axum",
"clusters", "clusters",
"serde", "serde",
"serde_json",
"subtle", "subtle",
"tokio",
] ]
[[package]] [[package]]
@@ -93,6 +91,7 @@ dependencies = [
name = "backend" name = "backend"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"admin_backend",
"axum", "axum",
"db", "db",
"serde_json", "serde_json",
+17 -16
View File
@@ -8,27 +8,28 @@ Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has i
Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake) Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake)
## Web backends ## Web backend
The workspace has two independently started Axum services. Run the packages Run the Axum service with `cargo run --locked -p backend`. One process owns
with `cargo run --locked -p backend` and `cargo run --locked -p admin_backend` the database connection, loads one deployment configuration, and serves
in a development environment. separate routers on the business and optional admin listeners.
| Package | Listen setting and default | Routes | | Listener | Setting and default | Routes |
|---|---|---| |---|---|---|
| `backend` | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` | | Business | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` |
| `admin_backend` | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` | | Admin | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` when enabled | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` |
Both services use the `BEDROCK_DB_CONFIG` setting described below. The business The business readiness probe checks access to the current deployment revision.
service opens storage at startup and verifies access to the current deployment Set `BEDROCK_ADMIN_TOKEN` from a private credential source to enable the admin
revision in its readiness handler. The admin service resolves the deployment listener. Send it as `Authorization: Bearer <token>` for the status endpoint.
configuration at startup. Its status endpoint reports the configured deployment, Keep the admin listener on loopback or behind an internal TLS endpoint.
storage driver, read-only mode, and optional `BEDROCK_CONFIG_VERSION`.
Set `BEDROCK_ADMIN_TOKEN` from a private credential source before starting The `admin_backend` library reports the deployment, storage driver, read-only
`admin_backend`. Send it as `Authorization: Bearer <token>` for the status mode, and optional `BEDROCK_CONFIG_VERSION` for the instance that served the
endpoint. Keep the admin listener on loopback or behind an internal TLS endpoint. request. It reads the same resolved configuration that the process used to open
The root `bedrock` binary remains the one-shot storage initializer. the database. Give every replica the same config file and version label through
your deployment process. The root `bedrock` binary remains the one-shot storage
initializer.
## Database configuration ## Database configuration
-2
View File
@@ -8,6 +8,4 @@ rust-version.workspace = true
axum.workspace = true axum.workspace = true
clusters.workspace = true clusters.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true
subtle.workspace = true subtle.workspace = true
tokio = { workspace = true, features = ["net", "signal"] }
+26 -12
View File
@@ -12,19 +12,26 @@ use clusters::{Driver, ResolvedDeployment};
use serde::Serialize; use serde::Serialize;
use subtle::ConstantTimeEq; use subtle::ConstantTimeEq;
#[derive(Clone, Serialize)] #[derive(Clone)]
pub struct DeploymentStatus { struct AdminState {
deployment: String, config: Arc<ResolvedDeployment>,
config_version: Option<String>, config_version: Option<String>,
}
#[derive(Serialize)]
struct DeploymentStatus<'a> {
deployment: &'a str,
config_version: Option<&'a str>,
storage_driver: &'static str, storage_driver: &'static str,
read_only: bool, read_only: bool,
} }
impl DeploymentStatus { impl AdminState {
pub fn new(config: ResolvedDeployment, config_version: Option<String>) -> Self { fn status(&self) -> DeploymentStatus<'_> {
Self { let config = &self.config;
deployment: config.deployment, DeploymentStatus {
config_version, deployment: &config.deployment,
config_version: self.config_version.as_deref(),
storage_driver: match config.driver { storage_driver: match config.driver {
Driver::Sqlite => "sqlite", Driver::Sqlite => "sqlite",
Driver::Postgres => "postgres", Driver::Postgres => "postgres",
@@ -35,7 +42,11 @@ impl DeploymentStatus {
} }
} }
pub fn router(status: DeploymentStatus, token: String) -> io::Result<Router> { 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()) { if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) {
return Err(io::Error::new( return Err(io::Error::new(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
@@ -53,11 +64,14 @@ pub fn router(status: DeploymentStatus, token: String) -> io::Result<Router> {
.route("/healthz", get(|| async { StatusCode::NO_CONTENT })) .route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
.route("/readyz", get(|| async { StatusCode::NO_CONTENT })) .route("/readyz", get(|| async { StatusCode::NO_CONTENT }))
.nest("/admin/v1", admin) .nest("/admin/v1", admin)
.with_state(status)) .with_state(AdminState {
config,
config_version,
}))
} }
async fn deployment_status(State(status): State<DeploymentStatus>) -> impl IntoResponse { async fn deployment_status(State(state): State<AdminState>) -> Response {
([(header::CACHE_CONTROL, "no-store")], Json(status)) ([(header::CACHE_CONTROL, "no-store")], Json(state.status())).into_response()
} }
async fn require_admin(State(token): State<Arc<str>>, request: Request, next: Next) -> Response { async fn require_admin(State(token): State<Arc<str>>, request: Request, next: Next) -> Response {
-50
View File
@@ -1,50 +0,0 @@
use std::{env, error::Error, fs, net::SocketAddr};
use admin_backend::{DeploymentStatus, router};
use clusters::DeploymentConfig;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let address: SocketAddr = env::var("BEDROCK_ADMIN_LISTEN")
.or_else(|error| match error {
env::VarError::NotPresent => Ok("127.0.0.1:8081".to_owned()),
error => Err(error),
})?
.parse()?;
let token = env::var("BEDROCK_ADMIN_TOKEN")?;
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
None => DeploymentConfig::default(),
};
let version = match env::var("BEDROCK_CONFIG_VERSION") {
Ok(version) => Some(version),
Err(env::VarError::NotPresent) => None,
Err(error) => return Err(error.into()),
};
let router = router(DeploymentStatus::new(config.resolve()?, version), token)?;
let listener = TcpListener::bind(address).await?;
println!(
"Bedrock admin backend listening on {}",
listener.local_addr()?
);
axum::serve(listener, router)
.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;
}
+2 -1
View File
@@ -5,7 +5,8 @@ edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
[dependencies] [dependencies]
admin_backend = { path = "../admin_backend" }
axum.workspace = true axum.workspace = true
db.workspace = true db.workspace = true
serde_json.workspace = true serde_json.workspace = true
tokio = { workspace = true, features = ["net", "signal", "time"] } tokio = { workspace = true, features = ["net", "signal", "sync", "time"] }
+69 -12
View File
@@ -1,30 +1,87 @@
use std::{env, error::Error, fs, net::SocketAddr}; use std::{env, error::Error, fs, io, net::SocketAddr, sync::Arc};
use db::{DeploymentConfig, connect}; use axum::Router;
use tokio::net::TcpListener; use db::{DeploymentConfig, connect_resolved};
use tokio::{net::TcpListener, sync::watch};
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let address: SocketAddr = env::var("BEDROCK_BACKEND_LISTEN") let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")?
.or_else(|error| match error { .as_deref()
env::VarError::NotPresent => Ok("127.0.0.1:8080".to_owned()), .unwrap_or("127.0.0.1:8080")
error => Err(error),
})?
.parse()?; .parse()?;
let config = match env::var_os("BEDROCK_DB_CONFIG") { let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?, Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
None => DeploymentConfig::default(), 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 db = connect(&config).await?;
let listener = TcpListener::bind(address).await?; let listener = TcpListener::bind(address).await?;
let db = connect_resolved(&config).await?;
println!("Bedrock backend listening on {}", listener.local_addr()?); println!("Bedrock backend listening on {}", listener.local_addr()?);
axum::serve(listener, backend::router(db))
.with_graceful_shutdown(shutdown()) let (stop, shutdown_signal) = watch::channel(false);
.await?; 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(()) 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() { async fn shutdown() {
#[cfg(unix)] #[cfg(unix)]
{ {
+6 -2
View File
@@ -44,6 +44,10 @@ pub struct Connection {
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> { pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
let config = config.resolve()?; 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 { let writer = if config.read_only {
None None
} else { } else {
@@ -60,7 +64,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
Some(Writer::Sql(store)) => store.reader(), Some(Writer::Sql(store)) => store.reader(),
Some(Writer::MySql(store)) => store.reader(), Some(Writer::MySql(store)) => store.reader(),
None => { None => {
let reader = reader(&config, &config.primary)?; let reader = reader(config, &config.primary)?;
reader.revision().await?; reader.revision().await?;
reader reader
} }
@@ -68,7 +72,7 @@ pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectErr
let replicas = config let replicas = config
.replicas .replicas
.iter() .iter()
.map(|address| reader(&config, address)) .map(|address| reader(config, address))
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
Ok(Connection { Ok(Connection {
driver: config.driver, driver: config.driver,
+1 -1
View File
@@ -7,7 +7,7 @@ pub mod postgres;
pub mod sqlite; pub mod sqlite;
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, Tls}; 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 mysql::{Lease, MySql};
pub use common::Error as StorageError; pub use common::Error as StorageError;