1use wasmtime::*;
2
3pub use wasmtime;
4
5pub const VERSION: &str = env!("CARGO_PKG_VERSION");
6
7pub fn engine_config() -> Config {
8 const MB: usize = 1024 * 1024;
9
10 let mut sys = sysinfo::System::new_all();
11 sys.refresh_all();
12
13 let total_memory_bytes = sys.total_memory() as usize;
14 let total_memory_mb = total_memory_bytes / (1024 * 1024);
15 const MAX_MEMORY_MB: usize = 128;
16 let max_instance_count = total_memory_mb / MAX_MEMORY_MB;
17
18 let mut pooling_allocation_config = PoolingAllocationConfig::new();
19 pooling_allocation_config
20 .max_memory_size(MB * MAX_MEMORY_MB)
21 .linear_memory_keep_resident(MB * 16)
22 .table_keep_resident(MB)
23 .total_core_instances(max_instance_count as _)
24 .total_memories(max_instance_count as _)
25 .total_tables(max_instance_count as _)
26 .pagemap_scan(wasmtime::Enabled::Auto)
27 .memory_protection_keys(wasmtime::Enabled::Auto);
28
29 let mut config = Config::new();
30
31 config
32 .allocation_strategy(InstanceAllocationStrategy::Pooling(
33 pooling_allocation_config,
34 ))
35 .epoch_interruption(true)
36 .wasm_component_model(true)
37 .wasm_component_model_async(true)
38 .cranelift_opt_level(wasmtime::OptLevel::None)
39 .cache(Some(
40 wasmtime::Cache::new(wasmtime::CacheConfig::new()).unwrap(),
41 ))
42 .parallel_compilation(true);
43
44 config
45}
46
47pub fn compile(wasm_bytes: &[u8]) -> Result<Vec<u8>, Error> {
48 let engine = Engine::new(&engine_config())?;
49
50 if wasm_bytes.len() > 8 && wasm_bytes[4..8] == [0x0d, 0x00, 0x01, 0x00] {
51 engine.precompile_component(wasm_bytes)
52 } else {
53 engine.precompile_module(wasm_bytes)
54 }
55}