Skip to main content

boatramp_types/
compute.rs

1//! Compute workloads: legacy apps run as Firecracker microVMs.
2//!
3//! This is the wasm-clean **artifact model** — the content-addressed, immutable
4//! [`ComputeSpec`] (rootfs/kernel/spec, exactly like a site deployment) and the
5//! mutable [`ComputeWorkload`] desired state (active version + replicas +
6//! placement). The executor that actually boots a microVM from a spec
7//! (`boatramp-firecracker`, KVM-only) and the scheduler that places it are
8//! native-only and live elsewhere; this module is just the shared types + their
9//! content-addressing, so the CLI, control plane, and executor agree.
10
11use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15use crate::manifest::sha256_hex;
16
17/// KV key prefix for immutable, content-addressed compute specs. Stays **global**
18/// (a content hash is a self-authenticating capability; specs dedup across projects).
19pub const SPEC_PREFIX: &str = "computever/";
20
21/// The mutable desired-state key for a workload, **project-scoped** (0.2.0):
22/// `project/<proj>/compute/<name>`. `project` is a bare `&str` (this crate is
23/// wasm-clean); `boatramp-core` callers pass `ProjectRef::as_str()`.
24pub fn workload_key(project: &str, name: &str) -> String {
25    format!("project/{project}/compute/{name}")
26}
27
28/// The prefix listing every workload's desired state in a project.
29pub fn workloads_prefix(project: &str) -> String {
30    format!("project/{project}/compute/")
31}
32
33/// The immutable spec key for a content hash (global CAS).
34pub fn spec_key(hash: &str) -> String {
35    format!("{SPEC_PREFIX}{hash}")
36}
37
38/// What to do when a workload's guest process exits.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
40#[serde(rename_all = "snake_case")]
41pub enum RestartPolicy {
42    /// Never restart (run-to-completion / job).
43    Never,
44    /// Restart only on a non-zero exit.
45    OnFailure,
46    /// Always keep it running (the default for a service).
47    #[default]
48    Always,
49}
50
51/// The isolation a workload **requires** — the floor the operator's site policy
52/// and the available backends are matched against.
53/// This is the workload's stated need, distinct from the isolation *class* a
54/// backend provides.
55#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum IsolationRequirement {
58    /// Shared-kernel isolation is acceptable (a namespace/container is fine).
59    /// The default — strong isolation is opt-in.
60    #[default]
61    Trusted,
62    /// Strong isolation is required: only a microVM (KVM) or a managed platform
63    /// may run this workload, never a shared-kernel container.
64    Untrusted,
65}
66
67impl IsolationRequirement {
68    /// Whether this is the default (`Trusted`) — used to omit it from the
69    /// serialized spec so existing specs keep their content hash.
70    pub fn is_trusted(&self) -> bool {
71        matches!(self, Self::Trusted)
72    }
73}
74
75/// The source of a workload's **root filesystem**. Each variant is one concrete
76/// artifact form, matched 1:1 to the backends that accept it — modelled explicitly
77/// rather than overloading one string, because an image reference, a tar archive, and
78/// a rootfs block image are genuinely different things and a mismatch should be a
79/// typed error.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "snake_case")]
82pub enum RootSource {
83    /// An **OCI image reference** (`repo:tag` or a digest) a runtime **pulls** from a
84    /// registry; its unpacked layers become the root filesystem. Backends: `docker`,
85    /// `cloudflare`. [`ComputeSpec::kernel`] does not apply.
86    Image(String),
87    /// A **tar rootfs archive** — a blob hash in the shared store — that the node
88    /// **stages and unpacks** into a directory to run. Backend: the native `container`
89    /// runtime. [`ComputeSpec::kernel`] does not apply.
90    Tar(String),
91    /// A **rootfs filesystem image** — a blob hash in the shared store — that the node
92    /// **stages and attaches** as the guest's root **block device**. The filesystem is
93    /// opaque to boatramp: the guest kernel mounts whatever it finds (`ext4` by
94    /// default, since `compute build` uses `mke2fs`, but any kernel-supported
95    /// filesystem works). Backend: the `firecracker` micro-VM, which pairs it with
96    /// [`ComputeSpec::kernel`].
97    Rootfs(String),
98}
99
100impl RootSource {
101    /// The underlying reference string (an image reference for [`RootSource::Image`],
102    /// a blob hash for [`RootSource::Tar`] / [`RootSource::Rootfs`]).
103    pub fn as_str(&self) -> &str {
104        match self {
105            Self::Image(s) | Self::Tar(s) | Self::Rootfs(s) => s,
106        }
107    }
108}
109
110/// A persistent volume attached to the guest (a host block image, snapshotted
111/// to blob storage for durability). Opt-in; the default rootfs is read-only with
112/// an ephemeral scratch drive.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(deny_unknown_fields)]
115pub struct VolumeRef {
116    /// In-guest mount point.
117    pub mount: String,
118    /// Volume name (the host tracks its backing image).
119    pub name: String,
120    /// Size in MiB (used when first provisioning).
121    pub size_mib: u32,
122}
123
124/// An immutable, content-addressed compute workload version (the analogue of a
125/// deployment manifest). Stored at `computever/<hash>`; the rootfs + kernel are
126/// blob hashes in the shared blob store (deduped, cached forever).
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128#[serde(deny_unknown_fields)]
129pub struct ComputeSpec {
130    /// Pinned schema discriminant (`v1`).
131    #[serde(default = "crate::schema_version")]
132    pub version: u32,
133    /// The source of the workload's root filesystem: an OCI image reference, a tar
134    /// rootfs archive, or a rootfs filesystem image, per the target substrate (see
135    /// [`RootSource`]).
136    pub root: RootSource,
137    /// Blob hash of the `vmlinux` kernel (shared across workloads). Applies only to
138    /// the micro-VM substrate (a [`RootSource::Rootfs`] source); ignored otherwise, so
139    /// an image/tar workload omits it (empty ⇒ absent from the wire + the content hash).
140    #[serde(default, skip_serializing_if = "String::is_empty")]
141    pub kernel: String,
142    /// Kernel boot cmdline override; `None` uses the executor default.
143    #[serde(default, skip_serializing_if = "Option::is_none")]
144    pub kernel_cmdline: Option<String>,
145    /// Virtual CPUs.
146    pub vcpus: u32,
147    /// Guest memory in MiB.
148    pub mem_mib: u32,
149    /// The in-guest entrypoint (argv) the init execs.
150    #[serde(default, skip_serializing_if = "Vec::is_empty")]
151    pub entrypoint: Vec<String>,
152    /// Environment variables for the entrypoint.
153    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
154    pub env: BTreeMap<String, String>,
155    /// The TCP port the app listens on inside the guest (the gateway targets it).
156    pub port: u16,
157    /// Restart policy for the guest process.
158    #[serde(default)]
159    pub restart: RestartPolicy,
160    /// Snapshot + stop when idle; restore on the next request (cold start).
161    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
162    pub scale_to_zero: bool,
163    /// Persistent volumes (opt-in).
164    #[serde(default, skip_serializing_if = "Vec::is_empty")]
165    pub volumes: Vec<VolumeRef>,
166    /// Allow a writable root filesystem instead of the hardened read-only-root
167    /// default. Opt-in and honored **only under the single-tenant isolation
168    /// posture** (a backend forces read-only root under the multi-tenant guard).
169    /// The idiomatic path for app writes remains a [`VolumeRef`]; this is for images
170    /// that write outside a declared volume. Default off; omitted from the wire + the
171    /// content hash when false (back-compat).
172    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
173    pub writable_root: bool,
174    /// Isolation the workload requires; selects which backends are eligible.
175    /// Default `Trusted`; omitted from the serialized
176    /// spec when default, so existing specs keep their content hash.
177    #[serde(default, skip_serializing_if = "IsolationRequirement::is_trusted")]
178    pub isolation: IsolationRequirement,
179    /// Optional preferred backend id (`vmm`/`container`/`cloudflare`/`docker`);
180    /// the scheduler honors it when the backend is eligible, else falls back.
181    #[serde(default, skip_serializing_if = "Option::is_none")]
182    pub prefer_backend: Option<String>,
183    /// Managed resources this workload depends on — the opaque-process analogue of a
184    /// handler's `imports`. boatramp resolves each to a **tenant-scoped** endpoint +
185    /// credential at launch and injects the address into the guest env, so a workload
186    /// reaches the managed `sql` (and, later, kv/blob/messaging) without a hand-glued
187    /// URL. Empty ⇒ omitted from the wire + the content hash (back-compat).
188    #[serde(default, skip_serializing_if = "Vec::is_empty")]
189    pub bindings: Vec<ComputeBinding>,
190}
191
192/// A managed-resource dependency a compute workload declares. It names a *resource*,
193/// never a project: the owning project comes from the workload's key
194/// (`project/<proj>/compute/<name>`), so a workload cannot request another tenant's
195/// data. boatramp resolves it at launch and injects the endpoint into the guest env.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct ComputeBinding {
199    /// Which managed resource kind.
200    pub kind: BindingKind,
201    /// The named database/store within the kind (`""` = the site default, matching
202    /// `sql.open("")`).
203    #[serde(default, skip_serializing_if = "String::is_empty")]
204    pub name: String,
205    /// The env var the resolved endpoint URL is injected as; `None` ⇒ the kind default
206    /// (`sql` → `BOATRAMP_SQL_URL`). The credential is injected as `<url_env>_AUTH_TOKEN`.
207    #[serde(default, skip_serializing_if = "Option::is_none")]
208    pub url_env: Option<String>,
209}
210
211/// The managed-resource kinds a [`ComputeBinding`] may name. Phase 0 implements `Sql`;
212/// the others are reserved for the shared resolver mechanism.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
214#[serde(rename_all = "lowercase")]
215pub enum BindingKind {
216    /// The managed `sql` database (per-site libsql, or a named external DB).
217    Sql,
218    /// Per-site key-value store (Phase 2).
219    Kv,
220    /// Per-site blob store (Phase 2).
221    Blob,
222    /// Per-site pub/sub + queues (Phase 2).
223    Messaging,
224}
225
226impl ComputeBinding {
227    /// The env var the endpoint URL is injected as (explicit `url_env`, else the kind
228    /// default). The auth token is injected as this name plus `_AUTH_TOKEN`.
229    pub fn url_env(&self) -> String {
230        self.url_env
231            .clone()
232            .unwrap_or_else(|| self.kind.default_url_env().to_string())
233    }
234}
235
236impl BindingKind {
237    /// The default env var an endpoint of this kind is injected as.
238    pub fn default_url_env(self) -> &'static str {
239        match self {
240            Self::Sql => "BOATRAMP_SQL_URL",
241            Self::Kv => "BOATRAMP_KV_URL",
242            Self::Blob => "BOATRAMP_BLOB_URL",
243            Self::Messaging => "BOATRAMP_MESSAGING_URL",
244        }
245    }
246}
247
248impl ComputeSpec {
249    /// The content hash of this spec — its `computever/<hash>` id. Computed over
250    /// the canonical JSON so identical specs dedupe (like a deployment id).
251    pub fn id(&self) -> String {
252        let canonical = serde_json::to_vec(self).expect("ComputeSpec serializes");
253        sha256_hex(&canonical)
254    }
255}
256
257/// Placement constraints: where a workload's replicas may run.
258#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct PlacementConstraints {
261    /// If non-empty, only nodes in one of these regions are eligible.
262    pub regions: Vec<String>,
263    /// Required node labels (all must match a node's advertised labels).
264    pub labels: BTreeMap<String, String>,
265}
266
267impl PlacementConstraints {
268    /// Whether a node with `node_region` + `node_labels` satisfies these
269    /// constraints.
270    pub fn allows(
271        &self,
272        node_region: Option<&str>,
273        node_labels: &BTreeMap<String, String>,
274    ) -> bool {
275        if !self.regions.is_empty() {
276            match node_region {
277                Some(r) if self.regions.iter().any(|want| want == r) => {}
278                _ => return false,
279            }
280        }
281        self.labels
282            .iter()
283            .all(|(k, v)| node_labels.get(k).is_some_and(|nv| nv == v))
284    }
285}
286
287/// The mutable desired state for a workload (`compute/<name>`): the active spec
288/// version, replica count, and placement. Activation is a pointer flip to a new
289/// spec hash — the same atomic, roll-back-able model as a site deployment.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292pub struct ComputeWorkload {
293    /// Pinned schema discriminant (`v1`).
294    #[serde(default = "crate::schema_version")]
295    pub version: u32,
296    /// Human label (the workload name is the KV key).
297    pub name: String,
298    /// The active [`ComputeSpec`] content hash (`computever/<hash>`).
299    pub active: String,
300    /// Desired replica count.
301    pub replicas: u32,
302    /// Placement constraints.
303    #[serde(default)]
304    pub placement: PlacementConstraints,
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    fn spec() -> ComputeSpec {
312        ComputeSpec {
313            version: crate::SCHEMA_VERSION,
314            root: RootSource::Rootfs("a".repeat(64)),
315            kernel: "b".repeat(64),
316            kernel_cmdline: None,
317            vcpus: 2,
318            mem_mib: 512,
319            entrypoint: vec!["/app".into(), "--serve".into()],
320            env: BTreeMap::from([("PORT".to_string(), "8080".to_string())]),
321            port: 8080,
322            restart: RestartPolicy::Always,
323            scale_to_zero: true,
324            volumes: vec![],
325            writable_root: false,
326            isolation: IsolationRequirement::Trusted,
327            prefer_backend: None,
328            bindings: vec![],
329        }
330    }
331
332    #[test]
333    fn empty_bindings_do_not_change_the_spec_hash() {
334        // A spec that declares no bindings serializes without the field, so it hashes
335        // identically to a pre-bindings spec (back-compat).
336        let a = spec();
337        let json = serde_json::to_string(&a).unwrap();
338        assert!(!json.contains("bindings"), "empty bindings are omitted");
339
340        // Declaring a binding is recorded and changes the content hash.
341        let mut b = spec();
342        b.bindings = vec![ComputeBinding {
343            kind: BindingKind::Sql,
344            name: String::new(),
345            url_env: None,
346        }];
347        assert_ne!(a.id(), b.id(), "a declared binding changes the id");
348        assert!(serde_json::to_string(&b).unwrap().contains("bindings"));
349    }
350
351    #[test]
352    fn binding_kind_parses_lowercase_and_url_env_defaults_per_kind() {
353        assert_eq!(
354            serde_json::from_str::<BindingKind>("\"sql\"").unwrap(),
355            BindingKind::Sql
356        );
357        let sql = ComputeBinding {
358            kind: BindingKind::Sql,
359            name: String::new(),
360            url_env: None,
361        };
362        assert_eq!(sql.url_env(), "BOATRAMP_SQL_URL");
363        let custom = ComputeBinding {
364            kind: BindingKind::Sql,
365            name: "analytics".into(),
366            url_env: Some("ANALYTICS_URL".into()),
367        };
368        assert_eq!(custom.url_env(), "ANALYTICS_URL");
369    }
370
371    #[test]
372    fn spec_id_is_stable_and_content_addressed() {
373        let a = spec();
374        let mut b = spec();
375        assert_eq!(a.id(), b.id(), "identical specs share an id");
376        b.vcpus = 4;
377        assert_ne!(a.id(), b.id(), "a changed field changes the id");
378        assert_eq!(a.id().len(), 64);
379    }
380
381    #[test]
382    fn default_isolation_does_not_change_the_spec_hash() {
383        // `Trusted` (default) is omitted from the JSON, so a spec that doesn't
384        // touch isolation hashes identically to one explicitly set to Trusted.
385        let mut a = spec();
386        a.isolation = IsolationRequirement::Trusted;
387        let json = serde_json::to_string(&a).unwrap();
388        assert!(!json.contains("isolation"), "default isolation is omitted");
389        // Untrusted is recorded and changes the hash.
390        let mut b = spec();
391        b.isolation = IsolationRequirement::Untrusted;
392        assert_ne!(a.id(), b.id());
393        assert!(serde_json::to_string(&b).unwrap().contains("untrusted"));
394    }
395
396    #[test]
397    fn spec_round_trips_through_json() {
398        let a = spec();
399        let json = serde_json::to_string(&a).unwrap();
400        assert_eq!(serde_json::from_str::<ComputeSpec>(&json).unwrap(), a);
401    }
402
403    #[test]
404    fn keyspace_helpers() {
405        assert_eq!(
406            workload_key("default", "api"),
407            "project/default/compute/api"
408        );
409        assert_eq!(workload_key("acme", "api"), "project/acme/compute/api");
410        assert_eq!(workloads_prefix("default"), "project/default/compute/");
411        // The spec body is content-addressed and stays global (dedup across projects).
412        assert_eq!(spec_key("deadbeef"), "computever/deadbeef");
413    }
414
415    #[test]
416    fn placement_matches_region_and_labels() {
417        let c = PlacementConstraints {
418            regions: vec!["eu".into()],
419            labels: BTreeMap::from([("gpu".to_string(), "yes".to_string())]),
420        };
421        let labels = BTreeMap::from([("gpu".to_string(), "yes".to_string())]);
422        assert!(c.allows(Some("eu"), &labels));
423        assert!(!c.allows(Some("us"), &labels), "wrong region");
424        assert!(!c.allows(Some("eu"), &BTreeMap::new()), "missing label");
425        // No constraints → any node.
426        assert!(PlacementConstraints::default().allows(None, &BTreeMap::new()));
427    }
428}