wasmer_wasix/runtime/module_cache/
mod.rs

1//! Cache pre-compiled [`wasmer::Module`]s.
2//!
3//! The core of this module is the [`ModuleCache`] trait, which is designed to
4//! be implemented by different cache storage strategies, such as in-memory
5//! caches ([`SharedCache`] and [`ThreadLocalCache`]), file-based caches
6//! ([`FileSystemCache`]), or distributed caches. Implementing custom caching
7//! strategies allows you to optimize for your specific use case.
8//!
9//! ## Assumptions and Requirements
10//!
11//! The `module_cache` module makes several assumptions:
12//!
13//! - Cache keys are unique, typically derived from the original `*.wasm` or
14//!   `*.wat` file, and using the same key to load or save will always result in
15//!   the "same" module.
16//! - The [`ModuleCache::load()`] method will be called more often than the
17//!   [`ModuleCache::save()`] method, allowing for cache implementations to
18//!   optimize their strategy accordingly.
19//!
20//! Cache implementations are encouraged to take
21//! [`wasmer::Engine::deterministic_id()`] into account when saving and loading
22//! cached modules to ensure correct module retrieval.
23//!
24//! Cache implementations should choose a suitable eviction policy and implement
25//! invalidation transparently as part of [`ModuleCache::load()`] or
26//! [`ModuleCache::save()`].
27//!
28//! ## Combinators
29//!
30//! The `module_cache` module provides combinators for extending and combining
31//! caching strategies. For example, you could use the [`FallbackCache`] to
32//! chain a fast in-memory cache with a slower file-based cache as a fallback.
33
34mod hashed_module;
35
36mod fallback;
37#[cfg(feature = "sys-thread")]
38mod filesystem;
39mod shared;
40mod thread_local;
41mod types;
42
43pub use self::{
44    fallback::FallbackCache,
45    hashed_module::HashedModuleData,
46    shared::SharedCache,
47    thread_local::ThreadLocalCache,
48    types::{CacheError, ModuleCache},
49};
50use wasmer_types::ModuleHash;
51
52#[cfg(feature = "sys-thread")]
53pub use self::filesystem::FileSystemCache;
54
55/// Get a [`ModuleCache`] which should be good enough for most in-memory use
56/// cases.
57///
58/// # Platform-specific Notes
59///
60/// This will use the [`ThreadLocalCache`] when running in the browser.  Each
61/// thread lives in a separate worker, so sharing compiled modules in the
62/// browser requires using a custom [`ModuleCache`] built on top of
63/// [`postMessage()`][pm] and [`SharedArrayBuffer`][sab].
64///
65/// [pm]: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
66/// [sab]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
67pub fn in_memory() -> impl ModuleCache + Send + Sync {
68    cfg_if::cfg_if! {
69        if #[cfg(feature = "js")] {
70            ThreadLocalCache::default()
71        } else {
72            SharedCache::default()
73        }
74    }
75}