boatramp_node/node.rs
1//! The node-graph assembly: given a built store (blobs + KV), a configured
2//! [`Auth`](boatramp_server::Auth), and resolved
3//! [`ServerOptions`](boatramp_server::ServerOptions), wire the deploy store,
4//! handler runtime, compute reconcile loop, and domain-verify reconcile loop
5//! into a [`RunningNode`] ready to hand to a transport (`serve_with` & friends).
6//!
7//! This is the headline extraction of `PLAN-node-library`: the binary's
8//! `serve::run` used to inline this wiring, so no embedder or in-process test
9//! could exercise the same graph the `boatramp serve` binary runs. `run` now
10//! resolves the *environment* (args -> backends -> store, signal handlers,
11//! migration, auth) and calls [`assemble`]; the cluster path keeps its own inline
12//! copy until a later step converges it here.
13
14use std::path::Path;
15use std::sync::Arc;
16
17use boatramp_core::deploy::DeployStore;
18use boatramp_core::kv::KvStore;
19use boatramp_core::Storage;
20
21use crate::config::ServerConfig;
22use crate::error::{Error, Result};
23
24/// How often the compute reconcile loop converges desired vs actual workloads.
25/// Defaults to 30s; override with `BOATRAMP_COMPUTE_RECONCILE_TICK_MS` (milliseconds)
26/// so compute-backed tests can converge in a fraction of a second instead of
27/// waiting a full tick for the launch/scale reconcile.
28pub fn compute_reconcile_tick() -> std::time::Duration {
29 std::env::var("BOATRAMP_COMPUTE_RECONCILE_TICK_MS")
30 .ok()
31 .and_then(|s| s.parse::<u64>().ok())
32 .filter(|&ms| ms > 0)
33 .map(std::time::Duration::from_millis)
34 .unwrap_or(std::time::Duration::from_secs(30))
35}
36/// How often the domain-verify reconcile loop re-checks pending challenges.
37pub const DOMAIN_VERIFY_RECONCILE_TICK: std::time::Duration = std::time::Duration::from_secs(60);
38/// How long a compute workload may be idle before scale-to-zero sleeps it.
39pub const COMPUTE_IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300);
40
41/// The built store + resolved config handed to [`assemble`]. Owns the blob/KV
42/// backends and the auth/options the caller already resolved; borrows the parsed
43/// config and data directory.
44pub struct NodeInput<'a> {
45 /// The full parsed server config (the handler + compute sections are read here).
46 pub config: &'a ServerConfig,
47 /// The node data directory (per-site SQL, handler state).
48 pub data_dir: &'a Path,
49 /// The object store built by [`crate::blobs::build_blobs`].
50 pub storage: Arc<dyn Storage>,
51 /// The metadata KV, already cache-fronted, built by [`crate::backends::build_kv`].
52 pub kv: Arc<dyn KvStore>,
53 /// The control-plane auth built by [`crate::auth::configure_auth`].
54 pub auth: boatramp_server::Auth,
55 /// Server options, already carrying the resolved posture, daemon runtime, and
56 /// (post-`configure_auth`/`configure_oidc`) issuer / OIDC verifier.
57 pub options: boatramp_server::ServerOptions,
58 /// The public HTTP serve bind address, if known — used (under
59 /// `allow_guest_self_egress`) to let a handler guest's `wasi:http` reach this
60 /// instance's own front door over loopback. `None` (an in-process embedder with no
61 /// listener) disables self-egress.
62 pub serve_addr: Option<std::net::SocketAddr>,
63 /// The cloud blob-change watch provider (FA-5b2), if the backend is a cloud one.
64 pub watch_provider: Option<Arc<dyn boatramp_core::blob_provision::WatchProvider>>,
65 /// The provisioning tier for the watch provider.
66 pub provision_tier: boatramp_core::blob_notify::ProvisionTier,
67 /// The `wasi:messaging` substrate override for the handler runtime. `None` uses
68 /// the single-node default (`LogMessaging` over the same backends); the cluster
69 /// path passes its Raft-backed coordinator.
70 pub messaging: Option<Arc<dyn boatramp_core::messaging::Messaging>>,
71 /// The single leader gate for cron firing + the compute / domain-verify reconcile
72 /// loops. Single-node passes an always-true gate (there is one node); the cluster
73 /// passes its Raft `is_leader` check so a single node drives each sweep.
74 pub is_leader: boatramp_server::CronLeaderGate,
75 /// This node's compute scheduler id (`0` single-node; the cluster node id in a
76 /// fleet, so replicas are tagged to the right node).
77 pub node_id: u64,
78 /// The binary the re-exec'd compute workers run as — the container backend's
79 /// `__sandbox` jailer and the microVM backends' `__vmm-run`/`__vz-run` VM hosts.
80 /// `None` uses this process's own executable (`current_exe`), which is what
81 /// `boatramp serve` wants (the child *is* boatramp). An **embedding harness**
82 /// whose own binary doesn't implement those subcommands should point this at a
83 /// built `boatramp` binary, so it can drive the real container/microVM backends
84 /// in-process (only the per-workload worker re-execs; the serving plane stays
85 /// embedded). The docker backend needs neither — it talks to a daemon.
86 pub worker_exe: Option<std::path::PathBuf>,
87}
88
89/// A fully wired node: the deploy store, handler runtime, auth, and options a
90/// transport consumes, plus the detached reconcile loops kept alive for the
91/// node's serving life. Destructure it and hold `reconcile` across the serve
92/// await so the loops outlive assembly.
93pub struct RunningNode {
94 /// The deploy store (blob + KV) the router serves from.
95 pub deploy: DeployStore,
96 /// The handler runtime for wasm handlers (a disabled build ⇒ a no-op runtime).
97 pub handlers: boatramp_server::HandlerRuntime,
98 /// The control-plane auth.
99 pub auth: boatramp_server::Auth,
100 /// The resolved server options.
101 pub options: boatramp_server::ServerOptions,
102 /// The detached reconcile loops (compute + domain-verify). Tokio `JoinHandle`s
103 /// do not abort on drop, so the loops run for the process life regardless; the
104 /// handles are retained so an embedder can join/abort them on shutdown.
105 pub reconcile: Vec<tokio::task::JoinHandle<()>>,
106}
107
108/// The instance's own serve socket(s) a guest self-call may reach, given the bind `addr` and
109/// whether the posture (`allow_guest_self_egress`) permits it. A wildcard bind
110/// (`0.0.0.0`/`::`) is reachable over loopback, so it normalizes to `127.0.0.1` **and** `::1`
111/// on the serve port; a specific bind is reachable at itself. Empty when disabled or no
112/// listener.
113fn self_egress_addrs(
114 addr: Option<std::net::SocketAddr>,
115 enabled: bool,
116) -> Vec<std::net::SocketAddr> {
117 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
118 let Some(addr) = addr.filter(|_| enabled) else {
119 return Vec::new();
120 };
121 if addr.ip().is_unspecified() {
122 let port = addr.port();
123 vec![
124 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
125 SocketAddr::new(IpAddr::V6(Ipv6Addr::LOCALHOST), port),
126 ]
127 } else {
128 vec![addr]
129 }
130}
131
132/// Wire [`NodeInput`] into a [`RunningNode`]: build the handler runtime, the
133/// deploy store (materializing the reserved `default` project), the compute
134/// backends + reconcile loop, and the domain-verify reconcile loop.
135///
136/// The caller has already built the store and configured auth/OIDC on `options`;
137/// this is the pure node-graph wiring, identical to what `boatramp serve` runs.
138pub async fn assemble(input: NodeInput<'_>) -> Result<RunningNode> {
139 let NodeInput {
140 config,
141 data_dir,
142 storage,
143 kv,
144 auth,
145 options,
146 serve_addr,
147 watch_provider,
148 provision_tier,
149 messaging,
150 is_leader,
151 node_id,
152 worker_exe,
153 } = input;
154 // Copy out the posture scalars up front so `options` can be moved into the
155 // returned `RunningNode` without a lingering borrow.
156 let max_handler_blob_bytes = options.posture.max_handler_blob_bytes;
157 let max_component_bytes = options.posture.max_component_bytes;
158 let allow_guest_private_egress = options.posture.allow_guest_private_egress;
159 // The instance's own serve socket(s) a guest self-call may reach, when the posture allows
160 // it: a wildcard bind (`0.0.0.0`/`::`) is reachable on loopback, so normalize to
161 // `127.0.0.1`/`::1`; a specific bind is itself.
162 let self_egress_addrs = self_egress_addrs(serve_addr, options.posture.allow_guest_self_egress);
163 let allow_shared_kernel = options.posture.allow_shared_kernel_compute;
164 let domain_verify_allow_private = options.posture.domain_verify_allow_private;
165
166 // The deploy store the router serves from — built up front so the handler
167 // runtime's managed compute-backed `sql` binding can resolve DB endpoints from
168 // the same store the reconcile writes.
169 let compute_storage = storage.clone();
170 let deploy = DeployStore::new(storage, kv.clone());
171 // The `[secrets]` envelope (local KEK / Vault) that seals a managed SQL
172 // credential at rest. `None` ⇒ no wrapping (a managed DB then fails closed).
173 let secrets_envelope = build_secrets_envelope(config.secrets.as_ref(), data_dir)?;
174
175 // The handler runtime reuses the same blob/KV backends (per-site prefixed)
176 // for its wasi:blobstore/keyvalue bindings; the sql binding is selected by
177 // `[handlers.bindings.sql]` (default: per-site libsql files under <data-dir>).
178 let handlers = crate::handlers::build_handler_runtime(
179 kv.clone(),
180 compute_storage.clone(),
181 data_dir,
182 config.handlers.as_ref(),
183 messaging,
184 max_handler_blob_bytes,
185 max_component_bytes,
186 allow_guest_private_egress,
187 self_egress_addrs,
188 &deploy,
189 secrets_envelope.clone(),
190 )
191 .await?;
192 // Leader-gate cron firing (cluster: only the Raft leader fires; single-node: an
193 // always-true gate, equivalent to the unset default). The same gate drives the
194 // reconcile loops below, so all three converge on one leader per fleet. Only the
195 // handler runtime has a scheduler, so this is a no-op without the `handlers` feature.
196 #[cfg(feature = "handlers")]
197 handlers.set_cron_leader_gate(is_leader.clone());
198 // FA-5b2: on a cloud backend, wire the blob-change notification provisioner +
199 // its tier so adding a `blob` trigger provisions (and removing it retracts).
200 #[cfg(feature = "handlers")]
201 if let Some(provider) = watch_provider {
202 handlers.set_watch_provider(provider);
203 handlers.set_provision_tier(provision_tier);
204 }
205 #[cfg(not(feature = "handlers"))]
206 let _ = (watch_provider, provision_tier);
207
208 // Materialize the reserved `default` project so `project ls` / `project show
209 // default` reflect it on a fresh install, not only after a migration. Best
210 // effort: the reader backstop keeps listings correct even if this write can't
211 // land, so a transient failure must never block serving.
212 match deploy.ensure_default_project().await {
213 Ok(true) => tracing::info!("materialized the reserved `default` project record"),
214 Ok(false) => {}
215 Err(e) => tracing::warn!(
216 error = %e,
217 "could not materialize the `default` project record; readers use the synthesized default"
218 ),
219 }
220 // Wire the function-to-function invoke resolver now the deploy store exists,
221 // so a function granted `invoke` can call a sibling in-process (FI).
222 #[cfg(feature = "handlers")]
223 handlers.set_invoker(deploy.clone());
224
225 // Compute reconcile loop. Single-node is always the "leader". Backends are
226 // built from the `[compute]` config + capability detection; a no-op when none
227 // are registered. Detached for the server's life.
228 let (compute_backends, compute_node) = crate::compute::build_compute(
229 config.compute.as_ref(),
230 compute_storage,
231 data_dir,
232 node_id,
233 !allow_shared_kernel,
234 options.daemon_runtime.clone(),
235 worker_exe.as_deref(),
236 )
237 .await;
238 // Activate the compute sql-shim (PLAN-compute-bindings): bind its listener +
239 // build the resolver when a sql provider and `compute.sql_shim_url` are both present.
240 #[cfg(feature = "handlers")]
241 let sql_resolver = boatramp_server::sql_shim::spawn_sql_shim(
242 handlers.sql_backends(),
243 config.compute.as_ref().and_then(|c| c.sql_shim_url.clone()),
244 )
245 .await;
246 #[cfg(not(feature = "handlers"))]
247 let sql_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
248
249 // Managed compute-backed SQL (PLAN-managed-compute-sql P2-b): if the handler
250 // `sql` config declares any managed database, inject its `POSTGRES_*`/`MYSQL_*`
251 // server-init env into the DB workload at launch from the sealed credential.
252 // Reaching here with a managed DB implies an envelope (build_handler_runtime
253 // fails closed otherwise), so the credential store always has one to seal with.
254 #[cfg(any(feature = "sql-postgres", feature = "sql-mysql"))]
255 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = match (
256 config
257 .handlers
258 .as_ref()
259 .and_then(|h| h.bindings.sql.as_ref()),
260 secrets_envelope,
261 ) {
262 (Some(sql), Some(envelope)) if !sql.databases.is_empty() => {
263 let creds = crate::managed_sql::ManagedSqlCredentials::new(kv.clone(), envelope);
264 let privilege = config
265 .compute
266 .as_ref()
267 .map(|c| c.managed_db_privilege)
268 .unwrap_or_default();
269 let env =
270 crate::managed_sql::ManagedDbEnv::from_config(&sql.databases, creds, privilege);
271 (!env.is_empty()).then(|| Arc::new(env) as Arc<_>)
272 }
273 _ => None,
274 };
275 #[cfg(not(any(feature = "sql-postgres", feature = "sql-mysql")))]
276 let managed_db_resolver: Option<Arc<dyn boatramp_core::compute::ManagedDbEnvResolver>> = None;
277
278 let compute_reconcile = boatramp_server::spawn_compute_reconcile(
279 deploy.clone(),
280 compute_backends,
281 vec![compute_node],
282 boatramp_core::compute::BackendPolicy::from_shared_kernel_allowed(allow_shared_kernel),
283 is_leader.clone(),
284 compute_reconcile_tick(),
285 COMPUTE_IDLE_TIMEOUT,
286 sql_resolver,
287 managed_db_resolver,
288 );
289
290 // Domain-verify auto-complete: periodically re-check every site's pending
291 // ownership challenges and attach any that now pass — a published token (e.g.
292 // via `domain add --provider`) converges without a manual `domain verify`.
293 let dv_reconcile = boatramp_server::spawn_domain_verify_reconcile(
294 deploy.clone(),
295 domain_verify_allow_private,
296 is_leader,
297 DOMAIN_VERIFY_RECONCILE_TICK,
298 );
299
300 Ok(RunningNode {
301 deploy,
302 handlers,
303 auth,
304 options,
305 reconcile: vec![compute_reconcile, dv_reconcile],
306 })
307}
308
309/// Build the `[secrets]` envelope (secrets-at-rest wrapping) from `boatramp.cfg`'s
310/// `[secrets]` section: `local` (a machine-local AES-256-GCM KEK) or `vault` (Vault
311/// Transit). `None`/empty ⇒ no wrapping. The Vault token is read from the
312/// environment (`token_env`), never a file. This seals a managed SQL credential at
313/// rest; a managed database fails closed without it.
314fn build_secrets_envelope(
315 secrets: Option<&crate::config::SecretsConfig>,
316 data_dir: &Path,
317) -> Result<Option<Arc<dyn boatramp_core::envelope::KeyEnvelope>>> {
318 use boatramp_server::envelope::{build_envelope, EnvelopeSpec};
319 let Some(cfg) = secrets else {
320 return Ok(None);
321 };
322 let spec = match cfg.envelope.as_str() {
323 "" => EnvelopeSpec::None,
324 "local" => EnvelopeSpec::Local {
325 kek_file: cfg
326 .kek_file
327 .clone()
328 .unwrap_or_else(|| data_dir.join("secrets/kek")),
329 },
330 "vault" => {
331 let v = cfg.vault.as_ref().ok_or_else(|| {
332 Error::Envelope(
333 "secrets.envelope = \"vault\" needs a [secrets.vault] section".into(),
334 )
335 })?;
336 let token = std::env::var(&v.token_env).map_err(|_| {
337 Error::Envelope(format!("Vault token env `{}` is not set", v.token_env))
338 })?;
339 EnvelopeSpec::Vault {
340 addr: v.addr.clone(),
341 key: v.key.clone(),
342 token,
343 }
344 }
345 other => {
346 return Err(Error::Envelope(format!(
347 "unknown secrets.envelope {other:?} (want \"local\" or \"vault\")"
348 )))
349 }
350 };
351 build_envelope(spec).map_err(|e| Error::Envelope(e.to_string()))
352}
353
354#[cfg(all(test, feature = "fs"))]
355mod tests {
356 use super::*;
357 use boatramp_core::kv::MemoryKv;
358 use boatramp_core::security::SecurityProfile;
359
360 /// The headline in-process fidelity check (PLAN-node-library N2b.3): `assemble`
361 /// over a temp `FsStorage` + `MemoryKv` produces a `RunningNode` whose deploy
362 /// store is live (the reserved `default` project was materialized during
363 /// assembly) and whose router — the exact one `boatramp serve` builds — answers
364 /// `/healthz`. No listener is bound: the request is driven through the router
365 /// via `tower::oneshot`, so the whole assembly runs in-process.
366 #[tokio::test]
367 async fn assemble_produces_a_serving_node_over_a_temp_store() {
368 use axum::body::Body;
369 use axum::http::{Request, StatusCode};
370 use tower::ServiceExt;
371
372 let tmp = tempfile::tempdir().unwrap();
373 let storage: Arc<dyn Storage> = Arc::new(boatramp_storage::FsStorage::new(tmp.path()));
374 let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
375 let config = ServerConfig::default();
376 let options = boatramp_server::ServerOptions {
377 // The strict `multi-tenant` posture, as an unconfigured `serve` resolves.
378 posture: SecurityProfile::MultiTenant.preset(),
379 ..Default::default()
380 };
381
382 let node = assemble(NodeInput {
383 config: &config,
384 data_dir: tmp.path(),
385 storage,
386 kv,
387 auth: boatramp_server::Auth::disabled(),
388 options,
389 serve_addr: None,
390 watch_provider: None,
391 provision_tier: boatramp_core::blob_notify::ProvisionTier::default(),
392 messaging: None,
393 is_leader: Arc::new(|| true),
394 node_id: 0,
395 worker_exe: None,
396 })
397 .await
398 .expect("assemble a node over a temp store");
399
400 // The deploy store is live: `assemble` already materialized the reserved
401 // `default` project, so a second ensure reports "already present" (`false`).
402 assert!(
403 !node
404 .deploy
405 .ensure_default_project()
406 .await
407 .expect("read the default project"),
408 "assemble should have materialized the default project"
409 );
410
411 // The assembled router (the same wiring `serve` binds) answers /healthz.
412 let router =
413 boatramp_server::router_with(node.deploy, node.auth, node.handlers, node.options);
414 let response = router
415 .oneshot(
416 Request::builder()
417 .uri("/healthz")
418 .body(Body::empty())
419 .unwrap(),
420 )
421 .await
422 .expect("route /healthz");
423 assert_eq!(response.status(), StatusCode::OK);
424 }
425}