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;
39pub mod progress;
40mod shared;
41mod thread_local;
42mod types;
43
44pub use self::{
45    fallback::FallbackCache,
46    hashed_module::HashedModuleData,
47    shared::SharedCache,
48    thread_local::ThreadLocalCache,
49    types::{CacheError, ModuleCache},
50};
51use wasmer_types::ModuleHash;
52
53#[cfg(feature = "sys-thread")]
54pub use self::filesystem::FileSystemCache;
55
56/// Get a [`ModuleCache`] which should be good enough for most in-memory use
57/// cases.
58///
59/// # Platform-specific Notes
60///
61/// This will use the [`ThreadLocalCache`] when running in the browser.  Each
62/// thread lives in a separate worker, so sharing compiled modules in the
63/// browser requires using a custom [`ModuleCache`] built on top of
64/// [`postMessage()`][pm] and [`SharedArrayBuffer`][sab].
65///
66/// [pm]: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage
67/// [sab]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer
68pub fn in_memory() -> impl ModuleCache + Send + Sync {
69    cfg_if::cfg_if! {
70        if #[cfg(feature = "js")] {
71            ThreadLocalCache::default()
72        } else {
73            SharedCache::default()
74        }
75    }
76}