tidaldb/tidal-server/src/main.rs

597 lines
24 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

use std::{net::SocketAddr, path::PathBuf, sync::Arc};
use clap::{Args, Parser, Subcommand};
use tidal_server::{
cluster::{
ClusterMode, ClusterState, RegionClusterState, build_cluster_router, build_region_router,
ensure_experimental_enabled, join_boot, load_topology,
},
config::{CONFIG_DIR_SCHEMA_FILE, CONFIG_DIR_TOPOLOGY_FILE, load_schema, resolve_config_path},
error::{Result, ServerError},
router::build_router,
state::ServerState,
};
use tidaldb::TidalDb;
#[derive(Parser)]
#[command(version, about = "HTTP wrapper for tidalDB")]
struct Cli {
#[command(subcommand)]
mode: Command,
}
#[derive(Subcommand)]
enum Command {
#[command(about = "Run a single-node server wrapping one tidalDB instance")]
Standalone(StandaloneArgs),
#[command(about = "Run a multi-region cluster behind a single HTTP surface")]
Cluster(ClusterArgs),
}
#[derive(Args)]
struct ClusterArgs {
#[arg(long, default_value = "127.0.0.1:9500", env = "PORT", value_parser = parse_listen_addr)]
listen: String,
#[arg(long)]
schema: Option<PathBuf>,
#[arg(long)]
topology: Option<PathBuf>,
/// Directory holding `default-schema.yaml` / `default-cluster.yaml`, used
/// when `--schema` / `--topology` are not given. Wired from the container's
/// `TIDAL_CONFIG` env var.
#[arg(long, env = "TIDAL_CONFIG")]
config_dir: Option<PathBuf>,
/// Opt in to the EXPERIMENTAL cluster mode (single- or multi-process).
///
/// Single-process cluster mode replicates between regions over the real
/// tidal-net gRPC transport (loopback), but every region runs inside THIS
/// one process — no host/process isolation. Multi-process mode (`--region`)
/// gives real process isolation but still lacks quorum-ack writes and
/// automatic failure detection. Either way it refuses to start without this
/// flag (or the `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1` env var).
#[arg(long)]
experimental_cluster: bool,
/// Run ONLY this region in this process (multi-process cluster mode).
///
/// Peers are reached via the topology's per-region `grpc_addr`/`http_addr`.
/// Omitted ⇒ the existing single-process cluster runs unchanged.
#[arg(long, env = "TIDAL_REGION")]
region: Option<String>,
/// Data directory for this region's `TidalDb` (multi-process mode).
/// Omitted ⇒ ephemeral.
#[arg(long)]
data_dir: Option<PathBuf>,
/// Seed-join boot (m11p5 §3.4): one or more seed HTTP base URLs
/// (`http://host:port`, repeatable; or `TIDAL_SEEDS` comma-separated). When
/// present, this node does NOT need its `--region` declared in the topology
/// file — it learns its roster, id, and term from any reachable seed and
/// joins as a Learner. The local topology/config file is still REQUIRED for
/// the behavioral knob blocks (`replication`/`wal`/`election`/`timeouts`/`grpc_tls`);
/// a bare `--seed` with neither `--topology` nor `TIDAL_CONFIG` refuses to
/// boot (§3.5) rather than silently falling back to the compiled-in defaults.
#[arg(long, env = "TIDAL_SEEDS", value_delimiter = ',')]
seed: Vec<String>,
/// This node's ADVERTISED gRPC `host:port` (seed-join, §3.4). Siblings dial
/// it; a DNS name re-resolves on reconnect. The local gRPC socket binds the
/// derived address (`0.0.0.0:<port>` for a DNS advertise, or the literal IP).
/// Required with `--seed` (the joiner has no topology entry of its own to
/// read it from).
#[arg(long)]
advertise_grpc: Option<String>,
/// This node's ADVERTISED HTTP `host:port` (seed-join, §3.4): the address
/// peers forward writes/status to. Required with `--seed`.
#[arg(long)]
advertise_http: Option<String>,
/// Bind address for this node's Prometheus `/metrics` endpoint
/// (e.g. `0.0.0.0:9091`), mirroring standalone's `--metrics`. In seed-join
/// mode the joiner has no topology entry, so its metrics listener comes from
/// this flag (§3.5).
#[arg(long)]
metrics: Option<String>,
}
#[derive(Args)]
struct StandaloneArgs {
#[arg(long, default_value = "127.0.0.1:9400", env = "PORT", value_parser = parse_listen_addr)]
listen: String,
#[arg(long)]
schema: Option<PathBuf>,
/// Directory holding `default-schema.yaml`, used when `--schema` is not
/// given. Wired from the container's `TIDAL_CONFIG` env var.
#[arg(long, env = "TIDAL_CONFIG")]
config_dir: Option<PathBuf>,
#[arg(long)]
data_dir: Option<PathBuf>,
#[arg(
long,
help = "Bind address for Prometheus /metrics endpoint (e.g. 127.0.0.1:9091)"
)]
metrics: Option<String>,
}
#[tokio::main]
async fn main() {
if let Err(err) = run().await {
eprintln!("error: {err}");
std::process::exit(1);
}
}
async fn run() -> Result<()> {
let cli = Cli::parse();
init_tracing();
match cli.mode {
Command::Standalone(args) => run_standalone(args).await,
Command::Cluster(args) => run_cluster(args).await,
}
}
/// Parse a listen address from either a full `host:port` string or a bare port number.
/// When `PORT=8080` is set, clap passes `"8080"` — this normalises it to `0.0.0.0:8080`.
fn parse_listen_addr(s: &str) -> std::result::Result<String, String> {
if s.contains(':') {
s.parse::<SocketAddr>()
.map(|_| s.to_string())
.map_err(|e| format!("invalid address '{s}': {e}"))
} else {
s.parse::<u16>()
.map(|port| format!("0.0.0.0:{port}"))
.map_err(|_| format!("expected host:port or port number, got '{s}'"))
}
}
fn init_tracing() {
let env_filter = std::env::var("TIDAL_SERVER_LOG").unwrap_or_else(|_| "info".into());
let _ = tracing_subscriber::fmt()
.with_env_filter(env_filter)
.try_init();
}
async fn run_standalone(args: StandaloneArgs) -> Result<()> {
let schema_path = resolve_config_path(
args.schema.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_SCHEMA_FILE,
)?;
let (schema, profiles) = load_schema(schema_path.as_deref())?;
let mut builder = TidalDb::builder()
.with_schema(schema.clone())
.with_profiles(profiles);
if let Some(dir) = args.data_dir {
builder = builder.with_data_dir(dir);
} else {
builder = builder.ephemeral();
}
if let Some(ref addr) = args.metrics {
builder = builder.enable_metrics(addr);
}
let db = builder.open()?;
if let Some(addr) = db.metrics_addr() {
tracing::info!("metrics endpoint listening on http://{addr}/metrics");
}
let state = ServerState::new(db);
let api_key = read_api_key();
serve_state(state, &args.listen, api_key, build_router).await
}
async fn run_cluster(args: ClusterArgs) -> Result<()> {
// `--region` selects true multi-process mode (this process owns ONE region
// and peers with siblings over real gRPC); without it the existing
// single-process cluster runs byte-for-byte unchanged.
match args.region.clone() {
Some(region) if !args.seed.is_empty() => run_seed_join_cluster(args, region).await,
Some(region) => run_region_cluster(args, region).await,
None => run_single_process_cluster(args).await,
}
}
async fn run_single_process_cluster(args: ClusterArgs) -> Result<()> {
// Honest gate: single-process cluster mode replicates between regions over
// the real tidal-net gRPC transport, but every region runs inside this one
// process (no host/process isolation), so it is not production HA. Refuse to
// start (and emit a loud WARN when permitted) so no operator mistakes it for
// production HA.
ensure_experimental_enabled(args.experimental_cluster, ClusterMode::SingleProcess)?;
let schema_path = resolve_config_path(
args.schema.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_SCHEMA_FILE,
)?;
let topology_path = resolve_config_path(
args.topology.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_TOPOLOGY_FILE,
)?;
let (schema, profiles) = load_schema(schema_path.as_deref())?;
let topology = load_topology(topology_path.as_deref())?;
tracing::info!(
regions = topology.regions.len(),
leader = %topology.leader,
"building cluster"
);
// `ClusterState::new` starts the follower gRPC servers via
// `GrpcTransport::new`, which blocks on its own tokio runtime and must not
// run inside this reactor. Build it on a dedicated thread; the constructed
// state (and its embedded runtimes) then lives for the server's lifetime.
let state = std::thread::Builder::new()
.name("cluster-build".into())
.spawn(move || ClusterState::new(&topology, schema, profiles))
.map_err(|e| ServerError::Cluster(format!("spawn cluster builder thread: {e}")))?
.join()
.map_err(|_| ServerError::Cluster("cluster builder thread panicked".into()))??;
let api_key = read_api_key();
serve_state(state, &args.listen, api_key, build_cluster_router).await
}
async fn run_region_cluster(args: ClusterArgs, region: String) -> Result<()> {
// Multi-process mode is experimental too: real process isolation, but no
// quorum-ack writes or automatic failure detection yet. The gate's WARN text
// differentiates the two modes honestly.
ensure_experimental_enabled(args.experimental_cluster, ClusterMode::MultiProcess)?;
let schema_path = resolve_config_path(
args.schema.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_SCHEMA_FILE,
)?;
let topology_path = resolve_config_path(
args.topology.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_TOPOLOGY_FILE,
)?;
let (schema, profiles) = load_schema(schema_path.as_deref())?;
let topology = load_topology(topology_path.as_deref())?;
// The operator/test surface for clock-skew injection: parse i64 strictly so
// an invalid value is a hard startup error, not a silent 0.
let hlc_offset_ms = match std::env::var("TIDAL_HLC_SKEW_MS") {
Ok(raw) => raw.trim().parse::<i64>().map_err(|e| {
ServerError::SchemaConfig(format!("invalid TIDAL_HLC_SKEW_MS '{raw}': {e}"))
})?,
Err(_) => 0,
};
tracing::info!(
region = %region,
leader = %topology.leader,
hlc_offset_ms,
"building region cluster node (multi-process)"
);
let data_dir = args.data_dir.clone();
let api_key = read_api_key();
// `RegionClusterState::new` builds the GrpcTransport via `GrpcTransport::new`,
// which blocks on its own tokio runtime — must run off this reactor. The
// m11p5 boot-time snapshot install (§2.2–§2.7) ALSO blocks (a leader-
// discovery loop + a synchronous snapshot fetch), so both run on the same
// dedicated thread, install FIRST: swap-recovery and the snapshot swap must
// complete BEFORE `RegionClusterState::new` opens the engine (a marker boot
// opens the NEW data dir; a fallback opens the existing one degraded).
let state = std::thread::Builder::new()
.name("region-build".into())
.spawn(move || -> Result<RegionClusterState> {
// §2.2: the install pre-open step runs ONLY when a reseed marker is
// present (plain topology boots never contact a peer before serving).
// `run_boot_install` returns immediately (NotNeeded) when no marker
// exists, after performing the always-safe swap-recovery.
if let Some(ref dir) = data_dir {
let outcome =
tidal_server::cluster::reseed::run_boot_install(&topology, &region, dir)?;
tracing::info!(?outcome, region = %region, "boot-time reseed install evaluated");
}
RegionClusterState::new(
&topology,
&region,
schema,
profiles,
data_dir,
hlc_offset_ms,
)
})
.map_err(|e| ServerError::Cluster(format!("spawn region builder thread: {e}")))?
.join()
.map_err(|_| ServerError::Cluster("region builder thread panicked".into()))??;
serve_state(state, &args.listen, api_key, build_region_router).await
}
/// Seed-join boot (m11p5 §3.4–§3.6): this node is NOT declared in the local
/// topology file. It learns its roster, assigned id, and term from a `--seed`,
/// installs a snapshot when needed, then constructs `RegionClusterState` from
/// the LEARNED roster (not the topology's `regions:` list).
///
/// §3.5 knob-source rule: the local topology/config file is STILL required for
/// the behavioral knob blocks (`replication`/`wal`/`election`/`timeouts`/
/// `grpc_tls`). A bare `--seed` with neither `--topology` nor `TIDAL_CONFIG`
/// REFUSES to boot, naming the rule — silently falling back to the compiled-in
/// `default-cluster.yaml` would give the wrong ack default, quorum timeout,
/// election timing, and no metrics/TLS material.
async fn run_seed_join_cluster(args: ClusterArgs, region: String) -> Result<()> {
ensure_experimental_enabled(args.experimental_cluster, ClusterMode::MultiProcess)?;
// §3.5: refuse a bare `--seed` with no knob source. The joiner reads its
// own id/roster/term from the seed, but the BEHAVIORAL knobs must come from
// a real file — never the compiled-in default.
if args.topology.is_none() && args.config_dir.is_none() {
return Err(ServerError::Cluster(
"a --seed boot still requires the local topology/config file for the behavioral knob \
blocks (replication/wal/election/timeouts/grpc_tls): pass --topology <file> or set \
TIDAL_CONFIG (m11p5 §3.5). Refusing to boot rather than silently using the \
compiled-in default-cluster.yaml (wrong ack default, quorum timeout, election \
timing, and no metrics/TLS material)."
.into(),
));
}
let schema_path = resolve_config_path(
args.schema.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_SCHEMA_FILE,
)?;
let topology_path = resolve_config_path(
args.topology.as_deref(),
args.config_dir.as_deref(),
CONFIG_DIR_TOPOLOGY_FILE,
)?;
let (schema, profiles) = load_schema(schema_path.as_deref())?;
// `load_topology` runs `validate_spec_values` (the knob value validation +
// the C2 election lease bound) on the loaded file — exactly what §3.5 keeps.
// We do NOT call `validate_multiproc` on this file's `regions:` (it would
// demand the joiner be declared there); the runtime roster is the join
// response, and the synthesized topology IS validated by `validate_multiproc`
// inside `RegionClusterState::new`.
let knobs = load_topology(topology_path.as_deref())?;
let advertise_grpc = args.advertise_grpc.clone().ok_or_else(|| {
ServerError::Cluster(
"a --seed boot requires --advertise-grpc (this node's advertised gRPC host:port — \
siblings dial it; §3.4)"
.into(),
)
})?;
let advertise_http = args.advertise_http.clone().ok_or_else(|| {
ServerError::Cluster(
"a --seed boot requires --advertise-http (this node's advertised HTTP host:port — \
peers forward to it; §3.4)"
.into(),
)
})?;
let data_dir = args.data_dir.clone().ok_or_else(|| {
ServerError::Cluster(
"a --seed boot requires --data-dir: the durable WAL is the replication stream and a \
snapshot install swaps the data dir, so it must be a subdirectory of a mount (§2.3)"
.into(),
)
})?;
let hlc_offset_ms = match std::env::var("TIDAL_HLC_SKEW_MS") {
Ok(raw) => raw.trim().parse::<i64>().map_err(|e| {
ServerError::SchemaConfig(format!("invalid TIDAL_HLC_SKEW_MS '{raw}': {e}"))
})?,
Err(_) => 0,
};
tracing::info!(
region = %region,
seeds = args.seed.len(),
%advertise_grpc,
%advertise_http,
"seed-join boot (m11p5 §3.4): discovering a leader to join through"
);
let api_key = read_api_key();
let api_key_for_join = api_key.as_deref().map(str::to_string);
let metrics = args.metrics.clone();
let seeds = args.seed.clone();
// The §2.7 join loop + snapshot install BLOCK (leader discovery, a
// synchronous JoinCluster, a snapshot fetch), and `RegionClusterState::new`
// builds the GrpcTransport on its own runtime — both must run off this
// reactor, on the same dedicated thread, install FIRST.
let state = std::thread::Builder::new()
.name("region-seed-join-build".into())
.spawn(move || -> Result<RegionClusterState> {
let join_boot::SeedJoinBoot {
topology: synth,
region: synth_region,
} = join_boot::seed_join_boot(&join_boot::SeedJoinInput {
seeds: &seeds,
knobs: &knobs,
region: &region,
advertise_grpc: &advertise_grpc,
advertise_http: &advertise_http,
metrics: metrics.as_deref(),
data_dir: &data_dir,
api_key: api_key_for_join,
})?;
RegionClusterState::new(
&synth,
&synth_region,
schema,
profiles,
Some(data_dir),
hlc_offset_ms,
)
})
.map_err(|e| ServerError::Cluster(format!("spawn seed-join builder thread: {e}")))?
.join()
.map_err(|_| ServerError::Cluster("seed-join builder thread panicked".into()))??;
serve_state(state, &args.listen, api_key, build_region_router).await
}
/// The serve/shutdown contract every server mode (standalone, single-process
/// cluster, multi-process region) satisfies, so the socket-bind → serve →
/// drain → deterministic-shutdown plumbing is written ONCE in [`serve_state`].
trait ServeState: Send + Sync + 'static {
/// Human label for the post-serve log lines.
const WHAT: &'static str;
/// Called once the state is in its final `Arc`, before serving begins
/// (the m11p4 election driver holds a `Weak` back-reference, so it can
/// only start here). Default: nothing.
fn started(self: &Arc<Self>) {}
/// Flip `/health` to not-ready BEFORE axum starts draining.
fn set_shutting_down(&self);
/// Final deterministic shutdown (checkpoint + WAL fsync + thread join),
/// run once `serve_state` has reclaimed sole ownership.
fn shutdown_owned(self);
}
impl ServeState for ServerState {
const WHAT: &'static str = "standalone server";
fn set_shutting_down(&self) {
// `Self::` resolves to the INHERENT method (inherent impls outrank
// trait impls in associated-fn resolution), not this trait fn.
Self::set_shutting_down(self);
}
fn shutdown_owned(self) {
// Dropping the sole-owner `ServerState` drops its `Arc<TidalDb>`; that
// runs `TidalDb::Drop`, which attempts every final durable flush and
// logs the first failure at error level (SHUTDOWN-2). The drop is
// deterministic here, not deferred.
drop(self);
tracing::info!("standalone shutdown: database closed (checkpoint + WAL fsync)");
}
}
impl ServeState for ClusterState {
const WHAT: &'static str = "cluster";
fn set_shutting_down(&self) {
Self::set_shutting_down(self); // the inherent method, as above
}
fn shutdown_owned(mut self) {
self.shutdown();
}
}
impl ServeState for RegionClusterState {
const WHAT: &'static str = "region";
fn started(self: &Arc<Self>) {
self.start_election_driver();
}
fn set_shutting_down(&self) {
Self::set_shutting_down(self); // the inherent method, as above
}
fn shutdown_owned(mut self) {
self.shutdown();
}
}
// The `state` binding deliberately lives until after `axum::serve` returns so
// the post-serve `Arc::try_unwrap` can reclaim sole ownership and run the
// deterministic shutdown (checkpoint + WAL fsync + receiver join). Dropping it
// "early" (clippy's suggestion) would drop the node BEFORE the server stops
// accepting requests — the exact ordering bug this ordering exists to avoid.
#[allow(clippy::significant_drop_tightening)]
async fn serve_state<S: ServeState>(
state: S,
addr: &str,
api_key: Option<Arc<str>>,
build_router: impl FnOnce(Arc<S>, Option<Arc<str>>) -> axum::Router,
) -> Result<()> {
let socket: SocketAddr = addr
.parse()
.map_err(|e| ServerError::BadRequest(format!("invalid addr: {e}")))?;
let listener = tokio::net::TcpListener::bind(socket).await?;
let actual = listener.local_addr()?;
tracing::info!("listening on http://{actual}");
let state = Arc::new(state);
state.started();
let shutdown_state = state.clone();
axum::serve(listener, build_router(state, api_key))
.with_graceful_shutdown(shutdown_signal(shutdown_state.clone()))
.await?;
// axum::serve has returned, so the router (and every `Arc<S>` it held) is
// dropped. We should now be the sole owner; reclaim ownership and run the
// final durable shutdown HERE — deterministically, before the process
// exits — instead of letting an implicit drop fire the `Drop` backstop at
// an unspecified point. If an Arc unexpectedly lingers we cannot observe
// the final flush from this stack frame, so we log that we are falling
// back to `Drop` (which still runs the same shutdown and logs any flush
// failure at error level) rather than silently exiting 0 on a
// possibly-failed flush.
match Arc::try_unwrap(shutdown_state) {
Ok(owned) => owned.shutdown_owned(),
Err(arc) => {
tracing::warn!(
strong = Arc::strong_count(&arc),
state = S::WHAT,
"state still shared after serve returned; relying on Drop for shutdown"
);
}
}
Ok(())
}
async fn shutdown_signal<S: ServeState>(state: Arc<S>) {
// SIGTERM is Unix-only; on other platforms we fall back to ctrl-c alone.
#[cfg(unix)]
let sigterm = async {
use tokio::signal::unix::{SignalKind, signal};
match signal(SignalKind::terminate()) {
Ok(mut stream) => {
stream.recv().await;
}
Err(err) => {
tracing::warn!("SIGTERM handler registration failed: {err}");
// If we cannot register SIGTERM, park this branch so the
// select falls back to ctrl_c exclusively.
std::future::pending::<()>().await;
}
}
};
#[cfg(not(unix))]
let sigterm = std::future::pending::<()>();
tokio::select! {
result = tokio::signal::ctrl_c() => {
if let Err(err) = result {
tracing::warn!("ctrl-c handler error: {err}");
}
}
() = sigterm => {}
// m11p5 §2.4: a reseed self-restart requests this latch, so a
// self-triggered exit runs the IDENTICAL graceful drain a SIGTERM would.
() = tidal_server::self_exit::wait_self_exit() => {
tracing::info!("graceful self-exit requested (reseed self-restart §2.4)");
}
}
// Flip readiness BEFORE axum starts draining.
state.set_shutting_down();
tracing::info!("shutdown signal received; readiness not-ready, draining in-flight requests");
}
/// Read the API key from the environment.
///
/// If `TIDAL_API_KEY` is not set, all requests are accepted without
/// authentication. This is appropriate for local development but should
/// never be used in production. A startup warning is emitted.
fn read_api_key() -> Option<Arc<str>> {
match std::env::var("TIDAL_API_KEY") {
Ok(key) if !key.is_empty() => Some(Arc::from(key.as_str())),
_ => {
tracing::warn!(
"TIDAL_API_KEY is not set — all endpoints are unauthenticated. \
Set this variable before exposing the server to any network."
);
None
}
}
}