-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathmod.rs
175 lines (160 loc) · 4.71 KB
/
mod.rs
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
/*
Copyright (c) 2015-2023 hkrn All rights reserved
This file is part of emapp component and it's licensed under Mozilla Public License. see LICENSE.md for more details.
*/
use std::{
any::Any,
collections::{HashMap, HashSet},
env::current_dir,
io::IoSliceMut,
sync::Arc,
};
use anyhow::Result;
use parking_lot::Mutex;
use pretty_assertions::assert_eq;
use rand::{thread_rng, Rng};
use serde_derive::{Deserialize, Serialize};
use serde_json::Value;
use wasi_common::{
file::{FileType, Filestat},
snapshots::preview_1::types::Error, WasiFile,
};
use wasmtime::{Engine, Linker};
use wasmtime_wasi::WasiCtxBuilder;
use crate::{motion::controller::MotionIOPluginController, Store};
use super::plugin::MotionIOPlugin;
#[derive(Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
struct PluginOutput {
function: String,
arguments: Option<HashMap<String, Value>>,
}
pub(super) struct Pipe {
content: Arc<Mutex<Vec<u8>>>,
}
impl Pipe {
pub fn channel() -> (Box<Self>, Box<Self>) {
let content = Arc::new(Mutex::new(Vec::new()));
(
Box::new(Self {
content: Arc::clone(&content),
}),
Box::new(Self {
content: Arc::clone(&content),
}),
)
}
}
#[async_trait::async_trait]
impl WasiFile for Pipe {
fn as_any(&self) -> &dyn Any {
self
}
async fn get_filetype(&self) -> Result<FileType, Error> {
Ok(FileType::RegularFile)
}
async fn get_filestat(&self) -> Result<Filestat, Error> {
Ok(Filestat {
device_id: 0,
inode: 0,
filetype: self.get_filetype().await?,
nlink: 0,
size: self.content.lock().len() as _,
atim: None,
mtim: None,
ctim: None,
})
}
async fn read_vectored<'a>(&self, _bufs: &mut [std::io::IoSliceMut<'a>]) -> Result<u64, Error> {
let guard = self.content.lock();
for slice in _bufs.iter_mut() {
slice.copy_from_slice(guard.as_slice());
}
Ok(guard.len() as u64)
}
async fn write_vectored<'a>(&self, _bufs: &[std::io::IoSlice<'a>]) -> Result<u64, Error> {
let mut guard = self.content.lock();
let size = guard.len();
for slice in _bufs.iter() {
guard.extend(slice.iter());
}
Ok((guard.len() - size) as u64)
}
}
fn build_type_and_flags() -> (&'static str, &'static str) {
if cfg!(debug_assertions) {
("debug", "")
} else {
("release-lto", " --profile release-lto")
}
}
fn create_random_data(size: usize) -> Vec<u8> {
let mut data = vec![];
let mut rng = thread_rng();
for _ in 0..size {
let v: u8 = rng.gen();
data.push(v);
}
data
}
fn read_plugin_output(pipe: Box<dyn WasiFile>) -> Result<Vec<PluginOutput>> {
let stat = futures::executor::block_on(pipe.get_filestat())?;
let mut buffer = vec![0; stat.size as _];
futures::executor::block_on(pipe.read_vectored(&mut [IoSliceMut::new(&mut buffer)]))?;
let s = String::from_utf8(buffer)?;
let mut data = s.split('\n').collect::<Vec<_>>();
data.pop();
Ok(data
.iter()
.map(|s| serde_json::from_str(s).unwrap())
.collect())
}
fn inner_create_controller(
pipe: Box<dyn WasiFile>,
path: &str,
) -> Result<MotionIOPluginController> {
let path = current_dir()?.parent().unwrap().join(path);
let engine = Engine::default();
let data = WasiCtxBuilder::new().stdout(pipe).build();
let store = Store::new(&engine, data);
let bytes = std::fs::read(&path)?;
let mut linker = Linker::new(&engine);
wasmtime_wasi::add_to_linker(&mut linker, |ctx| ctx)?;
let plugin = MotionIOPlugin::new(&linker, &path, &bytes, store)?;
let watcher = notify::recommended_watcher(|_res| {})?;
Ok(MotionIOPluginController::new(
Arc::new(Mutex::new(vec![plugin])),
watcher,
))
}
#[test]
fn from_path() -> Result<()> {
let (ty, _) = build_type_and_flags();
let path = current_dir()?
.parent()
.unwrap()
.join(format!("target/wasm32-wasi/{ty}/deps"));
let mut controller = MotionIOPluginController::from_path(&path, |_builder| ())?;
let mut names = vec![];
for plugin in controller.all_plugins_mut().lock().iter_mut() {
plugin.create()?;
names.push(plugin.name()?);
}
let mut names = names
.iter()
.cloned()
.collect::<HashSet<_>>()
.iter()
.cloned()
.collect::<Vec<_>>();
names.sort();
assert_eq!(
vec![
"plugin_wasm_test_motion_full",
"plugin_wasm_test_motion_minimum",
],
names
);
Ok(())
}
mod full;
mod minimum;