2024-01-01 19:58:21 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2024-09-30 13:19:24 +00:00
|
|
|
|
2021-05-22 16:08:24 +00:00
|
|
|
use deno_broadcast_channel::InMemoryBroadcastChannel;
|
2022-09-28 12:11:12 +00:00
|
|
|
use deno_cache::CreateCache;
|
|
|
|
use deno_cache::SqliteBackedCache;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::error::AnyError;
|
2021-06-22 14:30:16 +00:00
|
|
|
use deno_core::error::JsError;
|
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::stream::StreamExt;
|
2021-11-29 12:37:44 +00:00
|
|
|
use deno_core::futures::task::AtomicWaker;
|
2022-11-28 11:47:25 +00:00
|
|
|
use deno_core::located_script_name;
|
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::json;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::v8;
|
2021-06-22 14:30:16 +00:00
|
|
|
use deno_core::CancelHandle;
|
2021-09-29 08:47:24 +00:00
|
|
|
use deno_core::CompiledWasmModuleStore;
|
2024-03-16 00:59:18 +00:00
|
|
|
use deno_core::DetachedBuffer;
|
2021-04-28 16:41:50 +00:00
|
|
|
use deno_core::Extension;
|
2023-10-12 15:55:50 +00:00
|
|
|
use deno_core::FeatureChecker;
|
2020-12-13 18:45:53 +00:00
|
|
|
use deno_core::GetErrorClassFn;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::JsRuntime;
|
2024-01-10 04:18:40 +00:00
|
|
|
use deno_core::ModuleCodeString;
|
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;
|
2023-11-26 23:09:04 +00:00
|
|
|
use deno_core::PollEventLoopOptions;
|
2020-11-26 14:17:45 +00:00
|
|
|
use deno_core::RuntimeOptions;
|
2021-07-06 17:42:52 +00:00
|
|
|
use deno_core::SharedArrayBufferStore;
|
2023-11-01 18:57:55 +00:00
|
|
|
use deno_cron::local::LocalCronHandler;
|
2023-05-04 18:28:42 +00:00
|
|
|
use deno_fs::FileSystem;
|
2023-05-10 14:23:26 +00:00
|
|
|
use deno_http::DefaultHttpPropertyExtractor;
|
2023-03-05 00:39:48 +00:00
|
|
|
use deno_io::Stdio;
|
2023-08-22 05:56:00 +00:00
|
|
|
use deno_kv::dynamic::MultiBackendDbHandler;
|
2024-07-25 23:08:14 +00:00
|
|
|
use deno_node::NodeExtInitServices;
|
2024-06-07 03:37:53 +00:00
|
|
|
use deno_permissions::PermissionsContainer;
|
2024-02-07 16:25:14 +00:00
|
|
|
use deno_terminal::colors;
|
2023-05-01 20:42:05 +00:00
|
|
|
use deno_tls::RootCertStoreProvider;
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 16:54:47 +00:00
|
|
|
use deno_tls::TlsKeys;
|
2021-06-22 14:30:16 +00:00
|
|
|
use deno_web::create_entangled_message_port;
|
2024-03-16 00:59:18 +00:00
|
|
|
use deno_web::serialize_transferables;
|
2021-07-05 13:34:37 +00:00
|
|
|
use deno_web::BlobStore;
|
2024-03-11 22:18:03 +00:00
|
|
|
use deno_web::JsMessageData;
|
2021-06-22 14:30:16 +00:00
|
|
|
use deno_web::MessagePort;
|
2024-03-16 00:59:18 +00:00
|
|
|
use deno_web::Transferable;
|
2021-03-26 16:34:25 +00:00
|
|
|
use log::debug;
|
2021-05-11 19:09:09 +00:00
|
|
|
use std::cell::RefCell;
|
|
|
|
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;
|
2024-03-13 19:52:53 +00:00
|
|
|
use std::sync::atomic::AtomicU32;
|
2020-11-26 14:17:45 +00:00
|
|
|
use std::sync::atomic::Ordering;
|
|
|
|
use std::sync::Arc;
|
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
|
|
|
|
2024-09-30 13:19:24 +00:00
|
|
|
use crate::inspector_server::InspectorServer;
|
|
|
|
use crate::ops;
|
|
|
|
use crate::ops::process::NpmProcessStateProviderRc;
|
|
|
|
use crate::ops::worker_host::WorkersTable;
|
|
|
|
use crate::shared::maybe_transpile_source;
|
|
|
|
use crate::shared::runtime;
|
|
|
|
use crate::tokio_util::create_and_run_current_thread;
|
|
|
|
use crate::worker::create_op_metrics;
|
|
|
|
use crate::worker::import_meta_resolve_callback;
|
|
|
|
use crate::worker::validate_import_attributes_callback;
|
|
|
|
use crate::worker::FormatJsErrorFn;
|
|
|
|
use crate::BootstrapOptions;
|
|
|
|
|
2024-03-16 00:59:18 +00:00
|
|
|
pub struct WorkerMetadata {
|
|
|
|
pub buffer: DetachedBuffer,
|
|
|
|
pub transferables: Vec<Transferable>,
|
|
|
|
}
|
|
|
|
|
2024-03-13 19:52:53 +00:00
|
|
|
static WORKER_ID_COUNTER: AtomicU32 = AtomicU32::new(1);
|
2021-08-16 12:29:54 +00:00
|
|
|
|
2024-03-13 19:52:53 +00:00
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
2021-05-11 19:09:09 +00:00
|
|
|
pub struct WorkerId(u32);
|
2024-03-13 19:52:53 +00:00
|
|
|
impl WorkerId {
|
|
|
|
pub fn new() -> WorkerId {
|
|
|
|
let id = WORKER_ID_COUNTER.fetch_add(1, Ordering::SeqCst);
|
|
|
|
WorkerId(id)
|
|
|
|
}
|
|
|
|
}
|
2021-05-11 19:09:09 +00:00
|
|
|
impl fmt::Display for WorkerId {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
|
|
write!(f, "worker-{}", self.0)
|
|
|
|
}
|
|
|
|
}
|
2024-03-13 19:52:53 +00:00
|
|
|
impl Default for WorkerId {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self::new()
|
2021-05-11 19:09:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-13 19:52:53 +00:00
|
|
|
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
|
|
#[serde(rename_all = "lowercase")]
|
|
|
|
pub enum WebWorkerType {
|
|
|
|
Classic,
|
|
|
|
Module,
|
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
/// Events that are sent to host from child
|
|
|
|
/// worker.
|
2021-06-22 14:30:16 +00:00
|
|
|
pub enum WorkerControlEvent {
|
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-06-22 14:30:16 +00:00
|
|
|
use deno_core::serde::Serializer;
|
|
|
|
|
|
|
|
impl Serialize for WorkerControlEvent {
|
|
|
|
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
|
|
|
where
|
|
|
|
S: Serializer,
|
|
|
|
{
|
|
|
|
let type_id = match &self {
|
|
|
|
WorkerControlEvent::TerminalError(_) => 1_i32,
|
|
|
|
WorkerControlEvent::Error(_) => 2_i32,
|
|
|
|
WorkerControlEvent::Close => 3_i32,
|
|
|
|
};
|
|
|
|
|
|
|
|
match self {
|
|
|
|
WorkerControlEvent::TerminalError(error)
|
|
|
|
| WorkerControlEvent::Error(error) => {
|
|
|
|
let value = match error.downcast_ref::<JsError>() {
|
2022-04-15 14:08:09 +00:00
|
|
|
Some(js_error) => {
|
2022-04-26 23:06:10 +00:00
|
|
|
let frame = js_error.frames.iter().find(|f| match &f.file_name {
|
2023-03-08 11:44:54 +00:00
|
|
|
Some(s) => !s.trim_start_matches('[').starts_with("ext:"),
|
2022-04-26 23:06:10 +00:00
|
|
|
None => false,
|
|
|
|
});
|
2022-04-15 14:08:09 +00:00
|
|
|
json!({
|
|
|
|
"message": js_error.exception_message,
|
|
|
|
"fileName": frame.map(|f| f.file_name.as_ref()),
|
|
|
|
"lineNumber": frame.map(|f| f.line_number.as_ref()),
|
|
|
|
"columnNumber": frame.map(|f| f.column_number.as_ref()),
|
|
|
|
})
|
|
|
|
}
|
2021-06-22 14:30:16 +00:00
|
|
|
None => json!({
|
|
|
|
"message": error.to_string(),
|
|
|
|
}),
|
|
|
|
};
|
|
|
|
|
|
|
|
Serialize::serialize(&(type_id, value), serializer)
|
|
|
|
}
|
|
|
|
_ => Serialize::serialize(&(type_id, ()), serializer),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
// Channels used for communication with worker's parent
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WebWorkerInternalHandle {
|
2021-06-22 14:30:16 +00:00
|
|
|
sender: mpsc::Sender<WorkerControlEvent>,
|
|
|
|
pub port: Rc<MessagePort>,
|
|
|
|
pub cancel: Rc<CancelHandle>,
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal: Arc<AtomicBool>,
|
|
|
|
has_terminated: Arc<AtomicBool>,
|
|
|
|
terminate_waker: Arc<AtomicWaker>,
|
2021-05-11 19:09:09 +00:00
|
|
|
isolate_handle: v8::IsolateHandle,
|
2022-04-13 09:50:57 +00:00
|
|
|
pub name: String,
|
2021-08-16 12:29:54 +00:00
|
|
|
pub worker_type: WebWorkerType,
|
2021-05-11 19:09:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl WebWorkerInternalHandle {
|
|
|
|
/// Post WorkerEvent to parent as a worker
|
2024-10-22 08:41:08 +00:00
|
|
|
pub fn post_event(
|
|
|
|
&self,
|
|
|
|
event: WorkerControlEvent,
|
|
|
|
) -> Result<(), mpsc::TrySendError<WorkerControlEvent>> {
|
2021-05-11 19:09:09 +00:00
|
|
|
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() {
|
2021-11-29 12:37:44 +00:00
|
|
|
self.has_terminated.store(true, Ordering::SeqCst);
|
2021-05-11 19:09:09 +00:00
|
|
|
return Ok(());
|
|
|
|
}
|
2024-10-22 08:41:08 +00:00
|
|
|
sender.try_send(event)
|
2021-05-11 19:09:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if this worker is terminated or being terminated
|
|
|
|
pub fn is_terminated(&self) -> bool {
|
2021-11-29 12:37:44 +00:00
|
|
|
self.has_terminated.load(Ordering::SeqCst)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Check if this worker must terminate (because the termination signal is
|
|
|
|
/// set), and terminates it if so. Returns whether the worker is terminated or
|
|
|
|
/// being terminated, as with [`Self::is_terminated()`].
|
|
|
|
pub fn terminate_if_needed(&mut self) -> bool {
|
|
|
|
let has_terminated = self.is_terminated();
|
|
|
|
|
|
|
|
if !has_terminated && self.termination_signal.load(Ordering::SeqCst) {
|
|
|
|
self.terminate();
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
has_terminated
|
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) {
|
2021-06-22 14:30:16 +00:00
|
|
|
self.cancel.cancel();
|
2023-12-07 00:02:52 +00:00
|
|
|
self.terminate_waker.wake();
|
2021-06-22 14:30:16 +00:00
|
|
|
|
2021-05-11 19:09:09 +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.
|
2021-11-29 12:37:44 +00:00
|
|
|
let already_terminated = self.has_terminated.swap(true, Ordering::SeqCst);
|
2021-05-11 19:09:09 +00:00
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2021-06-22 14:30:16 +00:00
|
|
|
pub struct SendableWebWorkerHandle {
|
|
|
|
port: MessagePort,
|
|
|
|
receiver: mpsc::Receiver<WorkerControlEvent>,
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal: Arc<AtomicBool>,
|
|
|
|
has_terminated: Arc<AtomicBool>,
|
|
|
|
terminate_waker: Arc<AtomicWaker>,
|
2020-11-26 14:17:45 +00:00
|
|
|
isolate_handle: v8::IsolateHandle,
|
|
|
|
}
|
|
|
|
|
2021-06-22 14:30:16 +00:00
|
|
|
impl From<SendableWebWorkerHandle> for WebWorkerHandle {
|
|
|
|
fn from(handle: SendableWebWorkerHandle) -> Self {
|
|
|
|
WebWorkerHandle {
|
|
|
|
receiver: Rc::new(RefCell::new(handle.receiver)),
|
|
|
|
port: Rc::new(handle.port),
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal: handle.termination_signal,
|
|
|
|
has_terminated: handle.has_terminated,
|
|
|
|
terminate_waker: handle.terminate_waker,
|
2021-06-22 14:30:16 +00:00
|
|
|
isolate_handle: handle.isolate_handle,
|
2021-04-19 14:57:02 +00:00
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2021-06-22 14:30:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// This is the handle to the web worker that the parent thread uses to
|
|
|
|
/// communicate with the worker. It is created from a `SendableWebWorkerHandle`
|
|
|
|
/// which is sent to the parent thread from the worker thread where it is
|
2021-08-20 20:14:48 +00:00
|
|
|
/// created. The reason for this separation is that the handle first needs to be
|
2021-06-22 14:30:16 +00:00
|
|
|
/// `Send` when transferring between threads, and then must be `Clone` when it
|
|
|
|
/// has arrived on the parent thread. It can not be both at once without large
|
|
|
|
/// amounts of Arc<Mutex> and other fun stuff.
|
|
|
|
#[derive(Clone)]
|
|
|
|
pub struct WebWorkerHandle {
|
|
|
|
pub port: Rc<MessagePort>,
|
|
|
|
receiver: Rc<RefCell<mpsc::Receiver<WorkerControlEvent>>>,
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal: Arc<AtomicBool>,
|
|
|
|
has_terminated: Arc<AtomicBool>,
|
|
|
|
terminate_waker: Arc<AtomicWaker>,
|
2021-06-22 14:30:16 +00:00
|
|
|
isolate_handle: v8::IsolateHandle,
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2021-06-22 14:30:16 +00:00
|
|
|
impl WebWorkerHandle {
|
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
|
2023-09-11 23:12:33 +00:00
|
|
|
#[allow(clippy::await_holding_refcell_ref)] // TODO(ry) remove!
|
2024-10-22 08:41:08 +00:00
|
|
|
pub async fn get_control_event(&self) -> Option<WorkerControlEvent> {
|
2021-06-22 14:30:16 +00:00
|
|
|
let mut receiver = self.receiver.borrow_mut();
|
2024-10-22 08:41:08 +00:00
|
|
|
receiver.next().await
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2021-05-11 19:09:09 +00:00
|
|
|
/// Terminate the worker
|
2021-11-29 12:37:44 +00:00
|
|
|
/// This function will set the termination signal, close the message channel,
|
|
|
|
/// and schedule to terminate the isolate after two seconds.
|
2021-06-22 14:30:16 +00:00
|
|
|
pub fn terminate(self) {
|
2023-01-15 04:18:58 +00:00
|
|
|
use std::thread::sleep;
|
|
|
|
use std::thread::spawn;
|
2021-11-29 12:37:44 +00:00
|
|
|
use std::time::Duration;
|
2020-11-26 14:17:45 +00:00
|
|
|
|
2021-11-29 12:37:44 +00:00
|
|
|
let schedule_termination =
|
|
|
|
!self.termination_signal.swap(true, Ordering::SeqCst);
|
2021-05-11 19:09:09 +00:00
|
|
|
|
2021-06-22 14:30:16 +00:00
|
|
|
self.port.disentangle();
|
2021-11-29 12:37:44 +00:00
|
|
|
|
|
|
|
if schedule_termination && !self.has_terminated.load(Ordering::SeqCst) {
|
|
|
|
// Wake up the worker's event loop so it can terminate.
|
|
|
|
self.terminate_waker.wake();
|
|
|
|
|
|
|
|
let has_terminated = self.has_terminated.clone();
|
|
|
|
|
|
|
|
// Schedule to terminate the isolate's execution.
|
|
|
|
spawn(move || {
|
|
|
|
sleep(Duration::from_secs(2));
|
|
|
|
|
|
|
|
// A worker's isolate can only be terminated once, so we need a guard
|
|
|
|
// here.
|
|
|
|
let already_terminated = has_terminated.swap(true, Ordering::SeqCst);
|
|
|
|
|
|
|
|
if !already_terminated {
|
|
|
|
// Stop javascript execution
|
|
|
|
self.isolate_handle.terminate_execution();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
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,
|
2022-04-13 09:50:57 +00:00
|
|
|
name: String,
|
2021-08-16 12:29:54 +00:00
|
|
|
worker_type: WebWorkerType,
|
2021-06-22 14:30:16 +00:00
|
|
|
) -> (WebWorkerInternalHandle, SendableWebWorkerHandle) {
|
|
|
|
let (parent_port, worker_port) = create_entangled_message_port();
|
|
|
|
let (ctrl_tx, ctrl_rx) = mpsc::channel::<WorkerControlEvent>(1);
|
2021-11-29 12:37:44 +00:00
|
|
|
let termination_signal = Arc::new(AtomicBool::new(false));
|
|
|
|
let has_terminated = Arc::new(AtomicBool::new(false));
|
|
|
|
let terminate_waker = Arc::new(AtomicWaker::new());
|
2021-05-11 19:09:09 +00:00
|
|
|
let internal_handle = WebWorkerInternalHandle {
|
2022-04-13 09:50:57 +00:00
|
|
|
name,
|
2021-06-22 14:30:16 +00:00
|
|
|
port: Rc::new(parent_port),
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal: termination_signal.clone(),
|
|
|
|
has_terminated: has_terminated.clone(),
|
|
|
|
terminate_waker: terminate_waker.clone(),
|
2021-05-11 19:09:09 +00:00
|
|
|
isolate_handle: isolate_handle.clone(),
|
2021-06-22 14:30:16 +00:00
|
|
|
cancel: CancelHandle::new_rc(),
|
2022-04-13 09:50:57 +00:00
|
|
|
sender: ctrl_tx,
|
2021-08-16 12:29:54 +00:00
|
|
|
worker_type,
|
2020-11-26 14:17:45 +00:00
|
|
|
};
|
2021-06-22 14:30:16 +00:00
|
|
|
let external_handle = SendableWebWorkerHandle {
|
|
|
|
receiver: ctrl_rx,
|
|
|
|
port: worker_port,
|
2021-11-29 12:37:44 +00:00
|
|
|
termination_signal,
|
|
|
|
has_terminated,
|
|
|
|
terminate_waker,
|
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
|
|
|
}
|
|
|
|
|
2024-09-30 00:07:50 +00:00
|
|
|
pub struct WebWorkerServiceOptions {
|
|
|
|
pub blob_store: Arc<BlobStore>,
|
|
|
|
pub broadcast_channel: InMemoryBroadcastChannel,
|
|
|
|
pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
|
|
|
|
pub feature_checker: Arc<FeatureChecker>,
|
|
|
|
pub fs: Arc<dyn FileSystem>,
|
|
|
|
pub maybe_inspector_server: Option<Arc<InspectorServer>>,
|
|
|
|
pub module_loader: Rc<dyn ModuleLoader>,
|
|
|
|
pub node_services: Option<NodeExtInitServices>,
|
|
|
|
pub npm_process_state_provider: Option<NpmProcessStateProviderRc>,
|
|
|
|
pub permissions: PermissionsContainer,
|
|
|
|
pub root_cert_store_provider: Option<Arc<dyn RootCertStoreProvider>>,
|
|
|
|
pub shared_array_buffer_store: Option<SharedArrayBufferStore>,
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct WebWorkerOptions {
|
|
|
|
pub name: String,
|
|
|
|
pub main_module: ModuleSpecifier,
|
|
|
|
pub worker_id: WorkerId,
|
|
|
|
pub bootstrap: BootstrapOptions,
|
|
|
|
pub extensions: Vec<Extension>,
|
|
|
|
pub startup_snapshot: Option<&'static [u8]>,
|
|
|
|
pub unsafely_ignore_certificate_errors: Option<Vec<String>>,
|
2024-11-15 09:33:03 +00:00
|
|
|
/// Optional isolate creation parameters, such as heap limits.
|
|
|
|
pub create_params: Option<v8::CreateParams>,
|
2024-09-30 00:07:50 +00:00
|
|
|
pub seed: Option<u64>,
|
|
|
|
pub create_web_worker_cb: Arc<ops::worker_host::CreateWebWorkerCb>,
|
|
|
|
pub format_js_error_fn: Option<Arc<FormatJsErrorFn>>,
|
|
|
|
pub worker_type: WebWorkerType,
|
|
|
|
pub get_error_class_fn: Option<GetErrorClassFn>,
|
|
|
|
pub cache_storage_dir: Option<std::path::PathBuf>,
|
|
|
|
pub stdio: Stdio,
|
|
|
|
pub strace_ops: Option<Vec<String>>,
|
|
|
|
pub close_on_idle: bool,
|
|
|
|
pub maybe_worker_metadata: Option<WorkerMetadata>,
|
2024-11-20 21:24:04 +00:00
|
|
|
pub enable_stack_trace_arg_in_ops: bool,
|
2024-09-30 00:07:50 +00:00
|
|
|
}
|
|
|
|
|
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,
|
2020-12-13 18:45:53 +00:00
|
|
|
pub js_runtime: JsRuntime,
|
|
|
|
pub name: String,
|
2024-03-13 17:22:25 +00:00
|
|
|
close_on_idle: bool,
|
2024-03-15 20:38:16 +00:00
|
|
|
has_executed_main_module: bool,
|
2021-05-11 19:09:09 +00:00
|
|
|
internal_handle: WebWorkerInternalHandle,
|
2021-08-16 12:29:54 +00:00
|
|
|
pub worker_type: WebWorkerType,
|
2021-01-07 18:06:08 +00:00
|
|
|
pub main_module: ModuleSpecifier,
|
2022-02-11 12:41:56 +00:00
|
|
|
poll_for_messages_fn: Option<v8::Global<v8::Value>>,
|
2024-03-15 20:38:16 +00:00
|
|
|
has_message_event_listener_fn: Option<v8::Global<v8::Value>>,
|
2023-02-22 00:55:31 +00:00
|
|
|
bootstrap_fn_global: Option<v8::Global<v8::Function>>,
|
2024-03-11 22:18:03 +00:00
|
|
|
// Consumed when `bootstrap_fn` is called
|
2024-03-16 00:59:18 +00:00
|
|
|
maybe_worker_metadata: Option<WorkerMetadata>,
|
2020-12-11 17:49:26 +00:00
|
|
|
}
|
|
|
|
|
2024-11-13 15:10:09 +00:00
|
|
|
impl Drop for WebWorker {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
// clean up the package.json thread local cache
|
|
|
|
node_resolver::PackageJsonThreadLocalCache::clear();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
impl WebWorker {
|
2021-10-05 20:41:14 +00:00
|
|
|
pub fn bootstrap_from_options(
|
2024-09-30 00:07:50 +00:00
|
|
|
services: WebWorkerServiceOptions,
|
2021-10-05 20:41:14 +00:00
|
|
|
options: WebWorkerOptions,
|
|
|
|
) -> (Self, SendableWebWorkerHandle) {
|
2024-09-30 00:07:50 +00:00
|
|
|
let (mut worker, handle, bootstrap_options) =
|
|
|
|
Self::from_options(services, options);
|
2021-10-05 20:41:14 +00:00
|
|
|
worker.bootstrap(&bootstrap_options);
|
|
|
|
(worker, handle)
|
|
|
|
}
|
|
|
|
|
2024-09-30 00:07:50 +00:00
|
|
|
fn from_options(
|
|
|
|
services: WebWorkerServiceOptions,
|
2021-10-08 15:03:49 +00:00
|
|
|
mut options: WebWorkerOptions,
|
2024-09-30 00:07:50 +00:00
|
|
|
) -> (Self, SendableWebWorkerHandle, BootstrapOptions) {
|
2023-03-17 18:22:15 +00:00
|
|
|
deno_core::extension!(deno_permissions_web_worker,
|
2023-03-17 22:15:27 +00:00
|
|
|
options = {
|
2023-03-17 18:22:15 +00:00
|
|
|
permissions: PermissionsContainer,
|
|
|
|
enable_testing_features: bool,
|
|
|
|
},
|
2023-03-17 22:15:27 +00:00
|
|
|
state = |state, options| {
|
|
|
|
state.put::<PermissionsContainer>(options.permissions);
|
|
|
|
state.put(ops::TestingFeaturesEnabled(options.enable_testing_features));
|
2023-03-17 18:22:15 +00:00
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2021-05-02 23:22:57 +00:00
|
|
|
// Permissions: many ops depend on this
|
2021-10-05 20:41:14 +00:00
|
|
|
let enable_testing_features = options.bootstrap.enable_testing_features;
|
2023-03-09 20:09:45 +00:00
|
|
|
let create_cache = options.cache_storage_dir.map(|storage_dir| {
|
|
|
|
let create_cache_fn = move || SqliteBackedCache::new(storage_dir.clone());
|
|
|
|
CreateCache(Arc::new(create_cache_fn))
|
|
|
|
});
|
|
|
|
|
2023-03-16 17:36:53 +00:00
|
|
|
// NOTE(bartlomieju): ordering is important here, keep it in sync with
|
2024-01-10 15:30:50 +00:00
|
|
|
// `runtime/worker.rs` and `runtime/snapshot.rs`!
|
2023-08-05 23:47:15 +00:00
|
|
|
|
|
|
|
let mut extensions = vec![
|
2023-03-09 20:09:45 +00:00
|
|
|
// Web APIs
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_webidl::deno_webidl::init_ops_and_esm(),
|
|
|
|
deno_console::deno_console::init_ops_and_esm(),
|
|
|
|
deno_url::deno_url::init_ops_and_esm(),
|
|
|
|
deno_web::deno_web::init_ops_and_esm::<PermissionsContainer>(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.blob_store,
|
|
|
|
Some(options.main_module.clone()),
|
2023-03-09 20:09:45 +00:00
|
|
|
),
|
2023-12-09 00:19:16 +00:00
|
|
|
deno_webgpu::deno_webgpu::init_ops_and_esm(),
|
2024-01-22 11:08:01 +00:00
|
|
|
deno_canvas::deno_canvas::init_ops_and_esm(),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_fetch::deno_fetch::init_ops_and_esm::<PermissionsContainer>(
|
2023-03-17 18:22:15 +00:00
|
|
|
deno_fetch::Options {
|
|
|
|
user_agent: options.bootstrap.user_agent.clone(),
|
2024-09-30 00:07:50 +00:00
|
|
|
root_cert_store_provider: services.root_cert_store_provider.clone(),
|
2023-03-17 18:22:15 +00:00
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
.clone(),
|
|
|
|
file_fetch_handler: Rc::new(deno_fetch::FsFetchHandler),
|
|
|
|
..Default::default()
|
|
|
|
},
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_cache::deno_cache::init_ops_and_esm::<SqliteBackedCache>(
|
|
|
|
create_cache,
|
|
|
|
),
|
|
|
|
deno_websocket::deno_websocket::init_ops_and_esm::<PermissionsContainer>(
|
2023-03-09 20:09:45 +00:00
|
|
|
options.bootstrap.user_agent.clone(),
|
2024-09-30 00:07:50 +00:00
|
|
|
services.root_cert_store_provider.clone(),
|
2023-03-09 20:09:45 +00:00
|
|
|
options.unsafely_ignore_certificate_errors.clone(),
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_webstorage::deno_webstorage::init_ops_and_esm(None).disable(),
|
|
|
|
deno_crypto::deno_crypto::init_ops_and_esm(options.seed),
|
|
|
|
deno_broadcast_channel::deno_broadcast_channel::init_ops_and_esm(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.broadcast_channel,
|
2023-03-09 20:09:45 +00:00
|
|
|
),
|
2023-10-04 19:42:17 +00:00
|
|
|
deno_ffi::deno_ffi::init_ops_and_esm::<PermissionsContainer>(),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_net::deno_net::init_ops_and_esm::<PermissionsContainer>(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.root_cert_store_provider.clone(),
|
2023-03-16 17:36:53 +00:00
|
|
|
options.unsafely_ignore_certificate_errors.clone(),
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_tls::deno_tls::init_ops_and_esm(),
|
|
|
|
deno_kv::deno_kv::init_ops_and_esm(
|
2023-10-31 11:13:57 +00:00
|
|
|
MultiBackendDbHandler::remote_or_sqlite::<PermissionsContainer>(
|
|
|
|
None,
|
|
|
|
options.seed,
|
|
|
|
deno_kv::remote::HttpOptions {
|
|
|
|
user_agent: options.bootstrap.user_agent.clone(),
|
2024-09-30 00:07:50 +00:00
|
|
|
root_cert_store_provider: services.root_cert_store_provider,
|
2023-10-31 11:13:57 +00:00
|
|
|
unsafely_ignore_certificate_errors: options
|
|
|
|
.unsafely_ignore_certificate_errors
|
|
|
|
.clone(),
|
refactor(ext/tls): Implement required functionality for later SNI support (#23686)
Precursor to #23236
This implements the SNI features, but uses private symbols to avoid
exposing the functionality at this time. Note that to properly test this
feature, we need to add a way for `connectTls` to specify a hostname.
This is something that should be pushed into that API at a later time as
well.
```ts
Deno.test(
{ permissions: { net: true, read: true } },
async function listenResolver() {
let sniRequests = [];
const listener = Deno.listenTls({
hostname: "localhost",
port: 0,
[resolverSymbol]: (sni: string) => {
sniRequests.push(sni);
return {
cert,
key,
};
},
});
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-1",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
{
const conn = await Deno.connectTls({
hostname: "localhost",
[serverNameSymbol]: "server-2",
port: listener.addr.port,
});
const [_handshake, serverConn] = await Promise.all([
conn.handshake(),
listener.accept(),
]);
conn.close();
serverConn.close();
}
assertEquals(sniRequests, ["server-1", "server-2"]);
listener.close();
},
);
```
---------
Signed-off-by: Matt Mastracci <matthew@mastracci.com>
2024-05-09 16:54:47 +00:00
|
|
|
client_cert_chain_and_key: TlsKeys::Null,
|
2023-10-31 11:13:57 +00:00
|
|
|
proxy: None,
|
|
|
|
},
|
|
|
|
),
|
2024-08-27 07:30:19 +00:00
|
|
|
deno_kv::KvConfig::builder().build(),
|
2023-03-22 04:13:24 +00:00
|
|
|
),
|
2023-11-01 18:57:55 +00:00
|
|
|
deno_cron::deno_cron::init_ops_and_esm(LocalCronHandler::new()),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_napi::deno_napi::init_ops_and_esm::<PermissionsContainer>(),
|
2024-11-19 01:46:24 +00:00
|
|
|
deno_http::deno_http::init_ops_and_esm::<DefaultHttpPropertyExtractor>(
|
|
|
|
deno_http::Options::default(),
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_io::deno_io::init_ops_and_esm(Some(options.stdio)),
|
|
|
|
deno_fs::deno_fs::init_ops_and_esm::<PermissionsContainer>(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.fs.clone(),
|
2023-05-05 16:44:24 +00:00
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_node::deno_node::init_ops_and_esm::<PermissionsContainer>(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.node_services,
|
|
|
|
services.fs,
|
2023-03-17 18:22:15 +00:00
|
|
|
),
|
2023-03-09 20:09:45 +00:00
|
|
|
// Runtime ops that are always initialized for WebWorkers
|
2024-09-30 00:07:50 +00:00
|
|
|
ops::runtime::deno_runtime::init_ops_and_esm(options.main_module.clone()),
|
2023-08-05 23:47:15 +00:00
|
|
|
ops::worker_host::deno_worker_host::init_ops_and_esm(
|
2024-09-30 00:07:50 +00:00
|
|
|
options.create_web_worker_cb,
|
|
|
|
options.format_js_error_fn,
|
2023-03-09 20:09:45 +00:00
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
ops::fs_events::deno_fs_events::init_ops_and_esm(),
|
|
|
|
ops::os::deno_os_worker::init_ops_and_esm(),
|
2024-11-14 12:16:28 +00:00
|
|
|
ops::otel::deno_otel::init_ops_and_esm(),
|
2024-09-30 13:19:24 +00:00
|
|
|
ops::permissions::deno_permissions::init_ops_and_esm(),
|
2024-09-27 19:35:37 +00:00
|
|
|
ops::process::deno_process::init_ops_and_esm(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.npm_process_state_provider,
|
2024-09-27 19:35:37 +00:00
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
ops::signal::deno_signal::init_ops_and_esm(),
|
|
|
|
ops::tty::deno_tty::init_ops_and_esm(),
|
|
|
|
ops::http::deno_http_runtime::init_ops_and_esm(),
|
2024-08-29 02:18:41 +00:00
|
|
|
ops::bootstrap::deno_bootstrap::init_ops_and_esm(
|
|
|
|
if options.startup_snapshot.is_some() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(Default::default())
|
|
|
|
},
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
deno_permissions_web_worker::init_ops_and_esm(
|
2024-09-30 00:07:50 +00:00
|
|
|
services.permissions,
|
2023-03-17 18:22:15 +00:00
|
|
|
enable_testing_features,
|
|
|
|
),
|
2023-08-05 23:47:15 +00:00
|
|
|
runtime::init_ops_and_esm(),
|
2023-11-11 17:01:48 +00:00
|
|
|
ops::web_worker::deno_web_worker::init_ops_and_esm(),
|
2023-03-09 20:09:45 +00:00
|
|
|
];
|
2021-04-28 16:41:50 +00:00
|
|
|
|
2024-07-29 16:58:04 +00:00
|
|
|
#[cfg(feature = "hmr")]
|
2024-07-05 12:17:53 +00:00
|
|
|
assert!(
|
|
|
|
cfg!(not(feature = "only_snapshotted_js_sources")),
|
|
|
|
"'hmr' is incompatible with 'only_snapshotted_js_sources'."
|
|
|
|
);
|
2024-01-22 12:37:25 +00:00
|
|
|
|
2023-08-05 23:47:15 +00:00
|
|
|
for extension in &mut extensions {
|
2024-01-22 12:37:25 +00:00
|
|
|
if options.startup_snapshot.is_some() {
|
2023-08-05 23:47:15 +00:00
|
|
|
extension.js_files = std::borrow::Cow::Borrowed(&[]);
|
|
|
|
extension.esm_files = std::borrow::Cow::Borrowed(&[]);
|
|
|
|
extension.esm_entry_point = None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-10-08 15:03:49 +00:00
|
|
|
extensions.extend(std::mem::take(&mut options.extensions));
|
2021-05-02 23:22:57 +00:00
|
|
|
|
2024-01-22 12:37:25 +00:00
|
|
|
#[cfg(feature = "only_snapshotted_js_sources")]
|
|
|
|
options.startup_snapshot.as_ref().expect("A user snapshot was not provided, even though 'only_snapshotted_js_sources' is used.");
|
2023-02-20 20:45:34 +00:00
|
|
|
|
2024-03-13 17:22:25 +00:00
|
|
|
// Get our op metrics
|
|
|
|
let (op_summary_metrics, op_metrics_factory_fn) = create_op_metrics(
|
|
|
|
options.bootstrap.enable_op_summary_metrics,
|
|
|
|
options.strace_ops,
|
|
|
|
);
|
2023-11-05 21:27:36 +00:00
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
let mut js_runtime = JsRuntime::new(RuntimeOptions {
|
2024-09-30 00:07:50 +00:00
|
|
|
module_loader: Some(services.module_loader),
|
2024-01-10 15:30:50 +00:00
|
|
|
startup_snapshot: options.startup_snapshot,
|
2024-11-15 09:33:03 +00:00
|
|
|
create_params: options.create_params,
|
2020-12-13 18:45:53 +00:00
|
|
|
get_error_class_fn: options.get_error_class_fn,
|
2024-09-30 00:07:50 +00:00
|
|
|
shared_array_buffer_store: services.shared_array_buffer_store,
|
|
|
|
compiled_wasm_module_store: services.compiled_wasm_module_store,
|
2021-04-28 16:41:50 +00:00
|
|
|
extensions,
|
2024-03-05 01:17:39 +00:00
|
|
|
extension_transpiler: Some(Rc::new(|specifier, source| {
|
|
|
|
maybe_transpile_source(specifier, source)
|
|
|
|
})),
|
2024-11-06 14:08:26 +00:00
|
|
|
inspector: true,
|
2024-09-30 00:07:50 +00:00
|
|
|
feature_checker: Some(services.feature_checker),
|
2023-11-05 21:27:36 +00:00
|
|
|
op_metrics_factory_fn,
|
2023-12-28 19:37:10 +00:00
|
|
|
import_meta_resolve_callback: Some(Box::new(
|
|
|
|
import_meta_resolve_callback,
|
|
|
|
)),
|
2024-01-15 01:28:46 +00:00
|
|
|
validate_import_attributes_cb: Some(Box::new(
|
|
|
|
validate_import_attributes_callback,
|
|
|
|
)),
|
2024-09-04 10:49:31 +00:00
|
|
|
import_assertions_support: deno_core::ImportAssertionsSupport::Error,
|
2024-11-20 21:24:04 +00:00
|
|
|
maybe_op_stack_trace_callback: if options.enable_stack_trace_arg_in_ops {
|
|
|
|
Some(Box::new(|stack| {
|
|
|
|
deno_permissions::prompter::set_current_stacktrace(stack)
|
|
|
|
}))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
},
|
2020-11-26 14:17:45 +00:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
2023-11-05 21:27:36 +00:00
|
|
|
if let Some(op_summary_metrics) = op_summary_metrics {
|
|
|
|
js_runtime.op_state().borrow_mut().put(op_summary_metrics);
|
|
|
|
}
|
|
|
|
|
2024-11-06 14:08:26 +00:00
|
|
|
// Put inspector handle into the op state so we can put a breakpoint when
|
|
|
|
// executing a CJS entrypoint.
|
|
|
|
let op_state = js_runtime.op_state();
|
|
|
|
let inspector = js_runtime.inspector();
|
|
|
|
op_state.borrow_mut().put(inspector);
|
|
|
|
|
2024-09-30 00:07:50 +00:00
|
|
|
if let Some(server) = services.maybe_inspector_server {
|
2021-12-17 17:43:25 +00:00
|
|
|
server.register_inspector(
|
2024-09-30 00:07:50 +00:00
|
|
|
options.main_module.to_string(),
|
2021-12-17 17:43:25 +00:00
|
|
|
&mut js_runtime,
|
|
|
|
false,
|
|
|
|
);
|
2021-05-26 19:07:12 +00:00
|
|
|
}
|
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();
|
2021-08-16 12:29:54 +00:00
|
|
|
let (internal_handle, external_handle) =
|
2024-09-30 00:07:50 +00:00
|
|
|
create_handles(handle, options.name.clone(), options.worker_type);
|
2021-05-11 19:09:09 +00:00
|
|
|
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
|
|
|
|
2023-02-22 00:55:31 +00:00
|
|
|
let bootstrap_fn_global = {
|
2023-07-23 13:42:41 +00:00
|
|
|
let context = js_runtime.main_context();
|
2023-02-22 00:55:31 +00:00
|
|
|
let scope = &mut js_runtime.handle_scope();
|
|
|
|
let context_local = v8::Local::new(scope, context);
|
|
|
|
let global_obj = context_local.global(scope);
|
2023-03-06 16:37:46 +00:00
|
|
|
let bootstrap_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"bootstrap").unwrap();
|
2023-02-22 00:55:31 +00:00
|
|
|
let bootstrap_ns: v8::Local<v8::Object> = global_obj
|
|
|
|
.get(scope, bootstrap_str.into())
|
|
|
|
.unwrap()
|
|
|
|
.try_into()
|
|
|
|
.unwrap();
|
2023-03-06 16:37:46 +00:00
|
|
|
let main_runtime_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"workerRuntime")
|
|
|
|
.unwrap();
|
2023-02-22 00:55:31 +00:00
|
|
|
let bootstrap_fn =
|
|
|
|
bootstrap_ns.get(scope, main_runtime_str.into()).unwrap();
|
|
|
|
let bootstrap_fn =
|
|
|
|
v8::Local::<v8::Function>::try_from(bootstrap_fn).unwrap();
|
|
|
|
v8::Global::new(scope, bootstrap_fn)
|
|
|
|
};
|
|
|
|
|
2021-06-22 14:30:16 +00:00
|
|
|
(
|
|
|
|
Self {
|
2024-09-30 00:07:50 +00:00
|
|
|
id: options.worker_id,
|
2021-06-22 14:30:16 +00:00
|
|
|
js_runtime,
|
2024-09-30 00:07:50 +00:00
|
|
|
name: options.name,
|
2021-06-22 14:30:16 +00:00
|
|
|
internal_handle,
|
2021-08-16 12:29:54 +00:00
|
|
|
worker_type: options.worker_type,
|
2024-09-30 00:07:50 +00:00
|
|
|
main_module: options.main_module,
|
2022-02-11 12:41:56 +00:00
|
|
|
poll_for_messages_fn: None,
|
2024-03-15 20:38:16 +00:00
|
|
|
has_message_event_listener_fn: None,
|
2023-02-22 00:55:31 +00:00
|
|
|
bootstrap_fn_global: Some(bootstrap_fn_global),
|
2024-03-13 17:22:25 +00:00
|
|
|
close_on_idle: options.close_on_idle,
|
2024-03-15 20:38:16 +00:00
|
|
|
has_executed_main_module: false,
|
2024-03-11 22:18:03 +00:00
|
|
|
maybe_worker_metadata: options.maybe_worker_metadata,
|
2021-06-22 14:30:16 +00:00
|
|
|
},
|
2021-05-11 19:09:09 +00:00
|
|
|
external_handle,
|
2024-09-30 00:07:50 +00:00
|
|
|
options.bootstrap,
|
2021-06-22 14:30:16 +00:00
|
|
|
)
|
2020-12-11 17:49:26 +00:00
|
|
|
}
|
|
|
|
|
2021-10-05 20:41:14 +00:00
|
|
|
pub fn bootstrap(&mut self, options: &BootstrapOptions) {
|
2024-03-16 00:59:18 +00:00
|
|
|
let op_state = self.js_runtime.op_state();
|
|
|
|
op_state.borrow_mut().put(options.clone());
|
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.
|
2023-02-22 00:55:31 +00:00
|
|
|
{
|
|
|
|
let scope = &mut self.js_runtime.handle_scope();
|
2023-03-28 08:27:17 +00:00
|
|
|
let args = options.as_v8(scope);
|
2023-02-22 00:55:31 +00:00
|
|
|
let bootstrap_fn = self.bootstrap_fn_global.take().unwrap();
|
|
|
|
let bootstrap_fn = v8::Local::new(scope, bootstrap_fn);
|
|
|
|
let undefined = v8::undefined(scope);
|
2024-03-11 22:18:03 +00:00
|
|
|
let mut worker_data: v8::Local<v8::Value> = v8::undefined(scope).into();
|
|
|
|
if let Some(data) = self.maybe_worker_metadata.take() {
|
2024-03-16 00:59:18 +00:00
|
|
|
let js_transferables = serialize_transferables(
|
|
|
|
&mut op_state.borrow_mut(),
|
|
|
|
data.transferables,
|
|
|
|
);
|
|
|
|
let js_message_data = JsMessageData {
|
|
|
|
data: data.buffer,
|
|
|
|
transferables: js_transferables,
|
|
|
|
};
|
|
|
|
worker_data =
|
|
|
|
deno_core::serde_v8::to_v8(scope, js_message_data).unwrap();
|
2024-03-11 22:18:03 +00:00
|
|
|
}
|
2023-02-22 00:55:31 +00:00
|
|
|
let name_str: v8::Local<v8::Value> =
|
|
|
|
v8::String::new(scope, &self.name).unwrap().into();
|
|
|
|
let id_str: v8::Local<v8::Value> =
|
|
|
|
v8::String::new(scope, &format!("{}", self.id))
|
|
|
|
.unwrap()
|
|
|
|
.into();
|
2024-03-13 19:52:53 +00:00
|
|
|
let id: v8::Local<v8::Value> =
|
|
|
|
v8::Integer::new(scope, self.id.0 as i32).into();
|
2023-02-22 00:55:31 +00:00
|
|
|
bootstrap_fn
|
2024-03-11 22:18:03 +00:00
|
|
|
.call(
|
|
|
|
scope,
|
|
|
|
undefined.into(),
|
2024-03-13 19:52:53 +00:00
|
|
|
&[args, name_str, id_str, id, worker_data],
|
2024-03-11 22:18:03 +00:00
|
|
|
)
|
2023-02-22 00:55:31 +00:00
|
|
|
.unwrap();
|
2024-03-15 20:38:16 +00:00
|
|
|
|
|
|
|
let context = scope.get_current_context();
|
|
|
|
let global = context.global(scope);
|
|
|
|
let poll_for_messages_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"pollForMessages")
|
|
|
|
.unwrap();
|
|
|
|
let poll_for_messages_fn = global
|
|
|
|
.get(scope, poll_for_messages_str.into())
|
|
|
|
.expect("get globalThis.pollForMessages");
|
|
|
|
global.delete(scope, poll_for_messages_str.into());
|
|
|
|
self.poll_for_messages_fn =
|
|
|
|
Some(v8::Global::new(scope, poll_for_messages_fn));
|
|
|
|
|
|
|
|
let has_message_event_listener_str =
|
|
|
|
v8::String::new_external_onebyte_static(
|
|
|
|
scope,
|
|
|
|
b"hasMessageEventListener",
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let has_message_event_listener_fn = global
|
|
|
|
.get(scope, has_message_event_listener_str.into())
|
|
|
|
.expect("get globalThis.hasMessageEventListener");
|
|
|
|
global.delete(scope, has_message_event_listener_str.into());
|
|
|
|
self.has_message_event_listener_fn =
|
|
|
|
Some(v8::Global::new(scope, has_message_event_listener_fn));
|
2023-02-22 00:55:31 +00:00
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2021-06-21 23:45:41 +00:00
|
|
|
/// See [JsRuntime::execute_script](deno_core::JsRuntime::execute_script)
|
2023-04-04 12:46:31 +00:00
|
|
|
pub fn execute_script(
|
2021-06-21 23:45:41 +00:00
|
|
|
&mut self,
|
2023-03-21 22:33:12 +00:00
|
|
|
name: &'static str,
|
2024-01-10 04:18:40 +00:00
|
|
|
source_code: ModuleCodeString,
|
2021-06-21 23:45:41 +00:00
|
|
|
) -> Result<(), AnyError> {
|
2021-07-08 16:56:53 +00:00
|
|
|
self.js_runtime.execute_script(name, source_code)?;
|
|
|
|
Ok(())
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2022-08-10 22:10:51 +00:00
|
|
|
/// Loads and instantiates specified JavaScript module as "main" module.
|
|
|
|
pub async fn preload_main_module(
|
2021-05-11 19:09:09 +00:00
|
|
|
&mut self,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<ModuleId, AnyError> {
|
2024-03-05 01:17:39 +00:00
|
|
|
self.js_runtime.load_main_es_module(module_specifier).await
|
2022-08-10 22:10:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Loads and instantiates specified JavaScript module as "side" module.
|
|
|
|
pub async fn preload_side_module(
|
|
|
|
&mut self,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<ModuleId, AnyError> {
|
2024-03-05 01:17:39 +00:00
|
|
|
self.js_runtime.load_side_es_module(module_specifier).await
|
2021-05-11 19:09:09 +00:00
|
|
|
}
|
|
|
|
|
2020-11-26 14:17:45 +00:00
|
|
|
/// Loads, instantiates and executes specified JavaScript module.
|
2022-02-11 12:41:56 +00:00
|
|
|
///
|
|
|
|
/// This method assumes that worker can't be terminated when executing
|
|
|
|
/// side module code.
|
|
|
|
pub async fn execute_side_module(
|
2020-11-26 14:17:45 +00:00
|
|
|
&mut self,
|
|
|
|
module_specifier: &ModuleSpecifier,
|
|
|
|
) -> Result<(), AnyError> {
|
2022-08-10 22:10:51 +00:00
|
|
|
let id = self.preload_side_module(module_specifier).await?;
|
2022-02-11 12:41:56 +00:00
|
|
|
let mut receiver = self.js_runtime.mod_evaluate(id);
|
|
|
|
tokio::select! {
|
2022-05-10 09:26:57 +00:00
|
|
|
biased;
|
|
|
|
|
2022-02-11 12:41:56 +00:00
|
|
|
maybe_result = &mut receiver => {
|
|
|
|
debug!("received module evaluate {:#?}", maybe_result);
|
2023-11-27 23:01:27 +00:00
|
|
|
maybe_result
|
2022-02-11 12:41:56 +00:00
|
|
|
}
|
|
|
|
|
2023-12-13 15:07:26 +00:00
|
|
|
event_loop_result = self.js_runtime.run_event_loop(PollEventLoopOptions::default()) => {
|
2022-02-11 12:41:56 +00:00
|
|
|
event_loop_result?;
|
2023-11-27 23:01:27 +00:00
|
|
|
receiver.await
|
2022-02-11 12:41:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Loads, instantiates and executes specified JavaScript module.
|
|
|
|
///
|
|
|
|
/// This module will have "import.meta.main" equal to true.
|
|
|
|
pub async fn execute_main_module(
|
|
|
|
&mut self,
|
|
|
|
id: ModuleId,
|
|
|
|
) -> Result<(), AnyError> {
|
2021-03-04 12:19:47 +00:00
|
|
|
let mut receiver = self.js_runtime.mod_evaluate(id);
|
2023-12-13 15:07:26 +00:00
|
|
|
let poll_options = PollEventLoopOptions::default();
|
2023-11-26 23:09:04 +00:00
|
|
|
|
2021-03-04 12:19:47 +00:00
|
|
|
tokio::select! {
|
2022-05-10 09:26:57 +00:00
|
|
|
biased;
|
|
|
|
|
2021-07-30 11:36:43 +00:00
|
|
|
maybe_result = &mut receiver => {
|
2021-03-04 12:19:47 +00:00
|
|
|
debug!("received worker module evaluate {:#?}", maybe_result);
|
2024-03-15 20:38:16 +00:00
|
|
|
self.has_executed_main_module = true;
|
2023-11-27 23:01:27 +00:00
|
|
|
maybe_result
|
2021-03-04 12:19:47 +00:00
|
|
|
}
|
|
|
|
|
2023-11-26 23:09:04 +00:00
|
|
|
event_loop_result = self.run_event_loop(poll_options) => {
|
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?;
|
2023-11-27 23:01:27 +00:00
|
|
|
receiver.await
|
2021-03-04 12:19:47 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2021-09-24 22:35:35 +00:00
|
|
|
fn poll_event_loop(
|
2020-11-26 14:17:45 +00:00
|
|
|
&mut self,
|
|
|
|
cx: &mut Context,
|
2023-11-26 23:09:04 +00:00
|
|
|
poll_options: PollEventLoopOptions,
|
2020-11-26 14:17:45 +00:00
|
|
|
) -> Poll<Result<(), AnyError>> {
|
2021-05-11 19:09:09 +00:00
|
|
|
// If awakened because we are terminating, just return Ok
|
2021-11-29 12:37:44 +00:00
|
|
|
if self.internal_handle.terminate_if_needed() {
|
2020-11-26 14:17:45 +00:00
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2021-11-29 12:37:44 +00:00
|
|
|
self.internal_handle.terminate_waker.register(cx.waker());
|
|
|
|
|
2023-12-13 15:07:26 +00:00
|
|
|
match self.js_runtime.poll_event_loop(cx, poll_options) {
|
2021-05-11 19:09:09 +00:00
|
|
|
Poll::Ready(r) => {
|
|
|
|
// If js ended because we are terminating, just return Ok
|
2021-11-29 12:37:44 +00:00
|
|
|
if self.internal_handle.terminate_if_needed() {
|
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
|
|
|
|
|
|
|
if let Err(e) = r {
|
2021-10-01 09:30:55 +00:00
|
|
|
return Poll::Ready(Err(e));
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2024-03-13 17:22:25 +00:00
|
|
|
if self.close_on_idle {
|
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2023-11-22 17:02:13 +00:00
|
|
|
// TODO(mmastrac): we don't want to test this w/classic workers because
|
|
|
|
// WPT triggers a failure here. This is only exposed via --enable-testing-features-do-not-use.
|
|
|
|
if self.worker_type == WebWorkerType::Module {
|
|
|
|
panic!(
|
|
|
|
"coding error: either js is polling or the worker is terminated"
|
|
|
|
);
|
|
|
|
} else {
|
2024-11-14 12:16:28 +00:00
|
|
|
log::error!("classic worker terminated unexpectedly");
|
2023-11-22 17:02:13 +00:00
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2024-03-15 20:38:16 +00:00
|
|
|
Poll::Pending => {
|
|
|
|
// This is special code path for workers created from `node:worker_threads`
|
|
|
|
// module that have different semantics than Web workers.
|
|
|
|
// We want the worker thread to terminate automatically if we've done executing
|
|
|
|
// Top-Level await, there are no child workers spawned by that workers
|
|
|
|
// and there's no "message" event listener.
|
|
|
|
if self.close_on_idle
|
|
|
|
&& self.has_executed_main_module
|
|
|
|
&& !self.has_child_workers()
|
|
|
|
&& !self.has_message_event_listener()
|
|
|
|
{
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
} else {
|
|
|
|
Poll::Pending
|
|
|
|
}
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-26 19:07:12 +00:00
|
|
|
pub async fn run_event_loop(
|
|
|
|
&mut self,
|
2023-11-26 23:09:04 +00:00
|
|
|
poll_options: PollEventLoopOptions,
|
2021-05-26 19:07:12 +00:00
|
|
|
) -> Result<(), AnyError> {
|
2023-11-26 23:09:04 +00:00
|
|
|
poll_fn(|cx| self.poll_event_loop(cx, poll_options)).await
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
2022-02-11 12:41:56 +00:00
|
|
|
|
|
|
|
// Starts polling for messages from worker host from JavaScript.
|
|
|
|
fn start_polling_for_messages(&mut self) {
|
|
|
|
let poll_for_messages_fn = self.poll_for_messages_fn.take().unwrap();
|
|
|
|
let scope = &mut self.js_runtime.handle_scope();
|
|
|
|
let poll_for_messages =
|
|
|
|
v8::Local::<v8::Value>::new(scope, poll_for_messages_fn);
|
|
|
|
let fn_ = v8::Local::<v8::Function>::try_from(poll_for_messages).unwrap();
|
|
|
|
let undefined = v8::undefined(scope);
|
2022-04-19 08:59:51 +00:00
|
|
|
// This call may return `None` if worker is terminated.
|
|
|
|
fn_.call(scope, undefined.into(), &[]);
|
2022-02-11 12:41:56 +00:00
|
|
|
}
|
2024-03-15 20:38:16 +00:00
|
|
|
|
|
|
|
fn has_message_event_listener(&mut self) -> bool {
|
|
|
|
let has_message_event_listener_fn =
|
|
|
|
self.has_message_event_listener_fn.as_ref().unwrap();
|
|
|
|
let scope = &mut self.js_runtime.handle_scope();
|
|
|
|
let has_message_event_listener =
|
|
|
|
v8::Local::<v8::Value>::new(scope, has_message_event_listener_fn);
|
|
|
|
let fn_ =
|
|
|
|
v8::Local::<v8::Function>::try_from(has_message_event_listener).unwrap();
|
|
|
|
let undefined = v8::undefined(scope);
|
|
|
|
// This call may return `None` if worker is terminated.
|
|
|
|
match fn_.call(scope, undefined.into(), &[]) {
|
|
|
|
Some(result) => result.is_true(),
|
|
|
|
None => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn has_child_workers(&mut self) -> bool {
|
|
|
|
!self
|
|
|
|
.js_runtime
|
|
|
|
.op_state()
|
|
|
|
.borrow()
|
|
|
|
.borrow::<WorkersTable>()
|
|
|
|
.is_empty()
|
|
|
|
}
|
2020-11-26 14:17:45 +00:00
|
|
|
}
|
|
|
|
|
2022-04-26 23:06:10 +00:00
|
|
|
fn print_worker_error(
|
|
|
|
error: &AnyError,
|
|
|
|
name: &str,
|
|
|
|
format_js_error_fn: Option<&FormatJsErrorFn>,
|
|
|
|
) {
|
|
|
|
let error_str = match format_js_error_fn {
|
|
|
|
Some(format_js_error_fn) => match error.downcast_ref::<JsError>() {
|
|
|
|
Some(js_error) => format_js_error_fn(js_error),
|
|
|
|
None => error.to_string(),
|
|
|
|
},
|
|
|
|
None => error.to_string(),
|
|
|
|
};
|
2024-11-14 12:16:28 +00:00
|
|
|
log::error!(
|
2020-12-07 03:30:40 +00:00
|
|
|
"{}: 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(
|
2023-08-15 19:36:36 +00:00
|
|
|
mut worker: WebWorker,
|
2020-12-07 03:30:40 +00:00
|
|
|
specifier: ModuleSpecifier,
|
2023-03-21 22:33:12 +00:00
|
|
|
mut maybe_source_code: Option<String>,
|
2022-04-26 23:06:10 +00:00
|
|
|
format_js_error_fn: Option<Arc<FormatJsErrorFn>>,
|
2020-12-07 03:30:40 +00:00
|
|
|
) -> Result<(), AnyError> {
|
|
|
|
let name = worker.name.to_string();
|
|
|
|
|
|
|
|
// TODO(bartlomieju): run following block using "select!"
|
|
|
|
// with terminate
|
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
let fut = async move {
|
2022-02-11 12:41:56 +00:00
|
|
|
let internal_handle = worker.internal_handle.clone();
|
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
// Execute provided source code immediately
|
2023-03-21 22:33:12 +00:00
|
|
|
let result = if let Some(source_code) = maybe_source_code.take() {
|
2023-04-04 12:46:31 +00:00
|
|
|
let r = worker.execute_script(located_script_name!(), source_code.into());
|
2022-02-11 12:41:56 +00:00
|
|
|
worker.start_polling_for_messages();
|
|
|
|
r
|
2021-08-18 13:19:22 +00:00
|
|
|
} else {
|
|
|
|
// TODO(bartlomieju): add "type": "classic", ie. ability to load
|
|
|
|
// script instead of module
|
2022-08-10 22:10:51 +00:00
|
|
|
match worker.preload_main_module(&specifier).await {
|
2022-02-11 12:41:56 +00:00
|
|
|
Ok(id) => {
|
|
|
|
worker.start_polling_for_messages();
|
|
|
|
worker.execute_main_module(id).await
|
|
|
|
}
|
|
|
|
Err(e) => Err(e),
|
|
|
|
}
|
2021-08-18 13:19:22 +00:00
|
|
|
};
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
// If sender is closed it means that worker has already been closed from
|
|
|
|
// within using "globalThis.close()"
|
|
|
|
if internal_handle.is_terminated() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-10-01 09:30:55 +00:00
|
|
|
let result = if result.is_ok() {
|
2023-11-26 23:09:04 +00:00
|
|
|
worker
|
|
|
|
.run_event_loop(PollEventLoopOptions {
|
|
|
|
wait_for_inspector: true,
|
|
|
|
..Default::default()
|
|
|
|
})
|
|
|
|
.await
|
2021-10-01 09:30:55 +00:00
|
|
|
} else {
|
|
|
|
result
|
|
|
|
};
|
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
if let Err(e) = result {
|
2022-04-26 23:06:10 +00:00
|
|
|
print_worker_error(&e, &name, format_js_error_fn.as_deref());
|
2021-08-18 13:19:22 +00:00
|
|
|
internal_handle
|
|
|
|
.post_event(WorkerControlEvent::TerminalError(e))
|
|
|
|
.expect("Failed to post message to host");
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
// Failure to execute script is a terminal error, bye, bye.
|
|
|
|
return Ok(());
|
|
|
|
}
|
2020-12-07 03:30:40 +00:00
|
|
|
|
2021-08-18 13:19:22 +00:00
|
|
|
debug!("Worker thread shuts down {}", &name);
|
|
|
|
result
|
|
|
|
};
|
2023-05-14 21:40:01 +00:00
|
|
|
create_and_run_current_thread(fut)
|
2020-12-07 03:30:40 +00:00
|
|
|
}
|