2021-01-11 17:13:41 +00:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
2020-11-26 14:17:45 +00:00
|
|
|
use crate::colors;
|
2020-12-11 17:49:26 +00:00
|
|
|
use crate::inspector::InspectorServer;
|
2021-05-26 15:47:33 +00:00
|
|
|
use crate::inspector::JsRuntimeInspector;
|
2020-11-26 14:17:45 +00:00
|
|
|
use crate::js;
|
2021-04-28 16:41:50 +00:00
|
|
|
use crate::metrics;
|
2020-11-26 14:17:45 +00:00
|
|
|
use crate::ops;
|
|
|
|
use crate::permissions::Permissions;
|
2020-12-07 03:30:40 +00:00
|
|
|
use crate::tokio_util::create_basic_runtime;
|
2021-05-22 16:08:24 +00:00
|
|
|
use deno_broadcast_channel::InMemoryBroadcastChannel;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::error::AnyError;
|
2021-04-21 15:52:00 +00:00
|
|
|
use deno_core::error::Context as ErrorContext;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::futures::channel::mpsc;
|
|
|
|
use deno_core::futures::future::poll_fn;
|
|
|
|
use deno_core::futures::future::FutureExt;
|
|
|
|
use deno_core::futures::stream::StreamExt;
|
2021-05-11 19:09:09 +00:00
|
|
|
use deno_core::serde::Deserialize;
|
|
|
|
use deno_core::serde::Serialize;
|
2020-12-11 17:49:26 +00:00
|
|
|
use deno_core::serde_json;
|
|
|
|
use deno_core::serde_json::json;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::url::Url;
|
|
|
|
use deno_core::v8;
|
2021-04-28 16:41:50 +00:00
|
|
|
use deno_core::Extension;
|
2020-12-13 18:45:53 +00:00
|
|
|
use deno_core::GetErrorClassFn;
|
2020-12-11 17:49:26 +00:00
|
|
|
use deno_core::JsErrorCreateFn;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::JsRuntime;
|
2021-05-11 19:09:09 +00:00
|
|
|
use deno_core::ModuleId;
|
2020-12-11 17:49:26 +00:00
|
|
|
use deno_core::ModuleLoader;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::ModuleSpecifier;
|
|
|
|
use deno_core::RuntimeOptions;
|
2021-05-11 19:09:09 +00:00
|
|
|
use deno_core::ZeroCopyBuf;
|
2021-04-07 13:22:14 +00:00
|
|
|
use deno_file::BlobUrlStore;
|
2021-03-26 16:34:25 +00:00
|
|
|
use log::debug;
|
2021-05-11 19:09:09 +00:00
|
|
|
use std::cell::RefCell;
|
2020-11-26 14:17:45 +00:00
|
|
|
use std::env;
|
2021-05-11 19:09:09 +00:00
|
|
|
use std::fmt;
|
2020-12-11 17:49:26 +00:00
|
|
|
use std::rc::Rc;
|
2020-11-26 14:17:45 +00:00
|
|
|
use std::sync::atomic::AtomicBool;
|
|
|
|
use std::sync::atomic::Ordering;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
|
|
|
use tokio::sync::Mutex as AsyncMutex;
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
#[derive(
|
|
|
|
Debug, Default, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize,
|
|
|
|
)]
|
|
|
|
pub struct WorkerId(u32);
|
|
|
|
impl fmt::Display for WorkerId {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
write!(f, "worker-{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl WorkerId {
|
|
|
|
pub fn next(&self) -> Option<WorkerId> {
|
|
|
|
self.0.checked_add(1).map(WorkerId)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type WorkerMessage = ZeroCopyBuf;
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
/// Events that are sent to host from child
|
|
|
|
/// worker.
|
|
|
|
pub enum WorkerEvent {
|
2021-05-11 19:09:09 +00:00
|
|
|
Message(WorkerMessage),
|
2020-11-26 14:17:45 +00:00
|
|
|
Error(AnyError),
|
|
|
|
TerminalError(AnyError),
|
2021-05-11 19:09:09 +00:00
|
|
|
Close,
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// Channels used for communication with worker's parent
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WebWorkerInternalHandle {
|
|
|
|
sender: mpsc::Sender<WorkerEvent>,
|
|
|
|
receiver: Rc<RefCell<mpsc::Receiver<WorkerMessage>>>,
|
|
|
|
terminated: Arc<AtomicBool>,
|
|
|
|
isolate_handle: v8::IsolateHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorkerInternalHandle {
|
|
|
|
/// Post WorkerEvent to parent as a worker
|
|
|
|
pub fn post_event(&self, event: WorkerEvent) -> Result<(), AnyError> {
|
|
|
|
let mut sender = self.sender.clone();
|
|
|
|
// If the channel is closed,
|
|
|
|
// the worker must have terminated but the termination message has not yet been received.
|
|
|
|
//
|
|
|
|
// Therefore just treat it as if the worker has terminated and return.
|
|
|
|
if sender.is_closed() {
|
|
|
|
self.terminated.store(true, Ordering::SeqCst);
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
sender.try_send(event)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the WorkerEvent with lock
|
|
|
|
/// Panic if more than one listener tries to get event
|
|
|
|
pub async fn get_message(&self) -> Option<WorkerMessage> {
|
|
|
|
let mut receiver = self.receiver.borrow_mut();
|
|
|
|
receiver.next().await
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if this worker is terminated or being terminated
|
|
|
|
pub fn is_terminated(&self) -> bool {
|
|
|
|
self.terminated.load(Ordering::SeqCst)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Terminate the worker
|
|
|
|
/// This function will set terminated to true, terminate the isolate and close the message channel
|
|
|
|
pub fn terminate(&mut 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::SeqCst);
|
|
|
|
|
|
|
|
if !already_terminated {
|
|
|
|
// Stop javascript execution
|
|
|
|
self.isolate_handle.terminate_execution();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wake parent by closing the channel
|
|
|
|
self.sender.close_channel();
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WebWorkerHandle {
|
2021-05-11 19:09:09 +00:00
|
|
|
sender: mpsc::Sender<WorkerMessage>,
|
|
|
|
receiver: Arc<AsyncMutex<mpsc::Receiver<WorkerEvent>>>,
|
2020-11-26 14:17:45 +00:00
|
|
|
terminated: Arc<AtomicBool>,
|
|
|
|
isolate_handle: v8::IsolateHandle,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorkerHandle {
|
2021-05-11 19:09:09 +00:00
|
|
|
/// Post WorkerMessage to worker as a host
|
|
|
|
pub fn post_message(&self, buf: WorkerMessage) -> Result<(), AnyError> {
|
2020-11-26 14:17:45 +00:00
|
|
|
let mut sender = self.sender.clone();
|
2021-04-19 14:57:02 +00:00
|
|
|
// If the channel is closed,
|
|
|
|
// the worker must have terminated but the termination message has not yet been recieved.
|
|
|
|
//
|
|
|
|
// Therefore just treat it as if the worker has terminated and return.
|
|
|
|
if sender.is_closed() {
|
|
|
|
self.terminated.store(true, Ordering::SeqCst);
|
|
|
|
return Ok(());
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
sender.try_send(buf)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
/// Get the WorkerEvent with lock
|
2020-11-26 14:17:45 +00:00
|
|
|
/// Return error if more than one listener tries to get event
|
|
|
|
pub async fn get_event(&self) -> Result<Option<WorkerEvent>, AnyError> {
|
|
|
|
let mut receiver = self.receiver.try_lock()?;
|
|
|
|
Ok(receiver.next().await)
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
/// Terminate the worker
|
|
|
|
/// This function will set terminated to true, terminate the isolate and close the message channel
|
|
|
|
pub fn terminate(&mut self) {
|
2020-11-26 14:17:45 +00:00
|
|
|
// 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.
|
2020-12-07 03:30:40 +00:00
|
|
|
let already_terminated = self.terminated.swap(true, Ordering::SeqCst);
|
2020-11-26 14:17:45 +00:00
|
|
|
|
|
|
|
if !already_terminated {
|
2021-05-11 19:09:09 +00:00
|
|
|
// Stop javascript execution
|
2020-11-26 14:17:45 +00:00
|
|
|
self.isolate_handle.terminate_execution();
|
|
|
|
}
|
2021-05-11 19:09:09 +00:00
|
|
|
|
|
|
|
// Wake web worker by closing the channel
|
|
|
|
self.sender.close_channel();
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
fn create_handles(
|
2020-11-26 14:17:45 +00:00
|
|
|
isolate_handle: v8::IsolateHandle,
|
2021-05-11 19:09:09 +00:00
|
|
|
) -> (WebWorkerInternalHandle, WebWorkerHandle) {
|
|
|
|
let (in_tx, in_rx) = mpsc::channel::<WorkerMessage>(1);
|
2020-11-26 14:17:45 +00:00
|
|
|
let (out_tx, out_rx) = mpsc::channel::<WorkerEvent>(1);
|
2021-05-11 19:09:09 +00:00
|
|
|
let terminated = Arc::new(AtomicBool::new(false));
|
|
|
|
let internal_handle = WebWorkerInternalHandle {
|
2020-11-26 14:17:45 +00:00
|
|
|
sender: out_tx,
|
2021-05-11 19:09:09 +00:00
|
|
|
receiver: Rc::new(RefCell::new(in_rx)),
|
|
|
|
terminated: terminated.clone(),
|
|
|
|
isolate_handle: isolate_handle.clone(),
|
2020-11-26 14:17:45 +00:00
|
|
|
};
|
2021-05-11 19:09:09 +00:00
|
|
|
let external_handle = WebWorkerHandle {
|
2020-11-26 14:17:45 +00:00
|
|
|
sender: in_tx,
|
|
|
|
receiver: Arc::new(AsyncMutex::new(out_rx)),
|
2021-05-11 19:09:09 +00:00
|
|
|
terminated,
|
2020-11-26 14:17:45 +00:00
|
|
|
isolate_handle,
|
|
|
|
};
|
2021-05-11 19:09:09 +00:00
|
|
|
(internal_handle, external_handle)
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This struct is an implementation of `Worker` Web API
|
|
|
|
///
|
|
|
|
/// Each `WebWorker` is either a child of `MainWorker` or other
|
|
|
|
/// `WebWorker`.
|
|
|
|
pub struct WebWorker {
|
2021-05-11 19:09:09 +00:00
|
|
|
id: WorkerId,
|
2021-05-26 15:47:33 +00:00
|
|
|
inspector: Option<Box<JsRuntimeInspector>>,
|
2020-12-13 18:45:53 +00:00
|
|
|
pub js_runtime: JsRuntime,
|
|
|
|
pub name: String,
|
2021-05-11 19:09:09 +00:00
|
|
|
internal_handle: WebWorkerInternalHandle,
|
|
|
|
external_handle: WebWorkerHandle,
|
2020-12-11 17:49:26 +00:00
|
|
|
pub use_deno_namespace: bool,
|
2021-01-07 18:06:08 +00:00
|
|
|
pub main_module: ModuleSpecifier,
|
2020-12-11 17:49:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct WebWorkerOptions {
|
2020-12-11 23:36:18 +00:00
|
|
|
/// Sets `Deno.args` in JS runtime.
|
2020-12-11 17:49:26 +00:00
|
|
|
pub args: Vec<String>,
|
|
|
|
pub debug_flag: bool,
|
|
|
|
pub unstable: bool,
|
2021-01-04 23:15:52 +00:00
|
|
|
pub ca_data: Option<Vec<u8>>,
|
2020-12-11 23:36:18 +00:00
|
|
|
pub user_agent: String,
|
2020-12-11 17:49:26 +00:00
|
|
|
pub seed: Option<u64>,
|
|
|
|
pub module_loader: Rc<dyn ModuleLoader>,
|
|
|
|
pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>,
|
|
|
|
pub js_error_create_fn: Option<Rc<JsErrorCreateFn>>,
|
|
|
|
pub use_deno_namespace: bool,
|
|
|
|
pub attach_inspector: bool,
|
|
|
|
pub maybe_inspector_server: Option<Arc<InspectorServer>>,
|
|
|
|
pub apply_source_maps: bool,
|
2020-12-11 23:36:18 +00:00
|
|
|
/// Sets `Deno.version.deno` in JS runtime.
|
|
|
|
pub runtime_version: String,
|
|
|
|
/// Sets `Deno.version.typescript` in JS runtime.
|
|
|
|
pub ts_version: String,
|
|
|
|
/// Sets `Deno.noColor` in JS runtime.
|
|
|
|
pub no_color: bool,
|
2020-12-13 18:45:53 +00:00
|
|
|
pub get_error_class_fn: Option<GetErrorClassFn>,
|
2021-04-07 13:22:14 +00:00
|
|
|
pub blob_url_store: BlobUrlStore,
|
2021-05-22 16:08:24 +00:00
|
|
|
pub broadcast_channel: InMemoryBroadcastChannel,
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorker {
|
2020-12-11 17:49:26 +00:00
|
|
|
pub fn from_options(
|
2020-11-26 14:17:45 +00:00
|
|
|
name: String,
|
|
|
|
permissions: Permissions,
|
|
|
|
main_module: ModuleSpecifier,
|
2021-05-11 19:09:09 +00:00
|
|
|
worker_id: WorkerId,
|
2020-12-11 17:49:26 +00:00
|
|
|
options: &WebWorkerOptions,
|
2020-11-26 14:17:45 +00:00
|
|
|
) -> Self {
|
2021-05-02 23:22:57 +00:00
|
|
|
// Permissions: many ops depend on this
|
|
|
|
let unstable = options.unstable;
|
|
|
|
let perm_ext = Extension::builder()
|
|
|
|
.state(move |state| {
|
|
|
|
state.put::<Permissions>(permissions.clone());
|
|
|
|
state.put(ops::UnstableChecker { unstable });
|
|
|
|
Ok(())
|
|
|
|
})
|
|
|
|
.build();
|
|
|
|
|
|
|
|
let mut extensions: Vec<Extension> = vec![
|
2021-04-28 16:41:50 +00:00
|
|
|
// Web APIs
|
|
|
|
deno_webidl::init(),
|
|
|
|
deno_console::init(),
|
|
|
|
deno_url::init(),
|
|
|
|
deno_web::init(),
|
|
|
|
deno_file::init(
|
|
|
|
options.blob_url_store.clone(),
|
|
|
|
Some(main_module.clone()),
|
|
|
|
),
|
|
|
|
deno_fetch::init::<Permissions>(
|
|
|
|
options.user_agent.clone(),
|
|
|
|
options.ca_data.clone(),
|
|
|
|
),
|
|
|
|
deno_websocket::init::<Permissions>(
|
|
|
|
options.user_agent.clone(),
|
|
|
|
options.ca_data.clone(),
|
|
|
|
),
|
2021-05-22 16:08:24 +00:00
|
|
|
deno_broadcast_channel::init(
|
|
|
|
options.broadcast_channel.clone(),
|
|
|
|
options.unstable,
|
|
|
|
),
|
2021-04-28 16:41:50 +00:00
|
|
|
deno_crypto::init(options.seed),
|
|
|
|
deno_webgpu::init(options.unstable),
|
|
|
|
deno_timers::init::<Permissions>(),
|
|
|
|
// Metrics
|
|
|
|
metrics::init(),
|
2021-05-02 23:22:57 +00:00
|
|
|
// Permissions ext (worker specific state)
|
|
|
|
perm_ext,
|
|
|
|
];
|
|
|
|
|
|
|
|
// Runtime ops that are always initialized for WebWorkers
|
|
|
|
let runtime_exts = vec![
|
|
|
|
ops::web_worker::init(),
|
|
|
|
ops::runtime::init(main_module.clone()),
|
2021-05-11 19:09:09 +00:00
|
|
|
ops::worker_host::init(options.create_web_worker_cb.clone()),
|
2021-05-02 23:22:57 +00:00
|
|
|
ops::io::init(),
|
2021-04-28 16:41:50 +00:00
|
|
|
];
|
|
|
|
|
2021-05-02 23:22:57 +00:00
|
|
|
// Extensions providing Deno.* features
|
|
|
|
let deno_ns_exts = if options.use_deno_namespace {
|
|
|
|
vec![
|
|
|
|
ops::fs_events::init(),
|
|
|
|
ops::fs::init(),
|
|
|
|
ops::net::init(),
|
|
|
|
ops::os::init(),
|
|
|
|
ops::http::init(),
|
|
|
|
ops::permissions::init(),
|
|
|
|
ops::plugin::init(),
|
|
|
|
ops::process::init(),
|
|
|
|
ops::signal::init(),
|
|
|
|
ops::tls::init(),
|
|
|
|
ops::tty::init(),
|
|
|
|
ops::io::init_stdio(),
|
|
|
|
]
|
|
|
|
} else {
|
|
|
|
vec![]
|
|
|
|
};
|
|
|
|
|
|
|
|
// Append exts
|
|
|
|
extensions.extend(runtime_exts);
|
|
|
|
extensions.extend(deno_ns_exts); // May be empty
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
let mut js_runtime = JsRuntime::new(RuntimeOptions {
|
2020-12-11 17:49:26 +00:00
|
|
|
module_loader: Some(options.module_loader.clone()),
|
2020-11-26 14:17:45 +00:00
|
|
|
startup_snapshot: Some(js::deno_isolate_init()),
|
2020-12-11 17:49:26 +00:00
|
|
|
js_error_create_fn: options.js_error_create_fn.clone(),
|
2020-12-13 18:45:53 +00:00
|
|
|
get_error_class_fn: options.get_error_class_fn,
|
2021-04-28 16:41:50 +00:00
|
|
|
extensions,
|
2020-11-26 14:17:45 +00:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
2020-12-11 17:49:26 +00:00
|
|
|
let inspector = if options.attach_inspector {
|
2021-05-26 15:47:33 +00:00
|
|
|
let mut inspector = JsRuntimeInspector::new(&mut js_runtime);
|
|
|
|
|
|
|
|
if let Some(server) = options.maybe_inspector_server.clone() {
|
|
|
|
let session_sender = inspector.get_session_sender();
|
|
|
|
let deregister_rx = inspector.add_deregister_handler();
|
|
|
|
server.register_inspector(session_sender, deregister_rx);
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(inspector)
|
2020-12-11 17:49:26 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
let (internal_handle, external_handle) = {
|
|
|
|
let handle = js_runtime.v8_isolate().thread_safe_handle();
|
|
|
|
let (internal_handle, external_handle) = create_handles(handle);
|
|
|
|
let op_state = js_runtime.op_state();
|
|
|
|
let mut op_state = op_state.borrow_mut();
|
|
|
|
op_state.put(internal_handle.clone());
|
|
|
|
(internal_handle, external_handle)
|
|
|
|
};
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
Self {
|
2020-12-11 17:49:26 +00:00
|
|
|
id: worker_id,
|
2020-11-26 14:17:45 +00:00
|
|
|
inspector,
|
|
|
|
js_runtime,
|
2020-12-11 17:49:26 +00:00
|
|
|
name,
|
2021-05-11 19:09:09 +00:00
|
|
|
internal_handle,
|
|
|
|
external_handle,
|
2020-12-11 17:49:26 +00:00
|
|
|
use_deno_namespace: options.use_deno_namespace,
|
2021-05-02 23:22:57 +00:00
|
|
|
main_module,
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2020-12-11 17:49:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn bootstrap(&mut self, options: &WebWorkerOptions) {
|
|
|
|
let runtime_options = json!({
|
|
|
|
"args": options.args,
|
|
|
|
"applySourceMaps": options.apply_source_maps,
|
|
|
|
"debugFlag": options.debug_flag,
|
2020-12-11 23:36:18 +00:00
|
|
|
"denoVersion": options.runtime_version,
|
|
|
|
"noColor": options.no_color,
|
2020-12-11 17:49:26 +00:00
|
|
|
"pid": std::process::id(),
|
|
|
|
"ppid": ops::runtime::ppid(),
|
|
|
|
"target": env!("TARGET"),
|
2020-12-11 23:36:18 +00:00
|
|
|
"tsVersion": options.ts_version,
|
2020-12-11 17:49:26 +00:00
|
|
|
"unstableFlag": options.unstable,
|
|
|
|
"v8Version": deno_core::v8_version(),
|
2021-01-07 18:06:08 +00:00
|
|
|
"location": self.main_module,
|
2020-12-11 17:49:26 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
let runtime_options_str =
|
|
|
|
serde_json::to_string_pretty(&runtime_options).unwrap();
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2020-12-07 03:30:40 +00:00
|
|
|
// Instead of using name for log we use `worker-${id}` because
|
|
|
|
// WebWorkers can have empty string as name.
|
|
|
|
let script = format!(
|
2021-05-11 19:09:09 +00:00
|
|
|
"bootstrap.workerRuntime({}, \"{}\", {}, \"{}\")",
|
2020-12-11 17:49:26 +00:00
|
|
|
runtime_options_str, self.name, options.use_deno_namespace, self.id
|
2020-12-07 03:30:40 +00:00
|
|
|
);
|
2020-12-11 17:49:26 +00:00
|
|
|
self
|
2020-12-07 03:30:40 +00:00
|
|
|
.execute(&script)
|
|
|
|
.expect("Failed to execute worker bootstrap script");
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Same as execute2() but the filename defaults to "$CWD/__anonymous__".
|
|
|
|
pub fn execute(&mut self, js_source: &str) -> Result<(), AnyError> {
|
2021-04-21 15:52:00 +00:00
|
|
|
let path = env::current_dir()
|
|
|
|
.context("Failed to get current working directory")?
|
|
|
|
.join("__anonymous__");
|
2020-11-26 14:17:45 +00:00
|
|
|
let url = Url::from_file_path(path).unwrap();
|
|
|
|
self.js_runtime.execute(url.as_str(), js_source)
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
/// Loads and instantiates specified JavaScript module.
|
|
|
|
pub async fn preload_module(
|
|
|
|
&mut self,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<ModuleId, AnyError> {
|
|
|
|
self.js_runtime.load_module(module_specifier, None).await
|
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
/// Loads, instantiates and executes specified JavaScript module.
|
|
|
|
pub async fn execute_module(
|
|
|
|
&mut self,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<(), AnyError> {
|
2021-05-11 19:09:09 +00:00
|
|
|
let id = self.preload_module(module_specifier).await?;
|
2021-03-04 12:19:47 +00:00
|
|
|
|
|
|
|
let mut receiver = self.js_runtime.mod_evaluate(id);
|
|
|
|
tokio::select! {
|
|
|
|
maybe_result = receiver.next() => {
|
|
|
|
debug!("received worker module evaluate {:#?}", maybe_result);
|
|
|
|
// If `None` is returned it means that runtime was destroyed before
|
|
|
|
// evaluation was complete. This can happen in Web Worker when `self.close()`
|
|
|
|
// is called at top level.
|
|
|
|
let result = maybe_result.unwrap_or(Ok(()));
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
event_loop_result = self.run_event_loop() => {
|
2021-05-11 19:09:09 +00:00
|
|
|
if self.internal_handle.is_terminated() {
|
|
|
|
return Ok(());
|
2021-03-04 12:19:47 +00:00
|
|
|
}
|
|
|
|
event_loop_result?;
|
|
|
|
let maybe_result = receiver.next().await;
|
|
|
|
let result = maybe_result.unwrap_or(Ok(()));
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a way to communicate with the Worker from other threads.
|
|
|
|
pub fn thread_safe_handle(&self) -> WebWorkerHandle {
|
2021-05-11 19:09:09 +00:00
|
|
|
self.external_handle.clone()
|
2020-12-07 03:30:40 +00:00
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
pub fn poll_event_loop(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context,
|
|
|
|
) -> Poll<Result<(), AnyError>> {
|
2021-05-11 19:09:09 +00:00
|
|
|
// If awakened because we are terminating, just return Ok
|
|
|
|
if self.internal_handle.is_terminated() {
|
2020-11-26 14:17:45 +00:00
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// We always poll the inspector if it exists.
|
|
|
|
let _ = self.inspector.as_mut().map(|i| i.poll_unpin(cx));
|
|
|
|
match self.js_runtime.poll_event_loop(cx) {
|
|
|
|
Poll::Ready(r) => {
|
|
|
|
// If js ended because we are terminating, just return Ok
|
|
|
|
if self.internal_handle.is_terminated() {
|
2020-12-07 03:30:40 +00:00
|
|
|
return Poll::Ready(Ok(()));
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// In case of an error, pass to parent without terminating worker
|
2020-12-07 03:30:40 +00:00
|
|
|
if let Err(e) = r {
|
|
|
|
print_worker_error(e.to_string(), &self.name);
|
2021-05-11 19:09:09 +00:00
|
|
|
let handle = self.internal_handle.clone();
|
|
|
|
handle
|
|
|
|
.post_event(WorkerEvent::Error(e))
|
2020-12-07 03:30:40 +00:00
|
|
|
.expect("Failed to post message to host");
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
return Poll::Pending;
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
panic!(
|
|
|
|
"coding error: either js is polling or the worker is terminated"
|
|
|
|
);
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2021-05-11 19:09:09 +00:00
|
|
|
Poll::Pending => Poll::Pending,
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn run_event_loop(&mut self) -> Result<(), AnyError> {
|
|
|
|
poll_fn(|cx| self.poll_event_loop(cx)).await
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for WebWorker {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
// The Isolate object must outlive the Inspector object, but this is
|
|
|
|
// currently not enforced by the type system.
|
|
|
|
self.inspector.take();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-07 03:30:40 +00:00
|
|
|
fn print_worker_error(error_str: String, name: &str) {
|
|
|
|
eprintln!(
|
|
|
|
"{}: Uncaught (in worker \"{}\") {}",
|
|
|
|
colors::red_bold("error"),
|
|
|
|
name,
|
|
|
|
error_str.trim_start_matches("Uncaught "),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This function should be called from a thread dedicated to this worker.
|
|
|
|
// TODO(bartlomieju): check if order of actions is aligned to Worker spec
|
|
|
|
pub fn run_web_worker(
|
|
|
|
mut worker: WebWorker,
|
|
|
|
specifier: ModuleSpecifier,
|
|
|
|
maybe_source_code: Option<String>,
|
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let name = worker.name.to_string();
|
|
|
|
|
2021-01-12 07:50:02 +00:00
|
|
|
let rt = create_basic_runtime();
|
2020-12-07 03:30:40 +00:00
|
|
|
|
|
|
|
// TODO(bartlomieju): run following block using "select!"
|
|
|
|
// with terminate
|
|
|
|
|
|
|
|
// Execute provided source code immediately
|
|
|
|
let result = if let Some(source_code) = maybe_source_code {
|
|
|
|
worker.execute(&source_code)
|
|
|
|
} else {
|
|
|
|
// TODO(bartlomieju): add "type": "classic", ie. ability to load
|
|
|
|
// script instead of module
|
|
|
|
let load_future = worker.execute_module(&specifier).boxed_local();
|
|
|
|
|
|
|
|
rt.block_on(load_future)
|
|
|
|
};
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
let internal_handle = worker.internal_handle.clone();
|
2020-12-07 03:30:40 +00:00
|
|
|
|
|
|
|
// If sender is closed it means that worker has already been closed from
|
|
|
|
// within using "globalThis.close()"
|
2021-05-11 19:09:09 +00:00
|
|
|
if internal_handle.is_terminated() {
|
2020-12-07 03:30:40 +00:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Err(e) = result {
|
|
|
|
print_worker_error(e.to_string(), &name);
|
2021-05-11 19:09:09 +00:00
|
|
|
internal_handle
|
|
|
|
.post_event(WorkerEvent::TerminalError(e))
|
2020-12-07 03:30:40 +00:00
|
|
|
.expect("Failed to post message to host");
|
|
|
|
|
|
|
|
// Failure to execute script is a terminal error, bye, bye.
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
let result = rt.block_on(worker.run_event_loop());
|
|
|
|
debug!("Worker thread shuts down {}", &name);
|
|
|
|
result
|
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
|
|
|
use crate::tokio_util;
|
|
|
|
|
|
|
|
fn create_test_web_worker() -> WebWorker {
|
2021-02-17 18:47:18 +00:00
|
|
|
let main_module = deno_core::resolve_url_or_path("./hello.js").unwrap();
|
2020-12-11 17:49:26 +00:00
|
|
|
let module_loader = Rc::new(deno_core::NoopModuleLoader);
|
|
|
|
let create_web_worker_cb = Arc::new(|_| unreachable!());
|
|
|
|
|
|
|
|
let options = WebWorkerOptions {
|
|
|
|
args: vec![],
|
|
|
|
apply_source_maps: false,
|
|
|
|
debug_flag: false,
|
|
|
|
unstable: false,
|
2021-01-04 23:15:52 +00:00
|
|
|
ca_data: None,
|
2020-12-11 23:36:18 +00:00
|
|
|
user_agent: "x".to_string(),
|
2020-12-11 17:49:26 +00:00
|
|
|
seed: None,
|
|
|
|
module_loader,
|
|
|
|
create_web_worker_cb,
|
|
|
|
js_error_create_fn: None,
|
|
|
|
use_deno_namespace: false,
|
|
|
|
attach_inspector: false,
|
|
|
|
maybe_inspector_server: None,
|
2020-12-11 23:36:18 +00:00
|
|
|
runtime_version: "x".to_string(),
|
|
|
|
ts_version: "x".to_string(),
|
|
|
|
no_color: true,
|
2020-12-13 18:45:53 +00:00
|
|
|
get_error_class_fn: None,
|
2021-04-07 13:22:14 +00:00
|
|
|
blob_url_store: BlobUrlStore::default(),
|
2021-05-22 16:08:24 +00:00
|
|
|
broadcast_channel: InMemoryBroadcastChannel::default(),
|
2020-12-11 17:49:26 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
let mut worker = WebWorker::from_options(
|
2020-11-26 14:17:45 +00:00
|
|
|
"TEST".to_string(),
|
|
|
|
Permissions::allow_all(),
|
|
|
|
main_module,
|
2021-05-11 19:09:09 +00:00
|
|
|
WorkerId(1),
|
2020-12-11 17:49:26 +00:00
|
|
|
&options,
|
|
|
|
);
|
|
|
|
worker.bootstrap(&options);
|
|
|
|
worker
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_worker_messages() {
|
|
|
|
let (handle_sender, handle_receiver) =
|
|
|
|
std::sync::mpsc::sync_channel::<WebWorkerHandle>(1);
|
|
|
|
|
|
|
|
let join_handle = std::thread::spawn(move || {
|
|
|
|
let mut worker = create_test_web_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");
|
|
|
|
}
|
|
|
|
"#;
|
|
|
|
worker.execute(source).unwrap();
|
|
|
|
let handle = worker.thread_safe_handle();
|
|
|
|
handle_sender.send(handle).unwrap();
|
|
|
|
let r = tokio_util::run_basic(worker.run_event_loop());
|
|
|
|
assert!(r.is_ok())
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut handle = handle_receiver.recv().unwrap();
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// TODO(Inteon): use Deno.core.serialize() instead of hardcoded encoded value
|
|
|
|
let msg = vec![34, 2, 104, 105].into_boxed_slice(); // "hi" encoded
|
|
|
|
let r = handle.post_message(msg.clone().into());
|
2020-11-26 14:17:45 +00:00
|
|
|
assert!(r.is_ok());
|
|
|
|
|
|
|
|
let maybe_msg = handle.get_event().await.unwrap();
|
|
|
|
assert!(maybe_msg.is_some());
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
let r = handle.post_message(msg.clone().into());
|
2020-11-26 14:17:45 +00:00
|
|
|
assert!(r.is_ok());
|
|
|
|
|
|
|
|
let maybe_msg = handle.get_event().await.unwrap();
|
|
|
|
assert!(maybe_msg.is_some());
|
|
|
|
match maybe_msg {
|
|
|
|
Some(WorkerEvent::Message(buf)) => {
|
2021-05-11 19:09:09 +00:00
|
|
|
// TODO(Inteon): use Deno.core.serialize() instead of hardcoded encoded value
|
|
|
|
assert_eq!(*buf, [65, 3, 73, 2, 73, 4, 73, 6, 36, 0, 3]);
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// TODO(Inteon): use Deno.core.serialize() instead of hardcoded encoded value
|
|
|
|
let msg = vec![34, 4, 101, 120, 105, 116].into_boxed_slice(); // "exit" encoded
|
|
|
|
let r = handle.post_message(msg.into());
|
2020-11-26 14:17:45 +00:00
|
|
|
assert!(r.is_ok());
|
|
|
|
let event = handle.get_event().await.unwrap();
|
|
|
|
assert!(event.is_none());
|
|
|
|
handle.sender.close_channel();
|
|
|
|
join_handle.join().expect("Failed to join worker thread");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn removed_from_resource_table_on_close() {
|
|
|
|
let (handle_sender, handle_receiver) =
|
|
|
|
std::sync::mpsc::sync_channel::<WebWorkerHandle>(1);
|
|
|
|
|
|
|
|
let join_handle = std::thread::spawn(move || {
|
|
|
|
let mut worker = create_test_web_worker();
|
|
|
|
worker.execute("onmessage = () => { close(); }").unwrap();
|
|
|
|
let handle = worker.thread_safe_handle();
|
|
|
|
handle_sender.send(handle).unwrap();
|
|
|
|
let r = tokio_util::run_basic(worker.run_event_loop());
|
|
|
|
assert!(r.is_ok())
|
|
|
|
});
|
|
|
|
|
|
|
|
let mut handle = handle_receiver.recv().unwrap();
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// TODO(Inteon): use Deno.core.serialize() instead of hardcoded encoded value
|
|
|
|
let msg = vec![34, 2, 104, 105].into_boxed_slice(); // "hi" encoded
|
|
|
|
let r = handle.post_message(msg.clone().into());
|
2020-11-26 14:17:45 +00:00
|
|
|
assert!(r.is_ok());
|
|
|
|
let event = handle.get_event().await.unwrap();
|
|
|
|
assert!(event.is_none());
|
|
|
|
handle.sender.close_channel();
|
|
|
|
|
|
|
|
join_handle.join().expect("Failed to join worker thread");
|
|
|
|
}
|
|
|
|
}
|