2020-01-21 03:49:47 -05:00
|
|
|
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
|
|
|
|
use crate::ops;
|
2020-02-08 14:34:31 -05:00
|
|
|
use crate::state::State;
|
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;
|
|
|
|
use deno_core::v8;
|
2020-01-21 03:49:47 -05:00
|
|
|
use deno_core::ErrBox;
|
|
|
|
use deno_core::StartupData;
|
2020-04-09 18:15:17 -04:00
|
|
|
use futures::channel::mpsc;
|
2020-01-21 03:49:47 -05:00
|
|
|
use futures::future::FutureExt;
|
2020-02-18 14:47:11 -05:00
|
|
|
use futures::stream::StreamExt;
|
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,
|
|
|
|
startup_data: StartupData,
|
|
|
|
state: State,
|
|
|
|
has_deno_namespace: bool,
|
|
|
|
) -> Self {
|
2020-01-21 11:50:06 -05:00
|
|
|
let state_ = state.clone();
|
2020-02-05 02:40:38 -05:00
|
|
|
let mut worker = Worker::new(name, startup_data, state_);
|
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,
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut web_worker = Self {
|
|
|
|
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
|
|
|
};
|
|
|
|
|
|
|
|
let handle = web_worker.thread_safe_handle();
|
|
|
|
|
2020-01-21 11:50:06 -05:00
|
|
|
{
|
2020-04-09 18:15:17 -04:00
|
|
|
let isolate = &mut web_worker.worker.isolate;
|
2020-02-03 18:08:44 -05:00
|
|
|
ops::runtime::init(isolate, &state);
|
2020-04-09 18:15:17 -04:00
|
|
|
ops::web_worker::init(
|
|
|
|
isolate,
|
|
|
|
&state,
|
|
|
|
&web_worker.worker.internal_channels.sender,
|
|
|
|
handle,
|
|
|
|
);
|
2020-02-03 18:08:44 -05:00
|
|
|
ops::worker_host::init(isolate, &state);
|
2020-02-21 10:35:41 -05:00
|
|
|
ops::io::init(isolate, &state);
|
2020-03-07 07:20:27 -05:00
|
|
|
ops::resources::init(isolate, &state);
|
2020-02-03 18:08:44 -05:00
|
|
|
ops::errors::init(isolate, &state);
|
|
|
|
ops::timers::init(isolate, &state);
|
|
|
|
ops::fetch::init(isolate, &state);
|
2020-04-16 17:40:29 -04:00
|
|
|
|
|
|
|
if has_deno_namespace {
|
|
|
|
ops::runtime_compiler::init(isolate, &state);
|
|
|
|
ops::fs::init(isolate, &state);
|
|
|
|
ops::fs_events::init(isolate, &state);
|
2020-05-11 14:20:14 -04:00
|
|
|
ops::plugin::init(isolate, &state);
|
2020-04-16 17:40:29 -04:00
|
|
|
ops::net::init(isolate, &state);
|
|
|
|
ops::tls::init(isolate, &state);
|
|
|
|
ops::os::init(isolate, &state);
|
|
|
|
ops::permissions::init(isolate, &state);
|
|
|
|
ops::process::init(isolate, &state);
|
|
|
|
ops::random::init(isolate, &state);
|
|
|
|
ops::signal::init(isolate, &state);
|
|
|
|
ops::tty::init(isolate, &state);
|
|
|
|
}
|
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 {
|
|
|
|
type Output = Result<(), ErrBox>;
|
|
|
|
|
|
|
|
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::startup_data;
|
2020-02-08 14:34:31 -05:00
|
|
|
use crate::state::State;
|
2020-01-27 21:12:25 -05:00
|
|
|
use crate::tokio_util;
|
2020-02-11 04:04:59 -05:00
|
|
|
use crate::worker::WorkerEvent;
|
2020-01-27 21:12:25 -05:00
|
|
|
|
|
|
|
fn create_test_worker() -> WebWorker {
|
2020-02-08 14:34:31 -05:00
|
|
|
let state = State::mock("./hello.js");
|
2020-01-27 21:12:25 -05:00
|
|
|
let mut worker = WebWorker::new(
|
|
|
|
"TEST".to_string(),
|
|
|
|
startup_data::deno_isolate_init(),
|
|
|
|
state,
|
2020-04-16 17:40:29 -04:00
|
|
|
false,
|
2020-01-27 21:12:25 -05:00
|
|
|
);
|
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
|
|
|
}
|
|
|
|
}
|