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::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 handler runtime reuses the same blob/KV backends (per-site prefixed)
112    // for its wasi:blobstore/keyvalue bindings; the sql binding is selected by
113    // `[handlers.bindings.sql]` (default: per-site libsql files under <data-dir>).
114    let handlers = crate::handlers::build_handler_runtime(
115        kv.clone(),
116        storage.clone(),
117        data_dir,
118        config.handlers.as_ref(),
119        messaging,
120        max_handler_blob_bytes,
121        max_component_bytes,
122    )?;
123    // Leader-gate cron firing (cluster: only the Raft leader fires; single-node: an
124    // always-true gate, equivalent to the unset default). The same gate drives the
125    // reconcile loops below, so all three converge on one leader per fleet. Only the
126    // handler runtime has a scheduler, so this is a no-op without the `handlers` feature.
127    #[cfg(feature = "handlers")]
128    handlers.set_cron_leader_gate(is_leader.clone());
129    // FA-5b2: on a cloud backend, wire the blob-change notification provisioner +
130    // its tier so adding a `blob` trigger provisions (and removing it retracts).
131    #[cfg(feature = "handlers")]
132    if let Some(provider) = watch_provider {
133        handlers.set_watch_provider(provider);
134        handlers.set_provision_tier(provision_tier);
135    }
136    #[cfg(not(feature = "handlers"))]
137    let _ = (watch_provider, provision_tier);
138
139    let compute_storage = storage.clone();
140    let deploy = DeployStore::new(storage, kv);
141    // Materialize the reserved `default` project so `project ls` / `project show
142    // default` reflect it on a fresh install, not only after a migration. Best
143    // effort: the reader backstop keeps listings correct even if this write can't
144    // land, so a transient failure must never block serving.
145    match deploy.ensure_default_project().await {
146        Ok(true) => tracing::info!("materialized the reserved `default` project record"),
147        Ok(false) => {}
148        Err(e) => tracing::warn!(
149            error = %e,
150            "could not materialize the `default` project record; readers use the synthesized default"
151        ),
152    }
153    // Wire the function-to-function invoke resolver now the deploy store exists,
154    // so a function granted `invoke` can call a sibling in-process (FI).
155    #[cfg(feature = "handlers")]
156    handlers.set_invoker(deploy.clone());
157
158    // Compute reconcile loop. Single-node is always the "leader". Backends are
159    // built from the `[compute]` config + capability detection; a no-op when none
160    // are registered. Detached for the server's life.
161    let (compute_backends, compute_node) = crate::compute::build_compute(
162        config.compute.as_ref(),
163        compute_storage,
164        data_dir,
165        node_id,
166        !allow_shared_kernel,
167        options.daemon_runtime.clone(),
168    )
169    .await;
170    // Activate the compute sql-shim (PLAN-compute-bindings): bind its listener +
171    // build the resolver when a sql provider and `compute.sql_shim_url` are both present.
172    #[cfg(feature = "handlers")]
173    let sql_resolver = boatramp_server::sql_shim::spawn_sql_shim(
174        handlers.sql_backends(),
175        config.compute.as_ref().and_then(|c| c.sql_shim_url.clone()),
176    )
177    .await;
178    #[cfg(not(feature = "handlers"))]
179    let sql_resolver: Option<Arc<dyn boatramp_core::compute::ComputeBindingResolver>> = None;
180    let compute_reconcile = boatramp_server::spawn_compute_reconcile(
181        deploy.clone(),
182        compute_backends,
183        vec![compute_node],
184        boatramp_core::compute::BackendPolicy::from_shared_kernel_allowed(allow_shared_kernel),
185        is_leader.clone(),
186        COMPUTE_RECONCILE_TICK,
187        COMPUTE_IDLE_TIMEOUT,
188        sql_resolver,
189    );
190
191    // Domain-verify auto-complete: periodically re-check every site's pending
192    // ownership challenges and attach any that now pass — a published token (e.g.
193    // via `domain add --provider`) converges without a manual `domain verify`.
194    let dv_reconcile = boatramp_server::spawn_domain_verify_reconcile(
195        deploy.clone(),
196        domain_verify_allow_private,
197        is_leader,
198        DOMAIN_VERIFY_RECONCILE_TICK,
199    );
200
201    Ok(RunningNode {
202        deploy,
203        handlers,
204        auth,
205        options,
206        reconcile: vec![compute_reconcile, dv_reconcile],
207    })
208}
209
210#[cfg(all(test, feature = "fs"))]
211mod tests {
212    use super::*;
213    use boatramp_core::kv::MemoryKv;
214    use boatramp_core::security::SecurityProfile;
215
216    /// The headline in-process fidelity check (PLAN-node-library N2b.3): `assemble`
217    /// over a temp `FsStorage` + `MemoryKv` produces a `RunningNode` whose deploy
218    /// store is live (the reserved `default` project was materialized during
219    /// assembly) and whose router — the exact one `boatramp serve` builds — answers
220    /// `/healthz`. No listener is bound: the request is driven through the router
221    /// via `tower::oneshot`, so the whole assembly runs in-process.
222    #[tokio::test]
223    async fn assemble_produces_a_serving_node_over_a_temp_store() {
224        use axum::body::Body;
225        use axum::http::{Request, StatusCode};
226        use tower::ServiceExt;
227
228        let tmp = tempfile::tempdir().unwrap();
229        let storage: Arc<dyn Storage> = Arc::new(boatramp_storage::FsStorage::new(tmp.path()));
230        let kv: Arc<dyn KvStore> = Arc::new(MemoryKv::new());
231        let config = ServerConfig::default();
232        let options = boatramp_server::ServerOptions {
233            // The strict `multi-tenant` posture, as an unconfigured `serve` resolves.
234            posture: SecurityProfile::MultiTenant.preset(),
235            ..Default::default()
236        };
237
238        let node = assemble(NodeInput {
239            config: &config,
240            data_dir: tmp.path(),
241            storage,
242            kv,
243            auth: boatramp_server::Auth::disabled(),
244            options,
245            watch_provider: None,
246            provision_tier: boatramp_core::blob_notify::ProvisionTier::default(),
247            messaging: None,
248            is_leader: Arc::new(|| true),
249            node_id: 0,
250        })
251        .await
252        .expect("assemble a node over a temp store");
253
254        // The deploy store is live: `assemble` already materialized the reserved
255        // `default` project, so a second ensure reports "already present" (`false`).
256        assert!(
257            !node
258                .deploy
259                .ensure_default_project()
260                .await
261                .expect("read the default project"),
262            "assemble should have materialized the default project"
263        );
264
265        // The assembled router (the same wiring `serve` binds) answers /healthz.
266        let router =
267            boatramp_server::router_with(node.deploy, node.auth, node.handlers, node.options);
268        let response = router
269            .oneshot(
270                Request::builder()
271                    .uri("/healthz")
272                    .body(Body::empty())
273                    .unwrap(),
274            )
275            .await
276            .expect("route /healthz");
277        assert_eq!(response.status(), StatusCode::OK);
278    }
279}