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
2023-06-13 22:03:10 -04:00
use super ::bindings ;
use super ::jsrealm ::JsRealmInner ;
use super ::snapshot_util ;
use crate ::error ::exception_to_err_result ;
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 ;
2023-06-13 22:03:10 -04:00
use crate ::error ::GetErrorClassFn ;
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-05-09 06:37:13 -04:00
use crate ::modules ::AssertedModuleType ;
2023-05-28 14:44:41 -04:00
use crate ::modules ::ExtModuleLoader ;
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-06-13 22:03:10 -04:00
use crate ::runtime ::ContextState ;
use crate ::runtime ::JsRealm ;
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-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 ;
2023-06-13 22:03:10 -04:00
use crate ::V8_WRAPPER_OBJECT_INDEX ;
use crate ::V8_WRAPPER_TYPE_INDEX ;
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 ;
2019-11-16 19:17:47 -05:00
use futures ::stream ::StreamExt ;
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 ;
2023-05-31 10:19:06 -04:00
use std ::mem ::ManuallyDrop ;
use std ::ops ::Deref ;
use std ::ops ::DerefMut ;
2020-01-06 14:07:35 -05:00
use std ::option ::Option ;
2020-04-21 09:48:44 -04:00
use std ::rc ::Rc ;
2023-05-31 10:19:06 -04:00
use std ::sync ::atomic ::AtomicBool ;
use std ::sync ::atomic ::Ordering ;
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 ;
2023-05-31 10:19:06 -04:00
const STATE_DATA_OFFSET : u32 = 0 ;
const MODULE_MAP_DATA_OFFSET : u32 = 1 ;
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
}
2020-08-11 21:07:14 -04:00
/// Objects that need to live as long as the isolate
#[ derive(Default) ]
2023-06-13 22:03:10 -04:00
pub ( crate ) struct IsolateAllocations {
pub ( crate ) near_heap_limit_callback_data :
2020-08-11 21:07:14 -04:00
Option < ( Box < RefCell < dyn Any > > , v8 ::NearHeapLimitCallback ) > ,
}
2023-05-31 10:19:06 -04:00
/// ManuallyDrop<Rc<...>> is clone, but it returns a ManuallyDrop<Rc<...>> which is a massive
/// memory-leak footgun.
2023-06-13 22:03:10 -04:00
pub ( crate ) struct ManuallyDropRc < T > ( ManuallyDrop < Rc < T > > ) ;
2023-05-31 10:19:06 -04:00
impl < T > ManuallyDropRc < T > {
pub fn clone ( & self ) -> Rc < T > {
self . 0. deref ( ) . clone ( )
}
}
impl < T > Deref for ManuallyDropRc < T > {
type Target = Rc < T > ;
fn deref ( & self ) -> & Self ::Target {
self . 0. deref ( )
}
}
impl < T > DerefMut for ManuallyDropRc < T > {
fn deref_mut ( & mut self ) -> & mut Self ::Target {
self . 0. deref_mut ( )
}
}
/// This struct contains the [`JsRuntimeState`] and [`v8::OwnedIsolate`] that are required
/// to do an orderly shutdown of V8. We keep these in a separate struct to allow us to control
/// the destruction more closely, as snapshots require the isolate to be destroyed by the
/// snapshot process, not the destructor.
///
/// The way rusty_v8 works w/snapshots is that the [`v8::OwnedIsolate`] gets consumed by a
/// [`v8::snapshot::SnapshotCreator`] that is stored in its annex. It's a bit awkward, because this
/// means we cannot let it drop (because we don't have it after a snapshot). On top of that, we have
/// to consume it in the snapshot creator because otherwise it panics.
///
/// This inner struct allows us to let the outer JsRuntime drop normally without a Drop impl, while we
/// control dropping more closely here using ManuallyDrop.
2023-06-13 22:03:10 -04:00
pub ( crate ) struct InnerIsolateState {
2023-06-03 16:22:32 -04:00
will_snapshot : bool ,
2023-06-13 22:03:10 -04:00
pub ( crate ) state : ManuallyDropRc < RefCell < JsRuntimeState > > ,
2023-05-31 10:19:06 -04:00
v8_isolate : ManuallyDrop < v8 ::OwnedIsolate > ,
}
impl InnerIsolateState {
/// Clean out the opstate and take the inspector to prevent the inspector from getting destroyed
/// after we've torn down the contexts. If the inspector is not correctly torn down, random crashes
/// happen in tests (and possibly for users using the inspector).
pub fn prepare_for_cleanup ( & mut self ) {
let mut state = self . state . borrow_mut ( ) ;
let inspector = state . inspector . take ( ) ;
state . op_state . borrow_mut ( ) . clear ( ) ;
if let Some ( inspector ) = inspector {
assert_eq! (
Rc ::strong_count ( & inspector ) ,
1 ,
" The inspector must be dropped before the runtime "
) ;
}
}
pub fn cleanup ( & mut self ) {
self . prepare_for_cleanup ( ) ;
let state_ptr = self . v8_isolate . get_data ( STATE_DATA_OFFSET ) ;
// 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 module_map_ptr = self . v8_isolate . get_data ( MODULE_MAP_DATA_OFFSET ) ;
// 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 > ) } ;
self . state . borrow_mut ( ) . destroy_all_realms ( ) ;
debug_assert_eq! ( Rc ::strong_count ( & self . state ) , 1 ) ;
}
pub fn prepare_for_snapshot ( mut self ) -> v8 ::OwnedIsolate {
self . cleanup ( ) ;
// SAFETY: We're copying out of self and then immediately forgetting self
let ( state , isolate ) = unsafe {
(
ManuallyDrop ::take ( & mut self . state . 0 ) ,
ManuallyDrop ::take ( & mut self . v8_isolate ) ,
)
} ;
std ::mem ::forget ( self ) ;
drop ( state ) ;
isolate
}
}
impl Drop for InnerIsolateState {
fn drop ( & mut self ) {
self . cleanup ( ) ;
// SAFETY: We gotta drop these
unsafe {
ManuallyDrop ::drop ( & mut self . state . 0 ) ;
2023-06-03 16:22:32 -04:00
if self . will_snapshot {
2023-05-31 10:19:06 -04:00
// Create the snapshot and just drop it.
eprintln! ( " WARNING: v8::OwnedIsolate for snapshot was leaked " ) ;
} else {
ManuallyDrop ::drop ( & mut self . v8_isolate ) ;
}
}
}
}
2023-06-03 16:22:32 -04:00
#[ derive(Copy, Clone, Debug, Eq, PartialEq) ]
pub ( crate ) enum InitMode {
/// We have no snapshot -- this is a pristine context.
New ,
/// We are using a snapshot, thus certain initialization steps are skipped.
FromSnapshot ,
}
impl InitMode {
fn from_options ( options : & RuntimeOptions ) -> Self {
match options . startup_snapshot {
None = > Self ::New ,
Some ( _ ) = > Self ::FromSnapshot ,
}
}
}
2019-03-12 18:47:54 -04:00
/// A single execution context of JavaScript. Corresponds roughly to the "Web
2023-05-31 10:19:06 -04:00
/// Worker" concept in the DOM.
2020-09-06 15:44:29 -04:00
////
2023-06-03 16:22:32 -04:00
/// The JsRuntime future completes when there is an error or when all
2019-03-12 18:47:54 -04:00
/// pending ops have completed.
///
2023-06-03 16:22:32 -04:00
/// Use [`JsRuntimeForSnapshot`] to be able to create a snapshot.
pub struct JsRuntime {
2023-06-13 22:03:10 -04:00
pub ( crate ) inner : InnerIsolateState ,
pub ( crate ) module_map : Rc < RefCell < ModuleMap > > ,
pub ( crate ) allocations : IsolateAllocations ,
2023-05-31 10:19:06 -04:00
extensions : Vec < Extension > ,
2022-03-08 09:40:34 -05:00
event_loop_middlewares : Vec < Box < OpEventLoopFn > > ,
2023-06-03 16:22:32 -04:00
init_mode : InitMode ,
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
}
2023-05-31 10:19:06 -04:00
/// The runtime type used for snapshot creation.
2023-06-03 16:22:32 -04:00
pub struct JsRuntimeForSnapshot ( JsRuntime ) ;
2023-05-31 10:19:06 -04:00
impl Deref for JsRuntimeForSnapshot {
2023-06-03 16:22:32 -04:00
type Target = JsRuntime ;
2023-05-31 10:19:06 -04:00
fn deref ( & self ) -> & Self ::Target {
& self . 0
}
}
impl DerefMut for JsRuntimeForSnapshot {
fn deref_mut ( & mut self ) -> & mut Self ::Target {
& mut self . 0
}
}
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 > ;
2023-06-03 16:22:32 -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 > ,
2023-05-24 15:15:21 -04:00
known_realms : Vec < JsRealmInner > ,
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 > > ,
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 > > > ,
2020-05-29 17:41:39 -04:00
}
2023-05-24 15:15:21 -04:00
impl JsRuntimeState {
pub ( crate ) fn destroy_all_realms ( & mut self ) {
self . global_realm . take ( ) ;
for realm in self . known_realms . drain ( .. ) {
realm . destroy ( )
}
}
pub ( crate ) fn remove_realm (
& mut self ,
realm_context : & Rc < v8 ::Global < v8 ::Context > > ,
) {
self
. known_realms
. retain ( | realm | ! realm . is_same ( realm_context ) ) ;
}
}
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
}
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
2023-06-03 16:22:32 -04:00
/// JsRuntime extensions, not to be confused with ES modules.
2022-11-26 18:58:23 -05:00
/// 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
2023-06-14 12:45:59 -04:00
/// If provided, the module map will be cleared and left only with the specifiers
/// in this list, with the new names provided. If not provided, the module map is
/// left intact.
pub rename_modules : Option < Vec < ( & 'static str , & 'static str ) > > ,
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-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
2023-05-31 10:19:06 -04:00
#[ derive(Default) ]
pub struct RuntimeSnapshotOptions {
/// 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.
pub snapshot_module_load_cb : Option < ExtModuleLoaderCb > ,
2022-10-15 10:01:01 -04:00
}
2023-06-03 16:22:32 -04:00
impl JsRuntime {
/// Only constructor, configuration is done through `options`.
pub fn new ( mut options : RuntimeOptions ) -> JsRuntime {
JsRuntime ::init_v8 ( options . v8_platform . take ( ) , cfg! ( test ) ) ;
JsRuntime ::new_inner ( options , false , None )
}
pub ( crate ) fn state_from (
isolate : & v8 ::Isolate ,
) -> Rc < RefCell < JsRuntimeState > > {
let state_ptr = isolate . get_data ( 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 ( ) ;
std ::mem ::forget ( state_rc ) ;
state
}
2021-04-12 06:15:04 -04:00
2023-06-03 16:22:32 -04:00
pub ( crate ) fn module_map_from (
isolate : & v8 ::Isolate ,
) -> Rc < RefCell < ModuleMap > > {
let module_map_ptr = isolate . get_data ( 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 ( ) ;
std ::mem ::forget ( module_map_rc ) ;
module_map
}
pub ( crate ) fn event_loop_pending_state_from_scope (
scope : & mut v8 ::HandleScope ,
) -> EventLoopPendingState {
let state = JsRuntime ::state_from ( scope ) ;
let module_map = JsRuntime ::module_map_from ( scope ) ;
let state = EventLoopPendingState ::new (
scope ,
& mut state . borrow_mut ( ) ,
& module_map . borrow ( ) ,
) ;
state
}
fn init_v8 (
v8_platform : Option < v8 ::SharedRef < v8 ::Platform > > ,
predictable : bool ,
) {
2020-05-29 17:41:39 -04:00
static DENO_INIT : Once = Once ::new ( ) ;
2023-05-31 10:19:06 -04:00
static DENO_PREDICTABLE : AtomicBool = AtomicBool ::new ( false ) ;
static DENO_PREDICTABLE_SET : AtomicBool = AtomicBool ::new ( false ) ;
if DENO_PREDICTABLE_SET . load ( Ordering ::SeqCst ) {
let current = DENO_PREDICTABLE . load ( Ordering ::SeqCst ) ;
assert_eq! ( current , predictable , " V8 may only be initialized once in either snapshotting or non-snapshotting mode. Either snapshotting or non-snapshotting mode may be used in a single process, not both. " ) ;
DENO_PREDICTABLE_SET . store ( true , Ordering ::SeqCst ) ;
DENO_PREDICTABLE . store ( predictable , Ordering ::SeqCst ) ;
2022-11-26 18:58:23 -05:00
}
2022-03-14 13:44:15 -04:00
2023-05-31 10:19:06 -04:00
DENO_INIT . call_once ( move | | v8_init ( v8_platform , predictable ) ) ;
}
2022-03-14 13:44:15 -04:00
2023-06-03 16:22:32 -04:00
fn new_inner (
2023-05-31 10:19:06 -04:00
mut options : RuntimeOptions ,
2023-06-03 16:22:32 -04:00
will_snapshot : bool ,
2023-05-31 10:19:06 -04:00
maybe_load_callback : Option < ExtModuleLoaderCb > ,
2023-06-03 16:22:32 -04:00
) -> JsRuntime {
let init_mode = InitMode ::from_options ( & options ) ;
2023-06-13 18:36:16 -04:00
let ( op_state , ops ) = Self ::create_opstate ( & mut options , init_mode ) ;
2022-03-14 13:44:15 -04:00
let op_state = Rc ::new ( RefCell ::new ( op_state ) ) ;
2022-10-21 10:13:42 -04:00
2023-05-31 10:19:06 -04:00
// Collect event-loop middleware
let mut event_loop_middlewares =
Vec ::with_capacity ( options . extensions . len ( ) ) ;
for extension in & mut options . extensions {
if let Some ( middleware ) = extension . init_event_loop_middleware ( ) {
event_loop_middlewares . push ( middleware ) ;
}
}
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 ( ) ,
shared_array_buffer_store : options . shared_array_buffer_store ,
compiled_wasm_module_store : options . compiled_wasm_module_store ,
op_state : op_state . clone ( ) ,
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 ) ;
2023-05-24 15:15:21 -04:00
let context_state = Rc ::new ( RefCell ::new ( ContextState ::default ( ) ) ) ;
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-05-24 15:15:21 -04:00
OpCtx ::new (
id as u16 ,
context_state . clone ( ) ,
Rc ::new ( decl ) ,
op_state . clone ( ) ,
weak . clone ( ) ,
)
2022-04-08 04:32:48 -04:00
} )
. collect ::< Vec < _ > > ( )
. into_boxed_slice ( ) ;
2023-05-24 15:15:21 -04:00
context_state . borrow_mut ( ) . op_ctxs = op_ctxs ;
context_state . borrow_mut ( ) . isolate = Some ( isolate_ptr ) ;
2022-03-14 13:44:15 -04:00
2023-05-24 15:15:21 -04:00
let refs = bindings ::external_references ( & context_state . borrow ( ) . 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 ) ) ;
2022-10-05 10:06:44 -04:00
2023-06-03 16:22:32 -04:00
let mut isolate = if will_snapshot {
snapshot_util ::create_snapshot_creator (
refs ,
options . startup_snapshot . take ( ) ,
)
} else {
let mut params = options
. create_params
. take ( )
. unwrap_or_default ( )
. embedder_wrapper_type_info_offsets (
V8_WRAPPER_TYPE_INDEX ,
V8_WRAPPER_OBJECT_INDEX ,
)
. external_references ( & * * refs ) ;
if let Some ( snapshot ) = options . startup_snapshot . take ( ) {
params = match snapshot {
Snapshot ::Static ( data ) = > params . snapshot_blob ( data ) ,
Snapshot ::JustCreated ( data ) = > params . snapshot_blob ( data ) ,
Snapshot ::Boxed ( data ) = > params . snapshot_blob ( data ) ,
} ;
}
v8 ::Isolate ::new ( params )
2023-05-31 10:19:06 -04:00
} ;
2023-06-03 16:22:32 -04:00
isolate . set_capture_stack_trace_for_uncaught_exceptions ( true , 10 ) ;
isolate . set_promise_reject_callback ( bindings ::promise_reject_callback ) ;
isolate . set_host_initialize_import_meta_object_callback (
bindings ::host_initialize_import_meta_object_callback ,
2023-05-28 15:13:53 -04:00
) ;
2023-06-03 16:22:32 -04:00
isolate . set_host_import_module_dynamically_callback (
bindings ::host_import_module_dynamically_callback ,
) ;
isolate . set_wasm_async_resolve_promise_callback (
bindings ::wasm_async_resolve_promise_callback ,
) ;
let ( global_context , snapshotted_data ) = {
let scope = & mut v8 ::HandleScope ::new ( & mut isolate ) ;
let context = v8 ::Context ::new ( scope ) ;
// Get module map data from the snapshot
let snapshotted_data = if init_mode = = InitMode ::FromSnapshot {
Some ( snapshot_util ::get_snapshotted_data ( scope , context ) )
} else {
None
} ;
( v8 ::Global ::new ( scope , context ) , snapshotted_data )
} ;
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
2023-05-31 10:19:06 -04:00
let mut context_scope : v8 ::HandleScope =
2023-05-28 15:13:53 -04:00
v8 ::HandleScope ::with_context ( & mut isolate , global_context . clone ( ) ) ;
let scope = & mut context_scope ;
let context = v8 ::Local ::new ( scope , global_context . clone ( ) ) ;
bindings ::initialize_context (
scope ,
context ,
& context_state . borrow ( ) . op_ctxs ,
2023-06-03 16:22:32 -04:00
init_mode ,
2023-05-28 15:13:53 -04:00
) ;
context . set_slot ( scope , context_state . clone ( ) ) ;
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 {
2023-05-28 15:13:53 -04:00
Some ( JsRuntimeInspector ::new ( scope , context , options . is_main ) )
2022-10-26 07:37:50 -04:00
} else {
None
} ;
2021-05-26 15:07:12 -04:00
2023-05-03 20:44:59 -04:00
let loader = options
. module_loader
. unwrap_or_else ( | | Rc ::new ( NoopModuleLoader ) ) ;
2023-02-07 14:22:46 -05:00
2022-10-21 10:13:42 -04:00
{
2023-05-24 15:15:21 -04:00
let global_realm = JsRealmInner ::new (
context_state ,
2023-05-28 15:13:53 -04:00
global_context ,
2023-05-24 15:15:21 -04:00
state_rc . clone ( ) ,
true ,
) ;
2022-10-21 10:13:42 -04:00
let mut state = state_rc . borrow_mut ( ) ;
2023-05-24 15:15:21 -04:00
state . global_realm = Some ( JsRealm ::new ( global_realm . clone ( ) ) ) ;
2022-10-26 07:37:50 -04:00
state . inspector = inspector ;
2023-05-24 15:15:21 -04:00
state . known_realms . push ( global_realm ) ;
2022-10-21 10:13:42 -04:00
}
2023-05-28 15:13:53 -04:00
scope . set_data (
2023-05-31 10:19:06 -04:00
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
) ;
2023-06-01 01:35:14 -04:00
let module_map_rc = Rc ::new ( RefCell ::new ( ModuleMap ::new ( loader ) ) ) ;
2023-05-31 10:19:06 -04:00
if let Some ( snapshotted_data ) = snapshotted_data {
2023-01-19 04:00:35 -05:00
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
}
2023-05-28 15:13:53 -04:00
scope . set_data (
2023-05-31 10:19:06 -04:00
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
2023-05-28 15:13:53 -04:00
drop ( context_scope ) ;
2023-06-03 16:22:32 -04:00
let mut js_runtime = JsRuntime {
2023-05-31 10:19:06 -04:00
inner : InnerIsolateState {
2023-06-03 16:22:32 -04:00
will_snapshot ,
2023-05-31 10:19:06 -04:00
state : ManuallyDropRc ( ManuallyDrop ::new ( state_rc ) ) ,
v8_isolate : ManuallyDrop ::new ( isolate ) ,
} ,
2023-06-03 16:22:32 -04:00
init_mode ,
2020-08-11 21:07:14 -04:00
allocations : IsolateAllocations ::default ( ) ,
2023-05-31 10:19:06 -04:00
event_loop_middlewares ,
extensions : options . extensions ,
2023-06-01 01:35:14 -04:00
module_map : 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-11-26 18:58:23 -05:00
let realm = js_runtime . global_realm ( ) ;
2023-05-31 10:19:06 -04:00
// TODO(mmastrac): We should thread errors back out of the runtime
js_runtime
. init_extension_js ( & realm , maybe_load_callback )
. unwrap ( ) ;
2023-06-14 12:45:59 -04:00
// If the user has requested that we rename modules
if let Some ( rename_modules ) = options . rename_modules {
js_runtime
. module_map
. borrow_mut ( )
. clear_module_map ( rename_modules . into_iter ( ) ) ;
}
2021-01-05 16:10:50 -05:00
js_runtime
2020-01-06 10:24:44 -05:00
}
2023-06-01 01:35:14 -04:00
#[ cfg(test) ]
2022-10-25 08:27:33 -04:00
#[ inline ]
2023-05-31 10:19:06 -04:00
pub ( crate ) fn module_map ( & self ) -> & Rc < RefCell < ModuleMap > > {
2023-06-01 01:35:14 -04:00
& self . module_map
2022-10-25 08:27:33 -04:00
}
2022-10-21 10:13:42 -04:00
#[ inline ]
2023-05-28 15:13:53 -04:00
pub fn global_context ( & self ) -> v8 ::Global < v8 ::Context > {
2023-05-24 15:15:21 -04:00
self
2023-05-31 10:19:06 -04:00
. inner
2023-05-24 15:15:21 -04:00
. state
. borrow ( )
. known_realms
. get ( 0 )
. unwrap ( )
. 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 {
2023-05-31 10:19:06 -04:00
& mut self . inner . v8_isolate
2020-10-05 05:08:19 -04:00
}
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 > > {
2023-05-31 10:19:06 -04:00
self . inner . 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 {
2023-05-31 10:19:06 -04:00
let state = self . inner . state . borrow ( ) ;
2022-04-17 07:53:08 -04:00
state . global_realm . clone ( ) . unwrap ( )
}
2023-05-31 10:19:06 -04:00
/// Returns the extensions that this runtime is using (including internal ones).
pub fn extensions ( & self ) -> & Vec < Extension > {
& self . extensions
}
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-06-03 16:22:32 -04: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-05-24 15:15:21 -04:00
let context_state = Rc ::new ( RefCell ::new ( ContextState ::default ( ) ) ) ;
2022-12-26 11:00:13 -05:00
let op_ctxs : Box < [ OpCtx ] > = self
. global_realm ( )
2023-05-24 15:15:21 -04:00
. 0
. state ( )
2022-12-26 11:00:13 -05:00
. borrow ( )
. op_ctxs
. iter ( )
2023-03-18 18:30:04 -04:00
. map ( | op_ctx | {
OpCtx ::new (
op_ctx . id ,
2023-05-24 15:15:21 -04:00
context_state . clone ( ) ,
2023-03-18 18:30:04 -04:00
op_ctx . decl . clone ( ) ,
op_ctx . state . clone ( ) ,
op_ctx . runtime_state . clone ( ) ,
)
2022-12-26 11:00:13 -05:00
} )
. collect ( ) ;
2023-05-24 15:15:21 -04:00
context_state . borrow_mut ( ) . op_ctxs = op_ctxs ;
context_state . borrow_mut ( ) . isolate = Some ( self . v8_isolate ( ) as _ ) ;
2022-12-26 11:00:13 -05:00
2023-05-24 15:15:21 -04:00
let raw_ptr = self . v8_isolate ( ) as * mut v8 ::OwnedIsolate ;
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.
2023-05-24 15:15:21 -04:00
let isolate = unsafe { raw_ptr . as_mut ( ) } . unwrap ( ) ;
let scope = & mut v8 ::HandleScope ::new ( isolate ) ;
2023-05-28 15:13:53 -04:00
let context = v8 ::Context ::new ( scope ) ;
let scope = & mut v8 ::ContextScope ::new ( scope , context ) ;
2023-05-24 15:15:21 -04:00
let context = bindings ::initialize_context (
2022-04-17 07:53:08 -04:00
scope ,
2023-05-28 15:13:53 -04:00
context ,
2023-05-24 15:15:21 -04:00
& context_state . borrow ( ) . op_ctxs ,
2023-06-03 16:22:32 -04:00
self . init_mode ,
2022-04-17 07:53:08 -04:00
) ;
2023-05-24 15:15:21 -04:00
context . set_slot ( scope , context_state . clone ( ) ) ;
let realm = JsRealmInner ::new (
context_state ,
v8 ::Global ::new ( scope , context ) ,
2023-05-31 10:19:06 -04:00
self . inner . state . clone ( ) ,
2023-05-24 15:15:21 -04:00
false ,
) ;
2023-05-31 10:19:06 -04:00
let mut state = self . inner . state . borrow_mut ( ) ;
2023-05-24 15:15:21 -04:00
state . known_realms . push ( realm . clone ( ) ) ;
JsRealm ::new ( realm )
2022-04-17 07:53:08 -04:00
} ;
2023-05-31 10:19:06 -04:00
self . init_extension_js ( & realm , None ) ? ;
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
}
2023-05-09 06:37:13 -04:00
/// Initializes JS of provided Extensions in the given realm.
2023-05-31 10:19:06 -04:00
fn init_extension_js (
& mut self ,
realm : & JsRealm ,
maybe_load_callback : Option < ExtModuleLoaderCb > ,
) -> Result < ( ) , Error > {
// Initialization of JS happens in phases:
2023-05-09 06:37:13 -04:00
// 1. Iterate through all extensions:
// a. Execute all extension "script" JS files
// b. Load all extension "module" JS files (but do not execute them yet)
// 2. Iterate through all extensions:
// a. If an extension has a `esm_entry_point`, execute it.
2023-05-31 10:19:06 -04:00
// Take extensions temporarily so we can avoid have a mutable reference to self
let extensions = std ::mem ::take ( & mut self . extensions ) ;
2023-05-28 14:44:41 -04:00
// TODO(nayeemrmn): Module maps should be per-realm.
2023-06-01 01:35:14 -04:00
let loader = self . module_map . borrow ( ) . loader . clone ( ) ;
2023-05-28 14:44:41 -04:00
let ext_loader = Rc ::new ( ExtModuleLoader ::new (
2023-05-31 10:19:06 -04:00
& extensions ,
maybe_load_callback . map ( Rc ::new ) ,
2023-05-28 14:44:41 -04:00
) ) ;
2023-06-01 01:35:14 -04:00
self . module_map . borrow_mut ( ) . loader = ext_loader ;
2023-05-28 14:44:41 -04:00
2023-05-09 06:37:13 -04:00
let mut esm_entrypoints = vec! [ ] ;
2023-02-13 18:43:53 -05:00
2023-05-09 06:37:13 -04:00
futures ::executor ::block_on ( async {
2023-05-31 10:19:06 -04:00
for extension in & extensions {
let maybe_esm_entry_point = extension . get_esm_entry_point ( ) ;
2023-05-09 06:37:13 -04:00
2023-05-31 10:19:06 -04:00
if let Some ( esm_files ) = extension . get_esm_sources ( ) {
2023-05-09 06:37:13 -04:00
for file_source in esm_files {
self
. load_side_module (
& ModuleSpecifier ::parse ( file_source . specifier ) ? ,
None ,
)
. await ? ;
2023-02-13 18:43:53 -05:00
}
2023-02-07 14:22:46 -05:00
}
2023-05-09 06:37:13 -04:00
if let Some ( entry_point ) = maybe_esm_entry_point {
esm_entrypoints . push ( entry_point ) ;
}
2023-05-31 10:19:06 -04:00
if let Some ( js_files ) = extension . get_js_sources ( ) {
2023-03-09 19:22:27 -05:00
for file_source in js_files {
realm . execute_script (
self . v8_isolate ( ) ,
2023-03-18 16:09:13 -04:00
file_source . specifier ,
2023-06-13 18:36:16 -04:00
file_source . load ( ) ? ,
2023-03-09 19:22:27 -05:00
) ? ;
}
2023-02-07 14:22:46 -05:00
}
2023-05-09 06:37:13 -04:00
2023-05-31 10:19:06 -04:00
if extension . is_core {
2023-05-09 06:37:13 -04:00
self . init_cbs ( realm ) ;
}
}
for specifier in esm_entrypoints {
let mod_id = {
2023-06-01 01:35:14 -04:00
self
. module_map
2023-05-09 06:37:13 -04:00
. borrow ( )
. get_id ( specifier , AssertedModuleType ::JavaScriptOrWasm )
. unwrap_or_else ( | | {
panic! ( " {} not present in the module map " , specifier )
} )
} ;
let receiver = self . mod_evaluate ( mod_id ) ;
self . run_event_loop ( false ) . await ? ;
receiver
. await ?
. with_context ( | | format! ( " Couldn't execute ' {specifier} ' " ) ) ? ;
2021-04-28 12:41:50 -04:00
}
2023-04-13 20:41:32 -04:00
2023-05-09 06:37:13 -04:00
#[ cfg(debug_assertions) ]
{
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
2023-05-09 06:37:13 -04:00
let mut scope = realm . handle_scope ( self . v8_isolate ( ) ) ;
let module_map = module_map_rc . borrow ( ) ;
module_map . assert_all_modules_evaluated ( & mut scope ) ;
2023-04-13 20:41:32 -04:00
}
2023-05-09 06:37:13 -04:00
Ok ::< _ , anyhow ::Error > ( ( ) )
} ) ? ;
2023-03-09 19:22:27 -05:00
self . extensions = extensions ;
2023-06-01 01:35:14 -04:00
self . module_map . borrow_mut ( ) . loader = loader ;
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
2023-05-08 14:59:38 -04:00
let ops : Vec < _ > = 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 )
} )
2023-05-08 14:59:38 -04:00
. collect ( ) ;
// In debug build verify there are no duplicate ops.
#[ cfg(debug_assertions) ]
{
let mut count_by_name = HashMap ::new ( ) ;
for op in ops . iter ( ) {
count_by_name
. entry ( & op . name )
. or_insert ( vec! [ ] )
. push ( op . name . to_string ( ) ) ;
}
let mut duplicate_ops = vec! [ ] ;
for ( op_name , _count ) in
count_by_name . iter ( ) . filter ( | ( _k , v ) | v . len ( ) > 1 )
{
duplicate_ops . push ( op_name . to_string ( ) ) ;
}
if ! duplicate_ops . is_empty ( ) {
let mut msg = " Found ops with duplicate names: \n " . to_string ( ) ;
for op_name in duplicate_ops {
msg . push_str ( & format! ( " - {} \n " , op_name ) ) ;
}
msg . push_str ( " Op names need to be unique. " ) ;
panic! ( " {} " , msg ) ;
}
}
ops
2022-03-14 13:44:15 -04:00
}
/// Initializes ops of provided Extensions
2023-06-13 18:36:16 -04:00
fn create_opstate (
options : & mut RuntimeOptions ,
init_mode : InitMode ,
) -> ( OpState , Vec < OpDecl > ) {
2023-05-31 10:19:06 -04:00
// Add built-in extension
2023-06-13 18:36:16 -04:00
if init_mode = = InitMode ::FromSnapshot {
options
. extensions
. insert ( 0 , crate ::ops_builtin ::core ::init_ops ( ) ) ;
} else {
options
. extensions
. insert ( 0 , crate ::ops_builtin ::core ::init_ops_and_esm ( ) ) ;
}
2023-05-31 10:19:06 -04:00
let ops = Self ::collect_ops ( & mut options . extensions ) ;
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 ;
}
2023-05-03 20:44:59 -04:00
// Setup state
2023-05-31 10:19:06 -04:00
for e in & mut options . extensions {
2023-05-03 20:44:59 -04:00
// ops are already registered during in bindings::initialize_context();
2023-05-31 10:19:06 -04:00
e . init_state ( & mut op_state ) ;
2022-11-26 18:58:23 -05:00
}
2023-05-31 10:19:06 -04:00
( op_state , ops )
2021-04-28 12:41:50 -04:00
}
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
2023-05-24 15:15:21 -04:00
let state_rc = realm . 0. state ( ) ;
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 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 > > {
2023-05-31 10:19:06 -04:00
let state = self . inner . 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
}
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 > {
2023-06-14 12:45:59 -04:00
self
2023-06-01 01:35:14 -04:00
. module_map
2023-06-14 12:45:59 -04:00
. clone ( )
2022-03-22 09:32:32 -04:00
. borrow ( )
2023-06-14 12:45:59 -04:00
. get_module_namespace ( & mut self . handle_scope ( ) , module_id )
2022-03-22 09:32:32 -04:00
}
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 ) {
2023-05-31 10:19:06 -04:00
if self . inner . state . borrow ( ) . inspector . is_some ( ) {
2022-10-26 07:37:50 -04:00
return ;
}
2023-05-28 15:13:53 -04:00
let context = self . global_context ( ) ;
let scope = & mut v8 ::HandleScope ::with_context (
2023-05-31 10:19:06 -04:00
self . inner . v8_isolate . as_mut ( ) ,
2023-05-28 15:13:53 -04:00
context . clone ( ) ,
) ;
let context = v8 ::Local ::new ( scope , context ) ;
2023-05-31 10:19:06 -04:00
let mut state = self . inner . state . borrow_mut ( ) ;
2023-05-28 15:13:53 -04:00
state . inspector =
Some ( JsRuntimeInspector ::new ( scope , context , 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
{
2023-05-31 10:19:06 -04:00
let state = self . inner . state . borrow ( ) ;
2022-10-26 07:37:50 -04:00
has_inspector = state . inspector . is_some ( ) ;
2023-06-07 17:50:14 -04:00
state . op_state . borrow ( ) . waker . register ( cx . waker ( ) ) ;
2020-05-29 17:41:39 -04:00
}
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-06-14 12:45:59 -04:00
let module_map = self . module_map . clone ( ) ;
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 ;
{
2023-05-31 10:19:06 -04:00
let op_state = self . inner . state . borrow ( ) . op_state . clone ( ) ;
2023-04-16 10:05:13 -04:00
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-05-31 10:19:06 -04:00
let state = self . inner . state . borrow ( ) ;
2023-04-16 10:05:13 -04:00
// 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.
2023-06-07 17:50:14 -04:00
if pending_state . has_pending_background_tasks
2023-04-16 10:05:13 -04:00
| | pending_state . has_tick_scheduled
| | maybe_scheduling
{
2023-06-07 17:50:14 -04:00
state . op_state . borrow ( ) . waker . wake ( ) ;
2023-04-16 10:05:13 -04:00
}
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 ( ) ;
2023-06-14 12:45:59 -04:00
let messages = module_map . borrow ( ) . find_stalled_top_level_await ( scope ) ;
2023-04-16 10:05:13 -04:00
// 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
2023-05-31 10:19:06 -04:00
} else if self . inner . state . borrow ( ) . dyn_module_evaluate_idle_counter > = 1
{
2023-04-16 10:05:13 -04:00
let scope = & mut self . handle_scope ( ) ;
2023-06-14 12:45:59 -04:00
let messages = module_map . borrow ( ) . find_stalled_top_level_await ( scope ) ;
2023-04-16 10:05:13 -04:00
// 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 {
2023-05-31 10:19:06 -04:00
let mut state = self . inner . state . borrow_mut ( ) ;
2023-04-16 10:05:13 -04:00
// 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 ;
2023-06-07 17:50:14 -04:00
state . op_state . borrow ( ) . 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-05-31 10:19:06 -04:00
let mut scope = v8 ::HandleScope ::new ( self . inner . v8_isolate . as_mut ( ) ) ;
2022-12-13 17:28:38 -05:00
EventLoopPendingState ::new (
2023-04-18 18:52:12 -04:00
& mut scope ,
2023-05-31 10:19:06 -04:00
& mut self . inner . state . borrow_mut ( ) ,
2023-06-01 01:35:14 -04:00
& self . module_map . borrow ( ) ,
2022-12-13 17:28:38 -05:00
)
2022-10-21 10:13:42 -04:00
}
2023-05-31 10:19:06 -04:00
}
impl JsRuntimeForSnapshot {
pub fn new (
mut options : RuntimeOptions ,
runtime_snapshot_options : RuntimeSnapshotOptions ,
) -> JsRuntimeForSnapshot {
2023-06-03 16:22:32 -04:00
JsRuntime ::init_v8 ( options . v8_platform . take ( ) , true ) ;
JsRuntimeForSnapshot ( JsRuntime ::new_inner (
2023-05-31 10:19:06 -04:00
options ,
2023-06-03 16:22:32 -04:00
true ,
2023-05-31 10:19:06 -04:00
runtime_snapshot_options . snapshot_module_load_cb ,
) )
}
/// Takes a snapshot and consumes the runtime.
///
/// `Error` can usually be downcast to `JsError`.
pub fn snapshot ( mut self ) -> v8 ::StartupData {
// Ensure there are no live inspectors to prevent crashes.
self . inner . prepare_for_cleanup ( ) ;
// 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 ) ;
}
// Serialize the module map and store its data in the snapshot.
{
let snapshotted_data = {
2023-06-01 01:35:14 -04:00
// `self.module_map` points directly to the v8 isolate data slot, which
// we must explicitly drop before destroying the isolate. We have to
// take and drop this `Rc` before that.
let module_map_rc = std ::mem ::take ( & mut self . module_map ) ;
2023-05-31 10:19:06 -04:00
let module_map = module_map_rc . borrow ( ) ;
module_map . serialize_for_snapshotting ( & mut self . handle_scope ( ) )
} ;
let context = self . global_context ( ) ;
let mut scope = self . handle_scope ( ) ;
snapshot_util ::set_snapshotted_data (
& mut scope ,
context ,
snapshotted_data ,
) ;
}
self
. 0
. inner
. prepare_for_snapshot ( )
. create_blob ( v8 ::FunctionCodeHandling ::Keep )
. unwrap ( )
}
}
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-05-24 15:15:21 -04:00
let mut num_pending_ops = 0 ;
for realm in & state . known_realms {
num_unrefed_ops + = realm . num_unrefed_ops ( ) ;
num_pending_ops + = realm . num_pending_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
}
2022-12-13 17:28:38 -05:00
EventLoopPendingState {
2023-05-24 15:15:21 -04:00
has_pending_refed_ops : num_pending_ops > 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
2023-06-03 16:22:32 -04:00
// 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.
2023-06-07 17:50:14 -04:00
self . op_state . borrow ( ) . waker . wake ( ) ;
2020-09-06 10:50:49 -04:00
}
2020-05-29 17:41:39 -04:00
}
2020-09-06 10:50:49 -04:00
// Related to module loading
2023-06-03 16:22:32 -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 > > {
2023-06-14 12:45:59 -04:00
self
. module_map
. clone ( )
. borrow_mut ( )
. instantiate_module ( & mut self . handle_scope ( ) , id )
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 > {
2023-06-01 01:35:14 -04:00
let module_handle = self
. module_map
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
2023-05-31 10:19:06 -04:00
let global_realm =
self . inner . state . borrow_mut ( ) . global_realm . clone ( ) . unwrap ( ) ;
let scope = & mut global_realm . handle_scope ( & mut self . inner . v8_isolate ) ;
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
2023-05-31 10:19:06 -04:00
. inner
2022-10-21 10:13:42 -04:00
. 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.
2023-06-03 16:22:32 -04:00
/// Implementors must manually call [`JsRuntime::run_event_loop`] to drive
2022-06-20 08:40:57 -04:00
/// 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
2023-06-03 16:22:32 -04:00
/// 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 ( ) ;
2023-05-31 10:19:06 -04:00
let state_rc = self . inner . state . clone ( ) ;
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
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
2023-06-03 16:22:32 -04:00
// the promise to pending promise rejection table - meaning JsRuntime will return
2021-02-23 09:22:55 -05:00
// 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
2023-05-24 15:15:21 -04:00
. 0
. state ( )
2023-01-16 11:36:42 -05:00
. borrow_mut ( )
. pending_promise_rejections
2023-05-07 18:27:59 -04:00
. retain ( | ( key , _ ) | key ! = & 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 > ,
) {
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
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 ) {
2023-05-31 10:19:06 -04:00
let state_rc = self . inner . state . clone ( ) ;
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
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
2023-06-01 01:35:14 -04:00
. module_map
2022-10-25 08:27:33 -04:00
. borrow ( )
. preparing_dynamic_imports
. is_empty ( )
{
2020-10-05 05:08:19 -04:00
return Poll ::Ready ( Ok ( ( ) ) ) ;
}
2020-09-06 10:50:49 -04:00
loop {
2023-06-01 01:35:14 -04:00
let poll_result = self
. module_map
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 ) = > {
2023-06-01 01:35:14 -04:00
self
. module_map
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 > > {
2023-06-01 01:35:14 -04:00
if self . module_map . borrow ( ) . pending_dynamic_imports . is_empty ( ) {
2020-10-05 05:08:19 -04:00
return Poll ::Ready ( Ok ( ( ) ) ) ;
}
2020-09-06 10:50:49 -04:00
loop {
2023-06-01 01:35:14 -04:00
let poll_result = self
. module_map
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
2023-06-01 01:35:14 -04:00
self
. module_map
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 =
2023-05-31 10:19:06 -04:00
self . inner . 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 ( ) ;
2023-05-31 10:19:06 -04:00
let state_rc = self . inner . 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 {
2023-05-31 10:19:06 -04:00
let pending = std ::mem ::take (
& mut self . inner . 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
}
}
}
}
2023-05-31 10:19:06 -04:00
self . inner . 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
///
2023-06-03 16:22:32 -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 > {
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
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).
///
2023-06-03 16:22:32 -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 > {
2023-06-01 01:35:14 -04:00
let module_map_rc = self . module_map . clone ( ) ;
2021-09-17 21:44:53 -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
// 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-05-31 10:19:06 -04:00
let state = self . inner . state . clone ( ) ;
2023-04-18 18:52:12 -04:00
let scope = & mut self . handle_scope ( ) ;
let state = state . borrow ( ) ;
2023-05-24 15:15:21 -04:00
for realm in & state . known_realms {
realm . check_promise_rejections ( scope ) ? ;
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
// Handle responses for each realm.
2023-05-31 10:19:06 -04:00
let state = self . inner . state . clone ( ) ;
let isolate = & mut self . inner . v8_isolate ;
let realm_count = state . borrow ( ) . known_realms . len ( ) ;
2023-05-24 15:15:21 -04:00
for realm_idx in 0 .. realm_count {
2023-05-31 10:19:06 -04:00
let realm = state . borrow ( ) . known_realms . get ( realm_idx ) . unwrap ( ) . clone ( ) ;
2023-05-24 15:15:21 -04:00
let context_state = realm . state ( ) ;
let mut context_state = context_state . borrow_mut ( ) ;
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 ( 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-05-24 15:15:21 -04:00
SmallVec ::with_capacity ( 32 ) ;
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-06-07 17:50:14 -04:00
loop {
let item = {
let next = std ::pin ::pin! ( context_state . pending_ops . join_next ( ) ) ;
let Poll ::Ready ( Some ( item ) ) = next . poll ( cx ) else {
break ;
} ;
item
} ;
let ( promise_id , op_id , mut resp ) = item . unwrap ( ) . into_inner ( ) ;
2023-05-31 10:19:06 -04:00
state
2023-05-24 15:15:21 -04:00
. borrow ( )
. op_state
. borrow ( )
. tracker
. track_async_completed ( op_id ) ;
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
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 =
2023-05-31 10:19:06 -04:00
v8 ::Boolean ::new ( scope , self . inner . state . borrow ( ) . has_tick_scheduled ) ;
2023-04-13 20:41:32 -04:00
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 ( ( ) )
}
2020-09-06 10:50:49 -04:00
}