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