server: snapshot

This commit is contained in:
nym21
2026-01-12 12:34:30 +01:00
parent 1b9e18f98b
commit b12a72ea1a
24 changed files with 3619 additions and 5378 deletions
+9 -47
View File
@@ -1,25 +1,24 @@
use std::{borrow::Cow, sync::Arc};
use std::sync::Arc;
use aide::{
axum::{ApiRouter, routing::get_with},
axum::ApiRouter,
openapi::OpenApi,
};
use axum::{
Extension, Json,
extract::State,
Extension,
http::HeaderMap,
response::{Html, Redirect, Response},
routing::get,
};
use brk_types::Health;
use crate::{
CacheStrategy, VERSION,
VERSION,
api::{
addresses::AddressRoutes, blocks::BlockRoutes, mempool::MempoolRoutes,
metrics::ApiMetricsRoutes, mining::MiningRoutes, transactions::TxRoutes,
metrics::ApiMetricsRoutes, mining::MiningRoutes, server::ServerRoutes,
transactions::TxRoutes,
},
extended::{HeaderMapExtended, ResponseExtended, TransformResponseExtended},
extended::{HeaderMapExtended, ResponseExtended},
};
use super::AppState;
@@ -30,6 +29,7 @@ mod mempool;
mod metrics;
mod mining;
mod openapi;
mod server;
mod transactions;
pub use openapi::*;
@@ -46,46 +46,8 @@ impl ApiRoutes for ApiRouter<AppState> {
.add_mining_routes()
.add_tx_routes()
.add_metrics_routes()
.add_server_routes()
.route("/api/server", get(Redirect::temporary("/api#tag/server")))
.api_route(
"/version",
get_with(
async |headers: HeaderMap, State(state): State<AppState>| {
state
.cached_json(&headers, CacheStrategy::Static, |_| {
Ok(env!("CARGO_PKG_VERSION"))
})
.await
},
|op| {
op.id("get_version")
.server_tag()
.summary("API version")
.description("Returns the current version of the API server")
.ok_response::<String>()
.not_modified()
},
),
)
.api_route(
"/health",
get_with(
async || -> Json<Health> {
Json(Health {
status: Cow::Borrowed("healthy"),
service: Cow::Borrowed("brk"),
timestamp: jiff::Timestamp::now().to_string(),
})
},
|op| {
op.id("get_health")
.server_tag()
.summary("Health check")
.description("Returns the health status of the API server")
.ok_response::<Health>()
},
),
)
.route(
"/api.json",
get(
+174
View File
@@ -0,0 +1,174 @@
use std::{borrow::Cow, fs, path};
use aide::axum::{ApiRouter, routing::get_with};
use axum::{extract::State, http::HeaderMap};
use brk_types::{DiskUsage, Health, Height, SyncStatus};
use vecdb::GenericStoredVec;
use crate::{CacheStrategy, extended::TransformResponseExtended};
use super::AppState;
pub trait ServerRoutes {
fn add_server_routes(self) -> Self;
}
impl ServerRoutes for ApiRouter<AppState> {
fn add_server_routes(self) -> Self {
self.api_route(
"/api/server/sync",
get_with(
async |headers: HeaderMap, State(state): State<AppState>| {
let tip_height = state.client.get_last_height();
state
.cached_json(&headers, CacheStrategy::Height, move |q| {
let indexed_height = q.height();
let tip_height = tip_height?;
let blocks_behind = Height::from(tip_height.saturating_sub(*indexed_height));
let last_indexed_at_unix = q
.indexer()
.vecs
.blocks
.timestamp
.read_once(indexed_height)?;
Ok(SyncStatus {
indexed_height,
tip_height,
blocks_behind,
last_indexed_at: last_indexed_at_unix.to_iso8601(),
last_indexed_at_unix,
})
})
.await
},
|op| {
op.id("get_sync_status")
.server_tag()
.summary("Sync status")
.description(
"Returns the sync status of the indexer, including indexed height, \
tip height, blocks behind, and last indexed timestamp.",
)
.ok_response::<SyncStatus>()
.not_modified()
},
),
)
.api_route(
"/api/server/disk",
get_with(
async |headers: HeaderMap, State(state): State<AppState>| {
let brk_path = state.data_path.clone();
state
.cached_json(&headers, CacheStrategy::Height, move |q| {
let brk_bytes = dir_size(&brk_path)?;
let bitcoin_bytes = dir_size(q.blocks_dir())?;
Ok(DiskUsage::new(brk_bytes, bitcoin_bytes))
})
.await
},
|op| {
op.id("get_disk_usage")
.server_tag()
.summary("Disk usage")
.description(
"Returns the disk space used by the indexed data.",
)
.ok_response::<DiskUsage>()
.not_modified()
},
),
)
.api_route(
"/health",
get_with(
async |State(state): State<AppState>| -> axum::Json<Health> {
let uptime = state.started_instant.elapsed();
axum::Json(Health {
status: Cow::Borrowed("healthy"),
service: Cow::Borrowed("brk"),
timestamp: jiff::Timestamp::now().to_string(),
started_at: state.started_at.to_string(),
uptime_seconds: uptime.as_secs(),
})
},
|op| {
op.id("get_health")
.server_tag()
.summary("Health check")
.description("Returns the health status of the API server, including uptime information.")
.ok_response::<Health>()
},
),
)
.api_route(
"/version",
get_with(
async |headers: HeaderMap, State(state): State<AppState>| {
state
.cached_json(&headers, CacheStrategy::Static, |_| {
Ok(env!("CARGO_PKG_VERSION"))
})
.await
},
|op| {
op.id("get_version")
.server_tag()
.summary("API version")
.description("Returns the current version of the API server")
.ok_response::<String>()
.not_modified()
},
),
)
}
}
#[cfg(unix)]
fn dir_size(path: &path::Path) -> brk_error::Result<u64> {
use std::os::unix::fs::MetadataExt;
let mut total = 0u64;
if path.is_file() {
// blocks * 512 = actual disk usage (accounts for sparse files)
return Ok(fs::metadata(path)?.blocks() * 512);
}
let entries = fs::read_dir(path)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
total += dir_size(&path)?;
} else {
total += fs::metadata(&path)?.blocks() * 512;
}
}
Ok(total)
}
#[cfg(not(unix))]
fn dir_size(path: &path::Path) -> brk_error::Result<u64> {
let mut total = 0u64;
if path.is_file() {
return Ok(fs::metadata(path)?.len());
}
let entries = fs::read_dir(path)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
total += dir_size(&path)?;
} else {
total += fs::metadata(&path)?.len();
}
}
Ok(total)
}
+1 -1
View File
@@ -33,7 +33,7 @@ fn any_handler(
state: AppState,
path: Option<extract::Path<String>>,
) -> Response {
let files_path = state.path.as_ref().unwrap();
let files_path = state.files_path.as_ref().unwrap();
if let Some(path) = path.as_ref() {
// Sanitize path components to prevent traversal attacks
+8 -4
View File
@@ -1,6 +1,6 @@
#![doc = include_str!("../README.md")]
use std::{panic, path::PathBuf, sync::Arc, time::Duration};
use std::{panic, path::PathBuf, sync::Arc, time::{Duration, Instant}};
use aide::axum::ApiRouter;
use axum::{
@@ -37,11 +37,15 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Server(AppState);
impl Server {
pub fn new(query: &AsyncQuery, files_path: Option<PathBuf>) -> Self {
pub fn new(query: &AsyncQuery, data_path: PathBuf, files_path: Option<PathBuf>) -> Self {
Self(AppState {
client: query.client().clone(),
query: query.clone(),
path: files_path,
data_path,
files_path,
cache: Arc::new(Cache::new(5_000)),
started_at: jiff::Timestamp::now(),
started_instant: Instant::now(),
})
}
@@ -83,7 +87,7 @@ impl Server {
let vecs = state.query.inner().vecs();
let router = ApiRouter::new()
.add_api_routes()
.add_files_routes(state.path.as_ref())
.add_files_routes(state.files_path.as_ref())
.route(
"/discord",
get(Redirect::temporary("https://discord.gg/WACpShCB7M")),
+8 -2
View File
@@ -1,4 +1,4 @@
use std::{path::PathBuf, sync::Arc};
use std::{path::PathBuf, sync::Arc, time::Instant};
use derive_more::Deref;
@@ -7,6 +7,8 @@ use axum::{
http::{HeaderMap, Response},
};
use brk_query::AsyncQuery;
use brk_rpc::Client;
use jiff::Timestamp;
use quick_cache::sync::Cache;
use serde::Serialize;
@@ -19,8 +21,12 @@ use crate::{
pub struct AppState {
#[deref]
pub query: AsyncQuery,
pub path: Option<PathBuf>,
pub data_path: PathBuf,
pub files_path: Option<PathBuf>,
pub cache: Arc<Cache<String, Bytes>>,
pub client: Client,
pub started_at: Timestamp,
pub started_instant: Instant,
}
impl AppState {