Skip to main content

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