2020-01-21 03:49:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
2020-09-21 08:26:41 -04:00
|
|
|
|
2020-09-19 19:17:35 -04:00
|
|
|
use crate::global_state::GlobalState;
|
2020-09-11 09:18:49 -04:00
|
|
|
use crate::js;
|
2020-01-21 03:49:47 -05:00
|
|
|
use crate::ops;
|
2020-09-19 19:17:35 -04:00
|
|
|
use crate::permissions::Permissions;
|
|
|
|
use crate::state::CliModuleLoader;
|
2020-01-21 11:50:06 -05:00
|
|
|
use crate::worker::Worker;
|
2020-02-18 14:47:11 -05:00
|
|
|
use crate::worker::WorkerEvent;
|
2020-04-09 18:15:17 -04:00
|
|
|
use crate::worker::WorkerHandle;
|
2020-09-14 12:48:57 -04:00
|
|
|
use deno_core::error::AnyError;
|
2020-09-21 12:36:37 -04:00
|
|
|
use deno_core::futures::channel::mpsc;
|
|
|
|
use deno_core::futures::future::FutureExt;
|
|
|
|
use deno_core::futures::stream::StreamExt;
|
2020-04-09 18:15:17 -04:00
|
|
|
use deno_core::v8;
|
2020-09-19 19:17:35 -04:00
|
|
|
use deno_core::ModuleSpecifier;
|
2020-01-21 03:49:47 -05:00
|
|
|
use std::future::Future;
|
2020-01-21 11:50:06 -05:00
|
|
|
use std::ops::Deref;
|
|
|
|
use std::ops::DerefMut;
|
2020-01-21 03:49:47 -05:00
|
|
|
use std::pin::Pin;
|
2020-04-09 18:15:17 -04:00
|
|
|
use std::sync::atomic::AtomicBool;
|
|
|
|
use std::sync::atomic::Ordering;
|
|
|
|
use std::sync::Arc;
|
2020-01-21 03:49:47 -05:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2020-04-09 18:15:17 -04:00
|
|
|
|
|
|
|
/// Wrapper for `WorkerHandle` that adds functionality
|
|
|
|
/// for terminating workers.
|
|
|
|
///
|
|
|
|
/// This struct is used by host as well as worker itself.
|
|
|
|
///
|
|
|
|
/// Host uses it to communicate with worker and terminate it,
|
|
|
|
/// while worker uses it only to finish execution on `self.close()`.
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WebWorkerHandle {
|
|
|
|
worker_handle: WorkerHandle,
|
|
|
|
terminate_tx: mpsc::Sender<()>,
|
|
|
|
terminated: Arc<AtomicBool>,
|
|
|
|
isolate_handle: v8::IsolateHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for WebWorkerHandle {
|
|
|
|
type Target = WorkerHandle;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.worker_handle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for WebWorkerHandle {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
&mut self.worker_handle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorkerHandle {
|
|
|
|
pub fn terminate(&self) {
|
|
|
|
// This function can be called multiple times by whomever holds
|
|
|
|
// the handle. However only a single "termination" should occur so
|
|
|
|
// we need a guard here.
|
|
|
|
let already_terminated = self.terminated.swap(true, Ordering::Relaxed);
|
|
|
|
|
|
|
|
if !already_terminated {
|
|
|
|
self.isolate_handle.terminate_execution();
|
|
|
|
let mut sender = self.terminate_tx.clone();
|
|
|
|
// This call should be infallible hence the `expect`.
|
|
|
|
// This might change in the future.
|
|
|
|
sender.try_send(()).expect("Failed to terminate");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-21 11:50:06 -05:00
|
|
|
/// This worker is implementation of `Worker` Web API
|
|
|
|
///
|
|
|
|
/// At the moment this type of worker supports only
|
|
|
|
/// communication with parent and creating new workers.
|
|
|
|
///
|
|
|
|
/// Each `WebWorker` is either a child of `MainWorker` or other
|
|
|
|
/// `WebWorker`.
|
2020-02-18 14:47:11 -05:00
|
|
|
pub struct WebWorker {
|
|
|
|
worker: Worker,
|
2020-04-09 18:15:17 -04:00
|
|
|
event_loop_idle: bool,
|
|
|
|
terminate_rx: mpsc::Receiver<()>,
|
|
|
|
handle: WebWorkerHandle,
|
2020-04-16 17:40:29 -04:00
|
|
|
pub has_deno_namespace: bool,
|
2020-02-18 14:47:11 -05:00
|
|
|
}
|
2020-01-21 03:49:47 -05:00
|
|
|
|
|
|
|
impl WebWorker {
|
2020-04-16 17:40:29 -04:00
|
|
|
pub fn new(
|
|
|
|
name: String,
|
2020-09-19 19:17:35 -04:00
|
|
|
permissions: Permissions,
|
|
|
|
main_module: ModuleSpecifier,
|
|
|
|
global_state: Arc<GlobalState>,
|
2020-04-16 17:40:29 -04:00
|
|
|
has_deno_namespace: bool,
|
|
|
|
) -> Self {
|
2020-09-19 19:17:35 -04:00
|
|
|
let loader = CliModuleLoader::new_for_worker();
|
|
|
|
let mut worker = Worker::new(
|
|
|
|
name,
|
|
|
|
Some(js::deno_isolate_init()),
|
|
|
|
permissions,
|
|
|
|
main_module,
|
|
|
|
global_state,
|
|
|
|
loader,
|
|
|
|
false,
|
|
|
|
);
|
2020-04-09 18:15:17 -04:00
|
|
|
|
|
|
|
let terminated = Arc::new(AtomicBool::new(false));
|
2020-05-29 17:41:39 -04:00
|
|
|
let isolate_handle = worker.isolate.thread_safe_handle();
|
2020-04-09 18:15:17 -04:00
|
|
|
let (terminate_tx, terminate_rx) = mpsc::channel::<()>(1);
|
|
|
|
|
|
|
|
let handle = WebWorkerHandle {
|
|
|
|
worker_handle: worker.thread_safe_handle(),
|
|
|
|
terminated,
|
|
|
|
isolate_handle,
|
|
|
|
terminate_tx,
|
|
|
|
};
|
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
let mut web_worker = Self {
|
2020-04-09 18:15:17 -04:00
|
|
|
worker,
|
|
|
|
event_loop_idle: false,
|
|
|
|
terminate_rx,
|
|
|
|
handle,
|
2020-04-16 17:40:29 -04:00
|
|
|
has_deno_namespace,
|
2020-04-09 18:15:17 -04:00
|
|
|
};
|
|
|
|
|
2020-01-21 11:50:06 -05:00
|
|
|
{
|
2020-09-10 09:57:45 -04:00
|
|
|
ops::runtime::init(&mut web_worker.worker);
|
|
|
|
let sender = web_worker.worker.internal_channels.sender.clone();
|
|
|
|
let handle = web_worker.thread_safe_handle();
|
|
|
|
ops::web_worker::init(&mut web_worker.worker, sender, handle);
|
|
|
|
ops::worker_host::init(&mut web_worker.worker);
|
2020-09-17 13:13:20 -04:00
|
|
|
ops::reg_json_sync(
|
|
|
|
&mut web_worker.worker,
|
|
|
|
"op_domain_to_ascii",
|
|
|
|
deno_web::op_domain_to_ascii,
|
|
|
|
);
|
2020-09-10 09:57:45 -04:00
|
|
|
ops::io::init(&mut web_worker.worker);
|
2020-09-17 12:09:50 -04:00
|
|
|
ops::reg_json_sync(
|
|
|
|
&mut web_worker.worker,
|
|
|
|
"op_close",
|
|
|
|
deno_core::op_close,
|
|
|
|
);
|
|
|
|
ops::reg_json_sync(
|
|
|
|
&mut web_worker.worker,
|
|
|
|
"op_resources",
|
|
|
|
deno_core::op_resources,
|
|
|
|
);
|
2020-09-10 09:57:45 -04:00
|
|
|
ops::errors::init(&mut web_worker.worker);
|
|
|
|
ops::timers::init(&mut web_worker.worker);
|
|
|
|
ops::fetch::init(&mut web_worker.worker);
|
|
|
|
ops::websocket::init(&mut web_worker.worker);
|
2020-04-16 17:40:29 -04:00
|
|
|
|
|
|
|
if has_deno_namespace {
|
2020-09-10 09:57:45 -04:00
|
|
|
ops::runtime_compiler::init(&mut web_worker.worker);
|
|
|
|
ops::fs::init(&mut web_worker.worker);
|
|
|
|
ops::fs_events::init(&mut web_worker.worker);
|
|
|
|
ops::plugin::init(&mut web_worker.worker);
|
|
|
|
ops::net::init(&mut web_worker.worker);
|
|
|
|
ops::tls::init(&mut web_worker.worker);
|
|
|
|
ops::os::init(&mut web_worker.worker);
|
|
|
|
ops::permissions::init(&mut web_worker.worker);
|
|
|
|
ops::process::init(&mut web_worker.worker);
|
|
|
|
ops::random::init(&mut web_worker.worker);
|
|
|
|
ops::signal::init(&mut web_worker.worker);
|
|
|
|
ops::tty::init(&mut web_worker.worker);
|
2020-04-16 17:40:29 -04:00
|
|
|
}
|
2020-01-21 03:49:47 -05:00
|
|
|
}
|
|
|
|
|
2020-04-09 18:15:17 -04:00
|
|
|
web_worker
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorker {
|
|
|
|
/// Returns a way to communicate with the Worker from other threads.
|
|
|
|
pub fn thread_safe_handle(&self) -> WebWorkerHandle {
|
|
|
|
self.handle.clone()
|
2020-01-21 03:49:47 -05:00
|
|
|
}
|
2020-01-21 11:50:06 -05:00
|
|
|
}
|
2020-01-21 03:49:47 -05:00
|
|
|
|
2020-01-21 11:50:06 -05:00
|
|
|
impl Deref for WebWorker {
|
|
|
|
type Target = Worker;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
2020-02-18 14:47:11 -05:00
|
|
|
&self.worker
|
2020-01-21 03:49:47 -05:00
|
|
|
}
|
2020-01-21 11:50:06 -05:00
|
|
|
}
|
2020-01-21 03:49:47 -05:00
|
|
|
|
2020-01-21 11:50:06 -05:00
|
|
|
impl DerefMut for WebWorker {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
2020-02-18 14:47:11 -05:00
|
|
|
&mut self.worker
|
2020-01-21 03:49:47 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Future for WebWorker {
|
2020-09-14 12:48:57 -04:00
|
|
|
type Output = Result<(), AnyError>;
|
2020-01-21 03:49:47 -05:00
|
|
|
|
|
|
|
fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
|
|
|
|
let inner = self.get_mut();
|
2020-02-18 14:47:11 -05:00
|
|
|
let worker = &mut inner.worker;
|
|
|
|
|
2020-04-09 18:15:17 -04:00
|
|
|
let terminated = inner.handle.terminated.load(Ordering::Relaxed);
|
|
|
|
|
|
|
|
if terminated {
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
|
|
|
if !inner.event_loop_idle {
|
2020-02-18 14:47:11 -05:00
|
|
|
match worker.poll_unpin(cx) {
|
|
|
|
Poll::Ready(r) => {
|
2020-04-09 18:15:17 -04:00
|
|
|
let terminated = inner.handle.terminated.load(Ordering::Relaxed);
|
|
|
|
if terminated {
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2020-02-18 14:47:11 -05:00
|
|
|
if let Err(e) = r {
|
|
|
|
let mut sender = worker.internal_channels.sender.clone();
|
2020-04-09 18:15:17 -04:00
|
|
|
sender
|
|
|
|
.try_send(WorkerEvent::Error(e))
|
2020-02-18 14:47:11 -05:00
|
|
|
.expect("Failed to post message to host");
|
|
|
|
}
|
2020-04-09 18:15:17 -04:00
|
|
|
inner.event_loop_idle = true;
|
2020-02-18 14:47:11 -05:00
|
|
|
}
|
|
|
|
Poll::Pending => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-09 18:15:17 -04:00
|
|
|
if let Poll::Ready(r) = inner.terminate_rx.poll_next_unpin(cx) {
|
|
|
|
// terminate_rx should never be closed
|
|
|
|
assert!(r.is_some());
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Poll::Ready(r) =
|
|
|
|
worker.internal_channels.receiver.poll_next_unpin(cx)
|
|
|
|
{
|
|
|
|
match r {
|
|
|
|
Some(msg) => {
|
|
|
|
let msg = String::from_utf8(msg.to_vec()).unwrap();
|
|
|
|
let script = format!("workerMessageRecvCallback({})", msg);
|
|
|
|
|
|
|
|
if let Err(e) = worker.execute(&script) {
|
|
|
|
// If execution was terminated during message callback then
|
|
|
|
// just ignore it
|
|
|
|
if inner.handle.terminated.load(Ordering::Relaxed) {
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise forward error to host
|
|
|
|
let mut sender = worker.internal_channels.sender.clone();
|
|
|
|
sender
|
|
|
|
.try_send(WorkerEvent::Error(e))
|
|
|
|
.expect("Failed to post message to host");
|
2020-02-18 14:47:11 -05:00
|
|
|
}
|
|
|
|
|
2020-04-09 18:15:17 -04:00
|
|
|
// Let event loop be polled again
|
|
|
|
inner.event_loop_idle = false;
|
|
|
|
worker.waker.wake();
|
|
|
|
}
|
|
|
|
None => unreachable!(),
|
|
|
|
}
|
2020-02-18 14:47:11 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
Poll::Pending
|
2020-01-21 03:49:47 -05:00
|
|
|
}
|
|
|
|
}
|
2020-01-27 21:12:25 -05:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use crate::tokio_util;
|
2020-02-11 04:04:59 -05:00
|
|
|
use crate::worker::WorkerEvent;
|
2020-09-21 12:36:37 -04:00
|
|
|
use deno_core::serde_json::json;
|
2020-01-27 21:12:25 -05:00
|
|
|
|
|
|
|
fn create_test_worker() -> WebWorker {
|
2020-09-19 19:17:35 -04:00
|
|
|
let main_module =
|
|
|
|
ModuleSpecifier::resolve_url_or_path("./hello.js").unwrap();
|
|
|
|
let global_state = GlobalState::mock(vec!["deno".to_string()], None);
|
|
|
|
let mut worker = WebWorker::new(
|
|
|
|
"TEST".to_string(),
|
|
|
|
Permissions::allow_all(),
|
|
|
|
main_module,
|
|
|
|
global_state,
|
|
|
|
false,
|
|
|
|
);
|
2020-04-16 17:40:29 -04:00
|
|
|
worker
|
2020-04-24 19:03:45 -04:00
|
|
|
.execute("bootstrap.workerRuntime(\"TEST\", false)")
|
2020-04-16 17:40:29 -04:00
|
|
|
.unwrap();
|
2020-01-27 21:12:25 -05:00
|
|
|
worker
|
|
|
|
}
|
|
|
|
#[test]
|
|
|
|
fn test_worker_messages() {
|
2020-02-11 04:04:59 -05:00
|
|
|
let (handle_sender, handle_receiver) =
|
2020-04-09 18:15:17 -04:00
|
|
|
std::sync::mpsc::sync_channel::<WebWorkerHandle>(1);
|
2020-02-11 04:04:59 -05:00
|
|
|
|
|
|
|
let join_handle = std::thread::spawn(move || {
|
|
|
|
let mut worker = create_test_worker();
|
|
|
|
let source = r#"
|
|
|
|
onmessage = function(e) {
|
|
|
|
console.log("msg from main script", e.data);
|
|
|
|
if (e.data == "exit") {
|
|
|
|
return close();
|
|
|
|
} else {
|
|
|
|
console.assert(e.data === "hi");
|
|
|
|
}
|
|
|
|
postMessage([1, 2, 3]);
|
|
|
|
console.log("after postMessage");
|
2020-01-27 21:12:25 -05:00
|
|
|
}
|
2020-02-11 04:04:59 -05:00
|
|
|
"#;
|
|
|
|
worker.execute(source).unwrap();
|
|
|
|
let handle = worker.thread_safe_handle();
|
|
|
|
handle_sender.send(handle).unwrap();
|
2020-02-18 14:47:11 -05:00
|
|
|
let r = tokio_util::run_basic(worker);
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(r.is_ok())
|
2020-02-03 18:08:44 -05:00
|
|
|
});
|
2020-02-08 14:34:31 -05:00
|
|
|
|
2020-02-11 04:04:59 -05:00
|
|
|
let mut handle = handle_receiver.recv().unwrap();
|
2020-01-27 21:12:25 -05:00
|
|
|
|
2020-02-11 04:04:59 -05:00
|
|
|
tokio_util::run_basic(async move {
|
|
|
|
let msg = json!("hi").to_string().into_boxed_str().into_boxed_bytes();
|
2020-04-09 18:15:17 -04:00
|
|
|
let r = handle.post_message(msg.clone());
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(r.is_ok());
|
2020-02-08 14:34:31 -05:00
|
|
|
|
2020-05-17 00:50:38 -04:00
|
|
|
let maybe_msg = handle.get_event().await.unwrap();
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(maybe_msg.is_some());
|
2020-02-08 14:34:31 -05:00
|
|
|
|
2020-04-09 18:15:17 -04:00
|
|
|
let r = handle.post_message(msg.clone());
|
2020-02-08 14:34:31 -05:00
|
|
|
assert!(r.is_ok());
|
2020-02-11 04:04:59 -05:00
|
|
|
|
2020-05-17 00:50:38 -04:00
|
|
|
let maybe_msg = handle.get_event().await.unwrap();
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(maybe_msg.is_some());
|
|
|
|
match maybe_msg {
|
|
|
|
Some(WorkerEvent::Message(buf)) => {
|
|
|
|
assert_eq!(*buf, *b"[1,2,3]");
|
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
|
|
|
|
|
|
|
let msg = json!("exit")
|
|
|
|
.to_string()
|
|
|
|
.into_boxed_str()
|
|
|
|
.into_boxed_bytes();
|
2020-04-09 18:15:17 -04:00
|
|
|
let r = handle.post_message(msg);
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(r.is_ok());
|
2020-05-17 00:50:38 -04:00
|
|
|
let event = handle.get_event().await.unwrap();
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(event.is_none());
|
|
|
|
handle.sender.close_channel();
|
|
|
|
});
|
|
|
|
join_handle.join().expect("Failed to join worker thread");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn removed_from_resource_table_on_close() {
|
|
|
|
let (handle_sender, handle_receiver) =
|
2020-04-09 18:15:17 -04:00
|
|
|
std::sync::mpsc::sync_channel::<WebWorkerHandle>(1);
|
2020-02-11 04:04:59 -05:00
|
|
|
|
|
|
|
let join_handle = std::thread::spawn(move || {
|
|
|
|
let mut worker = create_test_worker();
|
|
|
|
worker.execute("onmessage = () => { close(); }").unwrap();
|
|
|
|
let handle = worker.thread_safe_handle();
|
|
|
|
handle_sender.send(handle).unwrap();
|
2020-02-18 14:47:11 -05:00
|
|
|
let r = tokio_util::run_basic(worker);
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(r.is_ok())
|
2020-02-03 18:08:44 -05:00
|
|
|
});
|
2020-01-27 21:12:25 -05:00
|
|
|
|
2020-02-11 04:04:59 -05:00
|
|
|
let mut handle = handle_receiver.recv().unwrap();
|
|
|
|
|
2020-02-03 18:08:44 -05:00
|
|
|
tokio_util::run_basic(async move {
|
2020-02-11 04:04:59 -05:00
|
|
|
let msg = json!("hi").to_string().into_boxed_str().into_boxed_bytes();
|
2020-04-09 18:15:17 -04:00
|
|
|
let r = handle.post_message(msg.clone());
|
2020-02-03 18:08:44 -05:00
|
|
|
assert!(r.is_ok());
|
2020-05-17 00:50:38 -04:00
|
|
|
let event = handle.get_event().await.unwrap();
|
2020-02-11 04:04:59 -05:00
|
|
|
assert!(event.is_none());
|
|
|
|
handle.sender.close_channel();
|
2020-02-03 18:08:44 -05:00
|
|
|
});
|
2020-02-11 04:04:59 -05:00
|
|
|
join_handle.join().expect("Failed to join worker thread");
|
2020-01-27 21:12:25 -05:00
|
|
|
}
|
|
|
|
}
|