0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-30 09:08:00 -04:00
denoland-deno/cli/ops/dispatch_json.rs

117 lines
3.1 KiB
Rust
Raw Normal View History

2020-01-02 15:13:47 -05:00
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
use crate::op_error::OpError;
use deno_core::Buf;
use deno_core::CoreIsolateState;
use deno_core::Op;
use deno_core::ZeroCopyBuf;
2019-11-16 19:17:47 -05:00
use futures::future::FutureExt;
pub use serde_derive::Deserialize;
use serde_json::json;
pub use serde_json::Value;
2019-11-16 19:17:47 -05:00
use std::future::Future;
use std::pin::Pin;
pub type JsonResult = Result<Value, OpError>;
pub type AsyncJsonOp = Pin<Box<dyn Future<Output = JsonResult>>>;
pub enum JsonOp {
Sync(Value),
Async(AsyncJsonOp),
/// AsyncUnref is the variation of Async, which doesn't block the program
/// exiting.
AsyncUnref(AsyncJsonOp),
}
fn json_err(err: OpError) -> Value {
json!({
"message": err.msg,
"kind": err.kind as u32,
})
}
fn serialize_result(promise_id: Option<u64>, result: JsonResult) -> Buf {
let value = match result {
Ok(v) => json!({ "ok": v, "promiseId": promise_id }),
Err(err) => json!({ "err": json_err(err), "promiseId": promise_id }),
};
serde_json::to_vec(&value).unwrap().into_boxed_slice()
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct AsyncArgs {
promise_id: Option<u64>,
}
pub fn json_op<D>(
d: D,
) -> impl Fn(&mut CoreIsolateState, &[u8], Option<ZeroCopyBuf>) -> Op
where
D: Fn(
&mut CoreIsolateState,
Value,
Option<ZeroCopyBuf>,
) -> Result<JsonOp, OpError>,
{
move |isolate_state: &mut CoreIsolateState,
control: &[u8],
zero_copy: Option<ZeroCopyBuf>| {
let async_args: AsyncArgs = match serde_json::from_slice(control) {
Ok(args) => args,
Err(e) => {
let buf = serialize_result(None, Err(OpError::from(e)));
2020-04-18 20:05:13 -04:00
return Op::Sync(buf);
}
};
let promise_id = async_args.promise_id;
let is_sync = promise_id.is_none();
let result = serde_json::from_slice(control)
.map_err(OpError::from)
.and_then(|args| d(isolate_state, args, zero_copy));
2020-04-18 20:05:13 -04:00
// Convert to Op
match result {
Ok(JsonOp::Sync(sync_value)) => {
assert!(promise_id.is_none());
2020-04-18 20:05:13 -04:00
Op::Sync(serialize_result(promise_id, Ok(sync_value)))
}
Ok(JsonOp::Async(fut)) => {
assert!(promise_id.is_some());
2019-11-16 19:17:47 -05:00
let fut2 = fut.then(move |result| {
2020-04-18 20:05:13 -04:00
futures::future::ready(serialize_result(promise_id, result))
2019-11-16 19:17:47 -05:00
});
2020-04-18 20:05:13 -04:00
Op::Async(fut2.boxed_local())
}
Ok(JsonOp::AsyncUnref(fut)) => {
assert!(promise_id.is_some());
let fut2 = fut.then(move |result| {
2020-04-18 20:05:13 -04:00
futures::future::ready(serialize_result(promise_id, result))
});
2020-04-18 20:05:13 -04:00
Op::AsyncUnref(fut2.boxed_local())
}
Err(sync_err) => {
let buf = serialize_result(promise_id, Err(sync_err));
if is_sync {
2020-04-18 20:05:13 -04:00
Op::Sync(buf)
} else {
2020-04-18 20:05:13 -04:00
Op::Async(futures::future::ready(buf).boxed_local())
}
}
}
}
}
pub fn blocking_json<F>(is_sync: bool, f: F) -> Result<JsonOp, OpError>
where
F: 'static + Send + FnOnce() -> JsonResult,
{
if is_sync {
Ok(JsonOp::Sync(f()?))
} else {
let fut = async move { tokio::task::spawn_blocking(f).await.unwrap() };
Ok(JsonOp::Async(fut.boxed_local()))
}
}