2020-01-02 15:13:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2019-08-26 08:50:21 -04:00
|
|
|
use super::dispatch_json::{Deserialize, JsonOp, Value};
|
2019-11-09 15:07:14 -05:00
|
|
|
use crate::deno_error::bad_resource;
|
2019-09-25 10:46:58 -04:00
|
|
|
use crate::deno_error::js_check;
|
2019-08-14 11:03:02 -04:00
|
|
|
use crate::deno_error::DenoError;
|
|
|
|
use crate::deno_error::ErrorKind;
|
2019-10-11 14:41:54 -04:00
|
|
|
use crate::ops::json_op;
|
2019-08-14 11:03:02 -04:00
|
|
|
use crate::startup_data;
|
|
|
|
use crate::state::ThreadSafeState;
|
|
|
|
use crate::worker::Worker;
|
2020-01-05 11:56:18 -05:00
|
|
|
use deno_core::*;
|
2019-08-14 11:03:02 -04:00
|
|
|
use futures;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::future::FutureExt;
|
|
|
|
use futures::future::TryFutureExt;
|
|
|
|
use futures::sink::SinkExt;
|
|
|
|
use futures::stream::StreamExt;
|
2019-08-14 11:03:02 -04:00
|
|
|
use std;
|
|
|
|
use std::convert::From;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::future::Future;
|
|
|
|
use std::pin::Pin;
|
2019-10-11 14:41:54 -04:00
|
|
|
use std::sync::atomic::Ordering;
|
2019-11-19 19:17:05 -05:00
|
|
|
use std::sync::mpsc;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2019-10-11 14:41:54 -04:00
|
|
|
|
|
|
|
pub fn init(i: &mut Isolate, s: &ThreadSafeState) {
|
|
|
|
i.register_op(
|
|
|
|
"create_worker",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_create_worker))),
|
|
|
|
);
|
|
|
|
i.register_op(
|
|
|
|
"host_get_worker_closed",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_host_get_worker_closed))),
|
|
|
|
);
|
|
|
|
i.register_op(
|
|
|
|
"host_post_message",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_host_post_message))),
|
|
|
|
);
|
|
|
|
i.register_op(
|
|
|
|
"host_get_message",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_host_get_message))),
|
|
|
|
);
|
|
|
|
// TODO: make sure these two ops are only accessible to appropriate Worker
|
|
|
|
i.register_op(
|
|
|
|
"worker_post_message",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_worker_post_message))),
|
|
|
|
);
|
|
|
|
i.register_op(
|
|
|
|
"worker_get_message",
|
|
|
|
s.core_op(json_op(s.stateful_op(op_worker_get_message))),
|
|
|
|
);
|
|
|
|
i.register_op("metrics", s.core_op(json_op(s.stateful_op(op_metrics))));
|
|
|
|
}
|
2019-08-14 11:03:02 -04:00
|
|
|
|
|
|
|
struct GetMessageFuture {
|
2019-11-04 10:38:52 -05:00
|
|
|
state: ThreadSafeState,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for GetMessageFuture {
|
2019-11-16 19:17:47 -05:00
|
|
|
type Output = Option<Buf>;
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
|
|
|
let inner = self.get_mut();
|
|
|
|
let mut channels = inner.state.worker_channels.lock().unwrap();
|
2019-11-04 10:38:52 -05:00
|
|
|
let receiver = &mut channels.receiver;
|
2019-11-16 19:17:47 -05:00
|
|
|
receiver.poll_next_unpin(cx)
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get message from host as guest worker
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_worker_get_message(
|
2019-08-14 11:03:02 -04:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
_args: Value,
|
|
|
|
_data: Option<PinnedBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
2019-08-14 11:03:02 -04:00
|
|
|
let op = GetMessageFuture {
|
|
|
|
state: state.clone(),
|
|
|
|
};
|
2019-08-26 08:50:21 -04:00
|
|
|
|
2020-01-04 05:20:52 -05:00
|
|
|
let op = async move {
|
|
|
|
let maybe_buf = op.await;
|
2019-11-16 19:17:47 -05:00
|
|
|
debug!("op_worker_get_message");
|
2020-01-04 05:20:52 -05:00
|
|
|
Ok(json!({ "data": maybe_buf }))
|
|
|
|
};
|
2019-08-26 08:50:21 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
Ok(JsonOp::Async(op.boxed()))
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Post message to host as guest worker
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_worker_post_message(
|
2019-08-14 11:03:02 -04:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
_args: Value,
|
2019-08-14 11:03:02 -04:00
|
|
|
data: Option<PinnedBuf>,
|
2019-08-26 08:50:21 -04:00
|
|
|
) -> Result<JsonOp, ErrBox> {
|
2019-08-14 11:03:02 -04:00
|
|
|
let d = Vec::from(data.unwrap().as_ref()).into_boxed_slice();
|
2019-11-04 10:38:52 -05:00
|
|
|
let mut channels = state.worker_channels.lock().unwrap();
|
|
|
|
let sender = &mut channels.sender;
|
2019-11-16 19:17:47 -05:00
|
|
|
futures::executor::block_on(sender.send(d))
|
2019-08-14 11:03:02 -04:00
|
|
|
.map_err(|e| DenoError::new(ErrorKind::Other, e.to_string()))?;
|
2019-08-26 08:50:21 -04:00
|
|
|
|
|
|
|
Ok(JsonOp::Sync(json!({})))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
#[serde(rename_all = "camelCase")]
|
|
|
|
struct CreateWorkerArgs {
|
|
|
|
specifier: String,
|
|
|
|
include_deno_namespace: bool,
|
|
|
|
has_source_code: bool,
|
|
|
|
source_code: String,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create worker as the host
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_create_worker(
|
2019-08-14 11:03:02 -04:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
args: Value,
|
|
|
|
_data: Option<PinnedBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let args: CreateWorkerArgs = serde_json::from_value(args)?;
|
|
|
|
|
|
|
|
let specifier = args.specifier.as_ref();
|
2019-08-14 11:03:02 -04:00
|
|
|
// Only include deno namespace if requested AND current worker
|
|
|
|
// has included namespace (to avoid escalation).
|
|
|
|
let include_deno_namespace =
|
2019-08-26 08:50:21 -04:00
|
|
|
args.include_deno_namespace && state.include_deno_namespace;
|
|
|
|
let has_source_code = args.has_source_code;
|
|
|
|
let source_code = args.source_code;
|
2019-08-14 11:03:02 -04:00
|
|
|
|
|
|
|
let parent_state = state.clone();
|
|
|
|
|
2019-11-04 10:38:52 -05:00
|
|
|
// TODO(bartlomieju): Isn't this wrong?
|
2019-08-14 11:03:02 -04:00
|
|
|
let mut module_specifier = ModuleSpecifier::resolve_url_or_path(specifier)?;
|
|
|
|
if !has_source_code {
|
2019-11-04 10:38:52 -05:00
|
|
|
if let Some(referrer) = parent_state.main_module.as_ref() {
|
|
|
|
let referrer = referrer.clone().to_string();
|
|
|
|
module_specifier = ModuleSpecifier::resolve_import(specifier, &referrer)?;
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-11-09 15:07:14 -05:00
|
|
|
let (int, ext) = ThreadSafeState::create_channels();
|
2019-08-14 11:03:02 -04:00
|
|
|
let child_state = ThreadSafeState::new(
|
2019-11-04 10:38:52 -05:00
|
|
|
state.global_state.clone(),
|
2019-11-24 10:42:30 -05:00
|
|
|
Some(parent_state.permissions.clone()), // by default share with parent
|
2019-11-04 10:38:52 -05:00
|
|
|
Some(module_specifier.clone()),
|
2019-08-14 11:03:02 -04:00
|
|
|
include_deno_namespace,
|
2019-11-09 15:07:14 -05:00
|
|
|
int,
|
2019-08-14 11:03:02 -04:00
|
|
|
)?;
|
2019-11-24 10:42:30 -05:00
|
|
|
// TODO: add a new option to make child worker not sharing permissions
|
|
|
|
// with parent (aka .clone(), requests from child won't reflect in parent)
|
2019-08-14 11:03:02 -04:00
|
|
|
let name = format!("USER-WORKER-{}", specifier);
|
|
|
|
let deno_main_call = format!("denoMain({})", include_deno_namespace);
|
|
|
|
let mut worker =
|
2019-11-09 15:07:14 -05:00
|
|
|
Worker::new(name, startup_data::deno_isolate_init(), child_state, ext);
|
2019-09-25 10:46:58 -04:00
|
|
|
js_check(worker.execute(&deno_main_call));
|
|
|
|
js_check(worker.execute("workerMain()"));
|
2019-08-14 11:03:02 -04:00
|
|
|
|
2019-11-19 19:17:05 -05:00
|
|
|
let worker_id = parent_state.add_child_worker(worker.clone());
|
|
|
|
let response = json!(worker_id);
|
2019-08-14 11:03:02 -04:00
|
|
|
|
|
|
|
// Has provided source code, execute immediately.
|
|
|
|
if has_source_code {
|
2019-09-25 10:46:58 -04:00
|
|
|
js_check(worker.execute(&source_code));
|
2019-11-19 19:17:05 -05:00
|
|
|
return Ok(JsonOp::Sync(response));
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
2019-11-19 19:17:05 -05:00
|
|
|
// TODO(bartlomieju): this should spawn mod execution on separate tokio task
|
|
|
|
// and block on receving message on a channel or even use sync channel /shrug
|
|
|
|
let (sender, receiver) = mpsc::sync_channel::<Result<(), ErrBox>>(1);
|
2019-12-30 08:57:17 -05:00
|
|
|
let fut = async move {
|
|
|
|
let result = worker
|
|
|
|
.execute_mod_async(&module_specifier, None, false)
|
|
|
|
.await;
|
|
|
|
sender.send(result).expect("Failed to send message");
|
|
|
|
}
|
|
|
|
.boxed();
|
2019-11-19 19:17:05 -05:00
|
|
|
tokio::spawn(fut);
|
|
|
|
|
|
|
|
let result = receiver.recv().expect("Failed to receive message");
|
|
|
|
result?;
|
|
|
|
Ok(JsonOp::Sync(response))
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
struct GetWorkerClosedFuture {
|
|
|
|
state: ThreadSafeState,
|
|
|
|
rid: ResourceId,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for GetWorkerClosedFuture {
|
|
|
|
type Output = Result<(), ErrBox>;
|
|
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
|
|
|
let inner = self.get_mut();
|
|
|
|
let mut workers_table = inner.state.workers.lock().unwrap();
|
|
|
|
let maybe_worker = workers_table.get_mut(&inner.rid);
|
|
|
|
if maybe_worker.is_none() {
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
match maybe_worker.unwrap().poll_unpin(cx) {
|
|
|
|
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
|
|
|
Poll::Ready(Ok(_)) => Poll::Ready(Ok(())),
|
|
|
|
Poll::Pending => Poll::Pending,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-08-26 08:50:21 -04:00
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct HostGetWorkerClosedArgs {
|
2019-11-09 15:07:14 -05:00
|
|
|
id: i32,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Return when the worker closes
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_host_get_worker_closed(
|
2019-08-14 11:03:02 -04:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
args: Value,
|
|
|
|
_data: Option<PinnedBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let args: HostGetWorkerClosedArgs = serde_json::from_value(args)?;
|
2019-11-09 15:07:14 -05:00
|
|
|
let id = args.id as u32;
|
|
|
|
let state_ = state.clone();
|
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
let future = GetWorkerClosedFuture {
|
|
|
|
state: state.clone(),
|
|
|
|
rid: id,
|
|
|
|
};
|
|
|
|
let op = future.then(move |_result| {
|
2019-11-09 15:07:14 -05:00
|
|
|
let mut workers_table = state_.workers.lock().unwrap();
|
2019-12-05 15:30:20 -05:00
|
|
|
let maybe_worker = workers_table.remove(&id);
|
|
|
|
if let Some(worker) = maybe_worker {
|
|
|
|
let mut channels = worker.state.worker_channels.lock().unwrap();
|
|
|
|
channels.sender.close_channel();
|
|
|
|
channels.receiver.close();
|
|
|
|
};
|
2019-11-09 15:07:14 -05:00
|
|
|
futures::future::ok(json!({}))
|
|
|
|
});
|
2019-08-26 08:50:21 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
Ok(JsonOp::Async(op.boxed()))
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct HostGetMessageArgs {
|
2019-11-09 15:07:14 -05:00
|
|
|
id: i32,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Get message from guest worker as host
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_host_get_message(
|
2019-11-09 15:07:14 -05:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
args: Value,
|
|
|
|
_data: Option<PinnedBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let args: HostGetMessageArgs = serde_json::from_value(args)?;
|
|
|
|
|
2019-11-09 15:07:14 -05:00
|
|
|
let id = args.id as u32;
|
|
|
|
let mut table = state.workers.lock().unwrap();
|
|
|
|
// TODO: don't return bad resource anymore
|
|
|
|
let worker = table.get_mut(&id).ok_or_else(bad_resource)?;
|
2020-01-04 05:20:52 -05:00
|
|
|
let fut = worker.get_message();
|
|
|
|
|
|
|
|
let op = async move {
|
|
|
|
let maybe_buf = fut.await.unwrap();
|
|
|
|
Ok(json!({ "data": maybe_buf }))
|
|
|
|
};
|
2019-08-26 08:50:21 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
Ok(JsonOp::Async(op.boxed()))
|
2019-08-26 08:50:21 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
struct HostPostMessageArgs {
|
2019-11-09 15:07:14 -05:00
|
|
|
id: i32,
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Post message to guest worker as host
|
2019-10-11 14:41:54 -04:00
|
|
|
fn op_host_post_message(
|
2019-11-09 15:07:14 -05:00
|
|
|
state: &ThreadSafeState,
|
2019-08-26 08:50:21 -04:00
|
|
|
args: Value,
|
2019-08-14 11:03:02 -04:00
|
|
|
data: Option<PinnedBuf>,
|
2019-08-26 08:50:21 -04:00
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let args: HostPostMessageArgs = serde_json::from_value(args)?;
|
2019-11-09 15:07:14 -05:00
|
|
|
let id = args.id as u32;
|
|
|
|
let msg = Vec::from(data.unwrap().as_ref()).into_boxed_slice();
|
|
|
|
|
|
|
|
debug!("post message to worker {}", id);
|
|
|
|
let mut table = state.workers.lock().unwrap();
|
|
|
|
// TODO: don't return bad resource anymore
|
|
|
|
let worker = table.get_mut(&id).ok_or_else(bad_resource)?;
|
2019-11-19 19:17:05 -05:00
|
|
|
let fut = worker
|
2019-11-17 08:14:50 -05:00
|
|
|
.post_message(msg)
|
2019-11-19 19:17:05 -05:00
|
|
|
.map_err(|e| DenoError::new(ErrorKind::Other, e.to_string()));
|
|
|
|
futures::executor::block_on(fut)?;
|
2019-08-26 08:50:21 -04:00
|
|
|
Ok(JsonOp::Sync(json!({})))
|
2019-08-14 11:03:02 -04:00
|
|
|
}
|
2019-10-11 14:41:54 -04:00
|
|
|
|
|
|
|
fn op_metrics(
|
|
|
|
state: &ThreadSafeState,
|
|
|
|
_args: Value,
|
|
|
|
_zero_copy: Option<PinnedBuf>,
|
|
|
|
) -> Result<JsonOp, ErrBox> {
|
|
|
|
let m = &state.metrics;
|
|
|
|
|
|
|
|
Ok(JsonOp::Sync(json!({
|
|
|
|
"opsDispatched": m.ops_dispatched.load(Ordering::SeqCst) as u64,
|
|
|
|
"opsCompleted": m.ops_completed.load(Ordering::SeqCst) as u64,
|
|
|
|
"bytesSentControl": m.bytes_sent_control.load(Ordering::SeqCst) as u64,
|
|
|
|
"bytesSentData": m.bytes_sent_data.load(Ordering::SeqCst) as u64,
|
|
|
|
"bytesReceived": m.bytes_received.load(Ordering::SeqCst) as u64
|
|
|
|
})))
|
|
|
|
}
|