-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.rs
287 lines (251 loc) · 9.4 KB
/
lib.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
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
// mod binding;
mod binding;
mod io;
use std::{
convert::Infallible,
env,
future::Future,
net::SocketAddr,
path::Path,
pin::Pin,
sync::{Arc, Mutex},
task::{self, Poll},
};
// use binding::add_exports_to_linker;
use futures::future::{self, Ready};
use hyper::{
header::{HeaderName, HeaderValue},
http::request::Parts,
server::conn::AddrStream,
service::Service,
Body, Request, Response,
};
use tracing::{error, event, info, Level};
use tracing_subscriber::{filter::EnvFilter, FmtSubscriber};
use wasi_common::WasiCtx;
use wasmtime_wasi::WasiCtxBuilder;
use wasmtime::{Caller, Config, Engine, Extern, Linker, Module, Store, Trap, WasmBacktraceDetails};
use crate::{
binding::add_exports_to_linker,
io::{WasmInput, WasmOutput},
};
#[derive(Clone)]
pub struct RequestService {
worker_ctx: WorkerCtx,
}
impl RequestService {
/// Create a new request service.
fn new(ctx: WorkerCtx) -> Self {
Self { worker_ctx: ctx }
}
}
#[derive(Clone)]
pub struct WorkerCtx {
engine: Engine,
module: Module,
}
impl WorkerCtx {
pub fn new(module_path: impl AsRef<Path>) -> anyhow::Result<Self> {
tracing_subscriber();
info!("Loading module from {:?}", module_path.as_ref());
let mut binding = Config::default();
let config = binding
.async_support(true)
.debug_info(true)
.wasm_backtrace(true)
.coredump_on_trap(true) // Enable core dumps on trap
.wasm_backtrace_details(WasmBacktraceDetails::Enable);
let engine = Engine::new(&config)?;
let module = Module::from_file(&engine, module_path)?;
Ok(Self { engine, module })
}
pub fn module(&self) -> &Module {
&self.module
}
pub fn engine(&self) -> &Engine {
&self.engine
}
pub async fn serve(self, addr: SocketAddr) -> Result<(), hyper::Error> {
info!("Starting server ...");
let server = hyper::Server::bind(&addr).serve(self);
event!(Level::INFO, "Listening on http://{}", server.local_addr());
server.await?;
Ok(())
}
pub async fn handle_request(
&self,
request: hyper::Request<hyper::Body>,
) -> anyhow::Result<(Response<Body>, Option<anyhow::Error>)> {
let (parts, body) = request.into_parts();
info!("Handling request: {:?} {:?}", parts.method, parts.uri);
let body = hyper::body::to_bytes(body).await.unwrap();
let body_str = String::from_utf8_lossy(&body).to_string();
let result = self.run(&parts, &body_str).await;
match result {
Ok(output) => {
let mut response = Response::builder();
response = response.status(output.status);
let headers = output.headers.clone();
let headers_vec: Vec<(String, String)> = headers
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_owned()))
.collect();
headers_vec.iter().for_each(|(key, value)| {
response.headers_mut().unwrap().insert(
HeaderName::from_bytes(key.as_bytes()).unwrap(),
HeaderValue::from_str(value).unwrap(),
);
});
let response = Response::new(Body::from(output.body()));
Ok((response, None))
}
Err(e) => {
error!("Error: {}", e);
let response = Response::builder()
.status(500)
.body(Body::from("Internal Server Error"))
.unwrap();
Ok((response, Some(e)))
}
}
}
async fn run(&self, parts: &Parts, body: &str) -> anyhow::Result<WasmOutput> {
let input = serde_json::to_vec(&WasmInput::new(parts, body)).unwrap();
let mem_len = input.len() as i32;
let mut linker: Linker<WasiCtx> = Linker::new(self.engine());
wasmtime_wasi::add_to_linker(&mut linker, |ctx| ctx)?;
println!("Adding exports to linker");
linker.func_wrap("arakoo", "get_request_len", move || -> i32 { mem_len })?;
println!("Added get_request_len");
match linker.func_wrap(
"arakoo",
"get_request",
move |mut caller: Caller<'_, WasiCtx>, ptr: i32| {
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Trap::NullReference.into()),
};
let offset = ptr as u32 as usize;
match mem.write(&mut caller, offset, &input) {
Ok(_) => {}
_ => return Err(Trap::MemoryOutOfBounds.into()),
};
Ok(())
},
) {
Ok(_) => {}
Err(e) => {
println!("Error adding get_request: {}", e);
}
}
println!("Added get_request");
let output: Arc<Mutex<WasmOutput>> = Arc::new(Mutex::new(WasmOutput::new()));
let output_clone = output.clone();
linker.func_wrap(
"arakoo",
"set_output",
move |mut caller: Caller<'_, WasiCtx>, ptr: i32, len: i32| {
let output = output_clone.clone();
let mem = match caller.get_export("memory") {
Some(Extern::Memory(mem)) => mem,
_ => return Err(Trap::NullReference.into()),
};
let offset = ptr as u32 as usize;
let mut buffer = vec![0; len as usize];
match mem.read(&caller, offset, &mut buffer) {
Ok(_) => match serde_json::from_slice::<WasmOutput>(&buffer) {
Ok(parsed_output) => {
let mut output = output.lock().unwrap();
*output = parsed_output;
Ok(())
}
Err(_e) => Err(Trap::BadSignature.into()),
},
_ => Err(Trap::MemoryOutOfBounds.into()),
}
},
)?;
add_exports_to_linker(&mut linker)?;
let wasi_builder = WasiCtxBuilder::new()
.inherit_stdout()
.inherit_stderr()
.build();
let mut store = Store::new(self.engine(), wasi_builder);
linker.module(&mut store, "", self.module())?;
let instance = linker
.instantiate_async(&mut store, self.module())
.await
.map_err(anyhow::Error::msg)?;
println!("Instantiated module");
let run_entrypoint_fn = instance.get_typed_func::<(), ()>(&mut store, "run_entrypoint")?;
println!("Got run_entrypoint_fn");
run_entrypoint_fn
.call_async(&mut store, ())
.await
.map_err(anyhow::Error::msg)?;
drop(store);
let output = output.lock().unwrap().clone();
Ok(output)
}
fn make_service(&self) -> RequestService {
RequestService::new(self.clone())
}
}
impl<'addr> Service<&'addr AddrStream> for WorkerCtx {
type Response = RequestService;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _addr: &'addr AddrStream) -> Self::Future {
future::ok(self.make_service())
}
}
impl Service<Request<hyper::Body>> for RequestService {
type Response = Response<Body>;
type Error = anyhow::Error;
#[allow(clippy::type_complexity)]
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<hyper::Body>) -> Self::Future {
let ctx = self.worker_ctx.clone();
Box::pin(async move { ctx.handle_request(req).await.map(|result| result.0) })
}
}
fn tracing_subscriber() {
let verbosity = match env::var("RUST_LOG_VERBOSITY") {
Ok(s) => s.parse().unwrap_or(0),
Err(_) => 0,
};
if env::var("RUST_LOG").ok().is_none() {
match verbosity {
0 => env::set_var("RUST_LOG", "info"),
1 => env::set_var("RUST_LOG", "debug"),
_ => env::set_var("RUST_LOG", "trace"),
}
}
// Build a subscriber, using the default `RUST_LOG` environment variable for our filter.
let builder = FmtSubscriber::builder()
.with_writer(std::io::stderr)
.with_env_filter(EnvFilter::from_default_env())
.with_target(false);
match env::var("RUST_LOG_PRETTY") {
// If the `RUST_LOG_PRETTY` environment variable is set to "true", we should emit logs in a
// pretty, human-readable output format.
Ok(s) if s == "true" => builder
.pretty()
// Show levels, because ANSI escape sequences are normally used to indicate this.
.with_level(true)
.init(),
// Otherwise, we should install the subscriber without any further additions.
_ => builder.with_ansi(false).init(),
}
event!(
Level::DEBUG,
"RUST_LOG set to '{}'",
env::var("RUST_LOG").unwrap_or_else(|_| String::from("<Could not get env>"))
);
}