2023-01-02 16:00:42 -05:00
|
|
|
// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
|
2019-03-26 11:56:34 -04:00
|
|
|
|
2020-01-06 14:07:35 -05:00
|
|
|
use crate::bindings;
|
2020-10-14 08:04:09 -04:00
|
|
|
use crate::error::generic_error;
|
2022-04-26 09:28:42 -04:00
|
|
|
use crate::error::to_v8_type_error;
|
2020-09-14 12:48:57 -04:00
|
|
|
use crate::error::JsError;
|
2022-03-15 18:43:17 -04:00
|
|
|
use crate::extensions::OpDecl;
|
2022-03-08 09:40:34 -05:00
|
|
|
use crate::extensions::OpEventLoopFn;
|
2021-05-26 15:07:12 -04:00
|
|
|
use crate::inspector::JsRuntimeInspector;
|
2020-09-06 10:50:49 -04:00
|
|
|
use crate::module_specifier::ModuleSpecifier;
|
2023-03-08 06:44:54 -05:00
|
|
|
use crate::modules::ExtModuleLoaderCb;
|
2023-03-21 18:33:12 -04:00
|
|
|
use crate::modules::ModuleCode;
|
2022-04-26 09:28:42 -04:00
|
|
|
use crate::modules::ModuleError;
|
2020-09-06 10:50:49 -04:00
|
|
|
use crate::modules::ModuleId;
|
|
|
|
use crate::modules::ModuleLoadId;
|
|
|
|
use crate::modules::ModuleLoader;
|
2021-02-23 09:22:55 -05:00
|
|
|
use crate::modules::ModuleMap;
|
2019-09-30 14:59:44 -04:00
|
|
|
use crate::ops::*;
|
2023-04-08 11:00:02 -04:00
|
|
|
use crate::realm::ContextState;
|
|
|
|
use crate::realm::JsRealm;
|
2023-04-18 18:52:12 -04:00
|
|
|
use crate::realm::JsRealmLocal;
|
2023-03-16 09:27:16 -04:00
|
|
|
use crate::snapshot_util;
|
2022-06-20 08:42:20 -04:00
|
|
|
use crate::source_map::SourceMapCache;
|
2022-04-15 10:08:09 -04:00
|
|
|
use crate::source_map::SourceMapGetter;
|
2021-04-28 12:41:50 -04:00
|
|
|
use crate::Extension;
|
2023-02-08 16:40:18 -05:00
|
|
|
use crate::ExtensionFileSource;
|
2023-02-07 14:22:46 -05:00
|
|
|
use crate::NoopModuleLoader;
|
2021-04-28 12:41:50 -04:00
|
|
|
use crate::OpMiddlewareFn;
|
2021-04-30 10:51:54 -04:00
|
|
|
use crate::OpResult;
|
2020-09-10 09:57:45 -04:00
|
|
|
use crate::OpState;
|
2021-03-31 10:37:38 -04:00
|
|
|
use crate::PromiseId;
|
2023-02-07 14:22:46 -05:00
|
|
|
use anyhow::Context as AnyhowContext;
|
2021-11-16 09:02:28 -05:00
|
|
|
use anyhow::Error;
|
2021-07-30 07:36:43 -04:00
|
|
|
use futures::channel::oneshot;
|
2020-10-11 07:20:40 -04:00
|
|
|
use futures::future::poll_fn;
|
2022-03-14 13:44:15 -04:00
|
|
|
use futures::future::Future;
|
2021-05-26 15:07:12 -04:00
|
|
|
use futures::future::FutureExt;
|
2023-04-26 14:02:27 -04:00
|
|
|
use futures::future::MaybeDone;
|
2019-08-07 12:55:39 -04:00
|
|
|
use futures::stream::FuturesUnordered;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::stream::StreamExt;
|
2023-04-26 14:02:27 -04:00
|
|
|
use futures::task::noop_waker;
|
2019-11-16 19:17:47 -05:00
|
|
|
use futures::task::AtomicWaker;
|
2022-11-10 06:56:02 -05:00
|
|
|
use smallvec::SmallVec;
|
2020-08-11 21:07:14 -04:00
|
|
|
use std::any::Any;
|
2020-04-21 09:48:44 -04:00
|
|
|
use std::cell::RefCell;
|
2020-01-06 14:07:35 -05:00
|
|
|
use std::collections::HashMap;
|
2020-08-11 21:07:14 -04:00
|
|
|
use std::ffi::c_void;
|
2020-01-06 14:07:35 -05:00
|
|
|
use std::option::Option;
|
2023-04-26 14:02:27 -04:00
|
|
|
use std::pin::Pin;
|
2020-04-21 09:48:44 -04:00
|
|
|
use std::rc::Rc;
|
2021-07-06 13:42:52 -04:00
|
|
|
use std::sync::Arc;
|
|
|
|
use std::sync::Mutex;
|
2020-05-29 17:41:39 -04:00
|
|
|
use std::sync::Once;
|
2019-11-16 19:17:47 -05:00
|
|
|
use std::task::Context;
|
|
|
|
use std::task::Poll;
|
2022-10-15 10:01:01 -04:00
|
|
|
use v8::OwnedIsolate;
|
2020-01-24 15:10:49 -05:00
|
|
|
|
2020-04-22 14:24:49 -04:00
|
|
|
pub enum Snapshot {
|
|
|
|
Static(&'static [u8]),
|
|
|
|
JustCreated(v8::StartupData),
|
2020-05-09 21:00:40 -04:00
|
|
|
Boxed(Box<[u8]>),
|
2020-04-22 14:24:49 -04:00
|
|
|
}
|
|
|
|
|
2021-11-16 09:02:28 -05:00
|
|
|
pub type JsErrorCreateFn = dyn Fn(JsError) -> Error;
|
2019-07-10 18:53:48 -04:00
|
|
|
|
2021-11-16 09:02:28 -05:00
|
|
|
pub type GetErrorClassFn = &'static dyn for<'e> Fn(&'e Error) -> &'static str;
|
2020-08-25 18:22:15 -04:00
|
|
|
|
2020-08-11 21:07:14 -04:00
|
|
|
/// Objects that need to live as long as the isolate
|
|
|
|
#[derive(Default)]
|
|
|
|
struct IsolateAllocations {
|
|
|
|
near_heap_limit_callback_data:
|
|
|
|
Option<(Box<RefCell<dyn Any>>, v8::NearHeapLimitCallback)>,
|
|
|
|
}
|
|
|
|
|
2019-03-12 18:47:54 -04:00
|
|
|
/// A single execution context of JavaScript. Corresponds roughly to the "Web
|
2020-09-06 15:44:29 -04:00
|
|
|
/// Worker" concept in the DOM. A JsRuntime is a Future that can be used with
|
|
|
|
/// an event loop (Tokio, async_std).
|
|
|
|
////
|
|
|
|
/// The JsRuntime future completes when there is an error or when all
|
2019-03-12 18:47:54 -04:00
|
|
|
/// pending ops have completed.
|
|
|
|
///
|
2021-04-23 11:50:45 -04:00
|
|
|
/// Pending ops are created in JavaScript by calling Deno.core.opAsync(), and in Rust
|
|
|
|
/// by implementing an async function that takes a serde::Deserialize "control argument"
|
|
|
|
/// and an optional zero copy buffer, each async Op is tied to a Promise in JavaScript.
|
2020-09-06 15:44:29 -04:00
|
|
|
pub struct JsRuntime {
|
2022-10-21 10:13:42 -04:00
|
|
|
state: Rc<RefCell<JsRuntimeState>>,
|
2022-10-25 08:27:33 -04:00
|
|
|
module_map: Option<Rc<RefCell<ModuleMap>>>,
|
2020-05-29 17:41:39 -04:00
|
|
|
// This is an Option<OwnedIsolate> instead of just OwnedIsolate to workaround
|
2021-06-21 13:37:51 -04:00
|
|
|
// a safety issue with SnapshotCreator. See JsRuntime::drop.
|
2020-05-29 17:41:39 -04:00
|
|
|
v8_isolate: Option<v8::OwnedIsolate>,
|
2023-03-16 09:27:16 -04:00
|
|
|
snapshot_options: snapshot_util::SnapshotOptions,
|
2020-08-11 21:07:14 -04:00
|
|
|
allocations: IsolateAllocations,
|
2021-04-28 12:41:50 -04:00
|
|
|
extensions: Vec<Extension>,
|
2022-03-08 09:40:34 -05:00
|
|
|
event_loop_middlewares: Vec<Box<OpEventLoopFn>>,
|
2022-11-26 17:09:48 -05:00
|
|
|
// Marks if this is considered the top-level runtime. Used only be inspector.
|
|
|
|
is_main: bool,
|
2020-05-29 17:41:39 -04:00
|
|
|
}
|
|
|
|
|
2022-06-28 10:49:30 -04:00
|
|
|
pub(crate) struct DynImportModEvaluate {
|
2021-04-28 12:28:46 -04:00
|
|
|
load_id: ModuleLoadId,
|
2020-10-14 08:04:09 -04:00
|
|
|
module_id: ModuleId,
|
|
|
|
promise: v8::Global<v8::Promise>,
|
|
|
|
module: v8::Global<v8::Module>,
|
|
|
|
}
|
|
|
|
|
2022-06-28 10:49:30 -04:00
|
|
|
pub(crate) struct ModEvaluate {
|
2022-07-18 15:20:38 -04:00
|
|
|
pub(crate) promise: Option<v8::Global<v8::Promise>>,
|
|
|
|
pub(crate) has_evaluated: bool,
|
|
|
|
pub(crate) handled_promise_rejections: Vec<v8::Global<v8::Promise>>,
|
2021-11-16 09:02:28 -05:00
|
|
|
sender: oneshot::Sender<Result<(), Error>>,
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
pub struct CrossIsolateStore<T>(Arc<Mutex<CrossIsolateStoreInner<T>>>);
|
2021-07-06 13:42:52 -04:00
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
struct CrossIsolateStoreInner<T> {
|
|
|
|
map: HashMap<u32, T>,
|
2021-07-06 13:42:52 -04:00
|
|
|
last_id: u32,
|
|
|
|
}
|
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
impl<T> CrossIsolateStore<T> {
|
|
|
|
pub(crate) fn insert(&self, value: T) -> u32 {
|
|
|
|
let mut store = self.0.lock().unwrap();
|
|
|
|
let last_id = store.last_id;
|
|
|
|
store.map.insert(last_id, value);
|
|
|
|
store.last_id += 1;
|
2021-07-06 13:42:52 -04:00
|
|
|
last_id
|
|
|
|
}
|
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
pub(crate) fn take(&self, id: u32) -> Option<T> {
|
|
|
|
let mut store = self.0.lock().unwrap();
|
|
|
|
store.map.remove(&id)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T> Default for CrossIsolateStore<T> {
|
|
|
|
fn default() -> Self {
|
|
|
|
CrossIsolateStore(Arc::new(Mutex::new(CrossIsolateStoreInner {
|
|
|
|
map: Default::default(),
|
|
|
|
last_id: 0,
|
|
|
|
})))
|
2021-07-06 13:42:52 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
impl<T> Clone for CrossIsolateStore<T> {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
Self(self.0.clone())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub type SharedArrayBufferStore =
|
|
|
|
CrossIsolateStore<v8::SharedRef<v8::BackingStore>>;
|
|
|
|
|
|
|
|
pub type CompiledWasmModuleStore = CrossIsolateStore<v8::CompiledWasmModule>;
|
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
/// Internal state for JsRuntime which is stored in one of v8::Isolate's
|
2020-05-29 17:41:39 -04:00
|
|
|
/// embedder slots.
|
2022-10-21 10:13:42 -04:00
|
|
|
pub struct JsRuntimeState {
|
2022-04-17 07:53:08 -04:00
|
|
|
global_realm: Option<JsRealm>,
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
known_realms: Vec<v8::Weak<v8::Context>>,
|
2021-11-16 14:23:12 -05:00
|
|
|
pub(crate) has_tick_scheduled: bool,
|
2022-06-28 10:49:30 -04:00
|
|
|
pub(crate) pending_dyn_mod_evaluate: Vec<DynImportModEvaluate>,
|
|
|
|
pub(crate) pending_mod_evaluate: Option<ModEvaluate>,
|
2021-07-05 12:59:49 -04:00
|
|
|
/// A counter used to delay our dynamic import deadlock detection by one spin
|
|
|
|
/// of the event loop.
|
|
|
|
dyn_module_evaluate_idle_counter: u32,
|
2023-04-18 18:52:12 -04:00
|
|
|
pub(crate) source_map_getter: Option<Rc<Box<dyn SourceMapGetter>>>,
|
|
|
|
pub(crate) source_map_cache: Rc<RefCell<SourceMapCache>>,
|
2023-04-26 14:02:27 -04:00
|
|
|
pub(crate) pending_ops: FuturesUnordered<OpCall>,
|
2023-02-02 18:24:20 -05:00
|
|
|
pub(crate) have_unpolled_ops: bool,
|
2020-09-10 09:57:45 -04:00
|
|
|
pub(crate) op_state: Rc<RefCell<OpState>>,
|
2021-07-06 13:42:52 -04:00
|
|
|
pub(crate) shared_array_buffer_store: Option<SharedArrayBufferStore>,
|
2021-09-29 04:47:24 -04:00
|
|
|
pub(crate) compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
|
2022-09-02 06:43:39 -04:00
|
|
|
/// The error that was passed to an `op_dispatch_exception` call.
|
2022-04-13 05:50:57 -04:00
|
|
|
/// It will be retrieved by `exception_to_err_result` and used as an error
|
|
|
|
/// instead of any other exceptions.
|
2022-09-02 06:43:39 -04:00
|
|
|
// TODO(nayeemrmn): This is polled in `exception_to_err_result()` which is
|
2023-01-16 10:19:04 -05:00
|
|
|
// flimsy. Try to poll it similarly to `pending_promise_rejections`.
|
2023-04-27 08:40:03 -04:00
|
|
|
pub(crate) dispatched_exception: Option<v8::Global<v8::Value>>,
|
2022-10-26 07:37:50 -04:00
|
|
|
pub(crate) inspector: Option<Rc<RefCell<JsRuntimeInspector>>>,
|
2019-11-16 19:17:47 -05:00
|
|
|
waker: AtomicWaker,
|
2020-05-29 17:41:39 -04:00
|
|
|
}
|
|
|
|
|
2022-05-17 11:19:55 -04:00
|
|
|
fn v8_init(
|
|
|
|
v8_platform: Option<v8::SharedRef<v8::Platform>>,
|
|
|
|
predictable: bool,
|
|
|
|
) {
|
2021-04-12 06:15:04 -04:00
|
|
|
// Include 10MB ICU data file.
|
|
|
|
#[repr(C, align(16))]
|
2023-02-07 07:36:41 -05:00
|
|
|
struct IcuData([u8; 10541264]);
|
2021-04-12 06:15:04 -04:00
|
|
|
static ICU_DATA: IcuData = IcuData(*include_bytes!("icudtl.dat"));
|
2023-02-07 07:36:41 -05:00
|
|
|
v8::icu::set_common_data_72(&ICU_DATA.0).unwrap();
|
2021-04-12 06:15:04 -04:00
|
|
|
|
2021-04-12 06:31:20 -04:00
|
|
|
let flags = concat!(
|
2021-07-03 17:33:36 -04:00
|
|
|
" --wasm-test-streaming",
|
2021-04-12 06:31:20 -04:00
|
|
|
" --harmony-import-assertions",
|
|
|
|
" --no-validate-asm",
|
2022-07-08 13:49:09 -04:00
|
|
|
" --turbo_fast_api_calls",
|
2022-10-26 10:54:22 -04:00
|
|
|
" --harmony-change-array-by-copy",
|
2021-04-12 06:31:20 -04:00
|
|
|
);
|
2022-05-17 11:19:55 -04:00
|
|
|
|
|
|
|
if predictable {
|
|
|
|
v8::V8::set_flags_from_string(&format!(
|
|
|
|
"{}{}",
|
|
|
|
flags, " --predictable --random-seed=42"
|
|
|
|
));
|
|
|
|
} else {
|
|
|
|
v8::V8::set_flags_from_string(flags);
|
|
|
|
}
|
2022-08-15 08:12:11 -04:00
|
|
|
|
|
|
|
let v8_platform = v8_platform
|
|
|
|
.unwrap_or_else(|| v8::new_default_platform(0, false).make_shared());
|
|
|
|
v8::V8::initialize_platform(v8_platform);
|
|
|
|
v8::V8::initialize();
|
2020-01-06 14:07:35 -05:00
|
|
|
}
|
|
|
|
|
2022-08-18 08:05:02 -04:00
|
|
|
pub const V8_WRAPPER_TYPE_INDEX: i32 = 0;
|
|
|
|
pub const V8_WRAPPER_OBJECT_INDEX: i32 = 1;
|
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
#[derive(Default)]
|
|
|
|
pub struct RuntimeOptions {
|
2022-04-15 10:08:09 -04:00
|
|
|
/// Source map reference for errors.
|
|
|
|
pub source_map_getter: Option<Box<dyn SourceMapGetter>>,
|
|
|
|
|
2020-11-21 09:56:14 -05:00
|
|
|
/// Allows to map error type to a string "class" used to represent
|
|
|
|
/// error in JavaScript.
|
|
|
|
pub get_error_class_fn: Option<GetErrorClassFn>,
|
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
/// Implementation of `ModuleLoader` which will be
|
|
|
|
/// called when V8 requests to load ES modules.
|
|
|
|
///
|
|
|
|
/// If not provided runtime will error if code being
|
|
|
|
/// executed tries to load modules.
|
|
|
|
pub module_loader: Option<Rc<dyn ModuleLoader>>,
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2022-11-26 18:58:23 -05:00
|
|
|
/// JsRuntime extensions, not to be confused with ES modules.
|
|
|
|
/// Only ops registered by extensions will be initialized. If you need
|
2023-03-09 19:22:27 -05:00
|
|
|
/// to execute JS code from extensions, pass source files in `js` or `esm`
|
|
|
|
/// option on `ExtensionBuilder`.
|
2022-11-26 18:58:23 -05:00
|
|
|
///
|
2023-03-09 19:22:27 -05:00
|
|
|
/// If you are creating a runtime from a snapshot take care not to include
|
|
|
|
/// JavaScript sources in the extensions.
|
|
|
|
pub extensions: Vec<Extension>,
|
2022-11-26 18:58:23 -05:00
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
/// V8 snapshot that should be loaded on startup.
|
|
|
|
pub startup_snapshot: Option<Snapshot>,
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
/// Prepare runtime to take snapshot of loaded code.
|
2023-01-26 01:54:01 -05:00
|
|
|
/// The snapshot is deterministic and uses predictable random numbers.
|
2020-09-11 09:18:49 -04:00
|
|
|
pub will_snapshot: bool,
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2023-02-08 16:40:18 -05:00
|
|
|
/// An optional callback that will be called for each module that is loaded
|
|
|
|
/// during snapshotting. This callback can be used to transpile source on the
|
|
|
|
/// fly, during snapshotting, eg. to transpile TypeScript to JavaScript.
|
2023-03-08 06:44:54 -05:00
|
|
|
pub snapshot_module_load_cb: Option<ExtModuleLoaderCb>,
|
2023-02-08 16:40:18 -05:00
|
|
|
|
2020-10-17 05:56:15 -04:00
|
|
|
/// Isolate creation parameters.
|
|
|
|
pub create_params: Option<v8::CreateParams>,
|
2021-04-12 06:15:04 -04:00
|
|
|
|
|
|
|
/// V8 platform instance to use. Used when Deno initializes V8
|
|
|
|
/// (which it only does once), otherwise it's silenty dropped.
|
2021-07-02 03:32:48 -04:00
|
|
|
pub v8_platform: Option<v8::SharedRef<v8::Platform>>,
|
2021-07-06 13:42:52 -04:00
|
|
|
|
2021-09-29 04:47:24 -04:00
|
|
|
/// The store to use for transferring SharedArrayBuffers between isolates.
|
2021-07-06 13:42:52 -04:00
|
|
|
/// If multiple isolates should have the possibility of sharing
|
2021-09-29 04:47:24 -04:00
|
|
|
/// SharedArrayBuffers, they should use the same [SharedArrayBufferStore]. If
|
|
|
|
/// no [SharedArrayBufferStore] is specified, SharedArrayBuffer can not be
|
|
|
|
/// serialized.
|
2021-07-06 13:42:52 -04:00
|
|
|
pub shared_array_buffer_store: Option<SharedArrayBufferStore>,
|
2021-09-29 04:47:24 -04:00
|
|
|
|
|
|
|
/// The store to use for transferring `WebAssembly.Module` objects between
|
|
|
|
/// isolates.
|
|
|
|
/// If multiple isolates should have the possibility of sharing
|
|
|
|
/// `WebAssembly.Module` objects, they should use the same
|
|
|
|
/// [CompiledWasmModuleStore]. If no [CompiledWasmModuleStore] is specified,
|
|
|
|
/// `WebAssembly.Module` objects cannot be serialized.
|
|
|
|
pub compiled_wasm_module_store: Option<CompiledWasmModuleStore>,
|
2022-11-26 17:09:48 -05:00
|
|
|
|
|
|
|
/// Start inspector instance to allow debuggers to connect.
|
2022-10-26 07:37:50 -04:00
|
|
|
pub inspector: bool,
|
2022-11-26 17:09:48 -05:00
|
|
|
|
|
|
|
/// Describe if this is the main runtime instance, used by debuggers in some
|
|
|
|
/// situation - like disconnecting when program finishes running.
|
|
|
|
pub is_main: bool,
|
2020-09-11 09:18:49 -04:00
|
|
|
}
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2022-10-15 10:01:01 -04:00
|
|
|
impl Drop for JsRuntime {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
if let Some(v8_isolate) = self.v8_isolate.as_mut() {
|
|
|
|
Self::drop_state_and_module_map(v8_isolate);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
impl JsRuntime {
|
2022-10-15 10:01:01 -04:00
|
|
|
const STATE_DATA_OFFSET: u32 = 0;
|
|
|
|
const MODULE_MAP_DATA_OFFSET: u32 = 1;
|
|
|
|
|
2020-11-05 20:26:14 -05:00
|
|
|
/// Only constructor, configuration is done through `options`.
|
2020-10-17 05:56:15 -04:00
|
|
|
pub fn new(mut options: RuntimeOptions) -> Self {
|
2021-04-12 06:15:04 -04:00
|
|
|
let v8_platform = options.v8_platform.take();
|
|
|
|
|
2020-05-29 17:41:39 -04:00
|
|
|
static DENO_INIT: Once = Once::new();
|
2022-05-17 11:19:55 -04:00
|
|
|
DENO_INIT.call_once(move || v8_init(v8_platform, options.will_snapshot));
|
2019-03-11 17:57:36 -04:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
// Add builtins extension
|
2023-03-18 18:30:04 -04:00
|
|
|
// TODO(bartlomieju): remove this in favor of `SnapshotOptions`.
|
2023-01-19 04:00:35 -05:00
|
|
|
let has_startup_snapshot = options.startup_snapshot.is_some();
|
|
|
|
if !has_startup_snapshot {
|
2022-11-26 18:58:23 -05:00
|
|
|
options
|
2023-03-09 19:22:27 -05:00
|
|
|
.extensions
|
2023-03-17 14:22:15 -04:00
|
|
|
.insert(0, crate::ops_builtin::core::init_ops_and_esm());
|
2022-11-26 18:58:23 -05:00
|
|
|
} else {
|
|
|
|
options
|
|
|
|
.extensions
|
2023-03-17 14:22:15 -04:00
|
|
|
.insert(0, crate::ops_builtin::core::init_ops());
|
2022-11-26 18:58:23 -05:00
|
|
|
}
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2023-03-09 19:22:27 -05:00
|
|
|
let ops = Self::collect_ops(&mut options.extensions);
|
2022-03-14 13:44:15 -04:00
|
|
|
let mut op_state = OpState::new(ops.len());
|
|
|
|
|
|
|
|
if let Some(get_error_class_fn) = options.get_error_class_fn {
|
|
|
|
op_state.get_error_class_fn = get_error_class_fn;
|
|
|
|
}
|
|
|
|
let op_state = Rc::new(RefCell::new(op_state));
|
2022-10-21 10:13:42 -04:00
|
|
|
|
|
|
|
let align = std::mem::align_of::<usize>();
|
|
|
|
let layout = std::alloc::Layout::from_size_align(
|
|
|
|
std::mem::size_of::<*mut v8::OwnedIsolate>(),
|
|
|
|
align,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert!(layout.size() > 0);
|
|
|
|
let isolate_ptr: *mut v8::OwnedIsolate =
|
|
|
|
// SAFETY: we just asserted that layout has non-0 size.
|
|
|
|
unsafe { std::alloc::alloc(layout) as *mut _ };
|
|
|
|
|
|
|
|
let state_rc = Rc::new(RefCell::new(JsRuntimeState {
|
|
|
|
pending_dyn_mod_evaluate: vec![],
|
|
|
|
pending_mod_evaluate: None,
|
|
|
|
dyn_module_evaluate_idle_counter: 0,
|
|
|
|
has_tick_scheduled: false,
|
2023-04-18 18:52:12 -04:00
|
|
|
source_map_getter: options.source_map_getter.map(Rc::new),
|
2022-10-21 10:13:42 -04:00
|
|
|
source_map_cache: Default::default(),
|
|
|
|
pending_ops: FuturesUnordered::new(),
|
|
|
|
shared_array_buffer_store: options.shared_array_buffer_store,
|
|
|
|
compiled_wasm_module_store: options.compiled_wasm_module_store,
|
|
|
|
op_state: op_state.clone(),
|
|
|
|
waker: AtomicWaker::new(),
|
2023-02-02 18:24:20 -05:00
|
|
|
have_unpolled_ops: false,
|
2023-04-27 08:40:03 -04:00
|
|
|
dispatched_exception: None,
|
2022-10-21 10:13:42 -04:00
|
|
|
// Some fields are initialized later after isolate is created
|
|
|
|
inspector: None,
|
|
|
|
global_realm: None,
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
known_realms: Vec::with_capacity(1),
|
2022-10-21 10:13:42 -04:00
|
|
|
}));
|
|
|
|
|
|
|
|
let weak = Rc::downgrade(&state_rc);
|
2022-04-08 04:32:48 -04:00
|
|
|
let op_ctxs = ops
|
|
|
|
.into_iter()
|
|
|
|
.enumerate()
|
2023-03-18 18:30:04 -04:00
|
|
|
.map(|(id, decl)| {
|
2023-04-26 14:02:27 -04:00
|
|
|
OpCtx::new(id as u16, 0, Rc::new(decl), op_state.clone(), weak.clone())
|
2022-04-08 04:32:48 -04:00
|
|
|
})
|
|
|
|
.collect::<Vec<_>>()
|
|
|
|
.into_boxed_slice();
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2023-03-16 09:27:16 -04:00
|
|
|
let snapshot_options = snapshot_util::SnapshotOptions::from_bools(
|
|
|
|
options.startup_snapshot.is_some(),
|
|
|
|
options.will_snapshot,
|
|
|
|
);
|
2023-03-18 18:30:04 -04:00
|
|
|
let refs = bindings::external_references(&op_ctxs);
|
2022-08-21 08:07:53 -04:00
|
|
|
// V8 takes ownership of external_references.
|
|
|
|
let refs: &'static v8::ExternalReferences = Box::leak(Box::new(refs));
|
2020-07-18 16:32:11 -04:00
|
|
|
let global_context;
|
2023-03-16 09:27:16 -04:00
|
|
|
let mut maybe_snapshotted_data = None;
|
2022-10-05 10:06:44 -04:00
|
|
|
|
2023-03-16 09:27:16 -04:00
|
|
|
let (mut isolate, snapshot_options) = if snapshot_options.will_snapshot() {
|
|
|
|
let snapshot_creator =
|
|
|
|
snapshot_util::create_snapshot_creator(refs, options.startup_snapshot);
|
2022-10-14 19:53:13 -04:00
|
|
|
let mut isolate = JsRuntime::setup_isolate(snapshot_creator);
|
2020-06-20 07:18:08 -04:00
|
|
|
{
|
|
|
|
let scope = &mut v8::HandleScope::new(&mut isolate);
|
2022-10-28 07:20:17 -04:00
|
|
|
let context =
|
2022-10-28 15:31:01 -04:00
|
|
|
bindings::initialize_context(scope, &op_ctxs, snapshot_options);
|
2023-01-19 04:00:35 -05:00
|
|
|
|
|
|
|
// Get module map data from the snapshot
|
|
|
|
if has_startup_snapshot {
|
2023-03-16 09:27:16 -04:00
|
|
|
maybe_snapshotted_data =
|
|
|
|
Some(snapshot_util::get_snapshotted_data(scope, context));
|
2023-01-19 04:00:35 -05:00
|
|
|
}
|
|
|
|
|
2020-07-18 16:32:11 -04:00
|
|
|
global_context = v8::Global::new(scope, context);
|
2020-06-20 07:18:08 -04:00
|
|
|
}
|
2022-10-28 15:31:01 -04:00
|
|
|
(isolate, snapshot_options)
|
2020-01-06 10:24:44 -05:00
|
|
|
} else {
|
2020-10-17 05:56:15 -04:00
|
|
|
let mut params = options
|
|
|
|
.create_params
|
|
|
|
.take()
|
2022-08-18 08:05:02 -04:00
|
|
|
.unwrap_or_else(|| {
|
|
|
|
v8::CreateParams::default().embedder_wrapper_type_info_offsets(
|
|
|
|
V8_WRAPPER_TYPE_INDEX,
|
|
|
|
V8_WRAPPER_OBJECT_INDEX,
|
|
|
|
)
|
|
|
|
})
|
2022-08-21 08:07:53 -04:00
|
|
|
.external_references(&**refs);
|
2023-03-16 09:27:16 -04:00
|
|
|
|
|
|
|
if let Some(snapshot) = options.startup_snapshot {
|
2020-04-22 14:24:49 -04:00
|
|
|
params = match snapshot {
|
|
|
|
Snapshot::Static(data) => params.snapshot_blob(data),
|
|
|
|
Snapshot::JustCreated(data) => params.snapshot_blob(data),
|
2020-05-09 21:00:40 -04:00
|
|
|
Snapshot::Boxed(data) => params.snapshot_blob(data),
|
2020-04-22 14:24:49 -04:00
|
|
|
};
|
2023-03-16 09:27:16 -04:00
|
|
|
}
|
2022-10-28 15:31:01 -04:00
|
|
|
|
2020-01-06 10:24:44 -05:00
|
|
|
let isolate = v8::Isolate::new(params);
|
2020-09-06 15:44:29 -04:00
|
|
|
let mut isolate = JsRuntime::setup_isolate(isolate);
|
2020-06-20 07:18:08 -04:00
|
|
|
{
|
|
|
|
let scope = &mut v8::HandleScope::new(&mut isolate);
|
2022-04-08 04:32:48 -04:00
|
|
|
let context =
|
2022-10-28 15:31:01 -04:00
|
|
|
bindings::initialize_context(scope, &op_ctxs, snapshot_options);
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
// Get module map data from the snapshot
|
|
|
|
if has_startup_snapshot {
|
2023-03-16 09:27:16 -04:00
|
|
|
maybe_snapshotted_data =
|
|
|
|
Some(snapshot_util::get_snapshotted_data(scope, context));
|
2023-01-19 04:00:35 -05:00
|
|
|
}
|
|
|
|
|
2020-07-18 16:32:11 -04:00
|
|
|
global_context = v8::Global::new(scope, context);
|
2020-06-20 07:18:08 -04:00
|
|
|
}
|
2022-10-05 10:06:44 -04:00
|
|
|
|
2022-10-28 15:31:01 -04:00
|
|
|
(isolate, snapshot_options)
|
2020-01-06 10:24:44 -05:00
|
|
|
};
|
|
|
|
|
2023-03-16 09:27:16 -04:00
|
|
|
// SAFETY: this is first use of `isolate_ptr` so we are sure we're
|
|
|
|
// not overwriting an existing pointer.
|
|
|
|
isolate = unsafe {
|
|
|
|
isolate_ptr.write(isolate);
|
|
|
|
isolate_ptr.read()
|
|
|
|
};
|
2023-03-18 18:30:04 -04:00
|
|
|
|
2022-12-26 11:00:13 -05:00
|
|
|
global_context.open(&mut isolate).set_slot(
|
|
|
|
&mut isolate,
|
|
|
|
Rc::new(RefCell::new(ContextState {
|
|
|
|
op_ctxs,
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
..Default::default()
|
2022-12-26 11:00:13 -05:00
|
|
|
})),
|
|
|
|
);
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
|
2022-10-05 10:06:44 -04:00
|
|
|
op_state.borrow_mut().put(isolate_ptr);
|
2022-10-26 07:37:50 -04:00
|
|
|
let inspector = if options.inspector {
|
|
|
|
Some(JsRuntimeInspector::new(
|
|
|
|
&mut isolate,
|
|
|
|
global_context.clone(),
|
2022-11-26 17:09:48 -05:00
|
|
|
options.is_main,
|
2022-10-26 07:37:50 -04:00
|
|
|
))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2021-05-26 15:07:12 -04:00
|
|
|
|
2023-03-16 09:27:16 -04:00
|
|
|
let loader = if snapshot_options != snapshot_util::SnapshotOptions::Load {
|
2023-02-08 16:40:18 -05:00
|
|
|
let esm_sources = options
|
2023-03-09 19:22:27 -05:00
|
|
|
.extensions
|
2023-02-08 16:40:18 -05:00
|
|
|
.iter()
|
2023-03-09 19:22:27 -05:00
|
|
|
.flat_map(|ext| match ext.get_esm_sources() {
|
|
|
|
Some(s) => s.to_owned(),
|
|
|
|
None => vec![],
|
|
|
|
})
|
2023-02-08 16:40:18 -05:00
|
|
|
.collect::<Vec<ExtensionFileSource>>();
|
|
|
|
|
2023-02-22 12:21:07 -05:00
|
|
|
#[cfg(feature = "include_js_files_for_snapshotting")]
|
2023-03-16 09:27:16 -04:00
|
|
|
if snapshot_options != snapshot_util::SnapshotOptions::None {
|
2023-03-15 09:58:44 -04:00
|
|
|
for source in &esm_sources {
|
|
|
|
use crate::ExtensionFileSourceCode;
|
|
|
|
if let ExtensionFileSourceCode::LoadedFromFsDuringSnapshot(path) =
|
|
|
|
&source.code
|
|
|
|
{
|
|
|
|
println!("cargo:rerun-if-changed={}", path.display())
|
|
|
|
}
|
2023-02-22 12:21:07 -05:00
|
|
|
}
|
|
|
|
}
|
2023-04-26 13:57:38 -04:00
|
|
|
// Cache bust plain JS (non-ES modules as well)
|
|
|
|
#[cfg(feature = "include_js_files_for_snapshotting")]
|
|
|
|
if snapshot_options != snapshot_util::SnapshotOptions::None {
|
|
|
|
let js_sources = options
|
|
|
|
.extensions
|
|
|
|
.iter()
|
|
|
|
.flat_map(|ext| match ext.get_js_sources() {
|
|
|
|
Some(s) => s.to_owned(),
|
|
|
|
None => vec![],
|
|
|
|
})
|
|
|
|
.collect::<Vec<ExtensionFileSource>>();
|
|
|
|
for source in js_sources {
|
|
|
|
use crate::ExtensionFileSourceCode;
|
|
|
|
if let ExtensionFileSourceCode::LoadedFromFsDuringSnapshot(path) =
|
|
|
|
&source.code
|
|
|
|
{
|
|
|
|
println!("cargo:rerun-if-changed={}", path.display())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-02-22 12:21:07 -05:00
|
|
|
|
2023-03-08 06:44:54 -05:00
|
|
|
Rc::new(crate::modules::ExtModuleLoader::new(
|
2023-02-07 14:22:46 -05:00
|
|
|
options.module_loader,
|
2023-02-08 16:40:18 -05:00
|
|
|
esm_sources,
|
|
|
|
options.snapshot_module_load_cb,
|
2023-02-07 14:22:46 -05:00
|
|
|
))
|
|
|
|
} else {
|
|
|
|
options
|
|
|
|
.module_loader
|
|
|
|
.unwrap_or_else(|| Rc::new(NoopModuleLoader))
|
|
|
|
};
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
{
|
|
|
|
let mut state = state_rc.borrow_mut();
|
2023-04-08 11:00:02 -04:00
|
|
|
state.global_realm = Some(JsRealm::new(global_context.clone()));
|
2022-10-26 07:37:50 -04:00
|
|
|
state.inspector = inspector;
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
state
|
|
|
|
.known_realms
|
2023-01-19 04:00:35 -05:00
|
|
|
.push(v8::Weak::new(&mut isolate, &global_context));
|
2022-10-21 10:13:42 -04:00
|
|
|
}
|
2022-10-15 10:01:01 -04:00
|
|
|
isolate.set_data(
|
|
|
|
Self::STATE_DATA_OFFSET,
|
2022-10-21 10:13:42 -04:00
|
|
|
Rc::into_raw(state_rc.clone()) as *mut c_void,
|
2022-10-15 10:01:01 -04:00
|
|
|
);
|
2020-01-06 10:24:44 -05:00
|
|
|
|
2023-02-08 12:13:33 -05:00
|
|
|
let module_map_rc = Rc::new(RefCell::new(ModuleMap::new(
|
|
|
|
loader,
|
|
|
|
op_state,
|
2023-03-16 09:27:16 -04:00
|
|
|
snapshot_options == snapshot_util::SnapshotOptions::Load,
|
2023-02-08 12:13:33 -05:00
|
|
|
)));
|
2023-03-16 09:27:16 -04:00
|
|
|
if let Some(snapshotted_data) = maybe_snapshotted_data {
|
2023-01-19 04:00:35 -05:00
|
|
|
let scope =
|
|
|
|
&mut v8::HandleScope::with_context(&mut isolate, global_context);
|
|
|
|
let mut module_map = module_map_rc.borrow_mut();
|
2023-03-16 09:27:16 -04:00
|
|
|
module_map.update_with_snapshotted_data(scope, snapshotted_data);
|
2023-01-19 04:00:35 -05:00
|
|
|
}
|
2022-10-15 10:01:01 -04:00
|
|
|
isolate.set_data(
|
|
|
|
Self::MODULE_MAP_DATA_OFFSET,
|
2022-10-25 08:27:33 -04:00
|
|
|
Rc::into_raw(module_map_rc.clone()) as *mut c_void,
|
2022-10-15 10:01:01 -04:00
|
|
|
);
|
2021-05-19 14:53:43 -04:00
|
|
|
|
2021-01-05 16:10:50 -05:00
|
|
|
let mut js_runtime = Self {
|
2020-05-29 17:41:39 -04:00
|
|
|
v8_isolate: Some(isolate),
|
2022-10-28 15:31:01 -04:00
|
|
|
snapshot_options,
|
2020-08-11 21:07:14 -04:00
|
|
|
allocations: IsolateAllocations::default(),
|
2022-03-08 09:40:34 -05:00
|
|
|
event_loop_middlewares: Vec::with_capacity(options.extensions.len()),
|
2021-04-28 12:41:50 -04:00
|
|
|
extensions: options.extensions,
|
2022-10-21 10:13:42 -04:00
|
|
|
state: state_rc,
|
2022-10-25 08:27:33 -04:00
|
|
|
module_map: Some(module_map_rc),
|
2022-11-26 17:09:48 -05:00
|
|
|
is_main: options.is_main,
|
2021-01-05 16:10:50 -05:00
|
|
|
};
|
|
|
|
|
2022-10-07 08:38:06 -04:00
|
|
|
// Init resources and ops before extensions to make sure they are
|
|
|
|
// available during the initialization process.
|
|
|
|
js_runtime.init_extension_ops().unwrap();
|
2022-11-26 18:58:23 -05:00
|
|
|
let realm = js_runtime.global_realm();
|
|
|
|
js_runtime.init_extension_js(&realm).unwrap();
|
2021-01-05 16:10:50 -05:00
|
|
|
|
|
|
|
js_runtime
|
2020-01-06 10:24:44 -05:00
|
|
|
}
|
|
|
|
|
2022-10-15 10:01:01 -04:00
|
|
|
fn drop_state_and_module_map(v8_isolate: &mut OwnedIsolate) {
|
|
|
|
let state_ptr = v8_isolate.get_data(Self::STATE_DATA_OFFSET);
|
|
|
|
let state_rc =
|
|
|
|
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
|
|
|
|
// the runtime.
|
|
|
|
unsafe { Rc::from_raw(state_ptr as *const RefCell<JsRuntimeState>) };
|
|
|
|
drop(state_rc);
|
|
|
|
|
|
|
|
let module_map_ptr = v8_isolate.get_data(Self::MODULE_MAP_DATA_OFFSET);
|
|
|
|
let module_map_rc =
|
|
|
|
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
|
|
|
|
// the runtime.
|
|
|
|
unsafe { Rc::from_raw(module_map_ptr as *const RefCell<ModuleMap>) };
|
|
|
|
drop(module_map_rc);
|
|
|
|
}
|
|
|
|
|
2022-10-25 08:27:33 -04:00
|
|
|
#[inline]
|
|
|
|
fn get_module_map(&mut self) -> &Rc<RefCell<ModuleMap>> {
|
|
|
|
self.module_map.as_ref().unwrap()
|
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
#[inline]
|
2020-10-07 09:56:52 -04:00
|
|
|
pub fn global_context(&mut self) -> v8::Global<v8::Context> {
|
2023-04-08 11:00:02 -04:00
|
|
|
let state = self.state.borrow();
|
|
|
|
let global_realm = state.global_realm.as_ref().unwrap();
|
|
|
|
global_realm.context().clone()
|
2020-09-14 23:49:12 -04:00
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
#[inline]
|
2020-10-07 09:56:52 -04:00
|
|
|
pub fn v8_isolate(&mut self) -> &mut v8::OwnedIsolate {
|
2020-10-05 05:08:19 -04:00
|
|
|
self.v8_isolate.as_mut().unwrap()
|
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
#[inline]
|
2022-09-02 06:43:39 -04:00
|
|
|
pub fn inspector(&mut self) -> Rc<RefCell<JsRuntimeInspector>> {
|
2022-10-21 10:13:42 -04:00
|
|
|
self.state.borrow().inspector()
|
2021-05-26 15:07:12 -04:00
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
#[inline]
|
2022-04-17 07:53:08 -04:00
|
|
|
pub fn global_realm(&mut self) -> JsRealm {
|
2022-10-21 10:13:42 -04:00
|
|
|
let state = self.state.borrow();
|
2022-04-17 07:53:08 -04:00
|
|
|
state.global_realm.clone().unwrap()
|
|
|
|
}
|
|
|
|
|
2022-10-15 16:44:51 -04:00
|
|
|
/// Creates a new realm (V8 context) in this JS execution context,
|
|
|
|
/// pre-initialized with all of the extensions that were passed in
|
2023-03-09 19:22:27 -05:00
|
|
|
/// [`RuntimeOptions::extensions`] when the [`JsRuntime`] was
|
2022-12-16 18:54:00 -05:00
|
|
|
/// constructed.
|
2022-04-17 07:53:08 -04:00
|
|
|
pub fn create_realm(&mut self) -> Result<JsRealm, Error> {
|
|
|
|
let realm = {
|
2023-04-26 14:02:27 -04:00
|
|
|
let realm_idx = self.state.borrow().known_realms.len() as u16;
|
2022-12-26 11:00:13 -05:00
|
|
|
|
|
|
|
let op_ctxs: Box<[OpCtx]> = self
|
|
|
|
.global_realm()
|
|
|
|
.state(self.v8_isolate())
|
|
|
|
.borrow()
|
|
|
|
.op_ctxs
|
|
|
|
.iter()
|
2023-03-18 18:30:04 -04:00
|
|
|
.map(|op_ctx| {
|
|
|
|
OpCtx::new(
|
|
|
|
op_ctx.id,
|
|
|
|
realm_idx,
|
|
|
|
op_ctx.decl.clone(),
|
|
|
|
op_ctx.state.clone(),
|
|
|
|
op_ctx.runtime_state.clone(),
|
|
|
|
)
|
2022-12-26 11:00:13 -05:00
|
|
|
})
|
|
|
|
.collect();
|
|
|
|
|
2022-04-17 07:53:08 -04:00
|
|
|
// SAFETY: Having the scope tied to self's lifetime makes it impossible to
|
2022-12-16 18:54:00 -05:00
|
|
|
// reference JsRuntimeState::op_ctxs while the scope is alive. Here we
|
|
|
|
// turn it into an unbound lifetime, which is sound because 1. it only
|
|
|
|
// lives until the end of this block, and 2. the HandleScope only has
|
|
|
|
// access to the isolate, and nothing else we're accessing from self does.
|
2022-04-17 07:53:08 -04:00
|
|
|
let scope = &mut v8::HandleScope::new(unsafe {
|
|
|
|
&mut *(self.v8_isolate() as *mut v8::OwnedIsolate)
|
|
|
|
});
|
2022-12-26 11:00:13 -05:00
|
|
|
let context =
|
|
|
|
bindings::initialize_context(scope, &op_ctxs, self.snapshot_options);
|
|
|
|
context.set_slot(
|
2022-04-17 07:53:08 -04:00
|
|
|
scope,
|
2022-12-26 11:00:13 -05:00
|
|
|
Rc::new(RefCell::new(ContextState {
|
|
|
|
op_ctxs,
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
..Default::default()
|
2022-12-26 11:00:13 -05:00
|
|
|
})),
|
2022-04-17 07:53:08 -04:00
|
|
|
);
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
|
|
|
|
self
|
|
|
|
.state
|
|
|
|
.borrow_mut()
|
|
|
|
.known_realms
|
|
|
|
.push(v8::Weak::new(scope, context));
|
|
|
|
|
2022-04-17 07:53:08 -04:00
|
|
|
JsRealm::new(v8::Global::new(scope, context))
|
|
|
|
};
|
|
|
|
|
2022-12-16 18:54:00 -05:00
|
|
|
self.init_extension_js(&realm)?;
|
2022-04-17 07:53:08 -04:00
|
|
|
Ok(realm)
|
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
#[inline]
|
2021-04-28 12:28:46 -04:00
|
|
|
pub fn handle_scope(&mut self) -> v8::HandleScope {
|
2022-07-05 18:45:10 -04:00
|
|
|
self.global_realm().handle_scope(self.v8_isolate())
|
2021-04-28 12:28:46 -04:00
|
|
|
}
|
|
|
|
|
2020-04-23 05:51:07 -04:00
|
|
|
fn setup_isolate(mut isolate: v8::OwnedIsolate) -> v8::OwnedIsolate {
|
2020-01-06 10:24:44 -05:00
|
|
|
isolate.set_capture_stack_trace_for_uncaught_exceptions(true, 10);
|
|
|
|
isolate.set_promise_reject_callback(bindings::promise_reject_callback);
|
2020-09-06 10:50:49 -04:00
|
|
|
isolate.set_host_initialize_import_meta_object_callback(
|
|
|
|
bindings::host_initialize_import_meta_object_callback,
|
|
|
|
);
|
|
|
|
isolate.set_host_import_module_dynamically_callback(
|
|
|
|
bindings::host_import_module_dynamically_callback,
|
|
|
|
);
|
2022-08-15 08:12:11 -04:00
|
|
|
isolate.set_wasm_async_resolve_promise_callback(
|
|
|
|
bindings::wasm_async_resolve_promise_callback,
|
|
|
|
);
|
2020-01-06 10:24:44 -05:00
|
|
|
isolate
|
|
|
|
}
|
|
|
|
|
2020-09-14 23:49:12 -04:00
|
|
|
pub(crate) fn state(isolate: &v8::Isolate) -> Rc<RefCell<JsRuntimeState>> {
|
2022-10-15 10:01:01 -04:00
|
|
|
let state_ptr = isolate.get_data(Self::STATE_DATA_OFFSET);
|
|
|
|
let state_rc =
|
|
|
|
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
|
|
|
|
// the runtime.
|
|
|
|
unsafe { Rc::from_raw(state_ptr as *const RefCell<JsRuntimeState>) };
|
|
|
|
let state = state_rc.clone();
|
|
|
|
Rc::into_raw(state_rc);
|
|
|
|
state
|
2019-03-21 09:48:19 -04:00
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
pub(crate) fn module_map(isolate: &v8::Isolate) -> Rc<RefCell<ModuleMap>> {
|
2022-10-15 10:01:01 -04:00
|
|
|
let module_map_ptr = isolate.get_data(Self::MODULE_MAP_DATA_OFFSET);
|
|
|
|
let module_map_rc =
|
|
|
|
// SAFETY: We are sure that it's a valid pointer for whole lifetime of
|
|
|
|
// the runtime.
|
|
|
|
unsafe { Rc::from_raw(module_map_ptr as *const RefCell<ModuleMap>) };
|
|
|
|
let module_map = module_map_rc.clone();
|
|
|
|
Rc::into_raw(module_map_rc);
|
|
|
|
module_map
|
2021-05-19 14:53:43 -04:00
|
|
|
}
|
|
|
|
|
2022-04-17 07:53:08 -04:00
|
|
|
/// Initializes JS of provided Extensions in the given realm
|
|
|
|
fn init_extension_js(&mut self, realm: &JsRealm) -> Result<(), Error> {
|
2023-02-13 18:43:53 -05:00
|
|
|
fn load_and_evaluate_module(
|
|
|
|
runtime: &mut JsRuntime,
|
|
|
|
file_source: &ExtensionFileSource,
|
|
|
|
) -> Result<(), Error> {
|
|
|
|
futures::executor::block_on(async {
|
|
|
|
let id = runtime
|
|
|
|
.load_side_module(
|
2023-03-18 16:09:13 -04:00
|
|
|
&ModuleSpecifier::parse(file_source.specifier)?,
|
2023-02-13 18:43:53 -05:00
|
|
|
None,
|
|
|
|
)
|
|
|
|
.await?;
|
|
|
|
let receiver = runtime.mod_evaluate(id);
|
2023-02-16 08:30:14 -05:00
|
|
|
runtime.run_event_loop(false).await?;
|
2023-02-13 18:43:53 -05:00
|
|
|
receiver.await?
|
|
|
|
})
|
|
|
|
.with_context(|| format!("Couldn't execute '{}'", file_source.specifier))
|
|
|
|
}
|
|
|
|
|
2021-04-28 12:41:50 -04:00
|
|
|
// Take extensions to avoid double-borrow
|
2023-03-09 19:22:27 -05:00
|
|
|
let extensions = std::mem::take(&mut self.extensions);
|
2023-01-08 17:48:46 -05:00
|
|
|
for ext in &extensions {
|
2023-02-07 14:22:46 -05:00
|
|
|
{
|
2023-03-09 19:22:27 -05:00
|
|
|
if let Some(esm_files) = ext.get_esm_sources() {
|
|
|
|
if let Some(entry_point) = ext.get_esm_entry_point() {
|
|
|
|
let file_source = esm_files
|
|
|
|
.iter()
|
|
|
|
.find(|file| file.specifier == entry_point)
|
|
|
|
.unwrap();
|
2023-02-13 18:43:53 -05:00
|
|
|
load_and_evaluate_module(self, file_source)?;
|
2023-03-09 19:22:27 -05:00
|
|
|
} else {
|
|
|
|
for file_source in esm_files {
|
|
|
|
load_and_evaluate_module(self, file_source)?;
|
|
|
|
}
|
2023-02-13 18:43:53 -05:00
|
|
|
}
|
2023-02-07 14:22:46 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
{
|
2023-03-09 19:22:27 -05:00
|
|
|
if let Some(js_files) = ext.get_js_sources() {
|
|
|
|
for file_source in js_files {
|
|
|
|
realm.execute_script(
|
|
|
|
self.v8_isolate(),
|
2023-03-18 16:09:13 -04:00
|
|
|
file_source.specifier,
|
2023-03-23 18:00:46 -04:00
|
|
|
file_source.load()?,
|
2023-03-09 19:22:27 -05:00
|
|
|
)?;
|
|
|
|
}
|
2023-02-07 14:22:46 -05:00
|
|
|
}
|
2021-04-28 12:41:50 -04:00
|
|
|
}
|
2023-04-13 20:41:32 -04:00
|
|
|
|
|
|
|
// TODO(bartlomieju): this not great that we need to have this conditional
|
|
|
|
// here, but I haven't found a better way to do it yet.
|
|
|
|
if ext.is_core {
|
|
|
|
self.init_cbs(realm);
|
|
|
|
}
|
2021-04-28 12:41:50 -04:00
|
|
|
}
|
|
|
|
// Restore extensions
|
2023-03-09 19:22:27 -05:00
|
|
|
self.extensions = extensions;
|
2021-04-28 12:41:50 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
/// Collects ops from extensions & applies middleware
|
2023-03-09 19:22:27 -05:00
|
|
|
fn collect_ops(exts: &mut [Extension]) -> Vec<OpDecl> {
|
2023-01-08 17:48:46 -05:00
|
|
|
for (ext, previous_exts) in
|
|
|
|
exts.iter().enumerate().map(|(i, ext)| (ext, &exts[..i]))
|
|
|
|
{
|
|
|
|
ext.check_dependencies(previous_exts);
|
|
|
|
}
|
|
|
|
|
2021-04-28 12:41:50 -04:00
|
|
|
// Middleware
|
2022-11-26 18:58:23 -05:00
|
|
|
let middleware: Vec<Box<OpMiddlewareFn>> = exts
|
2021-04-28 12:41:50 -04:00
|
|
|
.iter_mut()
|
|
|
|
.filter_map(|e| e.init_middleware())
|
|
|
|
.collect();
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2021-04-28 12:41:50 -04:00
|
|
|
// macroware wraps an opfn in all the middleware
|
2022-03-15 18:43:17 -04:00
|
|
|
let macroware = move |d| middleware.iter().fold(d, |d, m| m(d));
|
2021-04-28 12:41:50 -04:00
|
|
|
|
2022-03-22 11:39:58 -04:00
|
|
|
// Flatten ops, apply middlware & override disabled ops
|
2022-11-26 18:58:23 -05:00
|
|
|
exts
|
2022-03-14 13:44:15 -04:00
|
|
|
.iter_mut()
|
|
|
|
.filter_map(|e| e.init_ops())
|
|
|
|
.flatten()
|
2022-03-15 18:43:17 -04:00
|
|
|
.map(|d| OpDecl {
|
|
|
|
name: d.name,
|
|
|
|
..macroware(d)
|
|
|
|
})
|
2022-03-14 13:44:15 -04:00
|
|
|
.collect()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Initializes ops of provided Extensions
|
|
|
|
fn init_extension_ops(&mut self) -> Result<(), Error> {
|
|
|
|
let op_state = self.op_state();
|
|
|
|
// Take extensions to avoid double-borrow
|
2022-11-26 18:58:23 -05:00
|
|
|
{
|
|
|
|
let mut extensions: Vec<Extension> = std::mem::take(&mut self.extensions);
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2022-11-26 18:58:23 -05:00
|
|
|
// Setup state
|
|
|
|
for e in extensions.iter_mut() {
|
|
|
|
// ops are already registered during in bindings::initialize_context();
|
2023-03-07 16:37:37 -05:00
|
|
|
e.init_state(&mut op_state.borrow_mut());
|
2022-03-08 09:40:34 -05:00
|
|
|
|
2022-11-26 18:58:23 -05:00
|
|
|
// Setup event-loop middleware
|
|
|
|
if let Some(middleware) = e.init_event_loop_middleware() {
|
|
|
|
self.event_loop_middlewares.push(middleware);
|
|
|
|
}
|
2022-03-08 09:40:34 -05:00
|
|
|
}
|
2022-03-14 13:44:15 -04:00
|
|
|
|
2022-11-26 18:58:23 -05:00
|
|
|
// Restore extensions
|
|
|
|
self.extensions = extensions;
|
|
|
|
}
|
2021-04-28 12:41:50 -04:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-11-07 20:39:48 -05:00
|
|
|
pub fn eval<'s, T>(
|
2022-03-16 04:04:38 -04:00
|
|
|
scope: &mut v8::HandleScope<'s>,
|
2022-11-07 20:39:48 -05:00
|
|
|
code: &str,
|
2022-03-16 04:04:38 -04:00
|
|
|
) -> Option<v8::Local<'s, T>>
|
|
|
|
where
|
|
|
|
v8::Local<'s, T>: TryFrom<v8::Local<'s, v8::Value>, Error = v8::DataError>,
|
|
|
|
{
|
2022-11-07 20:39:48 -05:00
|
|
|
let scope = &mut v8::EscapableHandleScope::new(scope);
|
|
|
|
let source = v8::String::new(scope, code).unwrap();
|
|
|
|
let script = v8::Script::compile(scope, source, None).unwrap();
|
|
|
|
let v = script.run(scope)?;
|
|
|
|
scope.escape(v).try_into().ok()
|
2022-03-15 17:50:17 -04:00
|
|
|
}
|
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
/// Grabs a reference to core.js' eventLoopTick & buildCustomError
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
fn init_cbs(&mut self, realm: &JsRealm) {
|
2023-04-13 20:41:32 -04:00
|
|
|
let (event_loop_tick_cb, build_custom_error_cb) = {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let scope = &mut realm.handle_scope(self.v8_isolate());
|
2023-02-21 19:55:31 -05:00
|
|
|
let context = realm.context();
|
|
|
|
let context_local = v8::Local::new(scope, context);
|
|
|
|
let global = context_local.global(scope);
|
2023-03-06 11:37:46 -05:00
|
|
|
let deno_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"Deno").unwrap();
|
|
|
|
let core_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"core").unwrap();
|
2023-04-13 20:41:32 -04:00
|
|
|
let event_loop_tick_str =
|
|
|
|
v8::String::new_external_onebyte_static(scope, b"eventLoopTick")
|
|
|
|
.unwrap();
|
2023-02-21 19:55:31 -05:00
|
|
|
let build_custom_error_str =
|
2023-03-06 11:37:46 -05:00
|
|
|
v8::String::new_external_onebyte_static(scope, b"buildCustomError")
|
|
|
|
.unwrap();
|
2023-02-21 19:55:31 -05:00
|
|
|
|
|
|
|
let deno_obj: v8::Local<v8::Object> = global
|
|
|
|
.get(scope, deno_str.into())
|
|
|
|
.unwrap()
|
|
|
|
.try_into()
|
|
|
|
.unwrap();
|
|
|
|
let core_obj: v8::Local<v8::Object> = deno_obj
|
|
|
|
.get(scope, core_str.into())
|
|
|
|
.unwrap()
|
|
|
|
.try_into()
|
|
|
|
.unwrap();
|
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
let event_loop_tick_cb: v8::Local<v8::Function> = core_obj
|
|
|
|
.get(scope, event_loop_tick_str.into())
|
2023-02-21 19:55:31 -05:00
|
|
|
.unwrap()
|
|
|
|
.try_into()
|
|
|
|
.unwrap();
|
|
|
|
let build_custom_error_cb: v8::Local<v8::Function> = core_obj
|
|
|
|
.get(scope, build_custom_error_str.into())
|
|
|
|
.unwrap()
|
|
|
|
.try_into()
|
|
|
|
.unwrap();
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
(
|
2023-04-13 20:41:32 -04:00
|
|
|
v8::Global::new(scope, event_loop_tick_cb),
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
v8::Global::new(scope, build_custom_error_cb),
|
|
|
|
)
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
};
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
|
|
|
|
// Put global handles in the realm's ContextState
|
|
|
|
let state_rc = realm.state(self.v8_isolate());
|
|
|
|
let mut state = state_rc.borrow_mut();
|
2023-04-18 18:52:12 -04:00
|
|
|
state
|
|
|
|
.js_event_loop_tick_cb
|
|
|
|
.replace(Rc::new(event_loop_tick_cb));
|
2022-08-11 05:57:20 -04:00
|
|
|
state
|
|
|
|
.js_build_custom_error_cb
|
2023-04-18 18:52:12 -04:00
|
|
|
.replace(Rc::new(build_custom_error_cb));
|
2021-04-25 16:00:05 -04:00
|
|
|
}
|
|
|
|
|
2020-11-05 20:26:14 -05:00
|
|
|
/// Returns the runtime's op state, which can be used to maintain ops
|
|
|
|
/// and access resources between op calls.
|
2020-09-10 09:57:45 -04:00
|
|
|
pub fn op_state(&mut self) -> Rc<RefCell<OpState>> {
|
2022-10-21 10:13:42 -04:00
|
|
|
let state = self.state.borrow();
|
2020-09-10 09:57:45 -04:00
|
|
|
state.op_state.clone()
|
|
|
|
}
|
|
|
|
|
2021-06-21 19:45:41 -04:00
|
|
|
/// Executes traditional JavaScript code (traditional = not ES modules).
|
2020-01-07 06:45:44 -05:00
|
|
|
///
|
2020-11-05 20:26:14 -05:00
|
|
|
/// The execution takes place on the current global context, so it is possible
|
|
|
|
/// to maintain local JS state and invoke this method multiple times.
|
|
|
|
///
|
2023-03-21 18:33:12 -04:00
|
|
|
/// `name` can be a filepath or any other string, but it is required to be 7-bit ASCII, eg.
|
2021-06-21 19:45:41 -04:00
|
|
|
///
|
|
|
|
/// - "/some/file/path.js"
|
|
|
|
/// - "<anon>"
|
|
|
|
/// - "[native code]"
|
|
|
|
///
|
|
|
|
/// The same `name` value can be used for multiple executions.
|
|
|
|
///
|
2022-04-26 09:28:42 -04:00
|
|
|
/// `Error` can usually be downcast to `JsError`.
|
2023-04-04 08:46:31 -04:00
|
|
|
pub fn execute_script(
|
2020-01-06 10:24:44 -05:00
|
|
|
&mut self,
|
2023-03-21 18:33:12 -04:00
|
|
|
name: &'static str,
|
2023-04-04 08:46:31 -04:00
|
|
|
source_code: ModuleCode,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<v8::Global<v8::Value>, Error> {
|
2022-07-05 18:45:10 -04:00
|
|
|
self
|
|
|
|
.global_realm()
|
|
|
|
.execute_script(self.v8_isolate(), name, source_code)
|
2019-03-11 17:57:36 -04:00
|
|
|
}
|
|
|
|
|
2023-04-04 08:46:31 -04:00
|
|
|
/// Executes traditional JavaScript code (traditional = not ES modules).
|
|
|
|
///
|
|
|
|
/// The execution takes place on the current global context, so it is possible
|
|
|
|
/// to maintain local JS state and invoke this method multiple times.
|
|
|
|
///
|
|
|
|
/// `name` can be a filepath or any other string, but it is required to be 7-bit ASCII, eg.
|
|
|
|
///
|
|
|
|
/// - "/some/file/path.js"
|
|
|
|
/// - "<anon>"
|
|
|
|
/// - "[native code]"
|
|
|
|
///
|
|
|
|
/// The same `name` value can be used for multiple executions.
|
|
|
|
///
|
|
|
|
/// `Error` can usually be downcast to `JsError`.
|
|
|
|
pub fn execute_script_static(
|
|
|
|
&mut self,
|
|
|
|
name: &'static str,
|
|
|
|
source_code: &'static str,
|
|
|
|
) -> Result<v8::Global<v8::Value>, Error> {
|
|
|
|
self.global_realm().execute_script(
|
|
|
|
self.v8_isolate(),
|
|
|
|
name,
|
|
|
|
ModuleCode::from_static(source_code),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2023-04-27 08:40:03 -04:00
|
|
|
/// Call a function. If it returns a promise, run the event loop until that
|
|
|
|
/// promise is settled. If the promise rejects or there is an uncaught error
|
|
|
|
/// in the event loop, return `Err(error)`. Or return `Ok(<await returned>)`.
|
|
|
|
pub async fn call_and_await(
|
|
|
|
&mut self,
|
|
|
|
function: &v8::Global<v8::Function>,
|
|
|
|
) -> Result<v8::Global<v8::Value>, Error> {
|
|
|
|
let promise = {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let cb = function.open(scope);
|
|
|
|
let this = v8::undefined(scope).into();
|
|
|
|
let promise = cb.call(scope, this, &[]);
|
|
|
|
if promise.is_none() || scope.is_execution_terminating() {
|
|
|
|
let undefined = v8::undefined(scope).into();
|
|
|
|
return exception_to_err_result(scope, undefined, false);
|
|
|
|
}
|
|
|
|
v8::Global::new(scope, promise.unwrap())
|
|
|
|
};
|
|
|
|
self.resolve_value(promise).await
|
|
|
|
}
|
|
|
|
|
2019-07-10 18:53:48 -04:00
|
|
|
/// Takes a snapshot. The isolate should have been created with will_snapshot
|
|
|
|
/// set to true.
|
|
|
|
///
|
2022-04-26 09:28:42 -04:00
|
|
|
/// `Error` can usually be downcast to `JsError`.
|
2022-10-14 19:53:13 -04:00
|
|
|
pub fn snapshot(mut self) -> v8::StartupData {
|
2022-10-21 10:13:42 -04:00
|
|
|
self.state.borrow_mut().inspector.take();
|
2021-06-21 13:37:51 -04:00
|
|
|
|
2023-03-23 09:10:17 -04:00
|
|
|
// Set the context to be snapshot's default context
|
|
|
|
{
|
|
|
|
let context = self.global_context();
|
|
|
|
let mut scope = self.handle_scope();
|
|
|
|
let local_context = v8::Local::new(&mut scope, context);
|
|
|
|
scope.set_default_context(local_context);
|
|
|
|
}
|
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
// Serialize the module map and store its data in the snapshot.
|
|
|
|
{
|
2023-03-16 09:27:16 -04:00
|
|
|
let snapshotted_data = {
|
|
|
|
let module_map_rc = self.module_map.take().unwrap();
|
|
|
|
let module_map = module_map_rc.borrow();
|
|
|
|
module_map.serialize_for_snapshotting(&mut self.handle_scope())
|
|
|
|
};
|
2023-01-19 04:00:35 -05:00
|
|
|
|
|
|
|
let context = self.global_context();
|
|
|
|
let mut scope = self.handle_scope();
|
2023-03-16 09:27:16 -04:00
|
|
|
snapshot_util::set_snapshotted_data(
|
|
|
|
&mut scope,
|
|
|
|
context,
|
|
|
|
snapshotted_data,
|
|
|
|
);
|
2023-01-19 04:00:35 -05:00
|
|
|
}
|
|
|
|
|
2022-10-15 10:01:01 -04:00
|
|
|
// Drop existing ModuleMap to drop v8::Global handles
|
|
|
|
{
|
|
|
|
let v8_isolate = self.v8_isolate();
|
|
|
|
Self::drop_state_and_module_map(v8_isolate);
|
|
|
|
}
|
2023-01-19 04:00:35 -05:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
// Drop other v8::Global handles before snapshotting
|
feat(core): Add support for async ops in realms (#14734)
Pull request #14019 enabled initial support for realms, but it did not
include support for async ops anywhere other than the main realm. The
main issue was that the `js_recv_cb` callback, which resolves promises
corresponding to async ops, was only set for the main realm, so async
ops in other realms would never resolve. Furthermore, promise ID's are
specific to each realm, which meant that async ops from other realms
would result in a wrong promise from the main realm being resolved.
This change creates a `ContextState` struct, similar to
`JsRuntimeState` but stored in a slot of each `v8::Context`, which
contains a `js_recv_cb` callback for each realm. Combined with a new
list of known realms, which stores them as `v8::Weak<v8::Context>`,
and a change in the `#[op]` macro to pass the current context to
`queue_async_op`, this makes it possible to send the results of
promises for different realms to their realm, and prevent the ID's
from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get
the total number of unrefed ops to compare in the event loop.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2022-08-10 14:04:20 -04:00
|
|
|
{
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
for weak_context in &self.state.clone().borrow().known_realms {
|
2023-04-18 18:52:12 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
if let Some(context) = weak_context.to_local(scope) {
|
|
|
|
let realm = JsRealmLocal::new(context);
|
|
|
|
let realm_state_rc = realm.state(scope);
|
2023-01-14 22:39:00 -05:00
|
|
|
let mut realm_state = realm_state_rc.borrow_mut();
|
2023-04-13 20:41:32 -04:00
|
|
|
std::mem::take(&mut realm_state.js_event_loop_tick_cb);
|
2023-01-14 22:39:00 -05:00
|
|
|
std::mem::take(&mut realm_state.js_build_custom_error_cb);
|
|
|
|
std::mem::take(&mut realm_state.js_promise_reject_cb);
|
|
|
|
std::mem::take(&mut realm_state.js_format_exception_cb);
|
|
|
|
std::mem::take(&mut realm_state.js_wasm_streaming_cb);
|
2023-04-18 18:52:12 -04:00
|
|
|
context.clear_all_slots(scope);
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
let mut state = self.state.borrow_mut();
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
state.known_realms.clear();
|
2023-04-18 18:52:12 -04:00
|
|
|
state.global_realm.take();
|
feat(core): Add support for async ops in realms (#14734)
Pull request #14019 enabled initial support for realms, but it did not
include support for async ops anywhere other than the main realm. The
main issue was that the `js_recv_cb` callback, which resolves promises
corresponding to async ops, was only set for the main realm, so async
ops in other realms would never resolve. Furthermore, promise ID's are
specific to each realm, which meant that async ops from other realms
would result in a wrong promise from the main realm being resolved.
This change creates a `ContextState` struct, similar to
`JsRuntimeState` but stored in a slot of each `v8::Context`, which
contains a `js_recv_cb` callback for each realm. Combined with a new
list of known realms, which stores them as `v8::Weak<v8::Context>`,
and a change in the `#[op]` macro to pass the current context to
`queue_async_op`, this makes it possible to send the results of
promises for different realms to their realm, and prevent the ID's
from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get
the total number of unrefed ops to compare in the event loop.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2022-08-10 14:04:20 -04:00
|
|
|
}
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2022-10-15 10:01:01 -04:00
|
|
|
let snapshot_creator = self.v8_isolate.take().unwrap();
|
2022-10-14 19:53:13 -04:00
|
|
|
snapshot_creator
|
2020-01-06 10:24:44 -05:00
|
|
|
.create_blob(v8::FunctionCodeHandling::Keep)
|
2022-10-14 19:53:13 -04:00
|
|
|
.unwrap()
|
2019-04-08 10:12:43 -04:00
|
|
|
}
|
2020-05-29 17:41:39 -04:00
|
|
|
|
2022-03-22 09:32:32 -04:00
|
|
|
/// Returns the namespace object of a module.
|
|
|
|
///
|
|
|
|
/// This is only available after module evaluation has completed.
|
|
|
|
/// This function panics if module has not been instantiated.
|
|
|
|
pub fn get_module_namespace(
|
|
|
|
&mut self,
|
|
|
|
module_id: ModuleId,
|
|
|
|
) -> Result<v8::Global<v8::Object>, Error> {
|
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
|
|
|
|
|
|
|
let module_handle = module_map_rc
|
|
|
|
.borrow()
|
|
|
|
.get_handle(module_id)
|
|
|
|
.expect("ModuleInfo not found");
|
|
|
|
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
|
|
|
|
let module = module_handle.open(scope);
|
|
|
|
|
|
|
|
if module.get_status() == v8::ModuleStatus::Errored {
|
|
|
|
let exception = module.get_exception();
|
2022-04-26 09:28:42 -04:00
|
|
|
return exception_to_err_result(scope, exception, false);
|
2022-03-22 09:32:32 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
assert!(matches!(
|
|
|
|
module.get_status(),
|
|
|
|
v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated
|
|
|
|
));
|
|
|
|
|
|
|
|
let module_namespace: v8::Local<v8::Object> =
|
|
|
|
v8::Local::try_from(module.get_module_namespace())
|
|
|
|
.map_err(|err: v8::DataError| generic_error(err.to_string()))?;
|
|
|
|
|
|
|
|
Ok(v8::Global::new(scope, module_namespace))
|
|
|
|
}
|
|
|
|
|
2020-08-11 21:07:14 -04:00
|
|
|
/// Registers a callback on the isolate when the memory limits are approached.
|
|
|
|
/// Use this to prevent V8 from crashing the process when reaching the limit.
|
|
|
|
///
|
|
|
|
/// Calls the closure with the current heap limit and the initial heap limit.
|
|
|
|
/// The return value of the closure is set as the new limit.
|
|
|
|
pub fn add_near_heap_limit_callback<C>(&mut self, cb: C)
|
|
|
|
where
|
|
|
|
C: FnMut(usize, usize) -> usize + 'static,
|
|
|
|
{
|
|
|
|
let boxed_cb = Box::new(RefCell::new(cb));
|
|
|
|
let data = boxed_cb.as_ptr() as *mut c_void;
|
2020-08-12 00:08:50 -04:00
|
|
|
|
|
|
|
let prev = self
|
|
|
|
.allocations
|
|
|
|
.near_heap_limit_callback_data
|
|
|
|
.replace((boxed_cb, near_heap_limit_callback::<C>));
|
|
|
|
if let Some((_, prev_cb)) = prev {
|
|
|
|
self
|
2020-10-05 05:08:19 -04:00
|
|
|
.v8_isolate()
|
2020-08-12 00:08:50 -04:00
|
|
|
.remove_near_heap_limit_callback(prev_cb, 0);
|
|
|
|
}
|
|
|
|
|
2020-08-11 21:07:14 -04:00
|
|
|
self
|
2020-10-05 05:08:19 -04:00
|
|
|
.v8_isolate()
|
2020-08-11 21:07:14 -04:00
|
|
|
.add_near_heap_limit_callback(near_heap_limit_callback::<C>, data);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn remove_near_heap_limit_callback(&mut self, heap_limit: usize) {
|
|
|
|
if let Some((_, cb)) = self.allocations.near_heap_limit_callback_data.take()
|
|
|
|
{
|
|
|
|
self
|
2020-10-05 05:08:19 -04:00
|
|
|
.v8_isolate()
|
2020-08-11 21:07:14 -04:00
|
|
|
.remove_near_heap_limit_callback(cb, heap_limit);
|
|
|
|
}
|
|
|
|
}
|
2019-03-11 17:57:36 -04:00
|
|
|
|
2022-07-01 03:51:29 -04:00
|
|
|
fn pump_v8_message_loop(&mut self) -> Result<(), Error> {
|
2021-07-02 04:46:37 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
while v8::Platform::pump_message_loop(
|
|
|
|
&v8::V8::get_current_platform(),
|
|
|
|
scope,
|
|
|
|
false, // don't block if there are no tasks
|
|
|
|
) {
|
|
|
|
// do nothing
|
|
|
|
}
|
2021-07-03 17:33:36 -04:00
|
|
|
|
2022-07-01 03:51:29 -04:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
|
|
|
tc_scope.perform_microtask_checkpoint();
|
|
|
|
match tc_scope.exception() {
|
|
|
|
None => Ok(()),
|
|
|
|
Some(exception) => exception_to_err_result(tc_scope, exception, false),
|
|
|
|
}
|
2021-07-02 04:46:37 -04:00
|
|
|
}
|
|
|
|
|
2022-10-26 07:37:50 -04:00
|
|
|
pub fn maybe_init_inspector(&mut self) {
|
|
|
|
if self.state.borrow().inspector.is_some() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-04-08 11:00:02 -04:00
|
|
|
let global_context = self.global_context();
|
2022-10-26 07:37:50 -04:00
|
|
|
let mut state = self.state.borrow_mut();
|
|
|
|
state.inspector = Some(JsRuntimeInspector::new(
|
|
|
|
self.v8_isolate.as_mut().unwrap(),
|
2023-04-08 11:00:02 -04:00
|
|
|
global_context,
|
2022-11-26 17:09:48 -05:00
|
|
|
self.is_main,
|
2022-10-26 07:37:50 -04:00
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2022-01-24 11:59:41 -05:00
|
|
|
pub fn poll_value(
|
|
|
|
&mut self,
|
|
|
|
global: &v8::Global<v8::Value>,
|
|
|
|
cx: &mut Context,
|
|
|
|
) -> Poll<Result<v8::Global<v8::Value>, Error>> {
|
|
|
|
let state = self.poll_event_loop(cx, false);
|
|
|
|
|
|
|
|
let mut scope = self.handle_scope();
|
|
|
|
let local = v8::Local::<v8::Value>::new(&mut scope, global);
|
|
|
|
|
|
|
|
if let Ok(promise) = v8::Local::<v8::Promise>::try_from(local) {
|
|
|
|
match promise.state() {
|
|
|
|
v8::PromiseState::Pending => match state {
|
|
|
|
Poll::Ready(Ok(_)) => {
|
|
|
|
let msg = "Promise resolution is still pending but the event loop has already resolved.";
|
|
|
|
Poll::Ready(Err(generic_error(msg)))
|
|
|
|
}
|
|
|
|
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
|
|
|
|
Poll::Pending => Poll::Pending,
|
|
|
|
},
|
|
|
|
v8::PromiseState::Fulfilled => {
|
|
|
|
let value = promise.result(&mut scope);
|
|
|
|
let value_handle = v8::Global::new(&mut scope, value);
|
|
|
|
Poll::Ready(Ok(value_handle))
|
|
|
|
}
|
|
|
|
v8::PromiseState::Rejected => {
|
|
|
|
let exception = promise.result(&mut scope);
|
|
|
|
Poll::Ready(exception_to_err_result(&mut scope, exception, false))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
let value_handle = v8::Global::new(&mut scope, local);
|
|
|
|
Poll::Ready(Ok(value_handle))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-04 14:19:26 -04:00
|
|
|
/// Waits for the given value to resolve while polling the event loop.
|
|
|
|
///
|
|
|
|
/// This future resolves when either the value is resolved or the event loop runs to
|
|
|
|
/// completion.
|
|
|
|
pub async fn resolve_value(
|
|
|
|
&mut self,
|
|
|
|
global: v8::Global<v8::Value>,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<v8::Global<v8::Value>, Error> {
|
2022-01-24 11:59:41 -05:00
|
|
|
poll_fn(|cx| self.poll_value(&global, cx)).await
|
2021-09-04 14:19:26 -04:00
|
|
|
}
|
|
|
|
|
2020-10-11 07:20:40 -04:00
|
|
|
/// Runs event loop to completion
|
|
|
|
///
|
|
|
|
/// This future resolves when:
|
|
|
|
/// - there are no more pending dynamic imports
|
|
|
|
/// - there are no more pending ops
|
2021-05-26 15:07:12 -04:00
|
|
|
/// - there are no more active inspector sessions (only if `wait_for_inspector` is set to true)
|
|
|
|
pub async fn run_event_loop(
|
|
|
|
&mut self,
|
|
|
|
wait_for_inspector: bool,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<(), Error> {
|
2021-05-26 15:07:12 -04:00
|
|
|
poll_fn(|cx| self.poll_event_loop(cx, wait_for_inspector)).await
|
2020-10-11 07:20:40 -04:00
|
|
|
}
|
2019-06-12 13:53:24 -04:00
|
|
|
|
2020-10-11 07:20:40 -04:00
|
|
|
/// Runs a single tick of event loop
|
2021-05-26 15:07:12 -04:00
|
|
|
///
|
|
|
|
/// If `wait_for_inspector` is set to true event loop
|
|
|
|
/// will return `Poll::Pending` if there are active inspector sessions.
|
2020-10-11 07:20:40 -04:00
|
|
|
pub fn poll_event_loop(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context,
|
2021-05-26 15:07:12 -04:00
|
|
|
wait_for_inspector: bool,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Poll<Result<(), Error>> {
|
2022-10-26 07:37:50 -04:00
|
|
|
let has_inspector: bool;
|
|
|
|
|
2020-05-29 17:41:39 -04:00
|
|
|
{
|
2022-10-21 10:13:42 -04:00
|
|
|
let state = self.state.borrow();
|
2022-10-26 07:37:50 -04:00
|
|
|
has_inspector = state.inspector.is_some();
|
2020-05-29 17:41:39 -04:00
|
|
|
state.waker.register(cx.waker());
|
|
|
|
}
|
2020-02-24 18:53:29 -05:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
if has_inspector {
|
|
|
|
// We poll the inspector first.
|
2023-04-27 08:40:03 -04:00
|
|
|
let _ = self.inspector().borrow().poll_sessions(Some(cx)).unwrap();
|
2023-04-16 10:05:13 -04:00
|
|
|
}
|
2022-10-26 07:37:50 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
self.pump_v8_message_loop()?;
|
2021-07-03 17:33:36 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
// Dynamic module loading - ie. modules loaded using "import()"
|
|
|
|
{
|
|
|
|
// Run in a loop so that dynamic imports that only depend on another
|
|
|
|
// dynamic import can be resolved in this event loop iteration.
|
|
|
|
//
|
|
|
|
// For example, a dynamically imported module like the following can be
|
|
|
|
// immediately resolved after `dependency.ts` is fully evaluated, but it
|
|
|
|
// wouldn't if not for this loop.
|
|
|
|
//
|
|
|
|
// await delay(1000);
|
|
|
|
// await import("./dependency.ts");
|
|
|
|
// console.log("test")
|
|
|
|
//
|
|
|
|
loop {
|
|
|
|
let poll_imports = self.prepare_dyn_imports(cx)?;
|
|
|
|
assert!(poll_imports.is_ready());
|
|
|
|
|
|
|
|
let poll_imports = self.poll_dyn_imports(cx)?;
|
|
|
|
assert!(poll_imports.is_ready());
|
|
|
|
|
|
|
|
if !self.evaluate_dyn_imports() {
|
|
|
|
break;
|
2022-06-25 14:56:29 -04:00
|
|
|
}
|
|
|
|
}
|
2023-04-16 10:05:13 -04:00
|
|
|
}
|
2023-04-04 18:07:26 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
// Resolve async ops, run all next tick callbacks and macrotasks callbacks
|
|
|
|
// and only then check for any promise exceptions (`unhandledrejection`
|
|
|
|
// handlers are run in macrotasks callbacks so we need to let them run
|
|
|
|
// first).
|
|
|
|
self.do_js_event_loop_tick(cx)?;
|
|
|
|
self.check_promise_rejections()?;
|
2019-03-11 17:57:36 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
// Event loop middlewares
|
|
|
|
let mut maybe_scheduling = false;
|
|
|
|
{
|
|
|
|
let op_state = self.state.borrow().op_state.clone();
|
|
|
|
for f in &self.event_loop_middlewares {
|
|
|
|
if f(op_state.clone(), cx) {
|
|
|
|
maybe_scheduling = true;
|
2022-03-08 09:40:34 -05:00
|
|
|
}
|
|
|
|
}
|
2023-04-16 10:05:13 -04:00
|
|
|
}
|
2022-03-08 09:40:34 -05:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
// Top level module
|
|
|
|
self.evaluate_pending_module();
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
let pending_state = self.event_loop_pending_state();
|
|
|
|
if !pending_state.is_pending() && !maybe_scheduling {
|
|
|
|
if has_inspector {
|
|
|
|
let inspector = self.inspector();
|
|
|
|
let has_active_sessions = inspector.borrow().has_active_sessions();
|
|
|
|
let has_blocking_sessions = inspector.borrow().has_blocking_sessions();
|
|
|
|
|
|
|
|
if wait_for_inspector && has_active_sessions {
|
|
|
|
// If there are no blocking sessions (eg. REPL) we can now notify
|
|
|
|
// debugger that the program has finished running and we're ready
|
|
|
|
// to exit the process once debugger disconnects.
|
|
|
|
if !has_blocking_sessions {
|
|
|
|
let context = self.global_context();
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
inspector.borrow_mut().context_destroyed(scope, context);
|
|
|
|
println!("Program finished. Waiting for inspector to disconnect to exit the process...");
|
2022-11-26 18:44:39 -05:00
|
|
|
}
|
2019-03-11 17:57:36 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
return Poll::Pending;
|
|
|
|
}
|
2023-04-14 06:55:47 -04:00
|
|
|
}
|
2022-07-11 06:08:37 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
let state = self.state.borrow();
|
|
|
|
|
|
|
|
// Check if more async ops have been dispatched
|
|
|
|
// during this turn of event loop.
|
|
|
|
// If there are any pending background tasks, we also wake the runtime to
|
|
|
|
// make sure we don't miss them.
|
|
|
|
// TODO(andreubotella) The event loop will spin as long as there are pending
|
|
|
|
// background tasks. We should look into having V8 notify us when a
|
|
|
|
// background task is done.
|
|
|
|
if state.have_unpolled_ops
|
|
|
|
|| pending_state.has_pending_background_tasks
|
|
|
|
|| pending_state.has_tick_scheduled
|
|
|
|
|| maybe_scheduling
|
|
|
|
{
|
|
|
|
state.waker.wake();
|
|
|
|
}
|
|
|
|
|
|
|
|
drop(state);
|
2022-11-28 17:07:23 -05:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
if pending_state.has_pending_module_evaluation {
|
|
|
|
if pending_state.has_pending_refed_ops
|
|
|
|
|| pending_state.has_pending_dyn_imports
|
|
|
|
|| pending_state.has_pending_dyn_module_evaluation
|
|
|
|
|| pending_state.has_pending_background_tasks
|
2022-07-11 06:08:37 -04:00
|
|
|
|| pending_state.has_tick_scheduled
|
2022-03-08 09:40:34 -05:00
|
|
|
|| maybe_scheduling
|
2020-10-14 08:04:09 -04:00
|
|
|
{
|
2023-04-16 10:05:13 -04:00
|
|
|
// pass, will be polled again
|
|
|
|
} else {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let messages = find_stalled_top_level_await(scope);
|
|
|
|
// We are gonna print only a single message to provide a nice formatting
|
|
|
|
// with source line of offending promise shown. Once user fixed it, then
|
|
|
|
// they will get another error message for the next promise (but this
|
|
|
|
// situation is gonna be very rare, if ever happening).
|
|
|
|
assert!(!messages.is_empty());
|
|
|
|
let msg = v8::Local::new(scope, messages[0].clone());
|
|
|
|
let js_error = JsError::from_v8_message(scope, msg);
|
|
|
|
return Poll::Ready(Err(js_error.into()));
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
2023-04-16 10:05:13 -04:00
|
|
|
}
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2023-04-16 10:05:13 -04:00
|
|
|
if pending_state.has_pending_dyn_module_evaluation {
|
|
|
|
if pending_state.has_pending_refed_ops
|
|
|
|
|| pending_state.has_pending_dyn_imports
|
|
|
|
|| pending_state.has_pending_background_tasks
|
|
|
|
|| pending_state.has_tick_scheduled
|
|
|
|
{
|
|
|
|
// pass, will be polled again
|
|
|
|
} else if self.state.borrow().dyn_module_evaluate_idle_counter >= 1 {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let messages = find_stalled_top_level_await(scope);
|
|
|
|
// We are gonna print only a single message to provide a nice formatting
|
|
|
|
// with source line of offending promise shown. Once user fixed it, then
|
|
|
|
// they will get another error message for the next promise (but this
|
|
|
|
// situation is gonna be very rare, if ever happening).
|
|
|
|
assert!(!messages.is_empty());
|
|
|
|
let msg = v8::Local::new(scope, messages[0].clone());
|
|
|
|
let js_error = JsError::from_v8_message(scope, msg);
|
|
|
|
return Poll::Ready(Err(js_error.into()));
|
|
|
|
} else {
|
|
|
|
let mut state = self.state.borrow_mut();
|
|
|
|
// Delay the above error by one spin of the event loop. A dynamic import
|
|
|
|
// evaluation may complete during this, in which case the counter will
|
|
|
|
// reset.
|
|
|
|
state.dyn_module_evaluate_idle_counter += 1;
|
|
|
|
state.waker.wake();
|
2023-04-14 06:55:47 -04:00
|
|
|
}
|
|
|
|
}
|
2023-04-16 10:05:13 -04:00
|
|
|
|
2020-10-05 05:08:19 -04:00
|
|
|
Poll::Pending
|
2019-03-11 17:57:36 -04:00
|
|
|
}
|
2022-06-28 10:49:30 -04:00
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
fn event_loop_pending_state(&mut self) -> EventLoopPendingState {
|
2023-04-18 18:52:12 -04:00
|
|
|
let isolate = self.v8_isolate.as_mut().unwrap();
|
|
|
|
let mut scope = v8::HandleScope::new(isolate);
|
2022-12-13 17:28:38 -05:00
|
|
|
EventLoopPendingState::new(
|
2023-04-18 18:52:12 -04:00
|
|
|
&mut scope,
|
2022-12-13 17:28:38 -05:00
|
|
|
&mut self.state.borrow_mut(),
|
|
|
|
&self.module_map.as_ref().unwrap().borrow(),
|
|
|
|
)
|
2022-10-21 10:13:42 -04:00
|
|
|
}
|
|
|
|
|
2023-04-18 18:52:12 -04:00
|
|
|
pub(crate) fn event_loop_pending_state_from_scope(
|
|
|
|
scope: &mut v8::HandleScope,
|
2022-07-11 06:08:37 -04:00
|
|
|
) -> EventLoopPendingState {
|
2023-04-18 18:52:12 -04:00
|
|
|
let state = Self::state(scope);
|
|
|
|
let module_map = Self::module_map(scope);
|
|
|
|
let state = EventLoopPendingState::new(
|
|
|
|
scope,
|
|
|
|
&mut state.borrow_mut(),
|
|
|
|
&module_map.borrow(),
|
|
|
|
);
|
|
|
|
state
|
2022-07-11 06:08:37 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-30 14:19:32 -05:00
|
|
|
fn get_stalled_top_level_await_message_for_module(
|
|
|
|
scope: &mut v8::HandleScope,
|
2022-11-28 17:07:23 -05:00
|
|
|
module_id: ModuleId,
|
|
|
|
) -> Vec<v8::Global<v8::Message>> {
|
|
|
|
let module_map = JsRuntime::module_map(scope);
|
|
|
|
let module_map = module_map.borrow();
|
2023-01-19 07:47:41 -05:00
|
|
|
let module_handle = module_map.handles.get(module_id).unwrap();
|
2022-11-28 17:07:23 -05:00
|
|
|
|
|
|
|
let module = v8::Local::new(scope, module_handle);
|
|
|
|
let stalled = module.get_stalled_top_level_await_message(scope);
|
|
|
|
let mut messages = vec![];
|
|
|
|
for (_, message) in stalled {
|
|
|
|
messages.push(v8::Global::new(scope, message));
|
|
|
|
}
|
|
|
|
messages
|
|
|
|
}
|
|
|
|
|
2022-11-30 14:19:32 -05:00
|
|
|
fn find_stalled_top_level_await(
|
|
|
|
scope: &mut v8::HandleScope,
|
2022-11-28 17:07:23 -05:00
|
|
|
) -> Vec<v8::Global<v8::Message>> {
|
|
|
|
let module_map = JsRuntime::module_map(scope);
|
|
|
|
let module_map = module_map.borrow();
|
|
|
|
|
|
|
|
// First check if that's root module
|
|
|
|
let root_module_id = module_map
|
|
|
|
.info
|
2023-01-19 07:47:41 -05:00
|
|
|
.iter()
|
2022-11-28 17:07:23 -05:00
|
|
|
.filter(|m| m.main)
|
|
|
|
.map(|m| m.id)
|
|
|
|
.next();
|
|
|
|
|
|
|
|
if let Some(root_module_id) = root_module_id {
|
|
|
|
let messages =
|
|
|
|
get_stalled_top_level_await_message_for_module(scope, root_module_id);
|
|
|
|
if !messages.is_empty() {
|
|
|
|
return messages;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// It wasn't a top module, so iterate over all modules and try to find
|
|
|
|
// any with stalled top level await
|
2023-01-19 07:47:41 -05:00
|
|
|
for module_id in 0..module_map.handles.len() {
|
2022-11-28 17:07:23 -05:00
|
|
|
let messages =
|
|
|
|
get_stalled_top_level_await_message_for_module(scope, module_id);
|
|
|
|
if !messages.is_empty() {
|
|
|
|
return messages;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
|
2022-07-11 06:08:37 -04:00
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
|
|
pub(crate) struct EventLoopPendingState {
|
|
|
|
has_pending_refed_ops: bool,
|
|
|
|
has_pending_dyn_imports: bool,
|
|
|
|
has_pending_dyn_module_evaluation: bool,
|
|
|
|
has_pending_module_evaluation: bool,
|
|
|
|
has_pending_background_tasks: bool,
|
|
|
|
has_tick_scheduled: bool,
|
|
|
|
}
|
|
|
|
impl EventLoopPendingState {
|
2022-12-13 17:28:38 -05:00
|
|
|
pub fn new(
|
2023-04-18 18:52:12 -04:00
|
|
|
scope: &mut v8::HandleScope<()>,
|
2022-12-13 17:28:38 -05:00
|
|
|
state: &mut JsRuntimeState,
|
|
|
|
module_map: &ModuleMap,
|
|
|
|
) -> EventLoopPendingState {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let mut num_unrefed_ops = 0;
|
2023-04-18 18:52:12 -04:00
|
|
|
|
|
|
|
if state.known_realms.len() == 1 {
|
|
|
|
let realm = state.global_realm.as_ref().unwrap();
|
|
|
|
num_unrefed_ops += realm.state(scope).borrow().unrefed_ops.len();
|
|
|
|
} else {
|
|
|
|
for weak_context in &state.known_realms {
|
|
|
|
if let Some(context) = weak_context.to_local(scope) {
|
|
|
|
let realm = JsRealmLocal::new(context);
|
|
|
|
num_unrefed_ops += realm.state(scope).borrow().unrefed_ops.len();
|
|
|
|
}
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-13 17:28:38 -05:00
|
|
|
EventLoopPendingState {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
has_pending_refed_ops: state.pending_ops.len() > num_unrefed_ops,
|
2022-12-13 17:28:38 -05:00
|
|
|
has_pending_dyn_imports: module_map.has_pending_dynamic_imports(),
|
|
|
|
has_pending_dyn_module_evaluation: !state
|
|
|
|
.pending_dyn_mod_evaluate
|
|
|
|
.is_empty(),
|
|
|
|
has_pending_module_evaluation: state.pending_mod_evaluate.is_some(),
|
2023-04-18 18:52:12 -04:00
|
|
|
has_pending_background_tasks: scope.has_pending_background_tasks(),
|
2022-12-13 17:28:38 -05:00
|
|
|
has_tick_scheduled: state.has_tick_scheduled,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-11 06:08:37 -04:00
|
|
|
pub fn is_pending(&self) -> bool {
|
|
|
|
self.has_pending_refed_ops
|
|
|
|
|| self.has_pending_dyn_imports
|
|
|
|
|| self.has_pending_dyn_module_evaluation
|
|
|
|
|| self.has_pending_module_evaluation
|
|
|
|
|| self.has_pending_background_tasks
|
|
|
|
|| self.has_tick_scheduled
|
2022-06-28 10:49:30 -04:00
|
|
|
}
|
2019-03-11 17:57:36 -04:00
|
|
|
}
|
|
|
|
|
2020-10-11 07:20:40 -04:00
|
|
|
extern "C" fn near_heap_limit_callback<F>(
|
|
|
|
data: *mut c_void,
|
|
|
|
current_heap_limit: usize,
|
|
|
|
initial_heap_limit: usize,
|
|
|
|
) -> usize
|
|
|
|
where
|
|
|
|
F: FnMut(usize, usize) -> usize,
|
|
|
|
{
|
2022-06-25 18:13:24 -04:00
|
|
|
// SAFETY: The data is a pointer to the Rust callback function. It is stored
|
|
|
|
// in `JsRuntime::allocations` and thus is guaranteed to outlive the isolate.
|
2020-10-11 07:20:40 -04:00
|
|
|
let callback = unsafe { &mut *(data as *mut F) };
|
|
|
|
callback(current_heap_limit, initial_heap_limit)
|
|
|
|
}
|
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
impl JsRuntimeState {
|
2022-09-02 06:43:39 -04:00
|
|
|
pub(crate) fn inspector(&self) -> Rc<RefCell<JsRuntimeInspector>> {
|
|
|
|
self.inspector.as_ref().unwrap().clone()
|
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
/// Called by `bindings::host_import_module_dynamically_callback`
|
|
|
|
/// after initiating new dynamic import load.
|
|
|
|
pub fn notify_new_dynamic_import(&mut self) {
|
|
|
|
// Notify event loop to poll again soon.
|
2020-09-06 10:50:49 -04:00
|
|
|
self.waker.wake();
|
|
|
|
}
|
2020-05-29 17:41:39 -04:00
|
|
|
}
|
|
|
|
|
2023-01-27 10:43:16 -05:00
|
|
|
pub(crate) fn exception_to_err_result<T>(
|
|
|
|
scope: &mut v8::HandleScope,
|
2020-02-24 18:53:29 -05:00
|
|
|
exception: v8::Local<v8::Value>,
|
2020-10-25 23:34:00 -04:00
|
|
|
in_promise: bool,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<T, Error> {
|
2022-04-13 05:50:57 -04:00
|
|
|
let state_rc = JsRuntime::state(scope);
|
|
|
|
|
2022-08-21 07:57:10 -04:00
|
|
|
let was_terminating_execution = scope.is_execution_terminating();
|
2023-04-27 14:50:46 -04:00
|
|
|
// Disable running microtasks for a moment. When upgrading to V8 v11.4
|
|
|
|
// we discovered that canceling termination here will cause the queued
|
|
|
|
// microtasks to run which breaks some tests.
|
|
|
|
scope.set_microtasks_policy(v8::MicrotasksPolicy::Explicit);
|
2022-08-21 07:57:10 -04:00
|
|
|
// If TerminateExecution was called, cancel isolate termination so that the
|
|
|
|
// exception can be created. Note that `scope.is_execution_terminating()` may
|
|
|
|
// have returned false if TerminateExecution was indeed called but there was
|
|
|
|
// no JS to execute after the call.
|
|
|
|
scope.cancel_terminate_execution();
|
2020-02-24 18:53:29 -05:00
|
|
|
let mut exception = exception;
|
2022-08-21 07:57:10 -04:00
|
|
|
{
|
2022-09-02 06:43:39 -04:00
|
|
|
// If termination is the result of a `op_dispatch_exception` call, we want
|
2022-04-13 05:50:57 -04:00
|
|
|
// to use the exception that was passed to it rather than the exception that
|
|
|
|
// was passed to this function.
|
2022-09-06 07:18:23 -04:00
|
|
|
let state = state_rc.borrow();
|
2023-04-27 08:40:03 -04:00
|
|
|
exception = if let Some(exception) = &state.dispatched_exception {
|
|
|
|
v8::Local::new(scope, exception.clone())
|
|
|
|
} else if was_terminating_execution && exception.is_null_or_undefined() {
|
|
|
|
let message = v8::String::new(scope, "execution terminated").unwrap();
|
|
|
|
v8::Exception::error(scope, message)
|
|
|
|
} else {
|
|
|
|
exception
|
|
|
|
};
|
2019-03-21 09:48:19 -04:00
|
|
|
}
|
2020-02-24 18:53:29 -05:00
|
|
|
|
2020-10-25 23:34:00 -04:00
|
|
|
let mut js_error = JsError::from_v8_exception(scope, exception);
|
|
|
|
if in_promise {
|
2022-04-13 10:41:39 -04:00
|
|
|
js_error.exception_message = format!(
|
2020-10-25 23:34:00 -04:00
|
|
|
"Uncaught (in promise) {}",
|
2022-04-13 10:41:39 -04:00
|
|
|
js_error.exception_message.trim_start_matches("Uncaught ")
|
2020-10-25 23:34:00 -04:00
|
|
|
);
|
|
|
|
}
|
2020-02-24 18:53:29 -05:00
|
|
|
|
2022-08-21 07:57:10 -04:00
|
|
|
if was_terminating_execution {
|
|
|
|
// Resume exception termination.
|
2020-12-28 10:36:44 -05:00
|
|
|
scope.terminate_execution();
|
2020-02-24 18:53:29 -05:00
|
|
|
}
|
2023-04-27 14:50:46 -04:00
|
|
|
scope.set_microtasks_policy(v8::MicrotasksPolicy::Auto);
|
2020-02-24 18:53:29 -05:00
|
|
|
|
2022-04-26 19:06:10 -04:00
|
|
|
Err(js_error.into())
|
2020-02-24 18:53:29 -05:00
|
|
|
}
|
|
|
|
|
2020-09-06 10:50:49 -04:00
|
|
|
// Related to module loading
|
2020-09-06 15:44:29 -04:00
|
|
|
impl JsRuntime {
|
2021-05-19 14:53:43 -04:00
|
|
|
pub(crate) fn instantiate_module(
|
2020-09-06 10:50:49 -04:00
|
|
|
&mut self,
|
2021-05-19 14:53:43 -04:00
|
|
|
id: ModuleId,
|
2022-04-26 09:28:42 -04:00
|
|
|
) -> Result<(), v8::Global<v8::Value>> {
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2021-02-23 09:22:55 -05:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module = module_map_rc
|
2021-02-23 09:22:55 -05:00
|
|
|
.borrow()
|
|
|
|
.get_handle(id)
|
|
|
|
.map(|handle| v8::Local::new(tc_scope, handle))
|
|
|
|
.expect("ModuleInfo not found");
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
if module.get_status() == v8::ModuleStatus::Errored {
|
2022-04-26 09:28:42 -04:00
|
|
|
return Err(v8::Global::new(tc_scope, module.get_exception()));
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
2021-05-19 14:53:43 -04:00
|
|
|
|
|
|
|
// IMPORTANT: No borrows to `ModuleMap` can be held at this point because
|
|
|
|
// `module_resolve_callback` will be calling into `ModuleMap` from within
|
|
|
|
// the isolate.
|
|
|
|
let instantiate_result =
|
|
|
|
module.instantiate_module(tc_scope, bindings::module_resolve_callback);
|
|
|
|
|
|
|
|
if instantiate_result.is_none() {
|
|
|
|
let exception = tc_scope.exception().unwrap();
|
2022-04-26 09:28:42 -04:00
|
|
|
return Err(v8::Global::new(tc_scope, exception));
|
2021-05-19 14:53:43 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
fn dynamic_import_module_evaluate(
|
2020-10-14 08:04:09 -04:00
|
|
|
&mut self,
|
|
|
|
load_id: ModuleLoadId,
|
|
|
|
id: ModuleId,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<(), Error> {
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_handle = module_map_rc
|
2020-10-14 08:04:09 -04:00
|
|
|
.borrow()
|
2020-11-21 10:23:35 -05:00
|
|
|
.get_handle(id)
|
|
|
|
.expect("ModuleInfo not found");
|
2020-10-14 08:04:09 -04:00
|
|
|
|
|
|
|
let status = {
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2021-10-27 17:26:15 -04:00
|
|
|
let module = module_handle.open(scope);
|
2020-10-14 08:04:09 -04:00
|
|
|
module.get_status()
|
|
|
|
};
|
|
|
|
|
2021-04-04 07:26:00 -04:00
|
|
|
match status {
|
|
|
|
v8::ModuleStatus::Instantiated | v8::ModuleStatus::Evaluated => {}
|
|
|
|
_ => return Ok(()),
|
2021-02-23 09:22:55 -05:00
|
|
|
}
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
// IMPORTANT: Top-level-await is enabled, which means that return value
|
|
|
|
// of module evaluation is a promise.
|
|
|
|
//
|
|
|
|
// This promise is internal, and not the same one that gets returned to
|
|
|
|
// the user. We add an empty `.catch()` handler so that it does not result
|
|
|
|
// in an exception if it rejects. That will instead happen for the other
|
|
|
|
// promise if not handled by the user.
|
|
|
|
//
|
|
|
|
// For more details see:
|
|
|
|
// https://github.com/denoland/deno/issues/4908
|
|
|
|
// https://v8.dev/features/top-level-await#module-execution-order
|
2022-10-21 10:13:42 -04:00
|
|
|
let global_realm = self.state.borrow_mut().global_realm.clone().unwrap();
|
|
|
|
let scope =
|
|
|
|
&mut global_realm.handle_scope(self.v8_isolate.as_mut().unwrap());
|
2021-11-22 07:51:20 -05:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
|
|
|
let module = v8::Local::new(tc_scope, &module_handle);
|
|
|
|
let maybe_value = module.evaluate(tc_scope);
|
2021-02-23 09:22:55 -05:00
|
|
|
|
|
|
|
// Update status after evaluating.
|
|
|
|
let status = module.get_status();
|
|
|
|
|
|
|
|
if let Some(value) = maybe_value {
|
|
|
|
assert!(
|
|
|
|
status == v8::ModuleStatus::Evaluated
|
|
|
|
|| status == v8::ModuleStatus::Errored
|
|
|
|
);
|
|
|
|
let promise = v8::Local::<v8::Promise>::try_from(value)
|
|
|
|
.expect("Expected to get promise as module evaluation result");
|
2022-09-06 08:35:04 -04:00
|
|
|
let empty_fn = bindings::create_empty_fn(tc_scope).unwrap();
|
2021-11-22 07:51:20 -05:00
|
|
|
promise.catch(tc_scope, empty_fn);
|
|
|
|
let promise_global = v8::Global::new(tc_scope, promise);
|
|
|
|
let module_global = v8::Global::new(tc_scope, module);
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
let dyn_import_mod_evaluate = DynImportModEvaluate {
|
2021-04-28 12:28:46 -04:00
|
|
|
load_id,
|
2021-02-23 09:22:55 -05:00
|
|
|
module_id: id,
|
|
|
|
promise: promise_global,
|
|
|
|
module: module_global,
|
|
|
|
};
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2022-10-21 10:13:42 -04:00
|
|
|
self
|
|
|
|
.state
|
|
|
|
.borrow_mut()
|
|
|
|
.pending_dyn_mod_evaluate
|
|
|
|
.push(dyn_import_mod_evaluate);
|
2021-11-22 07:51:20 -05:00
|
|
|
} else if tc_scope.has_terminated() || tc_scope.is_execution_terminating() {
|
|
|
|
return Err(
|
|
|
|
generic_error("Cannot evaluate dynamically imported module, because JavaScript execution has been terminated.")
|
|
|
|
);
|
2021-02-23 09:22:55 -05:00
|
|
|
} else {
|
|
|
|
assert!(status == v8::ModuleStatus::Errored);
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2021-03-04 07:19:47 -05:00
|
|
|
// TODO(bartlomieju): make it return `ModuleEvaluationFuture`?
|
2020-10-14 08:04:09 -04:00
|
|
|
/// Evaluates an already instantiated ES module.
|
|
|
|
///
|
2021-03-04 07:19:47 -05:00
|
|
|
/// Returns a receiver handle that resolves when module promise resolves.
|
2022-06-20 08:40:57 -04:00
|
|
|
/// Implementors must manually call [`JsRuntime::run_event_loop`] to drive
|
|
|
|
/// module evaluation future.
|
2021-03-04 07:19:47 -05:00
|
|
|
///
|
2022-06-20 08:40:57 -04:00
|
|
|
/// `Error` can usually be downcast to `JsError` and should be awaited and
|
|
|
|
/// checked after [`JsRuntime::run_event_loop`] completion.
|
2021-02-23 09:22:55 -05:00
|
|
|
///
|
|
|
|
/// This function panics if module has not been instantiated.
|
2021-03-04 07:19:47 -05:00
|
|
|
pub fn mod_evaluate(
|
2020-10-14 08:04:09 -04:00
|
|
|
&mut self,
|
|
|
|
id: ModuleId,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> oneshot::Receiver<Result<(), Error>> {
|
2023-01-16 11:36:42 -05:00
|
|
|
let global_realm = self.global_realm();
|
2022-10-21 10:13:42 -04:00
|
|
|
let state_rc = self.state.clone();
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2021-11-22 07:51:20 -05:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let module = module_map_rc
|
2020-09-06 10:50:49 -04:00
|
|
|
.borrow()
|
2020-11-21 10:23:35 -05:00
|
|
|
.get_handle(id)
|
2021-11-22 07:51:20 -05:00
|
|
|
.map(|handle| v8::Local::new(tc_scope, handle))
|
2020-09-06 10:50:49 -04:00
|
|
|
.expect("ModuleInfo not found");
|
|
|
|
let mut status = module.get_status();
|
2023-02-13 18:43:53 -05:00
|
|
|
assert_eq!(
|
|
|
|
status,
|
|
|
|
v8::ModuleStatus::Instantiated,
|
|
|
|
"Module not instantiated {id}"
|
|
|
|
);
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-07-30 07:36:43 -04:00
|
|
|
let (sender, receiver) = oneshot::channel();
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2021-02-23 09:22:55 -05:00
|
|
|
// IMPORTANT: Top-level-await is enabled, which means that return value
|
|
|
|
// of module evaluation is a promise.
|
|
|
|
//
|
|
|
|
// Because that promise is created internally by V8, when error occurs during
|
|
|
|
// module evaluation the promise is rejected, and since the promise has no rejection
|
|
|
|
// handler it will result in call to `bindings::promise_reject_callback` adding
|
|
|
|
// the promise to pending promise rejection table - meaning JsRuntime will return
|
|
|
|
// error on next poll().
|
|
|
|
//
|
|
|
|
// This situation is not desirable as we want to manually return error at the
|
|
|
|
// end of this function to handle it further. It means we need to manually
|
|
|
|
// remove this promise from pending promise rejection table.
|
|
|
|
//
|
|
|
|
// For more details see:
|
|
|
|
// https://github.com/denoland/deno/issues/4908
|
|
|
|
// https://v8.dev/features/top-level-await#module-execution-order
|
2022-07-18 15:20:38 -04:00
|
|
|
{
|
|
|
|
let mut state = state_rc.borrow_mut();
|
|
|
|
assert!(
|
|
|
|
state.pending_mod_evaluate.is_none(),
|
|
|
|
"There is already pending top level module evaluation"
|
|
|
|
);
|
|
|
|
state.pending_mod_evaluate = Some(ModEvaluate {
|
|
|
|
promise: None,
|
|
|
|
has_evaluated: false,
|
|
|
|
handled_promise_rejections: vec![],
|
|
|
|
sender,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-11-22 07:51:20 -05:00
|
|
|
let maybe_value = module.evaluate(tc_scope);
|
2022-07-18 15:20:38 -04:00
|
|
|
{
|
|
|
|
let mut state = state_rc.borrow_mut();
|
|
|
|
let pending_mod_evaluate = state.pending_mod_evaluate.as_mut().unwrap();
|
|
|
|
pending_mod_evaluate.has_evaluated = true;
|
|
|
|
}
|
2021-02-23 09:22:55 -05:00
|
|
|
|
|
|
|
// Update status after evaluating.
|
|
|
|
status = module.get_status();
|
|
|
|
|
2022-09-02 06:43:39 -04:00
|
|
|
let has_dispatched_exception =
|
2023-04-27 08:40:03 -04:00
|
|
|
state_rc.borrow_mut().dispatched_exception.is_some();
|
2022-09-02 06:43:39 -04:00
|
|
|
if has_dispatched_exception {
|
|
|
|
// This will be overrided in `exception_to_err_result()`.
|
|
|
|
let exception = v8::undefined(tc_scope).into();
|
2022-07-18 15:20:38 -04:00
|
|
|
let pending_mod_evaluate = {
|
|
|
|
let mut state = state_rc.borrow_mut();
|
|
|
|
state.pending_mod_evaluate.take().unwrap()
|
|
|
|
};
|
|
|
|
pending_mod_evaluate
|
|
|
|
.sender
|
2022-04-13 05:50:57 -04:00
|
|
|
.send(exception_to_err_result(tc_scope, exception, false))
|
|
|
|
.expect("Failed to send module evaluation error.");
|
|
|
|
} else if let Some(value) = maybe_value {
|
2021-02-23 09:22:55 -05:00
|
|
|
assert!(
|
|
|
|
status == v8::ModuleStatus::Evaluated
|
|
|
|
|| status == v8::ModuleStatus::Errored
|
|
|
|
);
|
|
|
|
let promise = v8::Local::<v8::Promise>::try_from(value)
|
|
|
|
.expect("Expected to get promise as module evaluation result");
|
2021-11-22 07:51:20 -05:00
|
|
|
let promise_global = v8::Global::new(tc_scope, promise);
|
2021-02-23 09:22:55 -05:00
|
|
|
let mut state = state_rc.borrow_mut();
|
2022-07-22 18:40:42 -04:00
|
|
|
{
|
|
|
|
let pending_mod_evaluate = state.pending_mod_evaluate.as_ref().unwrap();
|
|
|
|
let pending_rejection_was_already_handled = pending_mod_evaluate
|
|
|
|
.handled_promise_rejections
|
|
|
|
.contains(&promise_global);
|
|
|
|
if !pending_rejection_was_already_handled {
|
2023-01-16 11:36:42 -05:00
|
|
|
global_realm
|
|
|
|
.state(tc_scope)
|
|
|
|
.borrow_mut()
|
|
|
|
.pending_promise_rejections
|
|
|
|
.remove(&promise_global);
|
2022-07-22 18:40:42 -04:00
|
|
|
}
|
|
|
|
}
|
2021-11-22 07:51:20 -05:00
|
|
|
let promise_global = v8::Global::new(tc_scope, promise);
|
2022-07-18 15:20:38 -04:00
|
|
|
state.pending_mod_evaluate.as_mut().unwrap().promise =
|
|
|
|
Some(promise_global);
|
2021-11-22 07:51:20 -05:00
|
|
|
tc_scope.perform_microtask_checkpoint();
|
|
|
|
} else if tc_scope.has_terminated() || tc_scope.is_execution_terminating() {
|
2022-07-18 15:20:38 -04:00
|
|
|
let pending_mod_evaluate = {
|
|
|
|
let mut state = state_rc.borrow_mut();
|
|
|
|
state.pending_mod_evaluate.take().unwrap()
|
|
|
|
};
|
|
|
|
pending_mod_evaluate.sender.send(Err(
|
2021-11-22 07:51:20 -05:00
|
|
|
generic_error("Cannot evaluate module, because JavaScript execution has been terminated.")
|
|
|
|
)).expect("Failed to send module evaluation error.");
|
2021-02-23 09:22:55 -05:00
|
|
|
} else {
|
|
|
|
assert!(status == v8::ModuleStatus::Errored);
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
|
2020-11-27 14:47:35 -05:00
|
|
|
receiver
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
|
2022-04-26 09:28:42 -04:00
|
|
|
fn dynamic_import_reject(
|
|
|
|
&mut self,
|
|
|
|
id: ModuleLoadId,
|
|
|
|
exception: v8::Global<v8::Value>,
|
|
|
|
) {
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let resolver_handle = module_map_rc
|
2020-09-06 10:50:49 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.dynamic_import_map
|
2020-09-06 10:50:49 -04:00
|
|
|
.remove(&id)
|
2021-05-19 14:53:43 -04:00
|
|
|
.expect("Invalid dynamic import id");
|
2021-10-27 17:26:15 -04:00
|
|
|
let resolver = resolver_handle.open(scope);
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
// IMPORTANT: No borrows to `ModuleMap` can be held at this point because
|
|
|
|
// rejecting the promise might initiate another `import()` which will
|
|
|
|
// in turn call `bindings::host_import_module_dynamically_callback` which
|
|
|
|
// will reach into `ModuleMap` from within the isolate.
|
2022-04-26 09:28:42 -04:00
|
|
|
let exception = v8::Local::new(scope, exception);
|
2020-09-06 10:50:49 -04:00
|
|
|
resolver.reject(scope, exception).unwrap();
|
|
|
|
scope.perform_microtask_checkpoint();
|
|
|
|
}
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
fn dynamic_import_resolve(&mut self, id: ModuleLoadId, mod_id: ModuleId) {
|
2022-10-21 10:13:42 -04:00
|
|
|
let state_rc = self.state.clone();
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
let resolver_handle = module_map_rc
|
2020-09-06 10:50:49 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.dynamic_import_map
|
2020-09-06 10:50:49 -04:00
|
|
|
.remove(&id)
|
2021-05-19 14:53:43 -04:00
|
|
|
.expect("Invalid dynamic import id");
|
2021-10-27 17:26:15 -04:00
|
|
|
let resolver = resolver_handle.open(scope);
|
2020-09-06 10:50:49 -04:00
|
|
|
|
|
|
|
let module = {
|
2021-05-19 14:53:43 -04:00
|
|
|
module_map_rc
|
|
|
|
.borrow()
|
2020-11-21 10:23:35 -05:00
|
|
|
.get_handle(mod_id)
|
|
|
|
.map(|handle| v8::Local::new(scope, handle))
|
2020-09-06 10:50:49 -04:00
|
|
|
.expect("Dyn import module info not found")
|
|
|
|
};
|
|
|
|
// Resolution success
|
|
|
|
assert_eq!(module.get_status(), v8::ModuleStatus::Evaluated);
|
|
|
|
|
2021-05-19 14:53:43 -04:00
|
|
|
// IMPORTANT: No borrows to `ModuleMap` can be held at this point because
|
|
|
|
// resolving the promise might initiate another `import()` which will
|
|
|
|
// in turn call `bindings::host_import_module_dynamically_callback` which
|
|
|
|
// will reach into `ModuleMap` from within the isolate.
|
2020-09-06 10:50:49 -04:00
|
|
|
let module_namespace = module.get_module_namespace();
|
|
|
|
resolver.resolve(scope, module_namespace).unwrap();
|
2021-07-05 12:59:49 -04:00
|
|
|
state_rc.borrow_mut().dyn_module_evaluate_idle_counter = 0;
|
2020-09-06 10:50:49 -04:00
|
|
|
scope.perform_microtask_checkpoint();
|
|
|
|
}
|
|
|
|
|
|
|
|
fn prepare_dyn_imports(
|
|
|
|
&mut self,
|
|
|
|
cx: &mut Context,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Poll<Result<(), Error>> {
|
2022-10-25 08:27:33 -04:00
|
|
|
if self
|
|
|
|
.get_module_map()
|
|
|
|
.borrow()
|
|
|
|
.preparing_dynamic_imports
|
|
|
|
.is_empty()
|
|
|
|
{
|
2020-10-05 05:08:19 -04:00
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2022-10-25 08:27:33 -04:00
|
|
|
let module_map_rc = self.get_module_map().clone();
|
|
|
|
|
2020-09-06 10:50:49 -04:00
|
|
|
loop {
|
2021-05-19 14:53:43 -04:00
|
|
|
let poll_result = module_map_rc
|
2021-04-28 12:28:46 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.preparing_dynamic_imports
|
2021-04-28 12:28:46 -04:00
|
|
|
.poll_next_unpin(cx);
|
|
|
|
|
|
|
|
if let Poll::Ready(Some(prepare_poll)) = poll_result {
|
|
|
|
let dyn_import_id = prepare_poll.0;
|
|
|
|
let prepare_result = prepare_poll.1;
|
|
|
|
|
|
|
|
match prepare_result {
|
|
|
|
Ok(load) => {
|
2021-05-19 14:53:43 -04:00
|
|
|
module_map_rc
|
2021-04-28 12:28:46 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.pending_dynamic_imports
|
2021-04-28 12:28:46 -04:00
|
|
|
.push(load.into_future());
|
|
|
|
}
|
|
|
|
Err(err) => {
|
2022-04-26 09:28:42 -04:00
|
|
|
let exception = to_v8_type_error(&mut self.handle_scope(), err);
|
|
|
|
self.dynamic_import_reject(dyn_import_id, exception);
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
// Continue polling for more prepared dynamic imports.
|
|
|
|
continue;
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
|
|
|
|
// There are no active dynamic import loads, or none are ready.
|
|
|
|
return Poll::Ready(Ok(()));
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-16 09:02:28 -05:00
|
|
|
fn poll_dyn_imports(&mut self, cx: &mut Context) -> Poll<Result<(), Error>> {
|
2022-10-25 08:27:33 -04:00
|
|
|
if self
|
|
|
|
.get_module_map()
|
|
|
|
.borrow()
|
|
|
|
.pending_dynamic_imports
|
|
|
|
.is_empty()
|
|
|
|
{
|
2020-10-05 05:08:19 -04:00
|
|
|
return Poll::Ready(Ok(()));
|
|
|
|
}
|
|
|
|
|
2022-10-25 08:27:33 -04:00
|
|
|
let module_map_rc = self.get_module_map().clone();
|
|
|
|
|
2020-09-06 10:50:49 -04:00
|
|
|
loop {
|
2021-05-19 14:53:43 -04:00
|
|
|
let poll_result = module_map_rc
|
2021-04-28 12:28:46 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.pending_dynamic_imports
|
2021-04-28 12:28:46 -04:00
|
|
|
.poll_next_unpin(cx);
|
|
|
|
|
|
|
|
if let Poll::Ready(Some(load_stream_poll)) = poll_result {
|
|
|
|
let maybe_result = load_stream_poll.0;
|
|
|
|
let mut load = load_stream_poll.1;
|
|
|
|
let dyn_import_id = load.id;
|
|
|
|
|
|
|
|
if let Some(load_stream_result) = maybe_result {
|
|
|
|
match load_stream_result {
|
2021-12-15 13:22:36 -05:00
|
|
|
Ok((request, info)) => {
|
2021-04-28 12:28:46 -04:00
|
|
|
// A module (not necessarily the one dynamically imported) has been
|
|
|
|
// fetched. Create and register it, and if successful, poll for the
|
|
|
|
// next recursive-load event related to this dynamic import.
|
2021-12-15 13:22:36 -05:00
|
|
|
let register_result = load.register_and_recurse(
|
|
|
|
&mut self.handle_scope(),
|
|
|
|
&request,
|
2023-04-04 08:46:31 -04:00
|
|
|
info,
|
2021-12-15 13:22:36 -05:00
|
|
|
);
|
2021-05-19 14:53:43 -04:00
|
|
|
|
|
|
|
match register_result {
|
2021-04-28 12:28:46 -04:00
|
|
|
Ok(()) => {
|
|
|
|
// Keep importing until it's fully drained
|
2021-05-19 14:53:43 -04:00
|
|
|
module_map_rc
|
2021-04-28 12:28:46 -04:00
|
|
|
.borrow_mut()
|
2021-05-19 14:53:43 -04:00
|
|
|
.pending_dynamic_imports
|
2021-04-28 12:28:46 -04:00
|
|
|
.push(load.into_future());
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
2022-04-26 09:28:42 -04:00
|
|
|
Err(err) => {
|
|
|
|
let exception = match err {
|
|
|
|
ModuleError::Exception(e) => e,
|
|
|
|
ModuleError::Other(e) => {
|
|
|
|
to_v8_type_error(&mut self.handle_scope(), e)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
self.dynamic_import_reject(dyn_import_id, exception)
|
|
|
|
}
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
Err(err) => {
|
|
|
|
// A non-javascript error occurred; this could be due to a an invalid
|
|
|
|
// module specifier, or a problem with the source map, or a failure
|
|
|
|
// to fetch the module source code.
|
2022-04-26 09:28:42 -04:00
|
|
|
let exception = to_v8_type_error(&mut self.handle_scope(), err);
|
|
|
|
self.dynamic_import_reject(dyn_import_id, exception);
|
2021-02-23 09:22:55 -05:00
|
|
|
}
|
2020-10-06 04:18:22 -04:00
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
} else {
|
|
|
|
// The top-level module from a dynamic import has been instantiated.
|
|
|
|
// Load is done.
|
2021-06-28 21:03:02 -04:00
|
|
|
let module_id =
|
|
|
|
load.root_module_id.expect("Root module should be loaded");
|
2021-05-19 14:53:43 -04:00
|
|
|
let result = self.instantiate_module(module_id);
|
2022-04-26 09:28:42 -04:00
|
|
|
if let Err(exception) = result {
|
|
|
|
self.dynamic_import_reject(dyn_import_id, exception);
|
2021-04-28 12:28:46 -04:00
|
|
|
}
|
2021-05-19 14:53:43 -04:00
|
|
|
self.dynamic_import_module_evaluate(dyn_import_id, module_id)?;
|
2020-10-06 04:18:22 -04:00
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
|
|
|
|
// Continue polling for more ready dynamic imports.
|
|
|
|
continue;
|
2020-10-06 04:18:22 -04:00
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
|
|
|
|
// There are no active dynamic import loads, or none are ready.
|
|
|
|
return Poll::Ready(Ok(()));
|
2020-10-06 04:18:22 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-22 11:47:09 -04:00
|
|
|
/// "deno_core" runs V8 with Top Level Await enabled. It means that each
|
|
|
|
/// module evaluation returns a promise from V8.
|
|
|
|
/// Feature docs: https://v8.dev/features/top-level-await
|
2020-10-14 08:04:09 -04:00
|
|
|
///
|
|
|
|
/// This promise resolves after all dependent modules have also
|
|
|
|
/// resolved. Each dependent module may perform calls to "import()" and APIs
|
|
|
|
/// using async ops will add futures to the runtime's event loop.
|
|
|
|
/// It means that the promise returned from module evaluation will
|
|
|
|
/// resolve only after all futures in the event loop are done.
|
|
|
|
///
|
|
|
|
/// Thus during turn of event loop we need to check if V8 has
|
|
|
|
/// resolved or rejected the promise. If the promise is still pending
|
|
|
|
/// then another turn of event loop must be performed.
|
2020-11-27 14:47:35 -05:00
|
|
|
fn evaluate_pending_module(&mut self) {
|
2021-04-28 12:28:46 -04:00
|
|
|
let maybe_module_evaluation =
|
2022-10-25 08:27:33 -04:00
|
|
|
self.state.borrow_mut().pending_mod_evaluate.take();
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2021-04-28 12:28:46 -04:00
|
|
|
if maybe_module_evaluation.is_none() {
|
|
|
|
return;
|
|
|
|
}
|
2020-10-14 08:04:09 -04:00
|
|
|
|
2022-07-18 15:20:38 -04:00
|
|
|
let mut module_evaluation = maybe_module_evaluation.unwrap();
|
2022-10-25 08:27:33 -04:00
|
|
|
let state_rc = self.state.clone();
|
2021-04-28 12:28:46 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
|
2022-07-18 15:20:38 -04:00
|
|
|
let promise_global = module_evaluation.promise.clone().unwrap();
|
|
|
|
let promise = promise_global.open(scope);
|
2021-04-28 12:28:46 -04:00
|
|
|
let promise_state = promise.state();
|
|
|
|
|
|
|
|
match promise_state {
|
|
|
|
v8::PromiseState::Pending => {
|
|
|
|
// NOTE: `poll_event_loop` will decide if
|
|
|
|
// runtime would be woken soon
|
|
|
|
state_rc.borrow_mut().pending_mod_evaluate = Some(module_evaluation);
|
|
|
|
}
|
|
|
|
v8::PromiseState::Fulfilled => {
|
|
|
|
scope.perform_microtask_checkpoint();
|
|
|
|
// Receiver end might have been already dropped, ignore the result
|
2021-07-30 07:36:43 -04:00
|
|
|
let _ = module_evaluation.sender.send(Ok(()));
|
2022-07-18 15:20:38 -04:00
|
|
|
module_evaluation.handled_promise_rejections.clear();
|
2021-04-28 12:28:46 -04:00
|
|
|
}
|
|
|
|
v8::PromiseState::Rejected => {
|
|
|
|
let exception = promise.result(scope);
|
|
|
|
scope.perform_microtask_checkpoint();
|
2022-07-18 15:20:38 -04:00
|
|
|
|
2021-04-28 12:28:46 -04:00
|
|
|
// Receiver end might have been already dropped, ignore the result
|
2022-07-18 15:20:38 -04:00
|
|
|
if module_evaluation
|
|
|
|
.handled_promise_rejections
|
|
|
|
.contains(&promise_global)
|
|
|
|
{
|
|
|
|
let _ = module_evaluation.sender.send(Ok(()));
|
|
|
|
module_evaluation.handled_promise_rejections.clear();
|
|
|
|
} else {
|
|
|
|
let _ = module_evaluation
|
|
|
|
.sender
|
|
|
|
.send(exception_to_err_result(scope, exception, false));
|
|
|
|
}
|
2021-04-28 12:28:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-25 14:56:29 -04:00
|
|
|
// Returns true if some dynamic import was resolved.
|
|
|
|
fn evaluate_dyn_imports(&mut self) -> bool {
|
2021-07-05 12:59:49 -04:00
|
|
|
let pending =
|
2022-10-21 10:13:42 -04:00
|
|
|
std::mem::take(&mut self.state.borrow_mut().pending_dyn_mod_evaluate);
|
2022-10-25 08:27:33 -04:00
|
|
|
if pending.is_empty() {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
let mut resolved_any = false;
|
|
|
|
let mut still_pending = vec![];
|
2021-07-05 12:59:49 -04:00
|
|
|
for pending_dyn_evaluate in pending {
|
2021-04-28 12:28:46 -04:00
|
|
|
let maybe_result = {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
|
|
|
|
let module_id = pending_dyn_evaluate.module_id;
|
2021-10-27 17:26:15 -04:00
|
|
|
let promise = pending_dyn_evaluate.promise.open(scope);
|
|
|
|
let _module = pending_dyn_evaluate.module.open(scope);
|
2020-10-14 08:04:09 -04:00
|
|
|
let promise_state = promise.state();
|
|
|
|
|
|
|
|
match promise_state {
|
|
|
|
v8::PromiseState::Pending => {
|
2021-07-05 12:59:49 -04:00
|
|
|
still_pending.push(pending_dyn_evaluate);
|
2021-04-28 12:28:46 -04:00
|
|
|
None
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
v8::PromiseState::Fulfilled => {
|
2021-04-28 12:28:46 -04:00
|
|
|
Some(Ok((pending_dyn_evaluate.load_id, module_id)))
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
v8::PromiseState::Rejected => {
|
|
|
|
let exception = promise.result(scope);
|
2022-04-26 09:28:42 -04:00
|
|
|
let exception = v8::Global::new(scope, exception);
|
|
|
|
Some(Err((pending_dyn_evaluate.load_id, exception)))
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if let Some(result) = maybe_result {
|
2022-06-25 14:56:29 -04:00
|
|
|
resolved_any = true;
|
2020-10-14 08:04:09 -04:00
|
|
|
match result {
|
|
|
|
Ok((dyn_import_id, module_id)) => {
|
2021-05-19 14:53:43 -04:00
|
|
|
self.dynamic_import_resolve(dyn_import_id, module_id);
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
2022-04-26 09:28:42 -04:00
|
|
|
Err((dyn_import_id, exception)) => {
|
|
|
|
self.dynamic_import_reject(dyn_import_id, exception);
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-10-21 10:13:42 -04:00
|
|
|
self.state.borrow_mut().pending_dyn_mod_evaluate = still_pending;
|
2022-06-25 14:56:29 -04:00
|
|
|
resolved_any
|
2020-10-14 08:04:09 -04:00
|
|
|
}
|
|
|
|
|
2021-09-17 21:44:53 -04:00
|
|
|
/// Asynchronously load specified module and all of its dependencies.
|
|
|
|
///
|
|
|
|
/// The module will be marked as "main", and because of that
|
|
|
|
/// "import.meta.main" will return true when checked inside that module.
|
2020-09-06 10:50:49 -04:00
|
|
|
///
|
2022-06-20 08:40:57 -04:00
|
|
|
/// User must call [`JsRuntime::mod_evaluate`] with returned `ModuleId`
|
2020-09-06 10:50:49 -04:00
|
|
|
/// manually after load is finished.
|
2021-09-17 21:44:53 -04:00
|
|
|
pub async fn load_main_module(
|
2020-09-06 10:50:49 -04:00
|
|
|
&mut self,
|
|
|
|
specifier: &ModuleSpecifier,
|
2023-03-21 18:33:12 -04:00
|
|
|
code: Option<ModuleCode>,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<ModuleId, Error> {
|
2021-05-19 14:53:43 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
2021-06-28 21:03:02 -04:00
|
|
|
if let Some(code) = code {
|
2023-04-04 08:46:31 -04:00
|
|
|
let specifier = specifier.as_str().to_owned().into();
|
2022-04-26 09:28:42 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2023-03-21 18:33:12 -04:00
|
|
|
// true for main module
|
2022-04-26 09:28:42 -04:00
|
|
|
module_map_rc
|
|
|
|
.borrow_mut()
|
2023-04-04 08:46:31 -04:00
|
|
|
.new_es_module(scope, true, specifier, code, false)
|
2022-04-26 09:28:42 -04:00
|
|
|
.map_err(|e| match e {
|
|
|
|
ModuleError::Exception(exception) => {
|
|
|
|
let exception = v8::Local::new(scope, exception);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
}
|
|
|
|
ModuleError::Other(error) => error,
|
|
|
|
})?;
|
2021-06-28 21:03:02 -04:00
|
|
|
}
|
2021-05-19 14:53:43 -04:00
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
let mut load =
|
2023-04-04 08:46:31 -04:00
|
|
|
ModuleMap::load_main(module_map_rc.clone(), &specifier).await?;
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2021-12-15 13:22:36 -05:00
|
|
|
while let Some(load_result) = load.next().await {
|
|
|
|
let (request, info) = load_result?;
|
2021-05-19 14:53:43 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2023-04-04 08:46:31 -04:00
|
|
|
load.register_and_recurse(scope, &request, info).map_err(
|
2022-04-26 09:28:42 -04:00
|
|
|
|e| match e {
|
|
|
|
ModuleError::Exception(exception) => {
|
|
|
|
let exception = v8::Local::new(scope, exception);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
}
|
|
|
|
ModuleError::Other(error) => error,
|
|
|
|
},
|
|
|
|
)?;
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
|
2021-06-28 21:03:02 -04:00
|
|
|
let root_id = load.root_module_id.expect("Root module should be loaded");
|
2022-04-26 09:28:42 -04:00
|
|
|
self.instantiate_module(root_id).map_err(|e| {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let exception = v8::Local::new(scope, e);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
})?;
|
2021-06-19 10:14:43 -04:00
|
|
|
Ok(root_id)
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
|
2021-09-17 21:44:53 -04:00
|
|
|
/// Asynchronously load specified ES module and all of its dependencies.
|
|
|
|
///
|
|
|
|
/// This method is meant to be used when loading some utility code that
|
|
|
|
/// might be later imported by the main module (ie. an entry point module).
|
|
|
|
///
|
2022-06-20 08:40:57 -04:00
|
|
|
/// User must call [`JsRuntime::mod_evaluate`] with returned `ModuleId`
|
2021-09-17 21:44:53 -04:00
|
|
|
/// manually after load is finished.
|
|
|
|
pub async fn load_side_module(
|
|
|
|
&mut self,
|
|
|
|
specifier: &ModuleSpecifier,
|
2023-03-21 18:33:12 -04:00
|
|
|
code: Option<ModuleCode>,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<ModuleId, Error> {
|
2021-09-17 21:44:53 -04:00
|
|
|
let module_map_rc = Self::module_map(self.v8_isolate());
|
|
|
|
if let Some(code) = code {
|
2023-04-04 08:46:31 -04:00
|
|
|
let specifier = specifier.as_str().to_owned().into();
|
2022-04-26 09:28:42 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2023-03-21 18:33:12 -04:00
|
|
|
// false for side module (not main module)
|
2022-04-26 09:28:42 -04:00
|
|
|
module_map_rc
|
|
|
|
.borrow_mut()
|
2023-04-04 08:46:31 -04:00
|
|
|
.new_es_module(scope, false, specifier, code, false)
|
2022-04-26 09:28:42 -04:00
|
|
|
.map_err(|e| match e {
|
|
|
|
ModuleError::Exception(exception) => {
|
|
|
|
let exception = v8::Local::new(scope, exception);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
}
|
|
|
|
ModuleError::Other(error) => error,
|
|
|
|
})?;
|
2021-09-17 21:44:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut load =
|
2023-04-04 08:46:31 -04:00
|
|
|
ModuleMap::load_side(module_map_rc.clone(), &specifier).await?;
|
2021-09-17 21:44:53 -04:00
|
|
|
|
2021-12-15 13:22:36 -05:00
|
|
|
while let Some(load_result) = load.next().await {
|
|
|
|
let (request, info) = load_result?;
|
2021-09-17 21:44:53 -04:00
|
|
|
let scope = &mut self.handle_scope();
|
2023-04-04 08:46:31 -04:00
|
|
|
load.register_and_recurse(scope, &request, info).map_err(
|
2022-04-26 09:28:42 -04:00
|
|
|
|e| match e {
|
|
|
|
ModuleError::Exception(exception) => {
|
|
|
|
let exception = v8::Local::new(scope, exception);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
}
|
|
|
|
ModuleError::Other(error) => error,
|
|
|
|
},
|
|
|
|
)?;
|
2021-09-17 21:44:53 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
let root_id = load.root_module_id.expect("Root module should be loaded");
|
2022-04-26 09:28:42 -04:00
|
|
|
self.instantiate_module(root_id).map_err(|e| {
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let exception = v8::Local::new(scope, e);
|
|
|
|
exception_to_err_result::<()>(scope, exception, false).unwrap_err()
|
|
|
|
})?;
|
2021-09-17 21:44:53 -04:00
|
|
|
Ok(root_id)
|
|
|
|
}
|
|
|
|
|
2023-01-16 10:19:04 -05:00
|
|
|
fn check_promise_rejections(&mut self) -> Result<(), Error> {
|
2023-04-18 18:52:12 -04:00
|
|
|
let state = self.state.clone();
|
|
|
|
let scope = &mut self.handle_scope();
|
|
|
|
let state = state.borrow();
|
|
|
|
for weak_context in &state.known_realms {
|
|
|
|
if let Some(context) = weak_context.to_local(scope) {
|
|
|
|
JsRealmLocal::new(context).check_promise_rejections(scope)?;
|
2023-01-16 11:36:42 -05:00
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
}
|
2023-01-16 11:36:42 -05:00
|
|
|
Ok(())
|
2020-10-05 05:08:19 -04:00
|
|
|
}
|
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
// Polls pending ops and then runs `Deno.core.eventLoopTick` callback.
|
|
|
|
fn do_js_event_loop_tick(&mut self, cx: &mut Context) -> Result<(), Error> {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
// We have a specialized implementation of this method for the common case
|
|
|
|
// where there is only one realm.
|
|
|
|
let num_realms = self.state.borrow().known_realms.len();
|
|
|
|
if num_realms == 1 {
|
2023-04-13 20:41:32 -04:00
|
|
|
return self.do_single_realm_js_event_loop_tick(cx);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// `responses_per_realm[idx]` is a vector containing the promise ID and
|
|
|
|
// response for all promises in realm `self.state.known_realms[idx]`.
|
|
|
|
let mut responses_per_realm: Vec<Vec<(PromiseId, OpResult)>> =
|
|
|
|
(0..num_realms).map(|_| vec![]).collect();
|
|
|
|
|
|
|
|
// Now handle actual ops.
|
|
|
|
{
|
|
|
|
let mut state = self.state.borrow_mut();
|
2023-02-02 18:24:20 -05:00
|
|
|
state.have_unpolled_ops = false;
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
|
|
|
|
while let Poll::Ready(Some(item)) = state.pending_ops.poll_next_unpin(cx)
|
|
|
|
{
|
|
|
|
let (realm_idx, promise_id, op_id, resp) = item;
|
|
|
|
state.op_state.borrow().tracker.track_async_completed(op_id);
|
2023-04-26 14:02:27 -04:00
|
|
|
responses_per_realm[realm_idx as usize].push((promise_id, resp));
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Handle responses for each realm.
|
|
|
|
let isolate = self.v8_isolate.as_mut().unwrap();
|
|
|
|
for (realm_idx, responses) in responses_per_realm.into_iter().enumerate() {
|
|
|
|
let realm = {
|
|
|
|
let context = self.state.borrow().known_realms[realm_idx]
|
|
|
|
.to_global(isolate)
|
|
|
|
.unwrap();
|
2023-04-08 11:00:02 -04:00
|
|
|
JsRealm::new(context)
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
};
|
|
|
|
let context_state_rc = realm.state(isolate);
|
|
|
|
let mut context_state = context_state_rc.borrow_mut();
|
|
|
|
let scope = &mut realm.handle_scope(isolate);
|
|
|
|
|
|
|
|
// We return async responses to JS in unbounded batches (may change),
|
|
|
|
// each batch is a flat vector of tuples:
|
|
|
|
// `[promise_id1, op_result1, promise_id2, op_result2, ...]`
|
|
|
|
// promise_id is a simple integer, op_result is an ops::OpResult
|
|
|
|
// which contains a value OR an error, encoded as a tuple.
|
|
|
|
// This batch is received in JS via the special `arguments` variable
|
|
|
|
// and then each tuple is used to resolve or reject promises
|
|
|
|
//
|
2023-04-13 20:41:32 -04:00
|
|
|
// This can handle 15 promises futures in a single batch without heap
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
// allocations.
|
|
|
|
let mut args: SmallVec<[v8::Local<v8::Value>; 32]> =
|
2023-04-13 20:41:32 -04:00
|
|
|
SmallVec::with_capacity(responses.len() * 2 + 2);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
|
|
|
|
for (promise_id, mut resp) in responses {
|
|
|
|
context_state.unrefed_ops.remove(&promise_id);
|
|
|
|
args.push(v8::Integer::new(scope, promise_id).into());
|
|
|
|
args.push(match resp.to_v8(scope) {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(e) => OpResult::Err(OpError::new(&|_| "TypeError", e.into()))
|
|
|
|
.to_v8(scope)
|
|
|
|
.unwrap(),
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
let has_tick_scheduled =
|
|
|
|
v8::Boolean::new(scope, self.state.borrow().has_tick_scheduled);
|
|
|
|
args.push(has_tick_scheduled.into());
|
|
|
|
|
|
|
|
let js_event_loop_tick_cb_handle =
|
|
|
|
context_state.js_event_loop_tick_cb.clone().unwrap();
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
2023-04-13 20:41:32 -04:00
|
|
|
let js_event_loop_tick_cb = js_event_loop_tick_cb_handle.open(tc_scope);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let this = v8::undefined(tc_scope).into();
|
|
|
|
drop(context_state);
|
2023-04-13 20:41:32 -04:00
|
|
|
js_event_loop_tick_cb.call(tc_scope, this, args.as_slice());
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
|
|
|
|
if let Some(exception) = tc_scope.exception() {
|
|
|
|
// TODO(@andreubotella): Returning here can cause async ops in other
|
|
|
|
// realms to never resolve.
|
|
|
|
return exception_to_err_result(tc_scope, exception, false);
|
|
|
|
}
|
2023-04-13 20:41:32 -04:00
|
|
|
|
|
|
|
if tc_scope.has_terminated() || tc_scope.is_execution_terminating() {
|
|
|
|
return Ok(());
|
|
|
|
}
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
fn do_single_realm_js_event_loop_tick(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
&mut self,
|
|
|
|
cx: &mut Context,
|
|
|
|
) -> Result<(), Error> {
|
2022-10-21 10:13:42 -04:00
|
|
|
let isolate = self.v8_isolate.as_mut().unwrap();
|
2022-11-10 06:56:02 -05:00
|
|
|
let scope = &mut self
|
|
|
|
.state
|
|
|
|
.borrow()
|
|
|
|
.global_realm
|
|
|
|
.as_ref()
|
|
|
|
.unwrap()
|
|
|
|
.handle_scope(isolate);
|
2020-10-05 05:08:19 -04:00
|
|
|
|
2022-10-20 22:54:22 -04:00
|
|
|
// We return async responses to JS in unbounded batches (may change),
|
|
|
|
// each batch is a flat vector of tuples:
|
|
|
|
// `[promise_id1, op_result1, promise_id2, op_result2, ...]`
|
|
|
|
// promise_id is a simple integer, op_result is an ops::OpResult
|
|
|
|
// which contains a value OR an error, encoded as a tuple.
|
|
|
|
// This batch is received in JS via the special `arguments` variable
|
|
|
|
// and then each tuple is used to resolve or reject promises
|
2022-11-10 06:56:02 -05:00
|
|
|
//
|
2023-04-13 20:41:32 -04:00
|
|
|
// This can handle 15 promises futures in a single batch without heap
|
2022-11-10 06:56:02 -05:00
|
|
|
// allocations.
|
|
|
|
let mut args: SmallVec<[v8::Local<v8::Value>; 32]> = SmallVec::new();
|
2021-10-24 15:41:57 -04:00
|
|
|
|
|
|
|
// Now handle actual ops.
|
|
|
|
{
|
2022-10-21 10:13:42 -04:00
|
|
|
let mut state = self.state.borrow_mut();
|
2023-02-02 18:24:20 -05:00
|
|
|
state.have_unpolled_ops = false;
|
2021-10-24 15:41:57 -04:00
|
|
|
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let realm_state_rc = state.global_realm.as_ref().unwrap().state(scope);
|
|
|
|
let mut realm_state = realm_state_rc.borrow_mut();
|
|
|
|
|
2021-11-25 13:49:09 -05:00
|
|
|
while let Poll::Ready(Some(item)) = state.pending_ops.poll_next_unpin(cx)
|
|
|
|
{
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let (realm_idx, promise_id, op_id, mut resp) = item;
|
|
|
|
debug_assert_eq!(
|
2023-04-26 14:02:27 -04:00
|
|
|
state.known_realms[realm_idx as usize],
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
state.global_realm.as_ref().unwrap().context()
|
|
|
|
);
|
|
|
|
realm_state.unrefed_ops.remove(&promise_id);
|
2022-03-14 13:44:15 -04:00
|
|
|
state.op_state.borrow().tracker.track_async_completed(op_id);
|
2022-12-17 17:20:15 -05:00
|
|
|
args.push(v8::Integer::new(scope, promise_id).into());
|
2022-09-01 16:20:11 -04:00
|
|
|
args.push(match resp.to_v8(scope) {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(e) => OpResult::Err(OpError::new(&|_| "TypeError", e.into()))
|
|
|
|
.to_v8(scope)
|
|
|
|
.unwrap(),
|
|
|
|
});
|
feat(core): Add support for async ops in realms (#14734)
Pull request #14019 enabled initial support for realms, but it did not
include support for async ops anywhere other than the main realm. The
main issue was that the `js_recv_cb` callback, which resolves promises
corresponding to async ops, was only set for the main realm, so async
ops in other realms would never resolve. Furthermore, promise ID's are
specific to each realm, which meant that async ops from other realms
would result in a wrong promise from the main realm being resolved.
This change creates a `ContextState` struct, similar to
`JsRuntimeState` but stored in a slot of each `v8::Context`, which
contains a `js_recv_cb` callback for each realm. Combined with a new
list of known realms, which stores them as `v8::Weak<v8::Context>`,
and a change in the `#[op]` macro to pass the current context to
`queue_async_op`, this makes it possible to send the results of
promises for different realms to their realm, and prevent the ID's
from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get
the total number of unrefed ops to compare in the event loop.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2022-08-10 14:04:20 -04:00
|
|
|
}
|
2022-10-20 22:54:22 -04:00
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
let has_tick_scheduled =
|
|
|
|
v8::Boolean::new(scope, self.state.borrow().has_tick_scheduled);
|
|
|
|
args.push(has_tick_scheduled.into());
|
feat(core): Add support for async ops in realms (#14734)
Pull request #14019 enabled initial support for realms, but it did not
include support for async ops anywhere other than the main realm. The
main issue was that the `js_recv_cb` callback, which resolves promises
corresponding to async ops, was only set for the main realm, so async
ops in other realms would never resolve. Furthermore, promise ID's are
specific to each realm, which meant that async ops from other realms
would result in a wrong promise from the main realm being resolved.
This change creates a `ContextState` struct, similar to
`JsRuntimeState` but stored in a slot of each `v8::Context`, which
contains a `js_recv_cb` callback for each realm. Combined with a new
list of known realms, which stores them as `v8::Weak<v8::Context>`,
and a change in the `#[op]` macro to pass the current context to
`queue_async_op`, this makes it possible to send the results of
promises for different realms to their realm, and prevent the ID's
from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get
the total number of unrefed ops to compare in the event loop.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2022-08-10 14:04:20 -04:00
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
let js_event_loop_tick_cb_handle = {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let state = self.state.borrow_mut();
|
|
|
|
let realm_state_rc = state.global_realm.as_ref().unwrap().state(scope);
|
2023-04-13 20:41:32 -04:00
|
|
|
let handle = realm_state_rc
|
|
|
|
.borrow()
|
|
|
|
.js_event_loop_tick_cb
|
|
|
|
.clone()
|
|
|
|
.unwrap();
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
handle
|
|
|
|
};
|
2022-10-20 22:54:22 -04:00
|
|
|
let tc_scope = &mut v8::TryCatch::new(scope);
|
2023-04-13 20:41:32 -04:00
|
|
|
let js_event_loop_tick_cb = js_event_loop_tick_cb_handle.open(tc_scope);
|
2022-10-20 22:54:22 -04:00
|
|
|
let this = v8::undefined(tc_scope).into();
|
2023-04-13 20:41:32 -04:00
|
|
|
js_event_loop_tick_cb.call(tc_scope, this, args.as_slice());
|
2022-10-20 22:54:22 -04:00
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
if let Some(exception) = tc_scope.exception() {
|
|
|
|
return exception_to_err_result(tc_scope, exception, false);
|
2022-10-20 22:54:22 -04:00
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
|
2023-04-13 20:41:32 -04:00
|
|
|
if tc_scope.has_terminated() || tc_scope.is_execution_terminating() {
|
2021-11-16 14:23:12 -05:00
|
|
|
return Ok(());
|
|
|
|
}
|
2020-10-05 05:08:19 -04:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
|
|
|
|
2022-11-11 08:44:53 -05:00
|
|
|
#[inline]
|
2023-04-26 14:02:27 -04:00
|
|
|
pub fn queue_fast_async_op<R: serde::Serialize + 'static>(
|
2022-11-11 08:44:53 -05:00
|
|
|
ctx: &OpCtx,
|
2023-04-26 14:02:27 -04:00
|
|
|
promise_id: PromiseId,
|
|
|
|
op: impl Future<Output = Result<R, Error>> + 'static,
|
2022-11-11 08:44:53 -05:00
|
|
|
) {
|
|
|
|
let runtime_state = match ctx.runtime_state.upgrade() {
|
|
|
|
Some(rc_state) => rc_state,
|
|
|
|
// atleast 1 Rc is held by the JsRuntime.
|
|
|
|
None => unreachable!(),
|
|
|
|
};
|
2023-04-26 14:02:27 -04:00
|
|
|
let get_class = {
|
|
|
|
let state = RefCell::borrow(&ctx.state);
|
|
|
|
state.tracker.track_async(ctx.id);
|
|
|
|
state.get_error_class_fn
|
|
|
|
};
|
|
|
|
let fut = op
|
|
|
|
.map(|result| crate::_ops::to_op_result(get_class, result))
|
|
|
|
.boxed_local();
|
2023-02-02 18:24:20 -05:00
|
|
|
let mut state = runtime_state.borrow_mut();
|
2023-04-26 14:02:27 -04:00
|
|
|
state
|
|
|
|
.pending_ops
|
|
|
|
.push(OpCall::pending(ctx, promise_id, fut));
|
2023-02-02 18:24:20 -05:00
|
|
|
state.have_unpolled_ops = true;
|
2022-11-11 08:44:53 -05:00
|
|
|
}
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[inline]
|
2023-04-26 14:02:27 -04:00
|
|
|
pub fn map_async_op1<R: serde::Serialize + 'static>(
|
|
|
|
ctx: &OpCtx,
|
|
|
|
op: impl Future<Output = Result<R, Error>> + 'static,
|
|
|
|
) -> MaybeDone<Pin<Box<dyn Future<Output = OpResult>>>> {
|
|
|
|
let get_class = {
|
|
|
|
let state = RefCell::borrow(&ctx.state);
|
|
|
|
state.tracker.track_async(ctx.id);
|
|
|
|
state.get_error_class_fn
|
|
|
|
};
|
|
|
|
|
|
|
|
let fut = op
|
|
|
|
.map(|result| crate::_ops::to_op_result(get_class, result))
|
|
|
|
.boxed_local();
|
|
|
|
MaybeDone::Future(fut)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn map_async_op2<R: serde::Serialize + 'static>(
|
|
|
|
ctx: &OpCtx,
|
|
|
|
op: impl Future<Output = R> + 'static,
|
|
|
|
) -> MaybeDone<Pin<Box<dyn Future<Output = OpResult>>>> {
|
|
|
|
let state = RefCell::borrow(&ctx.state);
|
|
|
|
state.tracker.track_async(ctx.id);
|
|
|
|
|
|
|
|
let fut = op.map(|result| OpResult::Ok(result.into())).boxed_local();
|
|
|
|
MaybeDone::Future(fut)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn map_async_op3<R: serde::Serialize + 'static>(
|
|
|
|
ctx: &OpCtx,
|
|
|
|
op: Result<impl Future<Output = Result<R, Error>> + 'static, Error>,
|
|
|
|
) -> MaybeDone<Pin<Box<dyn Future<Output = OpResult>>>> {
|
|
|
|
let get_class = {
|
|
|
|
let state = RefCell::borrow(&ctx.state);
|
|
|
|
state.tracker.track_async(ctx.id);
|
|
|
|
state.get_error_class_fn
|
|
|
|
};
|
|
|
|
|
|
|
|
match op {
|
|
|
|
Err(err) => MaybeDone::Done(OpResult::Err(OpError::new(get_class, err))),
|
|
|
|
Ok(fut) => MaybeDone::Future(
|
|
|
|
fut
|
|
|
|
.map(|result| crate::_ops::to_op_result(get_class, result))
|
|
|
|
.boxed_local(),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
pub fn map_async_op4<R: serde::Serialize + 'static>(
|
|
|
|
ctx: &OpCtx,
|
|
|
|
op: Result<impl Future<Output = R> + 'static, Error>,
|
|
|
|
) -> MaybeDone<Pin<Box<dyn Future<Output = OpResult>>>> {
|
|
|
|
let get_class = {
|
|
|
|
let state = RefCell::borrow(&ctx.state);
|
|
|
|
state.tracker.track_async(ctx.id);
|
|
|
|
state.get_error_class_fn
|
|
|
|
};
|
|
|
|
|
|
|
|
match op {
|
|
|
|
Err(err) => MaybeDone::Done(OpResult::Err(OpError::new(get_class, err))),
|
|
|
|
Ok(fut) => MaybeDone::Future(
|
|
|
|
fut.map(|result| OpResult::Ok(result.into())).boxed_local(),
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-13 08:32:47 -04:00
|
|
|
pub fn queue_async_op<'s>(
|
2022-10-21 10:13:42 -04:00
|
|
|
ctx: &OpCtx,
|
2023-04-13 08:32:47 -04:00
|
|
|
scope: &'s mut v8::HandleScope,
|
2022-09-06 13:38:37 -04:00
|
|
|
deferred: bool,
|
2023-04-26 14:02:27 -04:00
|
|
|
promise_id: PromiseId,
|
|
|
|
mut op: MaybeDone<Pin<Box<dyn Future<Output = OpResult>>>>,
|
2023-04-13 08:32:47 -04:00
|
|
|
) -> Option<v8::Local<'s, v8::Value>> {
|
2022-10-21 10:13:42 -04:00
|
|
|
let runtime_state = match ctx.runtime_state.upgrade() {
|
|
|
|
Some(rc_state) => rc_state,
|
|
|
|
// atleast 1 Rc is held by the JsRuntime.
|
|
|
|
None => unreachable!(),
|
|
|
|
};
|
|
|
|
|
2022-12-26 11:00:13 -05:00
|
|
|
// An op's realm (as given by `OpCtx::realm_idx`) must match the realm in
|
|
|
|
// which it is invoked. Otherwise, we might have cross-realm object exposure.
|
|
|
|
// deno_core doesn't currently support such exposure, even though embedders
|
|
|
|
// can cause them, so we panic in debug mode (since the check is expensive).
|
|
|
|
debug_assert_eq!(
|
2023-04-26 14:02:27 -04:00
|
|
|
runtime_state.borrow().known_realms[ctx.realm_idx as usize].to_local(scope),
|
2022-12-26 11:00:13 -05:00
|
|
|
Some(scope.get_current_context())
|
|
|
|
);
|
|
|
|
|
2023-04-26 14:02:27 -04:00
|
|
|
// All ops are polled immediately
|
|
|
|
let waker = noop_waker();
|
|
|
|
let mut cx = Context::from_waker(&waker);
|
|
|
|
|
|
|
|
// Note that MaybeDone returns () from the future
|
|
|
|
let op_call = match op.poll_unpin(&mut cx) {
|
|
|
|
Poll::Pending => {
|
|
|
|
let MaybeDone::Future(fut) = op else {
|
|
|
|
unreachable!()
|
|
|
|
};
|
|
|
|
OpCall::pending(ctx, promise_id, fut)
|
2022-09-06 13:38:37 -04:00
|
|
|
}
|
2023-04-26 14:02:27 -04:00
|
|
|
Poll::Ready(_) => {
|
|
|
|
let mut op_result = Pin::new(&mut op).take_output().unwrap();
|
|
|
|
// If the op is ready and is not marked as deferred we can immediately return
|
|
|
|
// the result.
|
|
|
|
if !deferred {
|
|
|
|
ctx.state.borrow_mut().tracker.track_async_completed(ctx.id);
|
|
|
|
return Some(op_result.to_v8(scope).unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
OpCall::ready(ctx, promise_id, op_result)
|
2022-09-06 13:38:37 -04:00
|
|
|
}
|
2023-04-26 14:02:27 -04:00
|
|
|
};
|
2023-04-13 08:32:47 -04:00
|
|
|
|
2023-04-26 14:02:27 -04:00
|
|
|
// Otherwise we will push it to the `pending_ops` and let it be polled again
|
|
|
|
// or resolved on the next tick of the event loop.
|
|
|
|
let mut state = runtime_state.borrow_mut();
|
|
|
|
state.pending_ops.push(op_call);
|
|
|
|
state.have_unpolled_ops = true;
|
2023-04-13 08:32:47 -04:00
|
|
|
None
|
2022-03-14 13:44:15 -04:00
|
|
|
}
|
|
|
|
|
2019-03-11 17:57:36 -04:00
|
|
|
#[cfg(test)]
|
2019-03-26 11:56:34 -04:00
|
|
|
pub mod tests {
|
2019-03-11 17:57:36 -04:00
|
|
|
use super::*;
|
2023-04-04 08:46:31 -04:00
|
|
|
use crate::ascii_str;
|
2021-05-03 11:30:41 -04:00
|
|
|
use crate::error::custom_error;
|
2022-03-14 13:44:15 -04:00
|
|
|
use crate::error::AnyError;
|
2023-04-04 08:46:31 -04:00
|
|
|
use crate::include_ascii_string;
|
2023-01-19 04:00:35 -05:00
|
|
|
use crate::modules::AssertedModuleType;
|
|
|
|
use crate::modules::ModuleInfo;
|
2021-11-22 07:51:20 -05:00
|
|
|
use crate::modules::ModuleSource;
|
2020-09-06 10:50:49 -04:00
|
|
|
use crate::modules::ModuleSourceFuture;
|
2021-12-15 13:22:36 -05:00
|
|
|
use crate::modules::ModuleType;
|
2023-01-10 08:35:44 -05:00
|
|
|
use crate::modules::ResolutionKind;
|
2023-01-19 04:00:35 -05:00
|
|
|
use crate::modules::SymbolicModule;
|
2021-05-06 13:32:03 -04:00
|
|
|
use crate::ZeroCopyBuf;
|
2022-03-14 13:44:15 -04:00
|
|
|
use deno_ops::op;
|
2019-04-14 21:58:27 -04:00
|
|
|
use futures::future::lazy;
|
|
|
|
use std::ops::FnOnce;
|
2021-10-09 16:37:19 -04:00
|
|
|
use std::pin::Pin;
|
2020-09-05 20:34:02 -04:00
|
|
|
use std::rc::Rc;
|
2023-01-14 23:18:58 -05:00
|
|
|
use std::sync::atomic::AtomicUsize;
|
|
|
|
use std::sync::atomic::Ordering;
|
2020-05-29 17:41:39 -04:00
|
|
|
use std::sync::Arc;
|
2023-01-19 04:00:35 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
// deno_ops macros generate code assuming deno_core in scope.
|
|
|
|
mod deno_core {
|
|
|
|
pub use crate::*;
|
|
|
|
}
|
2019-03-14 19:17:52 -04:00
|
|
|
|
2019-11-16 19:17:47 -05:00
|
|
|
pub fn run_in_task<F>(f: F)
|
2019-04-14 21:58:27 -04:00
|
|
|
where
|
2023-02-06 08:49:26 -05:00
|
|
|
F: FnOnce(&mut Context) + 'static,
|
2019-04-14 21:58:27 -04:00
|
|
|
{
|
2019-12-07 15:04:17 -05:00
|
|
|
futures::executor::block_on(lazy(move |cx| f(cx)));
|
2019-04-14 21:58:27 -04:00
|
|
|
}
|
|
|
|
|
2021-12-29 09:21:42 -05:00
|
|
|
#[derive(Copy, Clone)]
|
2023-03-17 14:22:15 -04:00
|
|
|
pub enum Mode {
|
2019-12-07 15:04:17 -05:00
|
|
|
Async,
|
2022-10-28 07:20:17 -04:00
|
|
|
AsyncDeferred,
|
2021-03-31 10:37:38 -04:00
|
|
|
AsyncZeroCopy(bool),
|
2019-03-14 19:17:52 -04:00
|
|
|
}
|
|
|
|
|
2020-09-10 09:57:45 -04:00
|
|
|
struct TestState {
|
2020-09-05 20:34:02 -04:00
|
|
|
mode: Mode,
|
|
|
|
dispatch_count: Arc<AtomicUsize>,
|
|
|
|
}
|
2019-10-02 13:05:48 -04:00
|
|
|
|
2022-10-28 07:20:17 -04:00
|
|
|
#[op]
|
2022-03-14 13:44:15 -04:00
|
|
|
async fn op_test(
|
|
|
|
rc_op_state: Rc<RefCell<OpState>>,
|
|
|
|
control: u8,
|
|
|
|
buf: Option<ZeroCopyBuf>,
|
|
|
|
) -> Result<u8, AnyError> {
|
2022-10-28 07:20:17 -04:00
|
|
|
#![allow(clippy::await_holding_refcell_ref)] // False positive.
|
2022-03-14 13:44:15 -04:00
|
|
|
let op_state_ = rc_op_state.borrow();
|
2020-09-10 09:57:45 -04:00
|
|
|
let test_state = op_state_.borrow::<TestState>();
|
|
|
|
test_state.dispatch_count.fetch_add(1, Ordering::Relaxed);
|
2022-10-28 07:20:17 -04:00
|
|
|
let mode = test_state.mode;
|
|
|
|
drop(op_state_);
|
|
|
|
match mode {
|
2020-09-10 09:57:45 -04:00
|
|
|
Mode::Async => {
|
2021-03-31 10:37:38 -04:00
|
|
|
assert_eq!(control, 42);
|
2022-03-14 13:44:15 -04:00
|
|
|
Ok(43)
|
2020-09-05 20:34:02 -04:00
|
|
|
}
|
2022-10-28 07:20:17 -04:00
|
|
|
Mode::AsyncDeferred => {
|
|
|
|
tokio::task::yield_now().await;
|
|
|
|
assert_eq!(control, 42);
|
|
|
|
Ok(43)
|
|
|
|
}
|
2021-03-31 10:37:38 -04:00
|
|
|
Mode::AsyncZeroCopy(has_buffer) => {
|
|
|
|
assert_eq!(buf.is_some(), has_buffer);
|
|
|
|
if let Some(buf) = buf {
|
2020-09-10 09:57:45 -04:00
|
|
|
assert_eq!(buf.len(), 1);
|
2021-03-31 10:37:38 -04:00
|
|
|
}
|
2022-03-14 13:44:15 -04:00
|
|
|
Ok(43)
|
2020-04-19 23:54:46 -04:00
|
|
|
}
|
2020-09-05 20:34:02 -04:00
|
|
|
}
|
|
|
|
}
|
2019-10-02 13:05:48 -04:00
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
fn setup(mode: Mode) -> (JsRuntime, Arc<AtomicUsize>) {
|
2020-09-05 20:34:02 -04:00
|
|
|
let dispatch_count = Arc::new(AtomicUsize::new(0));
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_test],
|
2023-03-17 18:15:27 -04:00
|
|
|
options = {
|
2023-03-17 14:22:15 -04:00
|
|
|
mode: Mode,
|
|
|
|
dispatch_count: Arc<AtomicUsize>,
|
|
|
|
},
|
2023-03-17 18:15:27 -04:00
|
|
|
state = |state, options| {
|
2021-12-29 09:21:42 -05:00
|
|
|
state.put(TestState {
|
2023-03-17 18:15:27 -04:00
|
|
|
mode: options.mode,
|
|
|
|
dispatch_count: options.dispatch_count
|
2023-03-17 14:22:15 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
);
|
2021-12-29 09:21:42 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops(mode, dispatch_count.clone())],
|
2022-06-07 05:25:10 -04:00
|
|
|
get_error_class_fn: Some(&|error| {
|
|
|
|
crate::error::get_custom_error_class(error).unwrap()
|
|
|
|
}),
|
2021-12-29 09:21:42 -05:00
|
|
|
..Default::default()
|
2020-09-05 20:34:02 -04:00
|
|
|
});
|
2020-09-10 09:57:45 -04:00
|
|
|
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"setup.js",
|
|
|
|
r#"
|
2019-04-23 18:58:00 -04:00
|
|
|
function assert(cond) {
|
|
|
|
if (!cond) {
|
|
|
|
throw Error("assert");
|
|
|
|
}
|
2019-03-14 19:17:52 -04:00
|
|
|
}
|
2019-04-23 18:58:00 -04:00
|
|
|
"#,
|
2020-09-22 17:30:03 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
2019-04-23 18:58:00 -04:00
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 0);
|
2020-09-06 15:44:29 -04:00
|
|
|
(runtime, dispatch_count)
|
2019-03-14 19:17:52 -04:00
|
|
|
}
|
2019-03-11 17:57:36 -04:00
|
|
|
|
2021-11-25 13:49:09 -05:00
|
|
|
#[test]
|
|
|
|
fn test_ref_unref_ops() {
|
2022-10-28 07:20:17 -04:00
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::AsyncDeferred);
|
2021-11-25 13:49:09 -05:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-25 13:49:09 -05:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2021-11-25 13:49:09 -05:00
|
|
|
var promiseIdSymbol = Symbol.for("Deno.core.internalPromiseId");
|
2023-02-23 14:50:15 -05:00
|
|
|
var p1 = Deno.core.opAsync("op_test", 42);
|
|
|
|
var p2 = Deno.core.opAsync("op_test", 42);
|
2021-11-25 13:49:09 -05:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
{
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let realm = runtime.global_realm();
|
2021-11-25 13:49:09 -05:00
|
|
|
let isolate = runtime.v8_isolate();
|
|
|
|
let state_rc = JsRuntime::state(isolate);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
assert_eq!(state_rc.borrow().pending_ops.len(), 2);
|
|
|
|
assert_eq!(realm.state(isolate).borrow().unrefed_ops.len(), 0);
|
2021-11-25 13:49:09 -05:00
|
|
|
}
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-25 13:49:09 -05:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_unref_op(p1[promiseIdSymbol]);
|
|
|
|
Deno.core.ops.op_unref_op(p2[promiseIdSymbol]);
|
2021-11-25 13:49:09 -05:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
{
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let realm = runtime.global_realm();
|
2021-11-25 13:49:09 -05:00
|
|
|
let isolate = runtime.v8_isolate();
|
|
|
|
let state_rc = JsRuntime::state(isolate);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
assert_eq!(state_rc.borrow().pending_ops.len(), 2);
|
|
|
|
assert_eq!(realm.state(isolate).borrow().unrefed_ops.len(), 2);
|
2021-11-25 13:49:09 -05:00
|
|
|
}
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-25 13:49:09 -05:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_ref_op(p1[promiseIdSymbol]);
|
|
|
|
Deno.core.ops.op_ref_op(p2[promiseIdSymbol]);
|
2021-11-25 13:49:09 -05:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
{
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let realm = runtime.global_realm();
|
2021-11-25 13:49:09 -05:00
|
|
|
let isolate = runtime.v8_isolate();
|
|
|
|
let state_rc = JsRuntime::state(isolate);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
assert_eq!(state_rc.borrow().pending_ops.len(), 2);
|
|
|
|
assert_eq!(realm.state(isolate).borrow().unrefed_ops.len(), 0);
|
2021-11-25 13:49:09 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-06 13:38:37 -04:00
|
|
|
#[test]
|
|
|
|
fn test_dispatch() {
|
|
|
|
let (mut runtime, dispatch_count) = setup(Mode::Async);
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-09-06 13:38:37 -04:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
|
|
|
let control = 42;
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2022-09-06 13:38:37 -04:00
|
|
|
Deno.core.opAsync("op_test", control);
|
|
|
|
async function main() {
|
|
|
|
Deno.core.opAsync("op_test", control);
|
|
|
|
}
|
|
|
|
main();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 2);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_op_async_promise_id() {
|
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::Async);
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-09-06 13:38:37 -04:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2022-09-06 13:38:37 -04:00
|
|
|
const p = Deno.core.opAsync("op_test", 42);
|
|
|
|
if (p[Symbol.for("Deno.core.internalPromiseId")] == undefined) {
|
|
|
|
throw new Error("missing id on returned promise");
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
2020-06-01 14:20:47 -04:00
|
|
|
#[test]
|
|
|
|
fn test_dispatch_no_zero_copy_buf() {
|
2021-03-31 10:37:38 -04:00
|
|
|
let (mut runtime, dispatch_count) = setup(Mode::AsyncZeroCopy(false));
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2021-04-30 21:08:29 -04:00
|
|
|
Deno.core.opAsync("op_test");
|
2020-06-01 14:20:47 -04:00
|
|
|
"#,
|
2020-09-22 17:30:03 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
2020-06-01 14:20:47 -04:00
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2020-07-08 11:23:50 -04:00
|
|
|
fn test_dispatch_stack_zero_copy_bufs() {
|
2021-03-31 10:37:38 -04:00
|
|
|
let (mut runtime, dispatch_count) = setup(Mode::AsyncZeroCopy(true));
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"filename.js",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2020-07-08 11:23:50 -04:00
|
|
|
let zero_copy_a = new Uint8Array([0]);
|
2023-03-31 11:58:21 -04:00
|
|
|
Deno.core.opAsync2("op_test", null, zero_copy_a);
|
2020-06-01 14:20:47 -04:00
|
|
|
"#,
|
2020-09-22 17:30:03 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
2020-06-01 14:20:47 -04:00
|
|
|
assert_eq!(dispatch_count.load(Ordering::Relaxed), 1);
|
|
|
|
}
|
|
|
|
|
2021-07-08 12:56:53 -04:00
|
|
|
#[test]
|
|
|
|
fn test_execute_script_return_value() {
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
2023-04-04 08:46:31 -04:00
|
|
|
let value_global =
|
|
|
|
runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
|
2021-07-08 12:56:53 -04:00
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
2021-10-27 17:26:15 -04:00
|
|
|
let value = value_global.open(scope);
|
2021-07-08 12:56:53 -04:00
|
|
|
assert_eq!(value.integer_value(scope).unwrap(), 3);
|
|
|
|
}
|
2023-04-04 08:46:31 -04:00
|
|
|
let value_global = runtime
|
|
|
|
.execute_script_static("b.js", "b = 'foobar'")
|
|
|
|
.unwrap();
|
2021-07-08 12:56:53 -04:00
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
2021-10-27 17:26:15 -04:00
|
|
|
let value = value_global.open(scope);
|
2021-07-08 12:56:53 -04:00
|
|
|
assert!(value.is_string());
|
|
|
|
assert_eq!(
|
|
|
|
value.to_string(scope).unwrap().to_rust_string_lossy(scope),
|
|
|
|
"foobar"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-24 11:59:41 -05:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_poll_value() {
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
run_in_task(move |cx| {
|
2022-01-24 11:59:41 -05:00
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "Promise.resolve(1 + 2)")
|
2022-01-24 11:59:41 -05:00
|
|
|
.unwrap();
|
|
|
|
let v = runtime.poll_value(&value_global, cx);
|
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
assert!(
|
|
|
|
matches!(v, Poll::Ready(Ok(v)) if v.open(scope).integer_value(scope).unwrap() == 3)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-01-24 11:59:41 -05:00
|
|
|
"a.js",
|
|
|
|
"Promise.resolve(new Promise(resolve => resolve(2 + 2)))",
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let v = runtime.poll_value(&value_global, cx);
|
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
assert!(
|
|
|
|
matches!(v, Poll::Ready(Ok(v)) if v.open(scope).integer_value(scope).unwrap() == 4)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "Promise.reject(new Error('fail'))")
|
2022-01-24 11:59:41 -05:00
|
|
|
.unwrap();
|
|
|
|
let v = runtime.poll_value(&value_global, cx);
|
|
|
|
assert!(
|
2022-04-13 10:41:39 -04:00
|
|
|
matches!(v, Poll::Ready(Err(e)) if e.downcast_ref::<JsError>().unwrap().exception_message == "Uncaught Error: fail")
|
2022-01-24 11:59:41 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "new Promise(resolve => {})")
|
2022-01-24 11:59:41 -05:00
|
|
|
.unwrap();
|
|
|
|
let v = runtime.poll_value(&value_global, cx);
|
|
|
|
matches!(v, Poll::Ready(Err(e)) if e.to_string() == "Promise resolution is still pending but the event loop has already resolved.");
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-09-04 14:19:26 -04:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_resolve_value() {
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "Promise.resolve(1 + 2)")
|
2021-09-04 14:19:26 -04:00
|
|
|
.unwrap();
|
|
|
|
let result_global = runtime.resolve_value(value_global).await.unwrap();
|
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
2021-10-27 17:26:15 -04:00
|
|
|
let value = result_global.open(scope);
|
2021-09-04 14:19:26 -04:00
|
|
|
assert_eq!(value.integer_value(scope).unwrap(), 3);
|
|
|
|
}
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-09-04 14:19:26 -04:00
|
|
|
"a.js",
|
|
|
|
"Promise.resolve(new Promise(resolve => resolve(2 + 2)))",
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let result_global = runtime.resolve_value(value_global).await.unwrap();
|
|
|
|
{
|
|
|
|
let scope = &mut runtime.handle_scope();
|
2021-10-27 17:26:15 -04:00
|
|
|
let value = result_global.open(scope);
|
2021-09-04 14:19:26 -04:00
|
|
|
assert_eq!(value.integer_value(scope).unwrap(), 4);
|
|
|
|
}
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "Promise.reject(new Error('fail'))")
|
2021-09-04 14:19:26 -04:00
|
|
|
.unwrap();
|
|
|
|
let err = runtime.resolve_value(value_global).await.unwrap_err();
|
|
|
|
assert_eq!(
|
|
|
|
"Uncaught Error: fail",
|
2022-04-13 10:41:39 -04:00
|
|
|
err.downcast::<JsError>().unwrap().exception_message
|
2021-09-04 14:19:26 -04:00
|
|
|
);
|
|
|
|
|
|
|
|
let value_global = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("a.js", "new Promise(resolve => {})")
|
2021-09-04 14:19:26 -04:00
|
|
|
.unwrap();
|
|
|
|
let error_string = runtime
|
|
|
|
.resolve_value(value_global)
|
|
|
|
.await
|
|
|
|
.unwrap_err()
|
|
|
|
.to_string();
|
|
|
|
assert_eq!(
|
|
|
|
"Promise resolution is still pending but the event loop has already resolved.",
|
|
|
|
error_string,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-07-01 03:51:29 -04:00
|
|
|
#[test]
|
|
|
|
fn terminate_execution_webassembly() {
|
2022-07-07 10:28:29 -04:00
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::Async);
|
|
|
|
let v8_isolate_handle = runtime.v8_isolate().thread_safe_handle();
|
2022-07-01 03:51:29 -04:00
|
|
|
|
|
|
|
// Run an infinite loop in Webassemby code, which should be terminated.
|
2023-04-04 08:46:31 -04:00
|
|
|
let promise = runtime.execute_script_static("infinite_wasm_loop.js",
|
2022-07-01 03:51:29 -04:00
|
|
|
r#"
|
|
|
|
(async () => {
|
|
|
|
const wasmCode = new Uint8Array([
|
|
|
|
0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1,
|
|
|
|
96, 0, 0, 3, 2, 1, 0, 7, 17, 1, 13,
|
|
|
|
105, 110, 102, 105, 110, 105, 116, 101, 95, 108, 111,
|
|
|
|
111, 112, 0, 0, 10, 9, 1, 7, 0, 3, 64,
|
|
|
|
12, 0, 11, 11,
|
|
|
|
]);
|
|
|
|
const wasmModule = await WebAssembly.compile(wasmCode);
|
2022-07-07 10:28:29 -04:00
|
|
|
globalThis.wasmInstance = new WebAssembly.Instance(wasmModule);
|
|
|
|
})()
|
|
|
|
"#).unwrap();
|
|
|
|
futures::executor::block_on(runtime.resolve_value(promise)).unwrap();
|
|
|
|
let terminator_thread = std::thread::spawn(move || {
|
|
|
|
std::thread::sleep(std::time::Duration::from_millis(1000));
|
|
|
|
|
|
|
|
// terminate execution
|
|
|
|
let ok = v8_isolate_handle.terminate_execution();
|
|
|
|
assert!(ok);
|
|
|
|
});
|
|
|
|
let err = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-07-07 10:28:29 -04:00
|
|
|
"infinite_wasm_loop2.js",
|
|
|
|
"globalThis.wasmInstance.exports.infinite_loop();",
|
|
|
|
)
|
|
|
|
.unwrap_err();
|
|
|
|
assert_eq!(err.to_string(), "Uncaught Error: execution terminated");
|
2022-07-01 03:51:29 -04:00
|
|
|
// Cancel the execution-terminating exception in order to allow script
|
|
|
|
// execution again.
|
2022-07-07 10:28:29 -04:00
|
|
|
let ok = runtime.v8_isolate().cancel_terminate_execution();
|
2022-07-01 03:51:29 -04:00
|
|
|
assert!(ok);
|
|
|
|
|
|
|
|
// Verify that the isolate usable again.
|
2022-07-07 10:28:29 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("simple.js", "1 + 1")
|
2022-07-01 03:51:29 -04:00
|
|
|
.expect("execution should be possible again");
|
|
|
|
|
|
|
|
terminator_thread.join().unwrap();
|
|
|
|
}
|
|
|
|
|
2019-03-21 09:48:19 -04:00
|
|
|
#[test]
|
|
|
|
fn terminate_execution() {
|
2019-12-07 15:04:17 -05:00
|
|
|
let (mut isolate, _dispatch_count) = setup(Mode::Async);
|
2020-10-05 05:08:19 -04:00
|
|
|
let v8_isolate_handle = isolate.v8_isolate().thread_safe_handle();
|
2019-03-21 09:48:19 -04:00
|
|
|
|
2020-02-24 18:53:29 -05:00
|
|
|
let terminator_thread = std::thread::spawn(move || {
|
2019-03-21 09:48:19 -04:00
|
|
|
// allow deno to boot and run
|
|
|
|
std::thread::sleep(std::time::Duration::from_millis(100));
|
|
|
|
|
|
|
|
// terminate execution
|
2020-02-24 18:53:29 -05:00
|
|
|
let ok = v8_isolate_handle.terminate_execution();
|
2020-02-27 19:27:24 -05:00
|
|
|
assert!(ok);
|
2019-03-21 09:48:19 -04:00
|
|
|
});
|
|
|
|
|
2020-02-24 18:53:29 -05:00
|
|
|
// Rn an infinite loop, which should be terminated.
|
2023-04-04 08:46:31 -04:00
|
|
|
match isolate.execute_script_static("infinite_loop.js", "for(;;) {}") {
|
2020-02-24 18:53:29 -05:00
|
|
|
Ok(_) => panic!("execution should be terminated"),
|
|
|
|
Err(e) => {
|
2020-10-31 14:57:19 -04:00
|
|
|
assert_eq!(e.to_string(), "Uncaught Error: execution terminated")
|
2020-02-24 18:53:29 -05:00
|
|
|
}
|
|
|
|
};
|
2019-03-21 09:48:19 -04:00
|
|
|
|
2020-02-24 18:53:29 -05:00
|
|
|
// Cancel the execution-terminating exception in order to allow script
|
|
|
|
// execution again.
|
2020-12-28 10:36:44 -05:00
|
|
|
let ok = isolate.v8_isolate().cancel_terminate_execution();
|
2020-02-24 18:53:29 -05:00
|
|
|
assert!(ok);
|
|
|
|
|
|
|
|
// Verify that the isolate usable again.
|
|
|
|
isolate
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("simple.js", "1 + 1")
|
2020-02-24 18:53:29 -05:00
|
|
|
.expect("execution should be possible again");
|
2019-03-21 09:48:19 -04:00
|
|
|
|
2020-02-24 18:53:29 -05:00
|
|
|
terminator_thread.join().unwrap();
|
2019-03-21 09:48:19 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn dangling_shared_isolate() {
|
2020-02-24 18:53:29 -05:00
|
|
|
let v8_isolate_handle = {
|
2019-03-21 09:48:19 -04:00
|
|
|
// isolate is dropped at the end of this block
|
2020-09-06 15:44:29 -04:00
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::Async);
|
2020-10-05 05:08:19 -04:00
|
|
|
runtime.v8_isolate().thread_safe_handle()
|
2019-03-21 09:48:19 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
// this should not SEGFAULT
|
2020-02-24 18:53:29 -05:00
|
|
|
v8_isolate_handle.terminate_execution();
|
2019-03-21 09:48:19 -04:00
|
|
|
}
|
|
|
|
|
2020-04-16 06:58:17 -04:00
|
|
|
#[test]
|
|
|
|
fn syntax_error() {
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
2020-04-16 06:58:17 -04:00
|
|
|
let src = "hocuspocus(";
|
2023-04-04 08:46:31 -04:00
|
|
|
let r = runtime.execute_script_static("i.js", src);
|
2020-04-16 06:58:17 -04:00
|
|
|
let e = r.unwrap_err();
|
2020-09-06 15:44:29 -04:00
|
|
|
let js_error = e.downcast::<JsError>().unwrap();
|
2022-04-15 10:08:09 -04:00
|
|
|
let frame = js_error.frames.first().unwrap();
|
|
|
|
assert_eq!(frame.column_number, Some(12));
|
2020-04-16 06:58:17 -04:00
|
|
|
}
|
|
|
|
|
2020-03-15 10:31:55 -04:00
|
|
|
#[test]
|
|
|
|
fn test_encode_decode() {
|
2023-02-06 08:49:26 -05:00
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::Async);
|
|
|
|
run_in_task(move |cx| {
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2020-09-22 17:30:03 -04:00
|
|
|
"encode_decode_test.js",
|
2023-03-21 18:33:12 -04:00
|
|
|
// Note: We make this to_owned because it contains non-ASCII chars
|
2023-04-04 08:46:31 -04:00
|
|
|
include_str!("encode_decode_test.js").to_owned().into(),
|
2020-09-22 17:30:03 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
2021-12-04 08:19:06 -05:00
|
|
|
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
|
2020-03-15 10:31:55 -04:00
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-02-16 08:20:21 -05:00
|
|
|
#[test]
|
|
|
|
fn test_serialize_deserialize() {
|
2023-02-06 08:49:26 -05:00
|
|
|
let (mut runtime, _dispatch_count) = setup(Mode::Async);
|
|
|
|
run_in_task(move |cx| {
|
2021-02-16 08:20:21 -05:00
|
|
|
runtime
|
2021-06-21 19:45:41 -04:00
|
|
|
.execute_script(
|
2021-02-16 08:20:21 -05:00
|
|
|
"serialize_deserialize_test.js",
|
2023-04-04 08:46:31 -04:00
|
|
|
include_ascii_string!("serialize_deserialize_test.js"),
|
2021-02-16 08:20:21 -05:00
|
|
|
)
|
|
|
|
.unwrap();
|
2021-12-04 08:19:06 -05:00
|
|
|
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
|
2021-02-16 08:20:21 -05:00
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2021-05-03 11:30:41 -04:00
|
|
|
#[test]
|
|
|
|
fn test_error_builder() {
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
fn op_err() -> Result<(), Error> {
|
2021-05-03 11:30:41 -04:00
|
|
|
Err(custom_error("DOMExceptionOperationError", "abc"))
|
|
|
|
}
|
|
|
|
|
2021-11-16 09:02:28 -05:00
|
|
|
pub fn get_error_class_name(_: &Error) -> &'static str {
|
2021-05-03 11:30:41 -04:00
|
|
|
"DOMExceptionOperationError"
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_err]);
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2023-02-06 08:49:26 -05:00
|
|
|
get_error_class_fn: Some(&get_error_class_name),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
run_in_task(move |cx| {
|
2021-05-03 11:30:41 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-05-03 11:30:41 -04:00
|
|
|
"error_builder_test.js",
|
|
|
|
include_str!("error_builder_test.js"),
|
|
|
|
)
|
|
|
|
.unwrap();
|
2021-12-04 08:19:06 -05:00
|
|
|
if let Poll::Ready(Err(_)) = runtime.poll_event_loop(cx, false) {
|
2021-05-03 11:30:41 -04:00
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-04-24 21:43:06 -04:00
|
|
|
#[test]
|
|
|
|
fn will_snapshot() {
|
|
|
|
let snapshot = {
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
2023-04-04 08:46:31 -04:00
|
|
|
runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
|
2020-09-06 15:44:29 -04:00
|
|
|
runtime.snapshot()
|
2019-04-24 21:43:06 -04:00
|
|
|
};
|
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
let snapshot = Snapshot::JustCreated(snapshot);
|
|
|
|
let mut runtime2 = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(snapshot),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime2
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check.js", "if (a != 3) throw Error('x')")
|
2020-09-22 17:30:03 -04:00
|
|
|
.unwrap();
|
2019-04-24 21:43:06 -04:00
|
|
|
}
|
2022-10-28 15:31:01 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn will_snapshot2() {
|
|
|
|
let startup_data = {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
2023-04-04 08:46:31 -04:00
|
|
|
runtime
|
|
|
|
.execute_script_static("a.js", "let a = 1 + 2")
|
|
|
|
.unwrap();
|
2022-10-28 15:31:01 -04:00
|
|
|
runtime.snapshot()
|
|
|
|
};
|
|
|
|
|
|
|
|
let snapshot = Snapshot::JustCreated(startup_data);
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
startup_snapshot: Some(snapshot),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let startup_data = {
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check_a.js", "if (a != 3) throw Error('x')")
|
2022-10-28 15:31:01 -04:00
|
|
|
.unwrap();
|
2023-04-04 08:46:31 -04:00
|
|
|
runtime.execute_script_static("b.js", "b = 2 + 3").unwrap();
|
2022-10-28 15:31:01 -04:00
|
|
|
runtime.snapshot()
|
|
|
|
};
|
|
|
|
|
|
|
|
let snapshot = Snapshot::JustCreated(startup_data);
|
|
|
|
{
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(snapshot),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check_b.js", "if (b != 5) throw Error('x')")
|
2022-10-28 15:31:01 -04:00
|
|
|
.unwrap();
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check2.js", "if (!Deno.core) throw Error('x')")
|
2022-10-28 15:31:01 -04:00
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-21 15:03:56 -04:00
|
|
|
#[test]
|
|
|
|
fn test_snapshot_callbacks() {
|
|
|
|
let snapshot = {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-08-21 15:03:56 -04:00
|
|
|
"a.js",
|
|
|
|
r#"
|
2023-04-13 20:41:32 -04:00
|
|
|
Deno.core.setMacrotaskCallback(() => {
|
2022-08-21 15:03:56 -04:00
|
|
|
return true;
|
|
|
|
});
|
|
|
|
Deno.core.ops.op_set_format_exception_callback(()=> {
|
|
|
|
return null;
|
|
|
|
})
|
|
|
|
Deno.core.setPromiseRejectCallback(() => {
|
|
|
|
return false;
|
|
|
|
});
|
2022-09-02 06:43:39 -04:00
|
|
|
a = 1 + 2;
|
2022-08-21 15:03:56 -04:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
runtime.snapshot()
|
|
|
|
};
|
|
|
|
|
|
|
|
let snapshot = Snapshot::JustCreated(snapshot);
|
|
|
|
let mut runtime2 = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(snapshot),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime2
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check.js", "if (a != 3) throw Error('x')")
|
2022-08-21 15:03:56 -04:00
|
|
|
.unwrap();
|
|
|
|
}
|
2020-05-09 21:00:40 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_from_boxed_snapshot() {
|
|
|
|
let snapshot = {
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
2023-04-04 08:46:31 -04:00
|
|
|
runtime.execute_script_static("a.js", "a = 1 + 2").unwrap();
|
2022-11-17 20:59:10 -05:00
|
|
|
let snap: &[u8] = &runtime.snapshot();
|
2020-05-09 21:00:40 -04:00
|
|
|
Vec::from(snap).into_boxed_slice()
|
|
|
|
};
|
|
|
|
|
2020-09-11 09:18:49 -04:00
|
|
|
let snapshot = Snapshot::Boxed(snapshot);
|
|
|
|
let mut runtime2 = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(snapshot),
|
|
|
|
..Default::default()
|
|
|
|
});
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime2
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("check.js", "if (a != 3) throw Error('x')")
|
2020-09-22 17:30:03 -04:00
|
|
|
.unwrap();
|
2020-05-09 21:00:40 -04:00
|
|
|
}
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2022-03-22 09:32:32 -04:00
|
|
|
#[test]
|
|
|
|
fn test_get_module_namespace() {
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2023-01-10 08:35:44 -05:00
|
|
|
_kind: ResolutionKind,
|
2022-03-22 09:32:32 -04:00
|
|
|
) -> Result<ModuleSpecifier, Error> {
|
|
|
|
assert_eq!(specifier, "file:///main.js");
|
|
|
|
assert_eq!(referrer, ".");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
2023-04-04 08:46:31 -04:00
|
|
|
_maybe_referrer: Option<&ModuleSpecifier>,
|
2022-03-22 09:32:32 -04:00
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
async { Err(generic_error("Module loading is not supported")) }
|
|
|
|
.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let loader = std::rc::Rc::new(ModsLoader::default());
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let specifier = crate::resolve_url("file:///main.js").unwrap();
|
2023-04-04 08:46:31 -04:00
|
|
|
let source_code = ascii_str!(
|
|
|
|
r#"
|
2022-03-22 09:32:32 -04:00
|
|
|
export const a = "b";
|
|
|
|
export default 1 + 2;
|
|
|
|
"#
|
2023-04-04 08:46:31 -04:00
|
|
|
);
|
2022-03-22 09:32:32 -04:00
|
|
|
|
|
|
|
let module_id = futures::executor::block_on(
|
|
|
|
runtime.load_main_module(&specifier, Some(source_code)),
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
2023-01-27 10:43:16 -05:00
|
|
|
#[allow(clippy::let_underscore_future)]
|
2022-03-22 09:32:32 -04:00
|
|
|
let _ = runtime.mod_evaluate(module_id);
|
|
|
|
|
|
|
|
let module_namespace = runtime.get_module_namespace(module_id).unwrap();
|
|
|
|
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
|
|
|
|
let module_namespace =
|
|
|
|
v8::Local::<v8::Object>::new(scope, module_namespace);
|
|
|
|
|
|
|
|
assert!(module_namespace.is_module_namespace_object());
|
|
|
|
|
|
|
|
let unknown_export_name = v8::String::new(scope, "none").unwrap();
|
|
|
|
let binding = module_namespace.get(scope, unknown_export_name.into());
|
|
|
|
|
|
|
|
assert!(binding.is_some());
|
|
|
|
assert!(binding.unwrap().is_undefined());
|
|
|
|
|
|
|
|
let empty_export_name = v8::String::new(scope, "").unwrap();
|
|
|
|
let binding = module_namespace.get(scope, empty_export_name.into());
|
|
|
|
|
|
|
|
assert!(binding.is_some());
|
|
|
|
assert!(binding.unwrap().is_undefined());
|
|
|
|
|
|
|
|
let a_export_name = v8::String::new(scope, "a").unwrap();
|
|
|
|
let binding = module_namespace.get(scope, a_export_name.into());
|
|
|
|
|
|
|
|
assert!(binding.unwrap().is_string());
|
|
|
|
assert_eq!(binding.unwrap(), v8::String::new(scope, "b").unwrap());
|
|
|
|
|
|
|
|
let default_export_name = v8::String::new(scope, "default").unwrap();
|
|
|
|
let binding = module_namespace.get(scope, default_export_name.into());
|
|
|
|
|
|
|
|
assert!(binding.unwrap().is_number());
|
|
|
|
assert_eq!(binding.unwrap(), v8::Number::new(scope, 3_f64));
|
|
|
|
}
|
|
|
|
|
2020-08-11 21:07:14 -04:00
|
|
|
#[test]
|
|
|
|
fn test_heap_limits() {
|
2021-07-02 06:18:30 -04:00
|
|
|
let create_params =
|
2023-04-26 04:02:03 -04:00
|
|
|
v8::Isolate::create_params().heap_limits(0, 5 * 1024 * 1024);
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2020-10-17 05:56:15 -04:00
|
|
|
create_params: Some(create_params),
|
2020-09-11 09:18:49 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
2020-10-07 09:56:52 -04:00
|
|
|
let cb_handle = runtime.v8_isolate().thread_safe_handle();
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
let callback_invoke_count = Rc::new(AtomicUsize::new(0));
|
2020-08-11 21:07:14 -04:00
|
|
|
let inner_invoke_count = Rc::clone(&callback_invoke_count);
|
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
runtime.add_near_heap_limit_callback(
|
2020-08-11 21:07:14 -04:00
|
|
|
move |current_limit, _initial_limit| {
|
|
|
|
inner_invoke_count.fetch_add(1, Ordering::SeqCst);
|
|
|
|
cb_handle.terminate_execution();
|
|
|
|
current_limit * 2
|
|
|
|
},
|
|
|
|
);
|
2020-09-06 15:44:29 -04:00
|
|
|
let err = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-08-11 21:07:14 -04:00
|
|
|
"script name",
|
|
|
|
r#"let s = ""; while(true) { s += "Hello"; }"#,
|
|
|
|
)
|
|
|
|
.expect_err("script should fail");
|
|
|
|
assert_eq!(
|
|
|
|
"Uncaught Error: execution terminated",
|
2022-04-13 10:41:39 -04:00
|
|
|
err.downcast::<JsError>().unwrap().exception_message
|
2020-08-11 21:07:14 -04:00
|
|
|
);
|
|
|
|
assert!(callback_invoke_count.load(Ordering::SeqCst) > 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_heap_limit_cb_remove() {
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
2020-08-11 21:07:14 -04:00
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
runtime.add_near_heap_limit_callback(|current_limit, _initial_limit| {
|
2020-08-11 21:07:14 -04:00
|
|
|
current_limit * 2
|
|
|
|
});
|
2021-07-02 06:18:30 -04:00
|
|
|
runtime.remove_near_heap_limit_callback(3 * 1024 * 1024);
|
2020-09-06 15:44:29 -04:00
|
|
|
assert!(runtime.allocations.near_heap_limit_callback_data.is_none());
|
2020-08-11 21:07:14 -04:00
|
|
|
}
|
2020-08-12 00:08:50 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_heap_limit_cb_multiple() {
|
2021-07-02 06:18:30 -04:00
|
|
|
let create_params =
|
2023-04-26 04:02:03 -04:00
|
|
|
v8::Isolate::create_params().heap_limits(0, 5 * 1024 * 1024);
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2020-10-17 05:56:15 -04:00
|
|
|
create_params: Some(create_params),
|
2020-09-11 09:18:49 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
2020-10-07 09:56:52 -04:00
|
|
|
let cb_handle = runtime.v8_isolate().thread_safe_handle();
|
2020-08-12 00:08:50 -04:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
let callback_invoke_count_first = Rc::new(AtomicUsize::new(0));
|
2020-08-12 00:08:50 -04:00
|
|
|
let inner_invoke_count_first = Rc::clone(&callback_invoke_count_first);
|
2020-09-06 15:44:29 -04:00
|
|
|
runtime.add_near_heap_limit_callback(
|
2020-08-12 00:08:50 -04:00
|
|
|
move |current_limit, _initial_limit| {
|
|
|
|
inner_invoke_count_first.fetch_add(1, Ordering::SeqCst);
|
|
|
|
current_limit * 2
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
let callback_invoke_count_second = Rc::new(AtomicUsize::new(0));
|
2020-08-12 00:08:50 -04:00
|
|
|
let inner_invoke_count_second = Rc::clone(&callback_invoke_count_second);
|
2020-09-06 15:44:29 -04:00
|
|
|
runtime.add_near_heap_limit_callback(
|
2020-08-12 00:08:50 -04:00
|
|
|
move |current_limit, _initial_limit| {
|
|
|
|
inner_invoke_count_second.fetch_add(1, Ordering::SeqCst);
|
|
|
|
cb_handle.terminate_execution();
|
|
|
|
current_limit * 2
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2020-09-06 15:44:29 -04:00
|
|
|
let err = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-08-12 00:08:50 -04:00
|
|
|
"script name",
|
|
|
|
r#"let s = ""; while(true) { s += "Hello"; }"#,
|
|
|
|
)
|
|
|
|
.expect_err("script should fail");
|
|
|
|
assert_eq!(
|
|
|
|
"Uncaught Error: execution terminated",
|
2022-04-13 10:41:39 -04:00
|
|
|
err.downcast::<JsError>().unwrap().exception_message
|
2020-08-12 00:08:50 -04:00
|
|
|
);
|
|
|
|
assert_eq!(0, callback_invoke_count_first.load(Ordering::SeqCst));
|
|
|
|
assert!(callback_invoke_count_second.load(Ordering::SeqCst) > 0);
|
|
|
|
}
|
2020-09-06 10:50:49 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn es_snapshot() {
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2023-01-10 08:35:44 -05:00
|
|
|
_kind: ResolutionKind,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<ModuleSpecifier, Error> {
|
2021-02-17 13:47:18 -05:00
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
2020-09-06 10:50:49 -04:00
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
2023-04-04 08:46:31 -04:00
|
|
|
_maybe_referrer: Option<&ModuleSpecifier>,
|
2020-09-06 10:50:49 -04:00
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
2023-01-19 04:00:35 -05:00
|
|
|
eprintln!("load() should not be called");
|
2020-09-06 10:50:49 -04:00
|
|
|
unreachable!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
fn create_module(
|
|
|
|
runtime: &mut JsRuntime,
|
|
|
|
i: usize,
|
|
|
|
main: bool,
|
|
|
|
) -> ModuleInfo {
|
|
|
|
let specifier = crate::resolve_url(&format!("file:///{i}.js")).unwrap();
|
|
|
|
let prev = i - 1;
|
|
|
|
let source_code = format!(
|
|
|
|
r#"
|
|
|
|
import {{ f{prev} }} from "file:///{prev}.js";
|
|
|
|
export function f{i}() {{ return f{prev}() }}
|
|
|
|
"#
|
2023-03-21 18:33:12 -04:00
|
|
|
)
|
|
|
|
.into();
|
2023-01-19 04:00:35 -05:00
|
|
|
|
|
|
|
let id = if main {
|
|
|
|
futures::executor::block_on(
|
|
|
|
runtime.load_main_module(&specifier, Some(source_code)),
|
|
|
|
)
|
|
|
|
.unwrap()
|
|
|
|
} else {
|
|
|
|
futures::executor::block_on(
|
|
|
|
runtime.load_side_module(&specifier, Some(source_code)),
|
|
|
|
)
|
|
|
|
.unwrap()
|
|
|
|
};
|
2023-01-19 07:47:41 -05:00
|
|
|
assert_eq!(i, id);
|
2023-01-19 04:00:35 -05:00
|
|
|
|
2023-01-27 10:43:16 -05:00
|
|
|
#[allow(clippy::let_underscore_future)]
|
2023-01-19 04:00:35 -05:00
|
|
|
let _ = runtime.mod_evaluate(id);
|
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
|
|
|
|
|
|
|
ModuleInfo {
|
|
|
|
id,
|
|
|
|
main,
|
2023-04-04 08:46:31 -04:00
|
|
|
name: specifier.into(),
|
2023-01-19 04:00:35 -05:00
|
|
|
requests: vec![crate::modules::ModuleRequest {
|
2023-02-21 15:12:22 -05:00
|
|
|
specifier: format!("file:///{prev}.js"),
|
2023-01-19 04:00:35 -05:00
|
|
|
asserted_module_type: AssertedModuleType::JavaScriptOrWasm,
|
|
|
|
}],
|
|
|
|
module_type: ModuleType::JavaScript,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn assert_module_map(runtime: &mut JsRuntime, modules: &Vec<ModuleInfo>) {
|
|
|
|
let module_map_rc = runtime.get_module_map();
|
|
|
|
let module_map = module_map_rc.borrow();
|
2023-01-19 07:47:41 -05:00
|
|
|
assert_eq!(module_map.handles.len(), modules.len());
|
2023-01-19 04:00:35 -05:00
|
|
|
assert_eq!(module_map.info.len(), modules.len());
|
2023-04-04 08:46:31 -04:00
|
|
|
assert_eq!(
|
|
|
|
module_map.by_name(AssertedModuleType::Json).len()
|
|
|
|
+ module_map
|
|
|
|
.by_name(AssertedModuleType::JavaScriptOrWasm)
|
|
|
|
.len(),
|
|
|
|
modules.len()
|
|
|
|
);
|
2023-01-19 04:00:35 -05:00
|
|
|
|
2023-01-19 07:47:41 -05:00
|
|
|
assert_eq!(module_map.next_load_id, (modules.len() + 1) as ModuleLoadId);
|
2023-01-19 04:00:35 -05:00
|
|
|
|
|
|
|
for info in modules {
|
2023-01-19 07:47:41 -05:00
|
|
|
assert!(module_map.handles.get(info.id).is_some());
|
|
|
|
assert_eq!(module_map.info.get(info.id).unwrap(), info);
|
2023-01-19 04:00:35 -05:00
|
|
|
assert_eq!(
|
|
|
|
module_map
|
2023-04-04 08:46:31 -04:00
|
|
|
.by_name(AssertedModuleType::JavaScriptOrWasm)
|
|
|
|
.get(&info.name)
|
2023-01-19 04:00:35 -05:00
|
|
|
.unwrap(),
|
|
|
|
&SymbolicModule::Mod(info.id)
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-18 18:30:04 -04:00
|
|
|
#[op]
|
|
|
|
fn op_test() -> Result<String, Error> {
|
|
|
|
Ok(String::from("test"))
|
|
|
|
}
|
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
let loader = Rc::new(ModsLoader::default());
|
2020-09-11 09:18:49 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-01-19 04:00:35 -05:00
|
|
|
module_loader: Some(loader.clone()),
|
2020-09-11 09:18:49 -04:00
|
|
|
will_snapshot: true,
|
2023-03-18 18:30:04 -04:00
|
|
|
extensions: vec![Extension::builder("text_ext")
|
|
|
|
.ops(vec![op_test::decl()])
|
|
|
|
.build()],
|
2020-09-11 09:18:49 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
let specifier = crate::resolve_url("file:///0.js").unwrap();
|
2023-04-04 08:46:31 -04:00
|
|
|
let source_code =
|
|
|
|
ascii_str!(r#"export function f0() { return "hello world" }"#);
|
2023-01-19 04:00:35 -05:00
|
|
|
let id = futures::executor::block_on(
|
|
|
|
runtime.load_side_module(&specifier, Some(source_code)),
|
2020-09-06 10:50:49 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
2023-01-27 10:43:16 -05:00
|
|
|
#[allow(clippy::let_underscore_future)]
|
2023-01-19 04:00:35 -05:00
|
|
|
let _ = runtime.mod_evaluate(id);
|
2021-05-26 15:07:12 -04:00
|
|
|
futures::executor::block_on(runtime.run_event_loop(false)).unwrap();
|
2020-09-06 10:50:49 -04:00
|
|
|
|
2023-01-19 04:00:35 -05:00
|
|
|
let mut modules = vec![];
|
|
|
|
modules.push(ModuleInfo {
|
|
|
|
id,
|
|
|
|
main: false,
|
2023-04-04 08:46:31 -04:00
|
|
|
name: specifier.into(),
|
2023-01-19 04:00:35 -05:00
|
|
|
requests: vec![],
|
|
|
|
module_type: ModuleType::JavaScript,
|
|
|
|
});
|
|
|
|
|
|
|
|
modules.extend((1..200).map(|i| create_module(&mut runtime, i, false)));
|
|
|
|
|
|
|
|
assert_module_map(&mut runtime, &modules);
|
|
|
|
|
|
|
|
let snapshot = runtime.snapshot();
|
|
|
|
|
|
|
|
let mut runtime2 = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader.clone()),
|
|
|
|
will_snapshot: true,
|
|
|
|
startup_snapshot: Some(Snapshot::JustCreated(snapshot)),
|
2023-03-18 18:30:04 -04:00
|
|
|
extensions: vec![Extension::builder("text_ext")
|
|
|
|
.ops(vec![op_test::decl()])
|
|
|
|
.build()],
|
2023-01-19 04:00:35 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_module_map(&mut runtime2, &modules);
|
|
|
|
|
|
|
|
modules.extend((200..400).map(|i| create_module(&mut runtime2, i, false)));
|
|
|
|
modules.push(create_module(&mut runtime2, 400, true));
|
|
|
|
|
|
|
|
assert_module_map(&mut runtime2, &modules);
|
|
|
|
|
|
|
|
let snapshot2 = runtime2.snapshot();
|
|
|
|
|
|
|
|
let mut runtime3 = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
startup_snapshot: Some(Snapshot::JustCreated(snapshot2)),
|
2023-03-18 18:30:04 -04:00
|
|
|
extensions: vec![Extension::builder("text_ext")
|
|
|
|
.ops(vec![op_test::decl()])
|
|
|
|
.build()],
|
2023-01-19 04:00:35 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
assert_module_map(&mut runtime3, &modules);
|
|
|
|
|
|
|
|
let source_code = r#"(async () => {
|
|
|
|
const mod = await import("file:///400.js");
|
2023-03-18 18:30:04 -04:00
|
|
|
return mod.f400() + " " + Deno.core.ops.op_test();
|
2023-04-04 08:46:31 -04:00
|
|
|
})();"#;
|
|
|
|
let val = runtime3.execute_script_static(".", source_code).unwrap();
|
2023-01-19 04:00:35 -05:00
|
|
|
let val = futures::executor::block_on(runtime3.resolve_value(val)).unwrap();
|
|
|
|
{
|
|
|
|
let scope = &mut runtime3.handle_scope();
|
|
|
|
let value = v8::Local::new(scope, val);
|
|
|
|
let str_ = value.to_string(scope).unwrap().to_rust_string_lossy(scope);
|
2023-03-18 18:30:04 -04:00
|
|
|
assert_eq!(str_, "hello world test");
|
2023-01-19 04:00:35 -05:00
|
|
|
}
|
2020-09-06 10:50:49 -04:00
|
|
|
}
|
2020-09-22 17:30:03 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_error_without_stack() {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
// SyntaxError
|
2023-04-04 08:46:31 -04:00
|
|
|
let result = runtime.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"error_without_stack.js",
|
|
|
|
r#"
|
|
|
|
function main() {
|
|
|
|
console.log("asdf);
|
|
|
|
}
|
|
|
|
main();
|
|
|
|
"#,
|
|
|
|
);
|
|
|
|
let expected_error = r#"Uncaught SyntaxError: Invalid or unexpected token
|
2022-04-15 10:08:09 -04:00
|
|
|
at error_without_stack.js:3:15"#;
|
2020-09-22 17:30:03 -04:00
|
|
|
assert_eq!(result.unwrap_err().to_string(), expected_error);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_error_stack() {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
2023-04-04 08:46:31 -04:00
|
|
|
let result = runtime.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"error_stack.js",
|
|
|
|
r#"
|
|
|
|
function assert(cond) {
|
|
|
|
if (!cond) {
|
|
|
|
throw Error("assert");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
function main() {
|
|
|
|
assert(false);
|
|
|
|
}
|
|
|
|
main();
|
|
|
|
"#,
|
|
|
|
);
|
|
|
|
let expected_error = r#"Error: assert
|
|
|
|
at assert (error_stack.js:4:11)
|
2022-10-28 07:20:17 -04:00
|
|
|
at main (error_stack.js:8:3)
|
|
|
|
at error_stack.js:10:1"#;
|
2020-09-22 17:30:03 -04:00
|
|
|
assert_eq!(result.unwrap_err().to_string(), expected_error);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_error_async_stack() {
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
run_in_task(move |cx| {
|
2020-09-22 17:30:03 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-09-22 17:30:03 -04:00
|
|
|
"error_async_stack.js",
|
|
|
|
r#"
|
|
|
|
(async () => {
|
|
|
|
const p = (async () => {
|
|
|
|
await Promise.resolve().then(() => {
|
|
|
|
throw new Error("async");
|
|
|
|
});
|
|
|
|
})();
|
|
|
|
try {
|
|
|
|
await p;
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error.stack);
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
})();"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let expected_error = r#"Error: async
|
|
|
|
at error_async_stack.js:5:13
|
|
|
|
at async error_async_stack.js:4:5
|
2022-10-28 07:20:17 -04:00
|
|
|
at async error_async_stack.js:9:5"#;
|
2020-09-22 17:30:03 -04:00
|
|
|
|
2021-05-26 15:07:12 -04:00
|
|
|
match runtime.poll_event_loop(cx, false) {
|
2020-09-22 17:30:03 -04:00
|
|
|
Poll::Ready(Err(e)) => {
|
|
|
|
assert_eq!(e.to_string(), expected_error);
|
|
|
|
}
|
|
|
|
_ => panic!(),
|
|
|
|
};
|
|
|
|
})
|
|
|
|
}
|
2020-12-07 18:36:15 -05:00
|
|
|
|
2022-10-26 11:30:44 -04:00
|
|
|
#[test]
|
|
|
|
fn test_error_context() {
|
|
|
|
use anyhow::anyhow;
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_err_sync() -> Result<(), Error> {
|
|
|
|
Err(anyhow!("original sync error").context("higher-level sync error"))
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
async fn op_err_async() -> Result<(), Error> {
|
|
|
|
Err(anyhow!("original async error").context("higher-level async error"))
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_err_sync, op_err_async]);
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2023-02-06 08:49:26 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
2022-10-26 11:30:44 -04:00
|
|
|
|
2023-02-06 08:49:26 -05:00
|
|
|
run_in_task(move |cx| {
|
2022-10-26 11:30:44 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-10-26 11:30:44 -04:00
|
|
|
"test_error_context_sync.js",
|
|
|
|
r#"
|
|
|
|
let errMessage;
|
|
|
|
try {
|
|
|
|
Deno.core.ops.op_err_sync();
|
|
|
|
} catch (err) {
|
|
|
|
errMessage = err.message;
|
|
|
|
}
|
|
|
|
if (errMessage !== "higher-level sync error: original sync error") {
|
|
|
|
throw new Error("unexpected error message from op_err_sync: " + errMessage);
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let promise = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-10-26 11:30:44 -04:00
|
|
|
"test_error_context_async.js",
|
|
|
|
r#"
|
2023-02-23 14:50:15 -05:00
|
|
|
|
2022-10-26 11:30:44 -04:00
|
|
|
(async () => {
|
|
|
|
let errMessage;
|
|
|
|
try {
|
|
|
|
await Deno.core.opAsync("op_err_async");
|
|
|
|
} catch (err) {
|
|
|
|
errMessage = err.message;
|
|
|
|
}
|
|
|
|
if (errMessage !== "higher-level async error: original async error") {
|
|
|
|
throw new Error("unexpected error message from op_err_async: " + errMessage);
|
|
|
|
}
|
|
|
|
})()
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
match runtime.poll_value(&promise, cx) {
|
|
|
|
Poll::Ready(Ok(_)) => {}
|
2023-01-27 10:43:16 -05:00
|
|
|
Poll::Ready(Err(err)) => panic!("{err:?}"),
|
2022-10-26 11:30:44 -04:00
|
|
|
_ => panic!(),
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-07-02 04:46:37 -04:00
|
|
|
#[test]
|
|
|
|
fn test_pump_message_loop() {
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
run_in_task(move |cx| {
|
2021-07-02 04:46:37 -04:00
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-07-02 04:46:37 -04:00
|
|
|
"pump_message_loop.js",
|
|
|
|
r#"
|
|
|
|
function assertEquals(a, b) {
|
|
|
|
if (a === b) return;
|
|
|
|
throw a + " does not equal " + b;
|
|
|
|
}
|
|
|
|
const sab = new SharedArrayBuffer(16);
|
|
|
|
const i32a = new Int32Array(sab);
|
|
|
|
globalThis.resolved = false;
|
|
|
|
(function() {
|
|
|
|
const result = Atomics.waitAsync(i32a, 0, 0);
|
|
|
|
result.value.then(
|
|
|
|
(value) => { assertEquals("ok", value); globalThis.resolved = true; },
|
|
|
|
() => { assertUnreachable();
|
|
|
|
});
|
|
|
|
})();
|
|
|
|
const notify_return_value = Atomics.notify(i32a, 0, 1);
|
|
|
|
assertEquals(1, notify_return_value);
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
match runtime.poll_event_loop(cx, false) {
|
|
|
|
Poll::Ready(Ok(())) => {}
|
|
|
|
_ => panic!(),
|
|
|
|
};
|
|
|
|
|
|
|
|
// noop script, will resolve promise from first script
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
|
|
|
"pump_message_loop2.js",
|
|
|
|
r#"assertEquals(1, 1);"#,
|
|
|
|
)
|
2021-07-02 04:46:37 -04:00
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
// check that promise from `Atomics.waitAsync` has been resolved
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-07-02 04:46:37 -04:00
|
|
|
"pump_message_loop3.js",
|
|
|
|
r#"assertEquals(globalThis.resolved, true);"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-12-07 18:36:15 -05:00
|
|
|
#[test]
|
|
|
|
fn test_core_js_stack_frame() {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
// Call non-existent op so we get error from `core.js`
|
|
|
|
let error = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2020-12-07 18:36:15 -05:00
|
|
|
"core_js_stack_frame.js",
|
2022-08-11 09:56:56 -04:00
|
|
|
"Deno.core.opAsync('non_existent');",
|
2020-12-07 18:36:15 -05:00
|
|
|
)
|
|
|
|
.unwrap_err();
|
|
|
|
let error_string = error.to_string();
|
2023-03-08 06:44:54 -05:00
|
|
|
// Test that the script specifier is a URL: `ext:<repo-relative path>`.
|
|
|
|
assert!(error_string.contains("ext:core/01_core.js"));
|
2020-12-07 18:36:15 -05:00
|
|
|
}
|
2021-04-12 06:15:04 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_v8_platform() {
|
|
|
|
let options = RuntimeOptions {
|
2021-07-02 03:32:48 -04:00
|
|
|
v8_platform: Some(v8::new_default_platform(0, false).make_shared()),
|
2021-04-12 06:15:04 -04:00
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
let mut runtime = JsRuntime::new(options);
|
2023-04-04 08:46:31 -04:00
|
|
|
runtime.execute_script_static("<none>", "").unwrap();
|
2021-04-12 06:15:04 -04:00
|
|
|
}
|
2021-10-01 14:25:33 -04:00
|
|
|
|
2022-08-30 05:01:36 -04:00
|
|
|
#[ignore] // TODO(@littledivy): Fast API ops when snapshot is not loaded.
|
2021-10-01 14:25:33 -04:00
|
|
|
#[test]
|
|
|
|
fn test_is_proxy() {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
let all_true: v8::Global<v8::Value> = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-10-01 14:25:33 -04:00
|
|
|
"is_proxy.js",
|
|
|
|
r#"
|
|
|
|
(function () {
|
|
|
|
const o = { a: 1, b: 2};
|
|
|
|
const p = new Proxy(o, {});
|
2022-08-11 09:56:56 -04:00
|
|
|
return Deno.core.ops.op_is_proxy(p) && !Deno.core.ops.op_is_proxy(o) && !Deno.core.ops.op_is_proxy(42);
|
2021-10-01 14:25:33 -04:00
|
|
|
})()
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
let mut scope = runtime.handle_scope();
|
|
|
|
let all_true = v8::Local::<v8::Value>::new(&mut scope, &all_true);
|
|
|
|
assert!(all_true.is_true());
|
|
|
|
}
|
2021-10-05 16:55:51 -04:00
|
|
|
|
2021-10-24 13:30:55 -04:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_async_opstate_borrow() {
|
|
|
|
struct InnerState(u64);
|
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2021-10-24 13:30:55 -04:00
|
|
|
async fn op_async_borrow(
|
|
|
|
op_state: Rc<RefCell<OpState>>,
|
2021-11-16 09:02:28 -05:00
|
|
|
) -> Result<(), Error> {
|
2021-11-03 09:27:36 -04:00
|
|
|
let n = {
|
|
|
|
let op_state = op_state.borrow();
|
|
|
|
let inner_state = op_state.borrow::<InnerState>();
|
|
|
|
inner_state.0
|
|
|
|
};
|
2021-10-24 13:30:55 -04:00
|
|
|
// Future must be Poll::Pending on first call
|
|
|
|
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
|
2021-11-03 09:27:36 -04:00
|
|
|
if n != 42 {
|
2021-10-24 13:30:55 -04:00
|
|
|
unreachable!();
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_async_borrow],
|
|
|
|
state = |state| state.put(InnerState(42))
|
|
|
|
);
|
2021-10-24 13:30:55 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2021-10-24 13:30:55 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-10-24 13:30:55 -04:00
|
|
|
"op_async_borrow.js",
|
2023-02-23 14:50:15 -05:00
|
|
|
"Deno.core.opAsync(\"op_async_borrow\")",
|
2021-10-24 13:30:55 -04:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
}
|
2021-11-16 14:23:12 -05:00
|
|
|
|
2022-10-02 16:18:31 -04:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_sync_op_serialize_object_with_numbers_as_keys() {
|
|
|
|
#[op]
|
|
|
|
fn op_sync_serialize_object_with_numbers_as_keys(
|
|
|
|
value: serde_json::Value,
|
|
|
|
) -> Result<(), Error> {
|
|
|
|
assert_eq!(
|
|
|
|
value.to_string(),
|
|
|
|
r#"{"lines":{"100":{"unit":"m"},"200":{"unit":"cm"}}}"#
|
|
|
|
);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_sync_serialize_object_with_numbers_as_keys]
|
|
|
|
);
|
2022-10-02 16:18:31 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-10-02 16:18:31 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-10-02 16:18:31 -04:00
|
|
|
"op_sync_serialize_object_with_numbers_as_keys.js",
|
|
|
|
r#"
|
|
|
|
Deno.core.ops.op_sync_serialize_object_with_numbers_as_keys({
|
|
|
|
lines: {
|
|
|
|
100: {
|
|
|
|
unit: "m"
|
|
|
|
},
|
|
|
|
200: {
|
|
|
|
unit: "cm"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_async_op_serialize_object_with_numbers_as_keys() {
|
|
|
|
#[op]
|
|
|
|
async fn op_async_serialize_object_with_numbers_as_keys(
|
|
|
|
value: serde_json::Value,
|
|
|
|
) -> Result<(), Error> {
|
|
|
|
assert_eq!(
|
|
|
|
value.to_string(),
|
|
|
|
r#"{"lines":{"100":{"unit":"m"},"200":{"unit":"cm"}}}"#
|
|
|
|
);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_async_serialize_object_with_numbers_as_keys]
|
|
|
|
);
|
2022-10-02 16:18:31 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-10-02 16:18:31 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-10-02 16:18:31 -04:00
|
|
|
"op_async_serialize_object_with_numbers_as_keys.js",
|
|
|
|
r#"
|
2023-02-23 14:50:15 -05:00
|
|
|
|
|
|
|
Deno.core.opAsync("op_async_serialize_object_with_numbers_as_keys", {
|
2022-10-02 16:18:31 -04:00
|
|
|
lines: {
|
|
|
|
100: {
|
|
|
|
unit: "m"
|
|
|
|
},
|
|
|
|
200: {
|
|
|
|
unit: "cm"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
}
|
|
|
|
|
2021-11-16 14:23:12 -05:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_set_macrotask_callback_set_next_tick_callback() {
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
async fn op_async_sleep() -> Result<(), Error> {
|
2021-11-16 14:23:12 -05:00
|
|
|
// Future must be Poll::Pending on first call
|
|
|
|
tokio::time::sleep(std::time::Duration::from_millis(1)).await;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_async_sleep]);
|
2021-11-16 14:23:12 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2021-11-16 14:23:12 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-16 14:23:12 -05:00
|
|
|
"macrotasks_and_nextticks.js",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2021-11-16 14:23:12 -05:00
|
|
|
(async function () {
|
|
|
|
const results = [];
|
2023-04-13 20:41:32 -04:00
|
|
|
Deno.core.setMacrotaskCallback(() => {
|
2021-11-16 14:23:12 -05:00
|
|
|
results.push("macrotask");
|
|
|
|
return true;
|
|
|
|
});
|
2023-04-13 20:41:32 -04:00
|
|
|
Deno.core.setNextTickCallback(() => {
|
2021-11-16 14:23:12 -05:00
|
|
|
results.push("nextTick");
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_set_has_tick_scheduled(false);
|
2021-11-16 14:23:12 -05:00
|
|
|
});
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_set_has_tick_scheduled(true);
|
2021-11-16 14:23:12 -05:00
|
|
|
await Deno.core.opAsync('op_async_sleep');
|
|
|
|
if (results[0] != "nextTick") {
|
|
|
|
throw new Error(`expected nextTick, got: ${results[0]}`);
|
|
|
|
}
|
|
|
|
if (results[1] != "macrotask") {
|
|
|
|
throw new Error(`expected macrotask, got: ${results[1]}`);
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
}
|
|
|
|
|
2021-11-29 18:31:12 -05:00
|
|
|
#[test]
|
|
|
|
fn test_has_tick_scheduled() {
|
|
|
|
use futures::task::ArcWake;
|
2021-11-19 08:01:30 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
static MACROTASK: AtomicUsize = AtomicUsize::new(0);
|
|
|
|
static NEXT_TICK: AtomicUsize = AtomicUsize::new(0);
|
2021-11-19 08:01:30 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
fn op_macrotask() -> Result<(), AnyError> {
|
2022-03-14 13:44:15 -04:00
|
|
|
MACROTASK.fetch_add(1, Ordering::Relaxed);
|
2021-11-29 18:31:12 -05:00
|
|
|
Ok(())
|
2022-03-14 13:44:15 -04:00
|
|
|
}
|
2021-11-19 08:01:30 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
fn op_next_tick() -> Result<(), AnyError> {
|
2022-03-14 13:44:15 -04:00
|
|
|
NEXT_TICK.fetch_add(1, Ordering::Relaxed);
|
2021-11-29 18:31:12 -05:00
|
|
|
Ok(())
|
2022-03-14 13:44:15 -04:00
|
|
|
}
|
2021-11-19 08:01:30 -05:00
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_macrotask, op_next_tick]);
|
2021-11-29 18:31:12 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2021-11-29 18:31:12 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-29 18:31:12 -05:00
|
|
|
"has_tick_scheduled.js",
|
|
|
|
r#"
|
2023-04-13 20:41:32 -04:00
|
|
|
Deno.core.setMacrotaskCallback(() => {
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_macrotask();
|
2021-11-19 08:01:30 -05:00
|
|
|
return true; // We're done.
|
|
|
|
});
|
2023-04-13 20:41:32 -04:00
|
|
|
Deno.core.setNextTickCallback(() => Deno.core.ops.op_next_tick());
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_set_has_tick_scheduled(true);
|
2021-11-19 08:01:30 -05:00
|
|
|
"#,
|
2021-11-29 18:31:12 -05:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
struct ArcWakeImpl(Arc<AtomicUsize>);
|
|
|
|
impl ArcWake for ArcWakeImpl {
|
|
|
|
fn wake_by_ref(arc_self: &Arc<Self>) {
|
|
|
|
arc_self.0.fetch_add(1, Ordering::Relaxed);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let awoken_times = Arc::new(AtomicUsize::new(0));
|
|
|
|
let waker =
|
|
|
|
futures::task::waker(Arc::new(ArcWakeImpl(awoken_times.clone())));
|
|
|
|
let cx = &mut Context::from_waker(&waker);
|
|
|
|
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
2022-03-14 13:44:15 -04:00
|
|
|
assert_eq!(1, MACROTASK.load(Ordering::Relaxed));
|
|
|
|
assert_eq!(1, NEXT_TICK.load(Ordering::Relaxed));
|
2021-11-29 18:31:12 -05:00
|
|
|
assert_eq!(awoken_times.swap(0, Ordering::Relaxed), 1);
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
|
|
|
assert_eq!(awoken_times.swap(0, Ordering::Relaxed), 1);
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
|
|
|
assert_eq!(awoken_times.swap(0, Ordering::Relaxed), 1);
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
|
|
|
assert_eq!(awoken_times.swap(0, Ordering::Relaxed), 1);
|
|
|
|
|
|
|
|
let state_rc = JsRuntime::state(runtime.v8_isolate());
|
|
|
|
state_rc.borrow_mut().has_tick_scheduled = false;
|
|
|
|
assert!(matches!(
|
|
|
|
runtime.poll_event_loop(cx, false),
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
));
|
|
|
|
assert_eq!(awoken_times.load(Ordering::Relaxed), 0);
|
|
|
|
assert!(matches!(
|
|
|
|
runtime.poll_event_loop(cx, false),
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
));
|
|
|
|
assert_eq!(awoken_times.load(Ordering::Relaxed), 0);
|
2021-11-19 08:01:30 -05:00
|
|
|
}
|
2021-11-22 07:51:20 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn terminate_during_module_eval() {
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2023-01-10 08:35:44 -05:00
|
|
|
_kind: ResolutionKind,
|
2021-11-22 07:51:20 -05:00
|
|
|
) -> Result<ModuleSpecifier, Error> {
|
|
|
|
assert_eq!(specifier, "file:///main.js");
|
|
|
|
assert_eq!(referrer, ".");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
2023-04-04 08:46:31 -04:00
|
|
|
_maybe_referrer: Option<&ModuleSpecifier>,
|
2021-11-22 07:51:20 -05:00
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
|
|
|
async move {
|
2023-04-04 08:46:31 -04:00
|
|
|
Ok(ModuleSource::for_test(
|
|
|
|
"console.log('hello world');",
|
|
|
|
"file:///main.js",
|
|
|
|
))
|
2021-11-22 07:51:20 -05:00
|
|
|
}
|
|
|
|
.boxed_local()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let loader = std::rc::Rc::new(ModsLoader::default());
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(loader),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let specifier = crate::resolve_url("file:///main.js").unwrap();
|
2023-04-04 08:46:31 -04:00
|
|
|
let source_code = ascii_str!("Deno.core.print('hello\\n')");
|
2021-11-22 07:51:20 -05:00
|
|
|
|
|
|
|
let module_id = futures::executor::block_on(
|
|
|
|
runtime.load_main_module(&specifier, Some(source_code)),
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
runtime.v8_isolate().terminate_execution();
|
|
|
|
|
|
|
|
let mod_result =
|
|
|
|
futures::executor::block_on(runtime.mod_evaluate(module_id)).unwrap();
|
|
|
|
assert!(mod_result
|
|
|
|
.unwrap_err()
|
|
|
|
.to_string()
|
|
|
|
.contains("JavaScript execution has been terminated"));
|
|
|
|
}
|
2021-11-27 18:46:12 -05:00
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn test_set_promise_reject_callback() {
|
2022-03-14 13:44:15 -04:00
|
|
|
static PROMISE_REJECT: AtomicUsize = AtomicUsize::new(0);
|
2021-11-27 18:46:12 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
#[op]
|
2022-03-15 19:33:46 -04:00
|
|
|
fn op_promise_reject() -> Result<(), AnyError> {
|
2022-03-14 13:44:15 -04:00
|
|
|
PROMISE_REJECT.fetch_add(1, Ordering::Relaxed);
|
2021-11-27 18:46:12 -05:00
|
|
|
Ok(())
|
2022-03-14 13:44:15 -04:00
|
|
|
}
|
2021-11-27 18:46:12 -05:00
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_promise_reject]);
|
2021-11-27 18:46:12 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2021-11-27 18:46:12 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-27 18:46:12 -05:00
|
|
|
"promise_reject_callback.js",
|
|
|
|
r#"
|
|
|
|
// Note: |promise| is not the promise created below, it's a child.
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_set_promise_reject_callback((type, promise, reason) => {
|
2021-11-27 18:46:12 -05:00
|
|
|
if (type !== /* PromiseRejectWithNoHandler */ 0) {
|
|
|
|
throw Error("unexpected type: " + type);
|
|
|
|
}
|
|
|
|
if (reason.message !== "reject") {
|
|
|
|
throw Error("unexpected reason: " + reason);
|
|
|
|
}
|
2023-01-16 10:19:04 -05:00
|
|
|
Deno.core.ops.op_store_pending_promise_rejection(promise);
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_promise_reject();
|
2021-11-27 18:46:12 -05:00
|
|
|
});
|
|
|
|
new Promise((_, reject) => reject(Error("reject")));
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2022-07-24 19:10:56 -04:00
|
|
|
runtime.run_event_loop(false).await.unwrap_err();
|
2021-11-27 18:46:12 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
assert_eq!(1, PROMISE_REJECT.load(Ordering::Relaxed));
|
2021-11-27 18:46:12 -05:00
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2021-11-27 18:46:12 -05:00
|
|
|
"promise_reject_callback.js",
|
|
|
|
r#"
|
|
|
|
{
|
2022-08-11 09:56:56 -04:00
|
|
|
const prev = Deno.core.ops.op_set_promise_reject_callback((...args) => {
|
2021-11-27 18:46:12 -05:00
|
|
|
prev(...args);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
new Promise((_, reject) => reject(Error("reject")));
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2022-07-24 19:10:56 -04:00
|
|
|
runtime.run_event_loop(false).await.unwrap_err();
|
2021-11-27 18:46:12 -05:00
|
|
|
|
2022-03-14 13:44:15 -04:00
|
|
|
assert_eq!(2, PROMISE_REJECT.load(Ordering::Relaxed));
|
2021-11-27 18:46:12 -05:00
|
|
|
}
|
2022-03-19 10:59:44 -04:00
|
|
|
|
2023-01-14 22:39:00 -05:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_set_promise_reject_callback_realms() {
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions::default());
|
|
|
|
let global_realm = runtime.global_realm();
|
|
|
|
let realm1 = runtime.create_realm().unwrap();
|
|
|
|
let realm2 = runtime.create_realm().unwrap();
|
|
|
|
|
|
|
|
let realm_expectations = &[
|
|
|
|
(&global_realm, "global_realm", 42),
|
|
|
|
(&realm1, "realm1", 140),
|
|
|
|
(&realm2, "realm2", 720),
|
|
|
|
];
|
|
|
|
|
|
|
|
// Set up promise reject callbacks.
|
|
|
|
for (realm, realm_name, number) in realm_expectations {
|
|
|
|
realm
|
|
|
|
.execute_script(
|
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
2023-03-21 18:33:12 -04:00
|
|
|
format!(
|
2023-01-14 22:39:00 -05:00
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2023-01-14 22:39:00 -05:00
|
|
|
globalThis.rejectValue = undefined;
|
|
|
|
Deno.core.setPromiseRejectCallback((_type, _promise, reason) => {{
|
|
|
|
globalThis.rejectValue = `{realm_name}/${{reason}}`;
|
|
|
|
}});
|
2023-02-23 14:50:15 -05:00
|
|
|
Deno.core.opAsync("op_void_async").then(() => Promise.reject({number}));
|
2023-01-27 10:43:16 -05:00
|
|
|
"#
|
2023-04-04 08:46:31 -04:00
|
|
|
).into()
|
2023-01-14 22:39:00 -05:00
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
|
|
|
|
for (realm, realm_name, number) in realm_expectations {
|
|
|
|
let reject_value = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
"globalThis.rejectValue",
|
|
|
|
)
|
2023-01-14 22:39:00 -05:00
|
|
|
.unwrap();
|
|
|
|
let scope = &mut realm.handle_scope(runtime.v8_isolate());
|
|
|
|
let reject_value = v8::Local::new(scope, reject_value);
|
|
|
|
assert!(reject_value.is_string());
|
|
|
|
let reject_value_string = reject_value.to_rust_string_lossy(scope);
|
2023-01-27 10:43:16 -05:00
|
|
|
assert_eq!(reject_value_string, format!("{realm_name}/{number}"));
|
2023-01-14 22:39:00 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-18 15:20:38 -04:00
|
|
|
#[tokio::test]
|
|
|
|
async fn test_set_promise_reject_callback_top_level_await() {
|
|
|
|
static PROMISE_REJECT: AtomicUsize = AtomicUsize::new(0);
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_promise_reject() -> Result<(), AnyError> {
|
|
|
|
PROMISE_REJECT.fetch_add(1, Ordering::Relaxed);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_promise_reject]);
|
2022-07-18 15:20:38 -04:00
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
2023-01-10 08:35:44 -05:00
|
|
|
_kind: ResolutionKind,
|
2022-07-18 15:20:38 -04:00
|
|
|
) -> Result<ModuleSpecifier, Error> {
|
|
|
|
assert_eq!(specifier, "file:///main.js");
|
|
|
|
assert_eq!(referrer, ".");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
2023-04-04 08:46:31 -04:00
|
|
|
_maybe_referrer: Option<&ModuleSpecifier>,
|
2022-07-18 15:20:38 -04:00
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
2023-04-04 08:46:31 -04:00
|
|
|
let code = r#"
|
2022-08-11 09:56:56 -04:00
|
|
|
Deno.core.ops.op_set_promise_reject_callback((type, promise, reason) => {
|
|
|
|
Deno.core.ops.op_promise_reject();
|
2022-07-18 15:20:38 -04:00
|
|
|
});
|
|
|
|
throw new Error('top level throw');
|
|
|
|
"#;
|
|
|
|
|
2023-04-04 08:46:31 -04:00
|
|
|
async move { Ok(ModuleSource::for_test(code, "file:///main.js")) }
|
|
|
|
.boxed_local()
|
2022-07-18 15:20:38 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-07-18 15:20:38 -04:00
|
|
|
module_loader: Some(Rc::new(ModsLoader)),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let id = runtime
|
|
|
|
.load_main_module(&crate::resolve_url("file:///main.js").unwrap(), None)
|
|
|
|
.await
|
|
|
|
.unwrap();
|
|
|
|
let receiver = runtime.mod_evaluate(id);
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
2022-07-24 19:10:56 -04:00
|
|
|
receiver.await.unwrap().unwrap_err();
|
2022-07-18 15:20:38 -04:00
|
|
|
|
|
|
|
assert_eq!(1, PROMISE_REJECT.load(Ordering::Relaxed));
|
|
|
|
}
|
|
|
|
|
2022-03-19 10:59:44 -04:00
|
|
|
#[test]
|
|
|
|
fn test_op_return_serde_v8_error() {
|
|
|
|
#[op]
|
|
|
|
fn op_err() -> Result<std::collections::BTreeMap<u64, u64>, anyhow::Error> {
|
|
|
|
Ok([(1, 2), (3, 4)].into_iter().collect()) // Maps can't have non-string keys in serde_v8
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_err]);
|
2022-03-19 10:59:44 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-03-19 10:59:44 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
assert!(runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-03-19 10:59:44 -04:00
|
|
|
"test_op_return_serde_v8_error.js",
|
2022-08-11 09:56:56 -04:00
|
|
|
"Deno.core.ops.op_err()"
|
2022-03-19 10:59:44 -04:00
|
|
|
)
|
|
|
|
.is_err());
|
|
|
|
}
|
2022-03-21 13:04:57 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_op_high_arity() {
|
|
|
|
#[op]
|
|
|
|
fn op_add_4(
|
|
|
|
x1: i64,
|
|
|
|
x2: i64,
|
|
|
|
x3: i64,
|
|
|
|
x4: i64,
|
|
|
|
) -> Result<i64, anyhow::Error> {
|
|
|
|
Ok(x1 + x2 + x3 + x4)
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_add_4]);
|
2022-03-21 13:04:57 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-03-21 13:04:57 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
let r = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("test.js", "Deno.core.ops.op_add_4(1, 2, 3, 4)")
|
2022-03-21 13:04:57 -04:00
|
|
|
.unwrap();
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
assert_eq!(r.open(scope).integer_value(scope), Some(10));
|
|
|
|
}
|
2022-03-22 11:39:58 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_op_disabled() {
|
|
|
|
#[op]
|
|
|
|
fn op_foo() -> Result<i64, anyhow::Error> {
|
|
|
|
Ok(42)
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
fn ops() -> Vec<OpDecl> {
|
|
|
|
vec![op_foo::decl().disable()]
|
|
|
|
}
|
|
|
|
|
|
|
|
deno_core::extension!(test_ext, ops_fn = ops);
|
2022-03-22 11:39:58 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-03-22 11:39:58 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
2023-04-21 09:22:45 -04:00
|
|
|
let err = runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static("test.js", "Deno.core.ops.op_foo()")
|
2023-04-21 09:22:45 -04:00
|
|
|
.unwrap_err();
|
|
|
|
assert!(err
|
|
|
|
.to_string()
|
|
|
|
.contains("TypeError: Deno.core.ops.op_foo is not a function"));
|
2022-03-22 11:39:58 -04:00
|
|
|
}
|
2022-04-01 18:09:21 -04:00
|
|
|
|
2022-04-02 07:35:57 -04:00
|
|
|
#[test]
|
|
|
|
fn test_op_detached_buffer() {
|
|
|
|
use serde_v8::DetachedBuffer;
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_sum_take(b: DetachedBuffer) -> Result<u64, anyhow::Error> {
|
|
|
|
Ok(b.as_ref().iter().clone().map(|x| *x as u64).sum())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_boomerang(
|
|
|
|
b: DetachedBuffer,
|
|
|
|
) -> Result<DetachedBuffer, anyhow::Error> {
|
|
|
|
Ok(b)
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_sum_take, op_boomerang]);
|
2022-04-02 07:35:57 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-04-02 07:35:57 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-04-02 07:35:57 -04:00
|
|
|
"test.js",
|
|
|
|
r#"
|
|
|
|
const a1 = new Uint8Array([1,2,3]);
|
|
|
|
const a1b = a1.subarray(0, 3);
|
|
|
|
const a2 = new Uint8Array([5,10,15]);
|
|
|
|
const a2b = a2.subarray(0, 3);
|
|
|
|
if (!(a1.length > 0 && a1b.length > 0)) {
|
|
|
|
throw new Error("a1 & a1b should have a length");
|
|
|
|
}
|
2022-08-11 09:56:56 -04:00
|
|
|
let sum = Deno.core.ops.op_sum_take(a1b);
|
2022-04-02 07:35:57 -04:00
|
|
|
if (sum !== 6) {
|
|
|
|
throw new Error(`Bad sum: ${sum}`);
|
|
|
|
}
|
|
|
|
if (a1.length > 0 || a1b.length > 0) {
|
|
|
|
throw new Error("expecting a1 & a1b to be detached");
|
|
|
|
}
|
2022-08-11 09:56:56 -04:00
|
|
|
const a3 = Deno.core.ops.op_boomerang(a2b);
|
2022-04-02 07:35:57 -04:00
|
|
|
if (a3.byteLength != 3) {
|
|
|
|
throw new Error(`Expected a3.byteLength === 3, got ${a3.byteLength}`);
|
|
|
|
}
|
|
|
|
if (a3[0] !== 5 || a3[1] !== 10) {
|
|
|
|
throw new Error(`Invalid a3: ${a3[0]}, ${a3[1]}`);
|
|
|
|
}
|
|
|
|
if (a2.byteLength > 0 || a2b.byteLength > 0) {
|
|
|
|
throw new Error("expecting a2 & a2b to be detached, a3 re-attached");
|
|
|
|
}
|
|
|
|
const wmem = new WebAssembly.Memory({ initial: 1, maximum: 2 });
|
|
|
|
const w32 = new Uint32Array(wmem.buffer);
|
|
|
|
w32[0] = 1; w32[1] = 2; w32[2] = 3;
|
|
|
|
const assertWasmThrow = (() => {
|
|
|
|
try {
|
2022-08-11 09:56:56 -04:00
|
|
|
let sum = Deno.core.ops.op_sum_take(w32.subarray(0, 2));
|
2022-04-02 07:35:57 -04:00
|
|
|
return false;
|
|
|
|
} catch(e) {
|
2023-04-26 20:12:39 -04:00
|
|
|
return e.message.includes('invalid type; expected: detachable');
|
2022-04-02 07:35:57 -04:00
|
|
|
}
|
|
|
|
});
|
|
|
|
if (!assertWasmThrow()) {
|
|
|
|
throw new Error("expected wasm mem to not be detachable");
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
|
2022-04-01 18:09:21 -04:00
|
|
|
#[test]
|
|
|
|
fn test_op_unstable_disabling() {
|
|
|
|
#[op]
|
|
|
|
fn op_foo() -> Result<i64, anyhow::Error> {
|
|
|
|
Ok(42)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[op(unstable)]
|
|
|
|
fn op_bar() -> Result<i64, anyhow::Error> {
|
|
|
|
Ok(42)
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_foo, op_bar],
|
|
|
|
middleware = |op| if op.is_unstable { op.disable() } else { op }
|
|
|
|
);
|
2022-04-01 18:09:21 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-04-01 18:09:21 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-04-01 18:09:21 -04:00
|
|
|
"test.js",
|
|
|
|
r#"
|
2022-08-11 09:56:56 -04:00
|
|
|
if (Deno.core.ops.op_foo() !== 42) {
|
2022-04-01 18:09:21 -04:00
|
|
|
throw new Error("Exptected op_foo() === 42");
|
|
|
|
}
|
2023-04-21 09:22:45 -04:00
|
|
|
if (typeof Deno.core.ops.op_bar !== "undefined") {
|
2022-04-01 18:09:21 -04:00
|
|
|
throw new Error("Expected op_bar to be disabled")
|
|
|
|
}
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
}
|
2022-04-17 07:53:08 -04:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn js_realm_simple() {
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
let main_context = runtime.global_context();
|
|
|
|
let main_global = {
|
|
|
|
let scope = &mut runtime.handle_scope();
|
|
|
|
let local_global = main_context.open(scope).global(scope);
|
|
|
|
v8::Global::new(scope, local_global)
|
|
|
|
};
|
|
|
|
|
|
|
|
let realm = runtime.create_realm().unwrap();
|
|
|
|
assert_ne!(realm.context(), &main_context);
|
2022-07-05 18:45:10 -04:00
|
|
|
assert_ne!(realm.global_object(runtime.v8_isolate()), main_global);
|
2022-04-17 07:53:08 -04:00
|
|
|
|
2023-04-04 08:46:31 -04:00
|
|
|
let main_object = runtime.execute_script_static("", "Object").unwrap();
|
2022-07-05 18:45:10 -04:00
|
|
|
let realm_object = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(runtime.v8_isolate(), "", "Object")
|
2022-07-05 18:45:10 -04:00
|
|
|
.unwrap();
|
2022-04-17 07:53:08 -04:00
|
|
|
assert_ne!(main_object, realm_object);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn js_realm_init() {
|
|
|
|
#[op]
|
|
|
|
fn op_test() -> Result<String, Error> {
|
|
|
|
Ok(String::from("Test"))
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_test]);
|
2022-04-17 07:53:08 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-04-17 07:53:08 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
let realm = runtime.create_realm().unwrap();
|
|
|
|
let ret = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
"Deno.core.ops.op_test()",
|
|
|
|
)
|
2022-04-17 07:53:08 -04:00
|
|
|
.unwrap();
|
|
|
|
|
2022-07-05 18:45:10 -04:00
|
|
|
let scope = &mut realm.handle_scope(runtime.v8_isolate());
|
2022-04-17 07:53:08 -04:00
|
|
|
assert_eq!(ret, serde_v8::to_v8(scope, "Test").unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn js_realm_init_snapshot() {
|
|
|
|
let snapshot = {
|
2022-10-14 19:53:13 -04:00
|
|
|
let runtime = JsRuntime::new(RuntimeOptions {
|
2022-04-17 07:53:08 -04:00
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
2022-11-17 20:59:10 -05:00
|
|
|
let snap: &[u8] = &runtime.snapshot();
|
2022-04-17 07:53:08 -04:00
|
|
|
Vec::from(snap).into_boxed_slice()
|
|
|
|
};
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_test() -> Result<String, Error> {
|
|
|
|
Ok(String::from("Test"))
|
|
|
|
}
|
|
|
|
|
2023-03-18 18:30:04 -04:00
|
|
|
deno_core::extension!(
|
|
|
|
test_ext,
|
|
|
|
ops = [op_test],
|
|
|
|
customizer = |ext: &mut deno_core::ExtensionBuilder| {
|
|
|
|
ext.force_op_registration();
|
|
|
|
},
|
|
|
|
);
|
2022-04-17 07:53:08 -04:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
startup_snapshot: Some(Snapshot::Boxed(snapshot)),
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2022-04-17 07:53:08 -04:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
let realm = runtime.create_realm().unwrap();
|
|
|
|
let ret = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
"Deno.core.ops.op_test()",
|
|
|
|
)
|
2022-04-17 07:53:08 -04:00
|
|
|
.unwrap();
|
|
|
|
|
2022-07-05 18:45:10 -04:00
|
|
|
let scope = &mut realm.handle_scope(runtime.v8_isolate());
|
2022-04-17 07:53:08 -04:00
|
|
|
assert_eq!(ret, serde_v8::to_v8(scope, "Test").unwrap());
|
|
|
|
}
|
2022-10-26 10:54:22 -04:00
|
|
|
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
#[test]
|
|
|
|
fn js_realm_sync_ops() {
|
|
|
|
// Test that returning a ZeroCopyBuf and throwing an exception from a sync
|
|
|
|
// op result in objects with prototypes from the right realm. Note that we
|
|
|
|
// don't test the result of returning structs, because they will be
|
|
|
|
// serialized to objects with null prototype.
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
fn op_test(fail: bool) -> Result<ZeroCopyBuf, Error> {
|
|
|
|
if !fail {
|
|
|
|
Ok(ZeroCopyBuf::empty())
|
|
|
|
} else {
|
|
|
|
Err(crate::error::type_error("Test"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_test]);
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
get_error_class_fn: Some(&|error| {
|
|
|
|
crate::error::get_custom_error_class(error).unwrap()
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
let new_realm = runtime.create_realm().unwrap();
|
|
|
|
|
|
|
|
// Test in both realms
|
|
|
|
for realm in [runtime.global_realm(), new_realm].into_iter() {
|
|
|
|
let ret = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
fix(core): Have custom errors be created in the right realm (#17050)
Although PR #16366 did not fully revert `deno_core`'s support for
realms, since `JsRealm` still existed after that, it did remove the
`ContextState` struct, originally introduced in #14734. This change made
`js_build_custom_error_cb`, among other properties, a per-runtime
callback, rather than per-realm, which cause a bug where errors thrown
from an op would always be constructed in the main realm, rather than in
the current one.
This change adds back `ContextState` to fix this bug, adds back the
`known_realms` field of `JsRuntimeState` (needed to be able to drop the
callback when snapshotting), and also relands #14750, which adds the
`js_realm_sync_ops` test for this bug that was removed in #16366.
2022-12-20 14:09:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
|
|
|
const buf = Deno.core.ops.op_test(false);
|
|
|
|
try {
|
|
|
|
Deno.core.ops.op_test(true);
|
|
|
|
} catch(e) {
|
|
|
|
err = e;
|
|
|
|
}
|
|
|
|
buf instanceof Uint8Array && buf.byteLength === 0 &&
|
|
|
|
err instanceof TypeError && err.message === "Test"
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert!(ret.open(runtime.v8_isolate()).is_true());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
#[tokio::test]
|
|
|
|
async fn js_realm_async_ops() {
|
|
|
|
// Test that returning a ZeroCopyBuf and throwing an exception from a async
|
|
|
|
// op result in objects with prototypes from the right realm. Note that we
|
|
|
|
// don't test the result of returning structs, because they will be
|
|
|
|
// serialized to objects with null prototype.
|
|
|
|
|
|
|
|
#[op]
|
|
|
|
async fn op_test(fail: bool) -> Result<ZeroCopyBuf, Error> {
|
|
|
|
if !fail {
|
|
|
|
Ok(ZeroCopyBuf::empty())
|
|
|
|
} else {
|
|
|
|
Err(crate::error::type_error("Test"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_test]);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
get_error_class_fn: Some(&|error| {
|
|
|
|
crate::error::get_custom_error_class(error).unwrap()
|
|
|
|
}),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let global_realm = runtime.global_realm();
|
|
|
|
let new_realm = runtime.create_realm().unwrap();
|
|
|
|
|
|
|
|
let mut rets = vec![];
|
|
|
|
|
|
|
|
// Test in both realms
|
|
|
|
for realm in [global_realm, new_realm].into_iter() {
|
|
|
|
let ret = realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
(async function () {
|
2023-02-23 14:50:15 -05:00
|
|
|
const buf = await Deno.core.opAsync("op_test", false);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let err;
|
|
|
|
try {
|
2023-02-23 14:50:15 -05:00
|
|
|
await Deno.core.opAsync("op_test", true);
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
} catch(e) {
|
|
|
|
err = e;
|
|
|
|
}
|
|
|
|
return buf instanceof Uint8Array && buf.byteLength === 0 &&
|
|
|
|
err instanceof TypeError && err.message === "Test" ;
|
|
|
|
})();
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
rets.push((realm, ret));
|
|
|
|
}
|
|
|
|
|
|
|
|
runtime.run_event_loop(false).await.unwrap();
|
|
|
|
|
|
|
|
for ret in rets {
|
|
|
|
let scope = &mut ret.0.handle_scope(runtime.v8_isolate());
|
|
|
|
let value = v8::Local::new(scope, ret.1);
|
|
|
|
let promise = v8::Local::<v8::Promise>::try_from(value).unwrap();
|
|
|
|
let result = promise.result(scope);
|
|
|
|
|
|
|
|
assert!(result.is_boolean() && result.is_true());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[tokio::test]
|
|
|
|
async fn js_realm_ref_unref_ops() {
|
2023-02-06 08:49:26 -05:00
|
|
|
// Never resolves.
|
|
|
|
#[op]
|
|
|
|
async fn op_pending() {
|
|
|
|
futures::future::pending().await
|
|
|
|
}
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
|
2023-03-17 14:22:15 -04:00
|
|
|
deno_core::extension!(test_ext, ops = [op_pending]);
|
2023-02-06 08:49:26 -05:00
|
|
|
let mut runtime = JsRuntime::new(RuntimeOptions {
|
2023-03-17 14:22:15 -04:00
|
|
|
extensions: vec![test_ext::init_ops()],
|
2023-02-06 08:49:26 -05:00
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
run_in_task(move |cx| {
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
let main_realm = runtime.global_realm();
|
|
|
|
let other_realm = runtime.create_realm().unwrap();
|
|
|
|
|
|
|
|
main_realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2023-02-23 14:50:15 -05:00
|
|
|
var promise = Deno.core.opAsync("op_pending");
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
other_realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
2023-04-27 08:40:03 -04:00
|
|
|
|
2023-02-23 14:50:15 -05:00
|
|
|
var promise = Deno.core.opAsync("op_pending");
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
|
|
|
|
|
|
|
main_realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
|
|
|
let promiseIdSymbol = Symbol.for("Deno.core.internalPromiseId");
|
|
|
|
Deno.core.unrefOp(promise[promiseIdSymbol]);
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert!(matches!(runtime.poll_event_loop(cx, false), Poll::Pending));
|
|
|
|
|
|
|
|
other_realm
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
feat(core): Reland support for async ops in realms (#17204)
Currently realms are supported on `deno_core`, but there was no support
for async ops anywhere other than the main realm. The main issue is that
the `js_recv_cb` callback, which resolves promises corresponding to
async ops, was only set for the main realm, so async ops in other realms
would never resolve. Furthermore, promise ID's are specific to each
realm, which meant that async ops from other realms would result in a
wrong promise from the main realm being resolved.
This change takes the `ContextState` struct added in #17050, and adds to
it a `js_recv_cb` callback for each realm. Combined with the fact that
that same PR also added a list of known realms to `JsRuntimeState`, and
that #17174 made `OpCtx` instances realm-specific and had them include
an index into that list of known realms, this makes it possible to know
the current realm in the `queue_async_op` and `queue_fast_async_op`
methods, and therefore to send the results of promises for each realm to
that realm, and prevent the ID's from getting mixed up.
Additionally, since promise ID's are no longer unique to the isolate,
having a single set of unrefed ops doesn't work. This change therefore
also moves `unrefed_ops` from `JsRuntimeState` to `ContextState`, and
adds the lengths of the unrefed op sets for all known realms to get the
total number of unrefed ops to compare in the event loop.
This PR is a reland of #14734 after it was reverted in #16366, except
that `ContextState` and `JsRuntimeState::known_realms` were previously
relanded in #17050. Another significant difference with the original PR
is passing around an index into `JsRuntimeState::known_realms` instead
of a `v8::Global<v8::Context>` to identify the realm, because async op
queuing in fast calls cannot call into V8, and therefore cannot have
access to V8 globals. This also simplified the implementation of
`resolve_async_ops`.
Co-authored-by: Luis Malheiro <luismalheiro@gmail.com>
2023-01-14 08:40:16 -05:00
|
|
|
runtime.v8_isolate(),
|
|
|
|
"",
|
|
|
|
r#"
|
|
|
|
let promiseIdSymbol = Symbol.for("Deno.core.internalPromiseId");
|
|
|
|
Deno.core.unrefOp(promise[promiseIdSymbol]);
|
|
|
|
"#,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
assert!(matches!(
|
|
|
|
runtime.poll_event_loop(cx, false),
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2022-10-26 10:54:22 -04:00
|
|
|
#[test]
|
|
|
|
fn test_array_by_copy() {
|
|
|
|
// Verify that "array by copy" proposal is enabled (https://github.com/tc39/proposal-change-array-by-copy)
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
assert!(runtime
|
2023-04-04 08:46:31 -04:00
|
|
|
.execute_script_static(
|
2022-10-26 10:54:22 -04:00
|
|
|
"test_array_by_copy.js",
|
|
|
|
"const a = [1, 2, 3];
|
|
|
|
const b = a.toReversed();
|
|
|
|
if (!(a[0] === 1 && a[1] === 2 && a[2] === 3)) {
|
|
|
|
throw new Error('Expected a to be intact');
|
|
|
|
}
|
|
|
|
if (!(b[0] === 3 && b[1] === 2 && b[2] === 1)) {
|
|
|
|
throw new Error('Expected b to be reversed');
|
|
|
|
}",
|
|
|
|
)
|
|
|
|
.is_ok());
|
|
|
|
}
|
2023-02-08 12:13:33 -05:00
|
|
|
|
2023-04-19 10:22:41 -04:00
|
|
|
#[test]
|
|
|
|
fn test_non_existent_async_op_error() {
|
|
|
|
// Verify that "resizable ArrayBuffer" is disabled
|
|
|
|
let mut runtime = JsRuntime::new(Default::default());
|
|
|
|
let err = runtime
|
|
|
|
.execute_script_static(
|
|
|
|
"test_rab.js",
|
|
|
|
r#"Deno.core.opAsync("this_op_doesnt_exist");"#,
|
|
|
|
)
|
|
|
|
.unwrap_err();
|
|
|
|
assert!(err
|
|
|
|
.to_string()
|
|
|
|
.contains("this_op_doesnt_exist is not a registered op"));
|
|
|
|
}
|
|
|
|
|
2023-02-08 12:13:33 -05:00
|
|
|
#[tokio::test]
|
|
|
|
async fn cant_load_internal_module_when_snapshot_is_loaded_and_not_snapshotting(
|
|
|
|
) {
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ModsLoader;
|
|
|
|
|
|
|
|
impl ModuleLoader for ModsLoader {
|
|
|
|
fn resolve(
|
|
|
|
&self,
|
|
|
|
specifier: &str,
|
|
|
|
referrer: &str,
|
|
|
|
_kind: ResolutionKind,
|
|
|
|
) -> Result<ModuleSpecifier, Error> {
|
|
|
|
assert_eq!(specifier, "file:///main.js");
|
|
|
|
assert_eq!(referrer, ".");
|
|
|
|
let s = crate::resolve_import(specifier, referrer).unwrap();
|
|
|
|
Ok(s)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn load(
|
|
|
|
&self,
|
|
|
|
_module_specifier: &ModuleSpecifier,
|
2023-04-04 08:46:31 -04:00
|
|
|
_maybe_referrer: Option<&ModuleSpecifier>,
|
2023-02-08 12:13:33 -05:00
|
|
|
_is_dyn_import: bool,
|
|
|
|
) -> Pin<Box<ModuleSourceFuture>> {
|
2023-04-04 08:46:31 -04:00
|
|
|
let code = r#"
|
2023-02-13 18:43:53 -05:00
|
|
|
// This module doesn't really exist, just verifying that we'll get
|
2023-03-08 06:44:54 -05:00
|
|
|
// an error when specifier starts with "ext:".
|
|
|
|
import { core } from "ext:core.js";
|
2023-02-08 12:13:33 -05:00
|
|
|
"#;
|
|
|
|
|
2023-04-04 08:46:31 -04:00
|
|
|
async move { Ok(ModuleSource::for_test(code, "file:///main.js")) }
|
|
|
|
.boxed_local()
|
2023-02-08 12:13:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let snapshot = {
|
|
|
|
let runtime = JsRuntime::new(RuntimeOptions {
|
|
|
|
will_snapshot: true,
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
let snap: &[u8] = &runtime.snapshot();
|
|
|
|
Vec::from(snap).into_boxed_slice()
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut runtime2 = JsRuntime::new(RuntimeOptions {
|
|
|
|
module_loader: Some(Rc::new(ModsLoader)),
|
|
|
|
startup_snapshot: Some(Snapshot::Boxed(snapshot)),
|
|
|
|
..Default::default()
|
|
|
|
});
|
|
|
|
|
|
|
|
let err = runtime2
|
|
|
|
.load_main_module(&crate::resolve_url("file:///main.js").unwrap(), None)
|
|
|
|
.await
|
|
|
|
.unwrap_err();
|
|
|
|
assert_eq!(
|
|
|
|
err.to_string(),
|
2023-03-08 06:44:54 -05:00
|
|
|
"Cannot load extension module from external code"
|
2023-02-08 12:13:33 -05:00
|
|
|
);
|
|
|
|
}
|
2019-03-11 17:57:36 -04:00
|
|
|
}
|