1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
use std::{
borrow::BorrowMut,
sync::{Arc, RwLock},
};
use crate::checksum::Checksum;
use crate::error::Error;
use clru::CLruCache;
use wasmer::{Instance, Module, Store};
pub struct InMemoryCache {
modules: CLruCache<Checksum, Module>,
}
impl InMemoryCache {
pub fn new(max_entries: u32) -> Self {
InMemoryCache { modules: CLruCache::new(max_entries as usize) }
}
pub fn store(&mut self, checksum: &Checksum, module: Module) -> Option<Module> {
self.modules.put(*checksum, module)
}
pub fn load(&mut self, checksum: &Checksum) -> Option<Module> {
self.modules.get(checksum).cloned()
}
}
#[derive(Clone, Debug)]
pub struct CacheOptions {
pub cache_size: u32,
}
pub struct Cache {
memory_cache: Arc<RwLock<InMemoryCache>>,
}
impl Cache {
pub fn new(options: CacheOptions) -> Self {
let CacheOptions { cache_size } = options;
Self { memory_cache: Arc::new(RwLock::new(InMemoryCache::new(cache_size))) }
}
fn with_in_memory_cache<C, R>(&mut self, callback: C) -> R
where
C: FnOnce(&mut InMemoryCache) -> R,
{
let mut guard = self.memory_cache.as_ref().write().unwrap();
let in_memory_cache = guard.borrow_mut();
callback(in_memory_cache)
}
pub fn get_instance(
&mut self,
wasm: &[u8],
store: &Store,
import_object: &wasmer::ImportObject,
) -> Result<(wasmer::Instance, bool), Error> {
let checksum = Checksum::generate(wasm);
self.with_in_memory_cache(|in_memory_cache| {
if let Some(module) = in_memory_cache.load(&checksum) {
return Ok((Instance::new(&module, &import_object).unwrap(), true));
}
let module = Module::new(store, &wasm).map_err(|_| Error::InstantiationError)?;
let instance =
Instance::new(&module, &import_object).map_err(|_| Error::InstantiationError)?;
in_memory_cache.store(&checksum, module);
Ok((instance, false))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{Read, Write};
use std::process::Command;
use tempfile::NamedTempFile;
use wasmer::{imports, Singlepass, Store, Universal};
fn wat2wasm(wat: impl AsRef<[u8]>) -> Vec<u8> {
let mut input_file = NamedTempFile::new().unwrap();
let mut output_file = NamedTempFile::new().unwrap();
input_file.write_all(wat.as_ref()).unwrap();
Command::new("wat2wasm")
.args(&[
input_file.path().to_str().unwrap(),
"-o",
output_file.path().to_str().unwrap(),
])
.output()
.unwrap();
let mut wasm = Vec::new();
output_file.read_to_end(&mut wasm).unwrap();
wasm
}
fn get_instance_without_err(cache: &mut Cache, wasm: &[u8]) -> (wasmer::Instance, bool) {
let compiler = Singlepass::new();
let store = Store::new(&Universal::new(compiler).engine());
let import_object = imports! {};
match cache.get_instance(&wasm, &store, &import_object) {
Ok((instance, is_hit)) => (instance, is_hit),
Err(_) => panic!("Fail to get instance"),
}
}
#[test]
fn test_cache_catch() {
let mut cache = Cache::new(CacheOptions { cache_size: 10000 });
let wasm = wat2wasm(
r#"(module
(func $execute (export "execute"))
(func $prepare (export "prepare"))
)"#,
);
let wasm2 = wat2wasm(
r#"(module
(func $execute (export "execute"))
(func $prepare (export "prepare"))
(func $foo2 (export "foo2"))
)"#,
);
let (instance1, is_hit) = get_instance_without_err(&mut cache, &wasm);
assert_eq!(false, is_hit);
let (instance2, is_hit) = get_instance_without_err(&mut cache, &wasm);
assert_eq!(true, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm2);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm);
assert_eq!(true, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm2);
assert_eq!(true, is_hit);
let ser1 = match instance1.module().serialize() {
Ok(r) => r,
Err(_) => panic!("Fail to serialize module"),
};
let ser2 = match instance2.module().serialize() {
Ok(r) => r,
Err(_) => panic!("Fail to serialize module"),
};
assert_eq!(ser1, ser2);
}
#[test]
fn test_cache_size() {
let mut cache = Cache::new(CacheOptions { cache_size: 2 });
let wasm1 = wat2wasm(
r#"(module
(func $execute (export "execute"))
(func $prepare (export "prepare"))
(func $foo (export "foo"))
)"#,
);
let wasm2 = wat2wasm(
r#"(module
(func $execute (export "execute"))
(func $prepare (export "prepare"))
(func $foo2 (export "foo2"))
)"#,
);
let wasm3 = wat2wasm(
r#"(module
(func $execute (export "execute"))
(func $prepare (export "prepare"))
(func $foo3 (export "foo3"))
)"#,
);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm1);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm2);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm3);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm2);
assert_eq!(true, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm1);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm2);
assert_eq!(true, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm3);
assert_eq!(false, is_hit);
cache = Cache::new(CacheOptions { cache_size: 0 });
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm1);
assert_eq!(false, is_hit);
let (_, is_hit) = get_instance_without_err(&mut cache, &wasm1);
assert_eq!(false, is_hit);
}
}