spin_core/lib.rs
1//! Spin core execution engine
2//!
3//! This crate provides low-level Wasm functionality required by Spin. Most of
4//! this functionality consists of wrappers around [`wasmtime`] that narrow the
5//! flexibility of `wasmtime` to the set of features used by Spin (such as only
6//! supporting `wasmtime`'s async calling style).
7
8#![deny(missing_docs)]
9
10mod limits;
11mod store;
12
13use std::sync::OnceLock;
14use std::{path::PathBuf, time::Duration};
15
16use anyhow::Result;
17use tracing::instrument;
18use wasmtime::{InstanceAllocationStrategy, PoolingAllocationConfig};
19
20pub use async_trait::async_trait;
21pub use wasmtime::Engine as WasmtimeEngine;
22pub use wasmtime::{
23 self,
24 component::{Component, Instance, InstancePre, Linker},
25 Instance as ModuleInstance, Module, Trap,
26};
27
28pub use store::{AsState, Store, StoreBuilder};
29
30/// The default [`EngineBuilder::epoch_tick_interval`].
31pub const DEFAULT_EPOCH_TICK_INTERVAL: Duration = Duration::from_millis(10);
32
33const MB: u64 = 1 << 20;
34const GB: usize = 1 << 30;
35
36/// Global configuration for `EngineBuilder`.
37///
38/// This is currently only used for advanced (undocumented) use cases.
39pub struct Config {
40 inner: wasmtime::Config,
41}
42
43impl Config {
44 /// Borrow the inner wasmtime::Config mutably.
45 /// WARNING: This is inherently unstable and may break at any time!
46 #[doc(hidden)]
47 pub fn wasmtime_config(&mut self) -> &mut wasmtime::Config {
48 &mut self.inner
49 }
50
51 /// Enable the Wasmtime compilation cache. If `path` is given it will override
52 /// the system default path.
53 ///
54 /// For more information, see the [Wasmtime cache config documentation][docs].
55 ///
56 /// [docs]: https://docs.wasmtime.dev/cli-cache.html
57 pub fn enable_cache(&mut self, config_path: &Option<PathBuf>) -> Result<()> {
58 self.inner
59 .cache(Some(wasmtime::Cache::from_file(config_path.as_deref())?));
60
61 Ok(())
62 }
63
64 /// Disable the pooling instance allocator.
65 pub fn disable_pooling(&mut self) -> &mut Self {
66 self.inner
67 .allocation_strategy(wasmtime::InstanceAllocationStrategy::OnDemand);
68 self
69 }
70}
71
72impl Default for Config {
73 fn default() -> Self {
74 let mut inner = wasmtime::Config::new();
75 inner.async_support(true);
76 inner.epoch_interruption(true);
77 inner.wasm_component_model(true);
78 inner.wasm_component_model_async(true);
79 // If targeting musl, disable native unwind to address this issue:
80 // https://github.com/spinframework/spin/issues/2889
81 // TODO: remove this when wasmtime is updated to >= v27.0.0
82 #[cfg(all(target_os = "linux", target_env = "musl"))]
83 inner.native_unwind_info(false);
84
85 if use_pooling_allocator_by_default() {
86 // Baseline for the maximum number of instances in spin through
87 // which a number of other defaults are derived below.
88 let max_instances = env("SPIN_MAX_INSTANCE_COUNT", 1_000);
89
90 // By default enable the pooling instance allocator in Wasmtime. This
91 // drastically reduces syscall/kernel overhead for wasm execution,
92 // especially in async contexts where async stacks must be allocated.
93 // The general goal here is that the default settings here rarely, if
94 // ever, need to be modified. As a result there aren't fine-grained
95 // knobs for each of these settings just yet and instead they're
96 // generally set to defaults. Environment-variable-based fallbacks are
97 // supported though as an escape valve for if this is a problem.
98 let mut pooling_config = PoolingAllocationConfig::default();
99 pooling_config
100 // Configuration parameters which affect the total size of the
101 // allocation pool as well as the maximum number of concurrently
102 // live instances at once. These can be configured individually
103 // but otherwise default to a factor-of-`max_instances` above.
104 //
105 // * Component instances are the maximum live number of
106 // component instances or instantiations. In other words this
107 // is the maximal concurrency that Spin can serve in terms of
108 // HTTP requests.
109 //
110 // * Memories mostly affect how big the virtual address space
111 // reservation is for the pooling allocator. Memories require
112 // ~4G of virtual address space meaning that we can run out
113 // pretty quickly.
114 //
115 // * Tables are not as costly as memories in terms of virtual
116 // memory and mostly just need to be in the same order of
117 // magnitude to run that many components.
118 //
119 // * Core instances do not have a virtual memory reservation at
120 // this time, it's just a counter to cap the maximum amount of
121 // memory allocated (multiplied by `max_core_instance_size`
122 // below) so the limit is more liberal.
123 //
124 // * Table elements limit the maximum size of any allocated
125 // table, so it's set generously large. This does affect
126 // virtual memory reservation but it's just 8 bytes per table
127 // slot.
128 .total_component_instances(env("SPIN_WASMTIME_INSTANCE_COUNT", max_instances))
129 .total_memories(env("SPIN_WASMTIME_TOTAL_MEMORIES", max_instances))
130 .total_tables(env("SPIN_WASMTIME_TOTAL_TABLES", 2 * max_instances))
131 .total_stacks(env("SPIN_WASMTIME_TOTAL_STACKS", max_instances))
132 .total_core_instances(env("SPIN_WASMTIME_TOTAL_CORE_INSTANCES", 4 * max_instances))
133 .table_elements(env("SPIN_WASMTIME_INSTANCE_TABLE_ELEMENTS", 100_000))
134 // This number accounts for internal data structures that Wasmtime allocates for each instance.
135 // Instance allocation is proportional to the number of "things" in a wasm module like functions,
136 // globals, memories, etc. Instance allocations are relatively small and are largely inconsequential
137 // compared to other runtime state, but a number needs to be chosen here so a relatively large threshold
138 // of 10MB is arbitrarily chosen. It should be unlikely that any reasonably-sized module hits this limit.
139 .max_component_instance_size(env("SPIN_WASMTIME_INSTANCE_SIZE", 10 * MB) as usize)
140 .max_core_instance_size(env("SPIN_WASMTIME_CORE_INSTANCE_SIZE", 10 * MB) as usize)
141 // Configuration knobs for hard limits per-component for various
142 // items that require allocations. Note that these are
143 // per-component limits and instantiating a component still has
144 // to fit into the `total_*` limits above at runtime.
145 //
146 // * Core instances are more or less a reflection of how many
147 // nested components can be in a component (e.g. via
148 // composition)
149 // * The number of memories an instance can have effectively
150 // limits the number of inner components a composed component
151 // can have (since each inner component has its own memory).
152 // We default to 32 for now, and we'll see how often this
153 // limit gets reached.
154 // * Tables here are roughly similar to memories but are set a
155 // bit higher as it's more likely to have more tables than
156 // memories in a component.
157 .max_core_instances_per_component(env("SPIN_WASMTIME_CORE_INSTANCE_COUNT", 200))
158 .max_tables_per_component(env("SPIN_WASMTIME_INSTANCE_TABLES", 64))
159 .max_memories_per_component(env("SPIN_WASMTIME_INSTANCE_MEMORIES", 32))
160 // Similar knobs as above, but as specified per-module instead
161 // of per-component. Note that these limits are much lower as
162 // core modules typically only have one of each.
163 .max_tables_per_module(env("SPIN_WASMTIME_MAX_TABLES_PER_MODULE", 2))
164 .max_memories_per_module(env("SPIN_WASMTIME_MAX_MEMORIES_PER_MODULE", 2))
165 // Nothing is lost from allowing the maximum size of memory for
166 // all instance as it's still limited through other the normal
167 // `StoreLimitsAsync` accounting method too.
168 .max_memory_size(4 * GB)
169 // These numbers are completely arbitrary at something above 0.
170 .linear_memory_keep_resident(env(
171 "SPIN_WASMTIME_LINEAR_MEMORY_KEEP_RESIDENT",
172 2 * MB,
173 ) as usize)
174 .table_keep_resident(env("SPIN_WASMTIME_TABLE_KEEP_RESIDENT", MB / 2) as usize);
175 inner.allocation_strategy(InstanceAllocationStrategy::Pooling(pooling_config));
176 }
177
178 return Self { inner };
179
180 fn env<T>(name: &str, default: T) -> T
181 where
182 T: std::str::FromStr,
183 T::Err: std::fmt::Display,
184 {
185 match std::env::var(name) {
186 Ok(val) => val
187 .parse()
188 .unwrap_or_else(|e| panic!("failed to parse env var `{name}={val}`: {e}")),
189 Err(_) => default,
190 }
191 }
192 }
193}
194
195/// The pooling allocator is tailor made for the `spin up` use case, so
196/// try to use it when we can. The main cost of the pooling allocator, however,
197/// is the virtual memory required to run it. Not all systems support the same
198/// amount of virtual memory, for example some aarch64 and riscv64 configuration
199/// only support 39 bits of virtual address space.
200///
201/// The pooling allocator, by default, will request 1000 linear memories each
202/// sized at 6G per linear memory. This is 6T of virtual memory which ends up
203/// being about 42 bits of the address space. This exceeds the 39 bit limit of
204/// some systems, so there the pooling allocator will fail by default.
205///
206/// This function attempts to dynamically determine the hint for the pooling
207/// allocator. This returns `true` if the pooling allocator should be used
208/// by default, or `false` otherwise.
209///
210/// The method for testing this is to allocate a 0-sized 64-bit linear memory
211/// with a maximum size that's N bits large where we force all memories to be
212/// static. This should attempt to acquire N bits of the virtual address space.
213/// If successful that should mean that the pooling allocator is OK to use, but
214/// if it fails then the pooling allocator is not used and the normal mmap-based
215/// implementation is used instead.
216fn use_pooling_allocator_by_default() -> bool {
217 static USE_POOLING: OnceLock<bool> = OnceLock::new();
218 const BITS_TO_TEST: u32 = 42;
219
220 *USE_POOLING.get_or_init(|| {
221 // Enable manual control through env vars as an escape hatch
222 match std::env::var("SPIN_WASMTIME_POOLING") {
223 Ok(s) if s == "1" => return true,
224 Ok(s) if s == "0" => return false,
225 Ok(s) => panic!("SPIN_WASMTIME_POOLING={s} not supported, only 1/0 supported"),
226 Err(_) => {}
227 }
228
229 // If the env var isn't set then perform the dynamic runtime probe
230 let mut config = wasmtime::Config::new();
231 config.wasm_memory64(true);
232 config.memory_reservation(1 << BITS_TO_TEST);
233
234 match wasmtime::Engine::new(&config) {
235 Ok(engine) => {
236 let mut store = wasmtime::Store::new(&engine, ());
237 // NB: the maximum size is in wasm pages so take out the 16-bits
238 // of wasm page size here from the maximum size.
239 let ty = wasmtime::MemoryType::new64(0, Some(1 << (BITS_TO_TEST - 16)));
240 wasmtime::Memory::new(&mut store, ty).is_ok()
241 }
242 Err(_) => {
243 tracing::debug!(
244 "unable to create an engine to test the pooling \
245 allocator, disabling pooling allocation"
246 );
247 false
248 }
249 }
250 })
251}
252
253/// Host state data associated with individual [Store]s and [Instance]s.
254#[derive(Default)]
255pub struct State {
256 store_limits: limits::StoreLimitsAsync,
257}
258
259impl State {
260 /// Get the amount of memory in bytes consumed by instances in the store
261 pub fn memory_consumed(&self) -> u64 {
262 self.store_limits.memory_consumed()
263 }
264}
265
266/// A builder interface for configuring a new [`Engine`].
267///
268/// A new [`EngineBuilder`] can be obtained with [`Engine::builder`].
269pub struct EngineBuilder<T: 'static> {
270 engine: wasmtime::Engine,
271 linker: Linker<T>,
272 epoch_tick_interval: Duration,
273 epoch_ticker_thread: bool,
274}
275
276impl<T: 'static> EngineBuilder<T> {
277 fn new(config: &Config) -> Result<Self> {
278 let engine = wasmtime::Engine::new(&config.inner)?;
279 let linker: Linker<T> = Linker::new(&engine);
280 Ok(Self {
281 engine,
282 linker,
283 epoch_tick_interval: DEFAULT_EPOCH_TICK_INTERVAL,
284 epoch_ticker_thread: true,
285 })
286 }
287
288 /// Returns a reference to the [`Linker`] for this [`Engine`].
289 pub fn linker(&mut self) -> &mut Linker<T> {
290 &mut self.linker
291 }
292
293 /// Sets the epoch tick internal for the built [`Engine`].
294 ///
295 /// This is used by [`Store::set_deadline`] to calculate the number of
296 /// "ticks" for epoch interruption, and by the default epoch ticker thread.
297 /// The default is [`DEFAULT_EPOCH_TICK_INTERVAL`].
298 ///
299 /// See [`EngineBuilder::epoch_ticker_thread`] and
300 /// [`wasmtime::Config::epoch_interruption`](https://docs.rs/wasmtime/latest/wasmtime/struct.Config.html#method.epoch_interruption).
301 pub fn epoch_tick_interval(&mut self, interval: Duration) {
302 self.epoch_tick_interval = interval;
303 }
304
305 /// Configures whether the epoch ticker thread will be spawned when this
306 /// [`Engine`] is built.
307 ///
308 /// Enabled by default; if disabled, the user must arrange to call
309 /// `engine.as_ref().increment_epoch()` every `epoch_tick_interval` or
310 /// interrupt-based features like `Store::set_deadline` will not work.
311 pub fn epoch_ticker_thread(&mut self, enable: bool) {
312 self.epoch_ticker_thread = enable;
313 }
314
315 fn maybe_spawn_epoch_ticker(&self) {
316 if !self.epoch_ticker_thread {
317 return;
318 }
319 let engine_weak = self.engine.weak();
320 let interval = self.epoch_tick_interval;
321 std::thread::spawn(move || loop {
322 std::thread::sleep(interval);
323 let Some(engine) = engine_weak.upgrade() else {
324 break;
325 };
326 engine.increment_epoch();
327 });
328 }
329
330 /// Builds an [`Engine`] from this builder.
331 pub fn build(self) -> Engine<T> {
332 self.maybe_spawn_epoch_ticker();
333 Engine {
334 inner: self.engine,
335 linker: self.linker,
336 epoch_tick_interval: self.epoch_tick_interval,
337 }
338 }
339}
340
341/// An `Engine` is a global context for the initialization and execution of
342/// Spin components.
343pub struct Engine<T: 'static> {
344 inner: wasmtime::Engine,
345 linker: Linker<T>,
346 epoch_tick_interval: Duration,
347}
348
349impl<T: 'static> Engine<T> {
350 /// Creates a new [`EngineBuilder`] with the given [`Config`].
351 pub fn builder(config: &Config) -> Result<EngineBuilder<T>> {
352 EngineBuilder::new(config)
353 }
354
355 /// Creates a new [`StoreBuilder`].
356 pub fn store_builder(&self) -> StoreBuilder {
357 StoreBuilder::new(self.inner.clone(), self.epoch_tick_interval)
358 }
359
360 /// Creates a new [`InstancePre`] for the given [`Component`].
361 #[instrument(skip_all, level = "debug")]
362 pub fn instantiate_pre(&self, component: &Component) -> Result<InstancePre<T>> {
363 self.linker.instantiate_pre(component)
364 }
365}
366
367impl<T> AsRef<wasmtime::Engine> for Engine<T> {
368 fn as_ref(&self) -> &wasmtime::Engine {
369 &self.inner
370 }
371}