Skip to main content

microvms_core/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The composition root for the MicroVMs client (ARCH-8). It wires production edges
3//! into application use cases and re-exports the domain, application, edges, and
4//! protocol APIs at the paths the CLI and bindings consume (ARCH-1).
5//!
6//! # What this crate is for
7//!
8//! The domain owns rules and values without I/O; the application owns use cases
9//! against ports; the edges implement those ports. This crate provides the
10//! production constructors while keeping callers independent of that wiring.
11//! It depends on neither the CLI nor the bindings (ARCH-4).
12//!
13//! `docs/PLATFORM.md` records dated observations of AWS Lambda MicroVMs.
14//! Shared rules turn those observations into validation and defaults so callers
15//! receive the same behavior through Rust, the CLI, Python, and Node.js.
16//!
17//! # How strongly a trap is closed
18//!
19//! The spec ranks each closure, strongest first:
20//!
21//! * **S1, inexpressible** — the mistake cannot be written down. [`region::Region`] is
22//!   an enum over the supported regions that carry MicroVMs, so a typo'd region is a
23//!   compile error rather than a runtime check; [`sizing::SizeClass`] is closed over
24//!   the documented baselines; [`hooks::RunHookTimeout`] and
25//!   [`hooks::BuildHookTimeout`] are separate types with no conversion between them,
26//!   so a 3600-second build timeout cannot reach a field that caps at 60.
27//! * **S2, expressible but rejected** — the mistake can be written and the client
28//!   refuses it locally, before any control-plane call, with an error naming the
29//!   `docs/PLATFORM.md` finding. Weaker because the guard is code that can regress,
30//!   but it costs seconds rather than a build cycle. Every boundary where a bare
31//!   integer or string still has to be judged lands here:
32//!   [`sizing::SizeClass::from_baseline_mib`], `Region::from_str`.
33//! * **S3, correct by default and overridable** — weakest, because it protects the
34//!   caller who does nothing and abandons the one who overrides. An S3 closure must
35//!   say what the override costs: [`region::Region::unlisted`] says it costs you the
36//!   diagnostic.
37//!
38//! # Every error message names its finding
39//!
40//! A local reject explains itself by naming the `docs/PLATFORM.md` section that
41//! measured the behavior, because the codes and the guards exist precisely so a
42//! reader can go to the measurement rather than to a constraint. "region
43//! 'eu-central-1' is invalid" sends someone to check their spelling; the message
44//! [`region::Region`] actually raises sends them to the null-message finding.
45//!
46//! # A guard that cannot fail is worse than no guard
47//!
48//! Carried over from the Python era unchanged: every guard here has a falsification —
49//! a specific plausible edit that must turn a specific test red. "Delete the feature
50//! and the test fails" does not count. The clearest case is TRAP-13 in
51//! [`sizing`]: every documented peak is exactly four times its baseline, so a test
52//! against the shipped table cannot tell a table lookup from `baseline * 4`, and the
53//! guard has to drive the lookup over a table where the pattern does not hold.
54//!
55//! # Layout
56//!
57//! This crate is the composition root (ARCH-8). The code lives in the crates below it, and
58//! every item they export is re-exported here at the path it had in 0.10:
59//!
60//! * `microvms-domain`: the rules and values, with no I/O (ARCH-6): [`error`], [`region`],
61//!   [`sizing`], [`hooks`], [`constants`], [`cost`], and the pure halves of [`names`],
62//!   [`preflight`], [`identity`] and [`provision`].
63//! * `microvms-app`: the use cases, written only against ports (ARCH-7): [`control`],
64//!   [`session`], [`sandbox`], [`agents`], and the ports themselves, [`clock`], [`entropy`] and
65//!   [`adapters`].
66//! * `microvms-edges`: the production port implementations: the signed transport, the reqwest
67//!   backend, the sockets, the name registry on disk, [`provision`]'s fetch, and
68//!   [`env`](mod@env), the one process-environment lookup.
69//! * `protocol`, the wire contract shared with the daemon.
70//!
71//! What this crate adds is the wiring: [`prelude`]'s constructors (`ControlPlane::new`,
72//! `Sandbox::new`, `Session::connect` and the rest) put the production transport, clock,
73//! entropy and adapters into each type's port-taking constructor, and the free functions that
74//! read the production clock or pool keep their paths here. `use microvms_core::prelude::*;`
75//! keeps a 0.10 call compiling. The shared test doubles are in `testing`, behind the
76//! `test-support` feature.
77
78// CLI-7: a print macro panics when its stream's reader has gone (#216). Every write goes
79// through a checked writer instead.
80#![deny(clippy::print_stdout, clippy::print_stderr)]
81
82pub mod identity;
83pub mod prelude;
84
85// The rules and values live in `microvms-domain`, which can't do I/O (ARCH-6). Re-exported
86// whole, so every `microvms_core::` path they had still resolves (ARCH-1).
87pub use microvms_domain::{constants, cost, duration, error, hooks, region, sizing};
88
89// Whole modules that live in one crate below.
90pub use microvms_app::{defaults, sandbox};
91pub use microvms_edges::{env, provision, secret_input};
92
93// Re-exported so consumers name wire types through this crate rather than
94// depending on `protocol` directly — the CLI's thinness guard counts on that.
95pub use protocol;
96
97pub use error::{Error, ErrorKind, WireKind};
98pub use hooks::{BuildHookTimeout, RunHookTimeout};
99pub use region::Region;
100pub use sizing::SizeClass;
101
102/// The crate's own version, for a `doctor` or `manifest` command to report.
103pub const VERSION: &str = env!("CARGO_PKG_VERSION");
104
105// The README's example is the first code a crates.io reader copies, so it compiles as a
106// doctest (`no_run`: it launches a billed VM).
107#[cfg(doctest)]
108#[doc = include_str!("../README.md")]
109struct ReadmeExample;
110
111/// The edges' S3 and STS request helpers stay out of this crate's API: they were
112/// `pub(crate)` in 0.10, and one of them returns an `aws-sigv4` type, so exporting it would
113/// tie this crate's semver to that one's.
114///
115/// ```compile_fail
116/// let _ = microvms_core::control::services::s3_signing_settings();
117/// ```
118#[cfg(doctest)]
119struct EdgesHelpersStayPrivate;
120
121// Each module below is a use-case module from `microvms-app` with the production pieces
122// `microvms-edges` supplies for it, at the paths both had when they were one crate. A local
123// item or module shadows a glob, which is how a submodule that has halves in both crates is
124// merged.
125
126pub mod adapters {
127    //! The adapters port and its production implementation.
128    pub use microvms_app::adapters::*;
129    pub use microvms_edges::adapters::SystemAdapters;
130}
131
132pub mod clock {
133    //! The one clock port and tokio's clock.
134    pub use microvms_app::clock::*;
135    pub use microvms_edges::clock::{SystemClock, TokioClock};
136}
137
138pub mod entropy {
139    //! The entropy port and the OS random pool.
140    pub use microvms_app::entropy::*;
141    pub use microvms_edges::entropy::OsEntropy;
142}
143
144pub mod names {
145    //! Named MicroVMs: the record, the store port, and the CLI's registry on disk.
146    pub use microvms_app::names::*;
147    pub use microvms_edges::names::{FileNameStore, state_root};
148}
149
150pub mod preflight {
151    //! Whether a harness can launch here, checked before it queues work (#223).
152    //!
153    //! The checks are `microvms_app::preflight`'s; [`preflight`] runs them over the
154    //! production control plane.
155    pub use microvms_app::preflight::*;
156
157    use crate::control::ControlPlane;
158    use crate::prelude::ControlPlaneExt as _;
159    use crate::region::Region;
160
161    /// Runs the three checks for `region`, or for the region the environment names.
162    ///
163    /// The bindings' `preflight`. See the module docs of `microvms_app::preflight` for what
164    /// it checks, what it does not, and why nothing it does bills.
165    pub async fn preflight(region: Option<Region>) -> PreflightReport {
166        let resolved = match region {
167            Some(region) => Ok(region),
168            None => Region::from_env(&crate::env::process),
169        };
170        preflight_with(resolved, ControlPlane::new).await
171    }
172}
173
174pub mod agents {
175    //! The coding-agent helpers `docs/AGENT-VMS.md` specifies, and the Bedrock minter.
176    pub use microvms_app::agents::*;
177
178    use crate::error::Error;
179
180    pub mod bedrock {
181        //! A Bedrock bearer token from the caller's own AWS credentials (AGENT-4).
182        pub use microvms_app::agents::bedrock::*;
183        pub use microvms_edges::agents::bedrock::*;
184    }
185
186    /// The start request for one task (AGENT-7), with an exec id from the production clock
187    /// when `options` carries none. [`prompt_request_with`] over [`crate::session::mint_exec_id`].
188    pub fn prompt_request(
189        spec: &AgentSpec,
190        task: &str,
191        options: &PromptOptions,
192    ) -> Result<crate::protocol::exec::StartRequest, Error> {
193        prompt_request_with(spec, task, options, crate::session::mint_exec_id)
194    }
195}
196
197pub mod control {
198    //! The control-plane client, with the signed transport and the build services.
199    pub use microvms_app::control::*;
200    pub use microvms_edges::clock::SystemClock;
201    pub use microvms_edges::control::SignedBuildServices;
202
203    pub mod context {
204        //! A task's build context, and reading one from a directory (#221, IMAGE-7).
205        pub use microvms_app::control::context::*;
206        pub use microvms_edges::control::context::from_dir;
207    }
208
209    pub mod project {
210        //! A project directory's dependency files: the pairing rule, and reading the pair
211        //! from a directory (#74, #264).
212        pub use microvms_app::control::project::*;
213        pub use microvms_edges::control::project::read_project_files;
214    }
215    pub use project::read_project_files;
216
217    pub mod services {
218        //! The STS and S3 calls `ensure_image` makes, and their SigV4 implementation.
219        pub use microvms_app::control::services::*;
220        // Named, not globbed: the edges' request helpers are `pub(crate)` there, and a glob
221        // would make the next one that goes `pub` (and its aws-sigv4 types) core's API too.
222        pub use microvms_edges::control::services::SignedBuildServices;
223    }
224
225    pub mod transport {
226        //! The control plane's calls, the transport port, and the signed transport.
227        pub use microvms_app::control::transport::*;
228        pub use microvms_edges::control::transport::SignedTransport;
229    }
230
231    pub mod token {
232        //! Idempotency tokens, unique per attempt by construction (TRAP-1).
233        pub use microvms_app::control::token::*;
234        use microvms_edges::entropy::OsEntropy;
235
236        /// An image-create idempotency token, unique per attempt, from the OS random pool.
237        ///
238        /// [`create_token_with`] over the OS pool. `scope` is a label only, folded in beside
239        /// the nonce; see the module docs of `microvms_app::control::token` for the
240        /// fifteen-hour wedge that closure exists to prevent. An unavailable pool panics. A
241        /// control plane mints through its own source instead, so a launch refuses rather
242        /// than panics.
243        pub fn create_token(scope: &str) -> String {
244            create_token_with(scope, &OsEntropy).expect("the OS random pool is available")
245        }
246
247        /// A run idempotency token, unique per attempt, from the OS random pool. Same rule as
248        /// [`create_token`].
249        pub fn run_token(scope: &str) -> String {
250            run_token_with(scope, &OsEntropy).expect("the OS random pool is available")
251        }
252    }
253}
254
255pub mod session {
256    //! The in-VM client, with the reqwest backend and the sockets.
257    pub use microvms_app::session::*;
258    pub use microvms_edges::clock::TokioClock;
259    pub use microvms_edges::session::*;
260
261    pub mod http {
262        //! The HTTP seam and the production backend.
263        pub use microvms_app::session::http::*;
264        pub use microvms_edges::session::http::ReqwestBackend;
265    }
266
267    pub mod proxy {
268        //! The two-header proxy auth and the mint schedule, on tokio's clock in production.
269        pub use microvms_app::session::proxy::*;
270        pub use microvms_edges::clock::TokioClock;
271    }
272
273    pub mod exec {
274        //! The exec handle and the cursor-driven stream, with the production exec id.
275        pub use microvms_app::session::exec::*;
276
277        pub use super::mint_exec_id;
278    }
279
280    /// A fresh exec id from the production clock: `x-` plus 16 hex characters.
281    ///
282    /// [`exec_id_at`] over tokio's clock. Code holding a [`Session`] mints through the
283    /// session's clock instead, so a test that pins the clock pins the id.
284    pub fn mint_exec_id() -> String {
285        use microvms_app::clock::Clock as _;
286        exec_id_at(TokioClock::new().unix_now())
287    }
288}
289
290pub mod workspace {
291    //! Directory transfer: the manifest, the diff and the sync pass, over the real filesystem's
292    //! walk, hash, pack and guarded extraction (#260).
293    pub use microvms_app::workspace::*;
294    pub use microvms_edges::workspace::*;
295}
296
297#[cfg(feature = "test-support")]
298pub mod testing {
299    //! The shared test doubles, for a dependent's tests: `microvms_app::testing`.
300    pub use microvms_app::testing::*;
301}
302
303#[cfg(test)]
304mod tests {
305    use std::collections::HashSet;
306
307    /// The OS-pool tokens are distinct per call. The nonce is the pool's draw, so this is the
308    /// pool's distinctness as the token functions see it (TRAP-1).
309    ///
310    /// **Falsification**: mint `create_token` from a fixed source and the set collapses to one.
311    #[test]
312    fn the_os_pool_tokens_never_repeat() {
313        let minted: HashSet<String> = (0..200)
314            .flat_map(|_| {
315                [
316                    crate::control::token::create_token("img"),
317                    crate::control::token::run_token("img"),
318                ]
319            })
320            .collect();
321        assert_eq!(minted.len(), 400);
322    }
323
324    /// Two production exec ids differ, even minted in one instant.
325    #[test]
326    fn production_exec_ids_are_distinct() {
327        let minted: HashSet<String> = (0..200).map(|_| crate::session::mint_exec_id()).collect();
328        assert_eq!(minted.len(), 200);
329    }
330}
331
332pub mod history;
333pub mod ledger;