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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use {
crate::{
body::Body,
config::{Backends, Dictionaries},
downstream::prepare_request,
error::ExecutionError,
linking::{create_store, dummy_store, link_host_functions, WasmCtx},
session::Session,
Error,
},
cfg_if::cfg_if,
hyper::{Request, Response},
std::{
net::IpAddr,
path::{Path, PathBuf},
sync::atomic::AtomicU64,
sync::Arc,
},
tokio::sync::oneshot::{self, Sender},
tracing::{event, info, info_span, Instrument, Level},
wasmtime::{Engine, InstancePre, Linker, Module},
};
#[derive(Clone)]
pub struct ExecuteCtx {
engine: Engine,
instance_pre: Arc<InstancePre<WasmCtx>>,
backends: Arc<Backends>,
dictionaries: Arc<Dictionaries>,
config_path: Arc<Option<PathBuf>>,
log_stdout: bool,
log_stderr: bool,
next_req_id: Arc<AtomicU64>,
}
impl ExecuteCtx {
pub fn new(module_path: impl AsRef<Path>) -> Result<Self, Error> {
use wasmtime::{
Config, InstanceAllocationStrategy, InstanceLimits, ModuleLimits,
PoolingAllocationStrategy, WasmBacktraceDetails,
};
let mut config = Config::new();
config.debug_info(false);
config.wasm_backtrace_details(WasmBacktraceDetails::Enable);
config.async_support(true);
config.consume_fuel(true);
let module_limits = ModuleLimits {
memory_pages: 2048,
types: 200,
globals: 64,
functions: 20000,
..ModuleLimits::default()
};
config.allocation_strategy(InstanceAllocationStrategy::Pooling {
strategy: PoolingAllocationStrategy::NextAvailable,
module_limits,
instance_limits: InstanceLimits::default(),
});
let engine = Engine::new(&config)?;
let mut linker = Linker::new(&engine);
link_host_functions(&mut linker)?;
let module = Module::from_file(&engine, module_path)?;
let mut dummy_store = dummy_store(&engine);
let instance_pre = linker.instantiate_pre(&mut dummy_store, &module)?;
Ok(Self {
engine,
instance_pre: Arc::new(instance_pre),
backends: Arc::new(Backends::default()),
dictionaries: Arc::new(Dictionaries::default()),
config_path: Arc::new(None),
log_stdout: false,
log_stderr: false,
next_req_id: Arc::new(AtomicU64::new(0)),
})
}
pub fn engine(&self) -> &Engine {
&self.engine
}
pub fn backends(&self) -> &Backends {
&self.backends
}
pub fn with_backends(self, backends: Backends) -> Self {
Self {
backends: Arc::new(backends),
..self
}
}
pub fn dictionaries(&self) -> &Dictionaries {
&self.dictionaries
}
pub fn with_dictionaries(self, dictionaries: Dictionaries) -> Self {
Self {
dictionaries: Arc::new(dictionaries),
..self
}
}
pub fn with_config_path(self, config_path: PathBuf) -> Self {
Self {
config_path: Arc::new(Some(config_path)),
..self
}
}
pub fn log_stdout(&self) -> bool {
self.log_stdout
}
pub fn with_log_stdout(self, log_stdout: bool) -> Self {
Self { log_stdout, ..self }
}
pub fn log_stderr(&self) -> bool {
self.log_stderr
}
pub fn with_log_stderr(self, log_stderr: bool) -> Self {
Self { log_stderr, ..self }
}
pub async fn handle_request(
self,
incoming_req: Request<hyper::Body>,
remote: IpAddr,
) -> Result<Response<Body>, Error> {
let req = prepare_request(incoming_req)?;
let (sender, receiver) = oneshot::channel();
let req_id = self
.next_req_id
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let guest_handle = tokio::task::spawn(
self.run_guest(req, req_id, sender, remote)
.instrument(info_span!("request", id = req_id)),
);
let resp = match receiver.await {
Ok(resp) => resp,
Err(_) => match guest_handle
.await
.expect("guest worker finished without panicking")
{
Ok(_) => Response::new(Body::empty()),
Err(ExecutionError::WasmTrap(_e)) => {
#[allow(unused_mut)]
let mut response = Response::builder()
.status(hyper::StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty())
.unwrap();
cfg_if! {
if #[cfg(feature = "test-fatalerror-config")] {
let error_msg = _e.to_string();
let msg = error_msg.split('\n').next().unwrap();
let hdr_val =
http::header::HeaderValue::from_str(&msg).expect("error message is a valid header");
response.headers_mut().insert(http::header::WARNING, hdr_val);
}
}
response
}
Err(e) => panic!("failed to run guest: {}", e),
},
};
Ok(resp)
}
async fn run_guest(
self,
req: Request<Body>,
req_id: u64,
sender: Sender<Response<Body>>,
remote: IpAddr,
) -> Result<(), ExecutionError> {
info!("handling request {} {}", req.method(), req.uri());
let session = Session::new(
req_id,
req,
sender,
remote,
self.backends.clone(),
self.dictionaries.clone(),
self.config_path.clone(),
);
let mut store = create_store(&self, session).map_err(ExecutionError::Context)?;
let instance = self
.instance_pre
.instantiate_async(&mut store)
.await
.map_err(ExecutionError::Instantiation)?;
let main_func = instance
.get_typed_func::<(), (), _>(&mut store, "_start")
.map_err(ExecutionError::Typechecking)?;
let outcome = main_func
.call_async(&mut store, ())
.await
.map(|_| ())
.map_err(|trap| {
event!(Level::ERROR, "WebAssembly trapped: {}", trap);
ExecutionError::WasmTrap(trap)
});
store.data_mut().close_downstream_response_sender();
let heap_pages = instance
.get_memory(&mut store, "memory")
.expect("`memory` is exported")
.size(&store);
info!(
"request completed using {} of WebAssembly heap",
bytesize::ByteSize::kib(heap_pages as u64 * 64)
);
outcome
}
}