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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::{path::Path, sync::Arc, time::Duration};
use exocore_protos::{
apps::{InMessage, MessageStatus, OutMessage},
prost::{self, Message},
};
use log::Level;
use wasmtime::*;
use crate::error::Error;
type FuncSendMessage = TypedFunc<(i32, i32), u32>;
type FuncTick = TypedFunc<(), u64>;
pub struct WasmTimeRuntime<E: HostEnvironment> {
instance: Instance,
send_message_func: FuncSendMessage,
tick_func: FuncTick,
store: Store<RuntimeState>,
_phantom: std::marker::PhantomData<E>,
}
struct RuntimeState;
impl<E: HostEnvironment> WasmTimeRuntime<E> {
pub fn from_file<P>(file: P, env: Arc<E>) -> Result<WasmTimeRuntime<E>, Error>
where
P: AsRef<Path>,
{
let engine = Engine::default();
let mut store = Store::new(&engine, RuntimeState);
let mut linker = Linker::new(&engine);
Self::setup_host_module(&mut linker, &env)?;
let module = Module::from_file(&engine, file)?;
let instance = linker.instantiate(&mut store, &module)?;
let (tick_func, send_message_func) = bootstrap_instance(&mut store, &instance)?;
Ok(WasmTimeRuntime {
instance,
send_message_func,
tick_func,
store,
_phantom: std::marker::PhantomData,
})
}
pub fn tick(&mut self) -> Result<Option<Duration>, Error> {
let now = unix_timestamp();
let next_tick_time = self.tick_func.call(&mut self.store, ())?;
if next_tick_time > now {
Ok(Some(Duration::from_nanos(next_tick_time - now)))
} else {
Ok(None)
}
}
pub fn send_message(&mut self, message: InMessage) -> Result<(), Error> {
let message_bytes = message.encode_to_vec();
let (message_ptr, message_size) =
wasm_alloc(&mut self.store, &self.instance, &message_bytes)?;
let res = self
.send_message_func
.call(&mut self.store, (message_ptr, message_size));
wasm_free(&mut self.store, &self.instance, message_ptr, message_size)?;
match MessageStatus::from_i32(res? as i32) {
Some(MessageStatus::Ok) => {}
other => return Err(Error::MessageStatus(other)),
}
Ok(())
}
fn setup_host_module(linker: &mut Linker<RuntimeState>, env: &Arc<E>) -> Result<(), Error> {
let env_clone = env.clone();
linker.func_wrap(
"exocore",
"__exocore_host_log",
move |mut caller: Caller<'_, RuntimeState>, level: i32, ptr: i32, len: i32| {
let log_level = log_level_from_i32(level);
read_wasm_str(&mut caller, ptr, len, |msg| {
env_clone.handle_log(log_level, msg);
})?;
Ok(())
},
)?;
linker.func_wrap(
"exocore",
"__exocore_host_now",
|_caller: Caller<'_, RuntimeState>| -> u64 { unix_timestamp() },
)?;
let env = env.clone();
linker.func_wrap(
"exocore",
"__exocore_host_out_message",
move |mut caller: Caller<'_, RuntimeState>, ptr: i32, len: i32| -> u32 {
let status = match read_wasm_message::<OutMessage>(&mut caller, ptr, len) {
Ok(msg) => {
env.as_ref().handle_message(msg);
MessageStatus::Ok
}
Err(err) => {
error!("Couldn't decode message sent from application: {}", err);
MessageStatus::DecodeError
}
};
status as u32
},
)?;
Ok(())
}
}
fn log_level_from_i32(level: i32) -> Level {
match level {
1 => Level::Error,
2 => Level::Warn,
3 => Level::Info,
4 => Level::Debug,
5 => Level::Trace,
_ => Level::Error,
}
}
pub trait HostEnvironment: Send + Sync + 'static {
fn handle_message(&self, msg: OutMessage);
fn handle_log(&self, level: log::Level, msg: &str);
}
fn bootstrap_instance(
mut store: &mut Store<RuntimeState>,
instance: &Instance,
) -> Result<(FuncTick, FuncSendMessage), Error> {
let exocore_init = instance
.get_typed_func::<(), (), _>(&mut store, "__exocore_init")
.map_err(|err| Error::MissingFunction(err, "__exocore_init"))?;
exocore_init.call(&mut store, ())?;
let exocore_app_init = instance
.get_typed_func::<(), (), _>(&mut store, "__exocore_app_init")
.map_err(|err| Error::MissingFunction(err, "__exocore_app_init"))?;
exocore_app_init.call(&mut store, ())?;
let exocore_app_boot = instance
.get_typed_func::<(), (), _>(&mut store, "__exocore_app_boot")
.map_err(|err| Error::MissingFunction(err, "__exocore_app_boot"))?;
exocore_app_boot.call(&mut store, ())?;
let exocore_tick = instance
.get_typed_func::<(), u64, _>(&mut store, "__exocore_tick")
.map_err(|err| Error::MissingFunction(err, "__exocore_tick"))?;
let exocore_send_message = instance
.get_typed_func::<(i32, i32), u32, _>(&mut store, "__exocore_in_message")
.map_err(|err| Error::MissingFunction(err, "__exocore_in_message"))?;
Ok((exocore_tick, exocore_send_message))
}
fn read_wasm_message<M: prost::Message + Default>(
caller: &mut Caller<'_, RuntimeState>,
ptr: i32,
len: i32,
) -> Result<M, Error> {
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Error::Runtime("failed to find host memory")),
};
let data = mem
.data(caller)
.get(ptr as u32 as usize..)
.and_then(|arr| arr.get(..len as u32 as usize));
match data {
Some(data) => Ok(M::decode(data)?),
None => Err(Error::Runtime("pointer/length out of bounds")),
}
}
fn read_wasm_str<F: FnOnce(&str)>(
caller: &mut Caller<'_, RuntimeState>,
ptr: i32,
len: i32,
f: F,
) -> Result<(), Error> {
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Error::Runtime("failed to find host memory")),
};
let data = mem
.data(caller)
.get(ptr as u32 as usize..)
.and_then(|arr| arr.get(..len as u32 as usize));
match data {
Some(data) => match std::str::from_utf8(data) {
Ok(s) => f(s),
Err(_) => return Err(Error::Runtime("invalid utf-8")),
},
None => return Err(Error::Runtime("pointer/length out of bounds")),
};
Ok(())
}
fn wasm_alloc(
mut store: &mut Store<RuntimeState>,
instance: &Instance,
bytes: &[u8],
) -> Result<(i32, i32), Error> {
let mem = match instance.get_export(&mut store, "memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Error::Runtime("failed to find host memory")),
};
let alloc = instance
.get_typed_func::<i32, i32, _>(&mut store, "__exocore_alloc")
.map_err(|err| Error::MissingFunction(err, "__exocore_alloc"))?;
let ptr = alloc.call(&mut store, bytes.len() as i32)?;
let data = mem.data_mut(store);
let ptr_usize = ptr as usize;
(&mut data[ptr_usize..ptr_usize + bytes.len()]).copy_from_slice(bytes);
Ok((ptr, bytes.len() as i32))
}
fn wasm_free(
mut store: &mut Store<RuntimeState>,
instance: &Instance,
ptr: i32,
size: i32,
) -> Result<(), Error> {
let alloc = instance
.get_typed_func::<(i32, i32), (), _>(&mut store, "__exocore_free")
.map_err(|err| Error::MissingFunction(err, "__exocore_free"))?;
alloc.call(&mut store, (ptr, size))?;
Ok(())
}
fn unix_timestamp() -> u64 {
let now = std::time::SystemTime::now();
now.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos() as u64
}
impl From<Error> for wasmtime::Trap {
fn from(err: Error) -> Self {
match err {
Error::Trap(t) => t,
other => wasmtime::Trap::new(other.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use std::{sync::Mutex, thread::sleep};
use exocore_core::tests_utils::find_test_fixture;
use exocore_protos::{
apps::{in_message::InMessageType, out_message::OutMessageType},
store::{EntityResults, MutationResult},
};
use super::*;
#[test]
fn example_golden_path() {
let example_path = find_test_fixture("fixtures/example.wasm");
let env = Arc::new(TestEnv::new());
let mut app = WasmTimeRuntime::from_file(example_path, env.clone()).unwrap();
app.tick().unwrap();
assert!(env.find_log("application initialized").is_some());
assert!(env.find_log("task starting").is_some());
let last_log = env.last_log().unwrap();
assert!(last_log.contains("before sleep"));
let time_before_sleep = last_log
.replace("before sleep ", "")
.parse::<u64>()
.unwrap();
let next_tick_duration = app
.tick()
.unwrap()
.unwrap_or_else(|| Duration::from_nanos(0));
let last_log = env.last_log().unwrap();
assert!(last_log.contains("before sleep"));
assert!(next_tick_duration > Duration::from_millis(10));
sleep(next_tick_duration);
app.tick().unwrap();
let after_sleep_log = env.find_log("after sleep").unwrap();
let time_after_sleep = after_sleep_log
.replace("after sleep ", "")
.parse::<u64>()
.unwrap();
assert!((time_after_sleep - time_before_sleep) > 100_000_000);
let message = env.pop_message().unwrap();
assert_eq!(message.r#type, OutMessageType::StoreMutationRequest as i32);
app.send_message(InMessage {
r#type: InMessageType::StoreMutationResult.into(),
rendez_vous_id: message.rendez_vous_id,
data: MutationResult::default().encode_to_vec(),
error: String::new(),
})
.unwrap();
app.tick().unwrap();
assert!(env.find_log("mutation success").is_some());
let message = env.pop_message().unwrap();
assert_eq!(message.r#type, OutMessageType::StoreEntityQuery as i32);
app.send_message(InMessage {
r#type: InMessageType::StoreEntityResults.into(),
rendez_vous_id: message.rendez_vous_id,
data: EntityResults::default().encode_to_vec(),
error: String::new(),
})
.unwrap();
app.tick().unwrap();
assert!(env.find_log("query success").is_some());
assert_eq!(env.last_log(), Some("task done".to_string()));
}
struct TestEnv {
logs: Mutex<Vec<String>>,
messages: Mutex<Vec<OutMessage>>,
}
impl TestEnv {
fn new() -> TestEnv {
TestEnv {
logs: Mutex::new(Vec::new()),
messages: Mutex::new(Vec::new()),
}
}
fn find_log(&self, needle: &str) -> Option<String> {
let logs = self.logs.lock().unwrap();
for log in logs.iter() {
if log.contains(needle) {
return Some(log.clone());
}
}
None
}
fn last_log(&self) -> Option<String> {
let logs = self.logs.lock().unwrap();
logs.last().cloned()
}
fn pop_message(&self) -> Option<OutMessage> {
let mut msgs = self.messages.lock().unwrap();
msgs.pop()
}
}
impl HostEnvironment for TestEnv {
fn handle_message(&self, msg: OutMessage) {
let mut messages = self.messages.lock().unwrap();
messages.push(msg);
}
fn handle_log(&self, level: log::Level, msg: &str) {
log!(level, "WASM APP: {}", msg);
let mut logs = self.logs.lock().unwrap();
logs.push(msg.to_string());
}
}
}