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