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