diff --git a/crates/base/src/deno_runtime.rs b/crates/base/src/deno_runtime.rs index aca991e9a..1cb4a1a58 100644 --- a/crates/base/src/deno_runtime.rs +++ b/crates/base/src/deno_runtime.rs @@ -194,7 +194,6 @@ impl GlobalMainContext { struct DispatchEventFunctions { dispatch_load_event_fn_global: v8::Global, - dispatch_willterminate_event_fn_global: v8::Global, dispatch_beforeunload_event_fn_global: v8::Global, dispatch_unload_event_fn_global: v8::Global, } @@ -223,8 +222,8 @@ pub struct DenoRuntime { mem_check_state: Arc, waker: Arc, - willterminate_mem_threshold: Arc>, - willterminate_cpu_threshold: Arc>, + beforeunload_mem_threshold: Arc>, + beforeunload_cpu_threshold: Arc>, } impl Drop for DenoRuntime { @@ -476,24 +475,24 @@ impl DenoRuntime { let mut create_params = None; let mut mem_check_state = MemCheckState::default(); - let willterminate_cpu_threshold = ArcSwapOption::::from_pointee(None); - let willterminate_mem_threshold = ArcSwapOption::::from_pointee(None); + let beforeunload_cpu_threshold = ArcSwapOption::::from_pointee(None); + let beforeunload_mem_threshold = ArcSwapOption::::from_pointee(None); if conf.is_user_worker() { let conf = conf.as_user_worker().unwrap(); let memory_limit_bytes = mib_to_bytes(conf.memory_limit_mb) as usize; - willterminate_mem_threshold.store( + beforeunload_mem_threshold.store( flags - .willterminate_memory_pct + .beforeunload_memory_pct .and_then(|it| percentage_value(memory_limit_bytes as u64, it)) .map(Arc::new), ); if conf.cpu_time_hard_limit_ms > 0 { - willterminate_cpu_threshold.store( + beforeunload_cpu_threshold.store( flags - .willterminate_cpu_pct + .beforeunload_cpu_pct .and_then(|it| percentage_value(conf.cpu_time_hard_limit_ms, it)) .map(Arc::new), ); @@ -547,14 +546,6 @@ impl DenoRuntime { .unwrap(); let dispatch_load_event_fn = v8::Local::::try_from(dispatch_load_event_fn).unwrap(); - let dispatch_willterminate_event_fn_str = - v8::String::new_external_onebyte_static(scope, b"dispatchWillTerminateEvent") - .unwrap(); - let dispatch_willterminate_event_fn = bootstrap_ns - .get(scope, dispatch_willterminate_event_fn_str.into()) - .unwrap(); - let dispatch_willterminate_event_fn = - v8::Local::::try_from(dispatch_willterminate_event_fn).unwrap(); let dispatch_beforeunload_event_fn_str = v8::String::new_external_onebyte_static(scope, b"dispatchBeforeUnloadEvent") .unwrap(); @@ -572,15 +563,12 @@ impl DenoRuntime { v8::Local::::try_from(dispatch_unload_event_fn).unwrap(); let dispatch_load_event_fn_global = v8::Global::new(scope, dispatch_load_event_fn); - let dispatch_willterminate_event_fn_global = - v8::Global::new(scope, dispatch_willterminate_event_fn); let dispatch_beforeunload_event_fn_global = v8::Global::new(scope, dispatch_beforeunload_event_fn); let dispatch_unload_event_fn_global = v8::Global::new(scope, dispatch_unload_event_fn); DispatchEventFunctions { dispatch_load_event_fn_global, - dispatch_willterminate_event_fn_global, dispatch_beforeunload_event_fn_global, dispatch_unload_event_fn_global, } @@ -729,8 +717,8 @@ impl DenoRuntime { mem_check_state, waker: Arc::default(), - willterminate_cpu_threshold: Arc::new(willterminate_cpu_threshold), - willterminate_mem_threshold: Arc::new(willterminate_mem_threshold), + beforeunload_cpu_threshold: Arc::new(beforeunload_cpu_threshold), + beforeunload_mem_threshold: Arc::new(beforeunload_mem_threshold), }) } @@ -862,16 +850,6 @@ impl DenoRuntime { .await { let mut this = self.get_v8_tls_guard(); - let _ = with_cpu_metrics_guard( - current_thread_id, - &maybe_cpu_usage_metrics_tx, - &mut accumulated_cpu_time_ns, - || MaybeDenoRuntime::DenoRuntime(&mut this).dispatch_beforeunload_event(), - ); - - // TODO(Nyannyacha): Here we also need to trigger the event for node platform (i.e; - // beforeExit) - let _ = with_cpu_metrics_guard( current_thread_id, &maybe_cpu_usage_metrics_tx, @@ -889,18 +867,6 @@ impl DenoRuntime { let mut this = self.get_v8_tls_guard(); - if let Err(err) = with_cpu_metrics_guard( - current_thread_id, - &maybe_cpu_usage_metrics_tx, - &mut accumulated_cpu_time_ns, - || MaybeDenoRuntime::DenoRuntime(&mut this).dispatch_beforeunload_event(), - ) { - return (Err(err), get_accumulated_cpu_time_ms!()); - } - - // TODO(Nyannyacha): Here we also need to trigger the event for node platform (i.e; - // beforeExit) - if let Err(err) = with_cpu_metrics_guard( current_thread_id, &maybe_cpu_usage_metrics_tx, @@ -927,8 +893,8 @@ impl DenoRuntime { let is_termination_requested = self.termination_request_token.clone(); let global_waker = self.waker.clone(); - let willterminate_cpu_threshold = self.willterminate_cpu_threshold.clone(); - let willterminate_mem_threshold = self.willterminate_mem_threshold.clone(); + let beforeunload_cpu_threshold = self.beforeunload_cpu_threshold.clone(); + let beforeunload_mem_threshold = self.beforeunload_mem_threshold.clone(); let mem_check_state = is_user_worker.then(|| self.mem_check_state.clone()); @@ -995,32 +961,31 @@ impl DenoRuntime { let mem_state = mem_check_state.as_ref().unwrap(); let total_malloced_bytes = mem_state.check(js_runtime.v8_isolate().as_mut()); - if let Some(threshold_ms) = willterminate_cpu_threshold.load().as_deref().copied() { + if let Some(threshold_ms) = beforeunload_cpu_threshold.load().as_deref().copied() { let threshold_ns = (threshold_ms as i128) * 1_000_000; let accumulated_cpu_time_ns = *accumulated_cpu_time_ns as i128; if accumulated_cpu_time_ns >= threshold_ns { - willterminate_cpu_threshold.store(None); + beforeunload_cpu_threshold.store(None); if let Err(err) = MaybeDenoRuntime::DenoRuntime(&mut this) - .dispatch_willterminate_event(WillTerminateReason::CPU) + .dispatch_beforeunload_event(WillTerminateReason::CPU) { return Poll::Ready(Err(err)); } } } - if let Some(threshold_bytes) = - willterminate_mem_threshold.load().as_deref().copied() + if let Some(threshold_bytes) = beforeunload_mem_threshold.load().as_deref().copied() { let total_malloced_bytes = total_malloced_bytes as u64; if total_malloced_bytes >= threshold_bytes { - willterminate_mem_threshold.store(None); + beforeunload_mem_threshold.store(None); if !this.mem_check_state.is_exceeded() { if let Err(err) = MaybeDenoRuntime::DenoRuntime(&mut this) - .dispatch_willterminate_event(WillTerminateReason::Memory) + .dispatch_beforeunload_event(WillTerminateReason::Memory) { return Poll::Ready(Err(err)); } @@ -1271,15 +1236,15 @@ impl<'l> MaybeDenoRuntime<'l> { ) } - /// Dispatches "willterminate" event to the JavaScript runtime. - /// - /// Does not poll event loop, and thus not await any of the "willterminate" event handlers. - pub fn dispatch_willterminate_event( + /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean + /// indicating if the event was prevented and thus event loop should continue + /// running. + pub fn dispatch_beforeunload_event( &mut self, reason: WillTerminateReason, - ) -> Result<(), AnyError> { + ) -> Result { self.dispatch_event_with_callback( - |fns| &fns.dispatch_willterminate_event_fn_global, + |fns| &fns.dispatch_beforeunload_event_fn_global, move |scope| { vec![v8::String::new_external_onebyte_static( scope, @@ -1288,17 +1253,6 @@ impl<'l> MaybeDenoRuntime<'l> { .unwrap() .into()] }, - |_| Ok(()), - ) - } - - /// Dispatches "beforeunload" event to the JavaScript runtime. Returns a boolean - /// indicating if the event was prevented and thus event loop should continue - /// running. - pub fn dispatch_beforeunload_event(&mut self) -> Result { - self.dispatch_event_with_callback( - |fns| &fns.dispatch_beforeunload_event_fn_global, - |_| vec![], |it| Ok(it.unwrap().is_false()), ) } diff --git a/crates/base/src/rt_worker/supervisor/mod.rs b/crates/base/src/rt_worker/supervisor/mod.rs index 4f867369f..deeb278ba 100644 --- a/crates/base/src/rt_worker/supervisor/mod.rs +++ b/crates/base/src/rt_worker/supervisor/mod.rs @@ -156,7 +156,7 @@ async fn wait_cpu_alarm(maybe_alarm: Option<&mut UnboundedReceiver<()>>) -> Opti } } -async fn create_wall_clock_willterminate_alert(wall_clock_limit_ms: u64, pct: Option) { +async fn create_wall_clock_beforeunload_alert(wall_clock_limit_ms: u64, pct: Option) { let dur = pct .and_then(|it| percentage_value(wall_clock_limit_ms, it)) .map(Duration::from_millis); @@ -169,15 +169,15 @@ async fn create_wall_clock_willterminate_alert(wall_clock_limit_ms: u64, pct: Op } } -extern "C" fn v8_handle_wall_clock_willterminate( +extern "C" fn v8_handle_wall_clock_beforeunload( isolate: &mut v8::Isolate, _data: *mut std::ffi::c_void, ) { if let Err(err) = MaybeDenoRuntime::Isolate(isolate) - .dispatch_willterminate_event(WillTerminateReason::WallClock) + .dispatch_beforeunload_event(WillTerminateReason::WallClock) { warn!( - "found an error while dispatching the willterminate event: {}", + "found an error while dispatching the beforeunload event: {}", err ); } diff --git a/crates/base/src/rt_worker/supervisor/strategy_per_request.rs b/crates/base/src/rt_worker/supervisor/strategy_per_request.rs index be0faea97..3b922155d 100644 --- a/crates/base/src/rt_worker/supervisor/strategy_per_request.rs +++ b/crates/base/src/rt_worker/supervisor/strategy_per_request.rs @@ -9,9 +9,8 @@ use sb_workers::context::{Timing, TimingStatus, UserWorkerMsgs}; use tokio::time::Instant; use crate::rt_worker::supervisor::{ - create_wall_clock_willterminate_alert, v8_handle_termination, - v8_handle_wall_clock_willterminate, wait_cpu_alarm, CPUUsage, CPUUsageMetrics, Tokens, - V8HandleTerminationData, + create_wall_clock_beforeunload_alert, v8_handle_termination, v8_handle_wall_clock_beforeunload, + wait_cpu_alarm, CPUUsage, CPUUsageMetrics, Tokens, V8HandleTerminationData, }; use super::Arguments; @@ -57,7 +56,7 @@ pub async fn supervise(args: Arguments, oneshot: bool) -> (ShutdownReason, i64) let is_wall_clock_limit_disabled = wall_clock_limit_ms == 0; let mut is_worker_entered = false; - let mut is_wall_clock_willterminate_armed = false; + let mut is_wall_clock_beforeunload_armed = false; let mut cpu_usage_metrics_rx = cpu_usage_metrics_rx.unwrap(); let mut cpu_usage_ms = 0i64; @@ -75,13 +74,13 @@ pub async fn supervise(args: Arguments, oneshot: bool) -> (ShutdownReason, i64) let wall_clock_duration = Duration::from_millis(wall_clock_limit_ms); let wall_clock_duration_alert = tokio::time::sleep(wall_clock_duration); - let wall_clock_willterminate_alert = create_wall_clock_willterminate_alert( + let wall_clock_beforeunload_alert = create_wall_clock_beforeunload_alert( wall_clock_limit_ms, - flags.willterminate_wall_clock_pct, + flags.beforeunload_wall_clock_pct, ); tokio::pin!(wall_clock_duration_alert); - tokio::pin!(wall_clock_willterminate_alert); + tokio::pin!(wall_clock_beforeunload_alert); loop { tokio::select! { @@ -188,17 +187,17 @@ pub async fn supervise(args: Arguments, oneshot: bool) -> (ShutdownReason, i64) } } - _ = &mut wall_clock_willterminate_alert, - if !is_wall_clock_limit_disabled && !is_wall_clock_willterminate_armed + _ = &mut wall_clock_beforeunload_alert, + if !is_wall_clock_limit_disabled && !is_wall_clock_beforeunload_armed => { if thread_safe_handle.request_interrupt( - v8_handle_wall_clock_willterminate, + v8_handle_wall_clock_beforeunload, std::ptr::null_mut() ) { waker.wake(); } - is_wall_clock_willterminate_armed = true; + is_wall_clock_beforeunload_armed = true; } Some(_) = memory_limit_rx.recv() => { diff --git a/crates/base/src/rt_worker/supervisor/strategy_per_worker.rs b/crates/base/src/rt_worker/supervisor/strategy_per_worker.rs index 9e6ef0c4a..5c5b3a69e 100644 --- a/crates/base/src/rt_worker/supervisor/strategy_per_worker.rs +++ b/crates/base/src/rt_worker/supervisor/strategy_per_worker.rs @@ -8,7 +8,7 @@ use log::error; use sb_workers::context::{Timing, TimingStatus, UserWorkerMsgs}; use crate::rt_worker::supervisor::{ - create_wall_clock_willterminate_alert, v8_handle_wall_clock_willterminate, wait_cpu_alarm, + create_wall_clock_beforeunload_alert, v8_handle_wall_clock_beforeunload, wait_cpu_alarm, CPUUsage, Tokens, }; @@ -54,7 +54,7 @@ pub async fn supervise(args: Arguments) -> (ShutdownReason, i64) { let is_wall_clock_limit_disabled = wall_clock_limit_ms == 0; let mut is_worker_entered = false; - let mut is_wall_clock_willterminate_armed = false; + let mut is_wall_clock_beforeunload_armed = false; let mut cpu_usage_metrics_rx = cpu_usage_metrics_rx.unwrap(); let mut cpu_usage_ms = 0i64; @@ -79,9 +79,9 @@ pub async fn supervise(args: Arguments) -> (ShutdownReason, i64) { .unwrap_or(Duration::from_millis(1)), ); - let wall_clock_willterminate_alert = create_wall_clock_willterminate_alert( + let wall_clock_beforeunload_alert = create_wall_clock_beforeunload_alert( wall_clock_limit_ms, - flags.willterminate_wall_clock_pct, + flags.beforeunload_wall_clock_pct, ); let terminate_fn = { @@ -101,7 +101,7 @@ pub async fn supervise(args: Arguments) -> (ShutdownReason, i64) { }; tokio::pin!(wall_clock_duration_alert); - tokio::pin!(wall_clock_willterminate_alert); + tokio::pin!(wall_clock_beforeunload_alert); loop { tokio::select! { @@ -223,17 +223,17 @@ pub async fn supervise(args: Arguments) -> (ShutdownReason, i64) { } } - _ = &mut wall_clock_willterminate_alert, - if !is_wall_clock_limit_disabled && !is_wall_clock_willterminate_armed + _ = &mut wall_clock_beforeunload_alert, + if !is_wall_clock_limit_disabled && !is_wall_clock_beforeunload_armed => { if thread_safe_handle.request_interrupt( - v8_handle_wall_clock_willterminate, + v8_handle_wall_clock_beforeunload, std::ptr::null_mut() ) { waker.wake(); } - is_wall_clock_willterminate_armed = true; + is_wall_clock_beforeunload_armed = true; } Some(_) = memory_limit_rx.recv() => { diff --git a/crates/base/src/server.rs b/crates/base/src/server.rs index c28917af1..42cc3511f 100644 --- a/crates/base/src/server.rs +++ b/crates/base/src/server.rs @@ -252,9 +252,9 @@ pub struct ServerFlags { pub request_idle_timeout_ms: Option, pub request_read_timeout_ms: Option, - pub willterminate_wall_clock_pct: Option, - pub willterminate_cpu_pct: Option, - pub willterminate_memory_pct: Option, + pub beforeunload_wall_clock_pct: Option, + pub beforeunload_cpu_pct: Option, + pub beforeunload_memory_pct: Option, } #[derive(Debug)] diff --git a/crates/cli/src/flags.rs b/crates/cli/src/flags.rs index 02ba50b08..147c9f754 100644 --- a/crates/cli/src/flags.rs +++ b/crates/cli/src/flags.rs @@ -198,17 +198,17 @@ fn get_start_command() -> Command { .default_missing_value("true"), ) .arg( - arg!(--"dispatch-willterminate-wall-clock-ratio" ) + arg!(--"dispatch-beforeunload-wall-clock-ratio" ) .value_parser(value_parser!(u8).range(..=99)) .default_value("90") ) .arg( - arg!(--"dispatch-willterminate-cpu-ratio" ) + arg!(--"dispatch-beforeunload-cpu-ratio" ) .value_parser(value_parser!(u8).range(..=99)) .default_value("90") ) .arg( - arg!(--"dispatch-willterminate-memory-ratio" ) + arg!(--"dispatch-beforeunload-memory-ratio" ) .value_parser(value_parser!(u8).range(..=99)) .default_value("90") ) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 055dabb4f..44b9beb7d 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -135,14 +135,14 @@ fn main() -> Result<(), anyhow::Error> { let maybe_request_read_timeout = sub_matches.get_one::("request-read-timeout").cloned(); - let maybe_willterminate_wall_clock_pct = sub_matches - .get_one::("dispatch-willterminate-wall-clock-ratio") + let maybe_beforeunload_wall_clock_pct = sub_matches + .get_one::("dispatch-beforeunload-wall-clock-ratio") .cloned(); - let maybe_willterminate_cpu_pct = sub_matches - .get_one::("dispatch-willterminate-cpu-ratio") + let maybe_beforeunload_cpu_pct = sub_matches + .get_one::("dispatch-beforeunload-cpu-ratio") .cloned(); - let maybe_willterminate_memory_pct = sub_matches - .get_one::("dispatch-willterminate-memory-ratio") + let maybe_beforeunload_memory_pct = sub_matches + .get_one::("dispatch-beforeunload-memory-ratio") .cloned(); let static_patterns = @@ -184,9 +184,9 @@ fn main() -> Result<(), anyhow::Error> { request_idle_timeout_ms: maybe_request_idle_timeout, request_read_timeout_ms: maybe_request_read_timeout, - willterminate_wall_clock_pct: maybe_willterminate_wall_clock_pct, - willterminate_cpu_pct: maybe_willterminate_cpu_pct, - willterminate_memory_pct: maybe_willterminate_memory_pct, + beforeunload_wall_clock_pct: maybe_beforeunload_wall_clock_pct, + beforeunload_cpu_pct: maybe_beforeunload_cpu_pct, + beforeunload_memory_pct: maybe_beforeunload_memory_pct, }; start_server( diff --git a/crates/sb_core/js/bootstrap.js b/crates/sb_core/js/bootstrap.js index b60c2df68..217524988 100644 --- a/crates/sb_core/js/bootstrap.js +++ b/crates/sb_core/js/bootstrap.js @@ -405,18 +405,13 @@ function dispatchLoadEvent() { globalThis_.dispatchEvent(new Event("load")); } -function dispatchWillTerminateEvent(reason) { - globalThis_.dispatchEvent(new CustomEvent("willterminate", { - detail: { reason } +function dispatchBeforeUnloadEvent(reason) { + globalThis_.dispatchEvent(new CustomEvent("beforeunload", { + cancelable: true, + detail: { reason: reason ?? null } })); } -function dispatchBeforeUnloadEvent() { - return globalThis_.dispatchEvent( - new Event("beforeunload", { cancelable: true }), - ); -} - function dispatchUnloadEvent() { globalThis_.dispatchEvent(new Event("unload")); } @@ -622,7 +617,6 @@ globalThis.bootstrapSBEdge = opts => { globalThis.bootstrap = { dispatchLoadEvent, - dispatchWillTerminateEvent, dispatchUnloadEvent, dispatchBeforeUnloadEvent, // dispatchProcessExitEvent, diff --git a/crates/sb_workers/context.rs b/crates/sb_workers/context.rs index ccbd88c99..4769423c0 100644 --- a/crates/sb_workers/context.rs +++ b/crates/sb_workers/context.rs @@ -63,9 +63,9 @@ pub struct UserWorkerRuntimeOpts { pub cpu_time_soft_limit_ms: u64, pub cpu_time_hard_limit_ms: u64, - pub willterminate_wall_clock_pct: Option, - pub willterminate_cpu_pct: Option, - pub willterminate_memory_pct: Option, + pub beforeunload_wall_clock_pct: Option, + pub beforeunload_cpu_pct: Option, + pub beforeunload_memory_pct: Option, pub force_create: bool, pub net_access_disabled: bool, @@ -84,9 +84,9 @@ impl Default for UserWorkerRuntimeOpts { cpu_time_soft_limit_ms: 50, cpu_time_hard_limit_ms: 100, - willterminate_wall_clock_pct: None, - willterminate_cpu_pct: None, - willterminate_memory_pct: None, + beforeunload_wall_clock_pct: None, + beforeunload_cpu_pct: None, + beforeunload_memory_pct: None, force_create: false, key: None,