feat(runtime): publish exception and script load diagnostics

This commit is contained in:
Noz Wu
2026-11-20 01:52:30 +08:00
committed by Donough Liu
parent d1ccee7e06
commit c687399bac
40 changed files with 954 additions and 42 deletions
+3 -1
View File
@@ -18,8 +18,10 @@ pub mod testing;
pub use moli_page_types as protocol_types;
pub use moli_page_types::{LayoutConfiguration, LayoutPolicy, OptionalResourceFetchMask};
pub use moli_renderer_v8::ProcessEnvironmentOwner;
pub use moli_renderer_v8::renderer_output_transport_channel;
pub use moli_renderer_v8::{
DiagnosticEvent, DiagnosticSource, DiagnosticsSubscription, ProcessEnvironmentOwner,
};
pub use moli_renderer_v8::{
PageId, RendererBrowserContextRuntimeId, RendererDocumentLifecycleIdentity,
RendererDocumentTitleChanged, RendererOutputCursor, RendererOutputFence,
+10
View File
@@ -261,6 +261,16 @@ fn initial_navigation_request(request: Request) -> Request {
}
impl Browser {
/// Subscribe to diagnostics from this Browser's Pages and Workers.
///
/// The subscription receives future events. Producers continue when a
/// receiver lags. Drop the subscription to stop receiving diagnostics.
pub fn subscribe_diagnostics(&self) -> crate::DiagnosticsSubscription {
self.js_runtime
.browser_context_runtime()
.subscribe_diagnostics()
}
fn resource_request_client(&self) -> ResourceRequestClient {
ResourceRequestClient::from_browser_resource_runtime_with_page_network_policy(
self.resource_runtime.clone(),
+254
View File
@@ -0,0 +1,254 @@
use std::time::Duration;
use anyhow::Result;
use moli_core::{
DiagnosticEvent, DiagnosticSource, DiagnosticsSubscription,
runtime::{Browser, BrowserConfig},
};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::TcpListener,
task::JoinHandle,
};
#[tokio::test]
async fn browser_diagnostics_are_isolated_and_do_not_read_author_stack_properties() -> Result<()> {
let browser = Browser::new(BrowserConfig::default())?;
let other = Browser::new(BrowserConfig::default())?;
let mut page = browser.fetch("about:blank").await?;
page.evaluate_runtime_expression_async("reportError(new Error('before subscribing'))")
.await?;
let mut diagnostics = browser.subscribe_diagnostics();
let mut other_diagnostics = other.subscribe_diagnostics();
assert_empty(&mut diagnostics);
let result = page
.evaluate_runtime_expression_async(
r#"(() => {
let getterCalls = 0;
let prepareCalls = 0;
const error = new Error("with custom stack");
Object.defineProperty(error, "stack", {
get() { getterCalls++; return "author stack"; }
});
Error.prepareStackTrace = () => { prepareCalls++; return "prepared by author"; };
try {
reportError(error);
reportError(new Error("with lazy stack"));
const element = document.createElement("button");
element.setAttribute("onclick", "return )");
void element.onclick;
return JSON.stringify([getterCalls, prepareCalls]);
} finally {
delete Error.prepareStackTrace;
}
})()"#,
)
.await?;
assert_eq!(result["value"], "[0,0]");
for marker in ["with custom stack", "with lazy stack", "SyntaxError"] {
let event = diagnostics.try_recv()?;
assert!(
matches!(
event.as_ref(),
DiagnosticEvent::RuntimeException {
source: DiagnosticSource::Page { page_id },
message,
handled: false,
..
} if *page_id == page.page_id() && message.contains(marker)
),
"{event:?}"
);
}
assert_empty(&mut diagnostics);
assert_empty(&mut other_diagnostics);
Ok(())
}
#[tokio::test]
async fn parser_script_failures_emit_one_diagnostic_and_one_dom_event_each() -> Result<()> {
let server = DiagnosticFixtureServer::spawn().await?;
let browser = Browser::new(BrowserConfig::default())?;
let mut diagnostics = browser.subscribe_diagnostics();
let mut page = browser.fetch(&server.url("/parser")).await?;
let result = page
.evaluate_runtime_expression_async("scriptEvents.slice().sort().join(',')")
.await?;
assert_eq!(result["value"], "blocking,defer,written");
let mut urls = Vec::new();
for _ in 0..3 {
let event = diagnostics.try_recv()?;
let DiagnosticEvent::ScriptLoadFailure {
source: DiagnosticSource::Page { page_id },
url,
message,
} = event.as_ref()
else {
panic!("expected a Page script load failure, got {event:?}");
};
assert_eq!(*page_id, page.page_id());
assert!(message.contains("404"), "{message}");
urls.push(url.clone());
}
urls.sort();
assert_eq!(
urls,
["/blocking.js", "/defer.js", "/written.js"].map(|path| server.url(path))
);
assert_empty(&mut diagnostics);
Ok(())
}
#[tokio::test]
async fn shared_worker_diagnostics_identify_the_instance_across_clients() -> Result<()> {
let server = DiagnosticFixtureServer::spawn().await?;
let browser = Browser::new(BrowserConfig::default())?;
let mut diagnostics = browser.subscribe_diagnostics();
let mut instance = None;
let mut first = browser.fetch(&server.url("/page")).await?;
let mut second = browser.fetch(&server.url("/page")).await?;
for page in [&mut first, &mut second] {
let result = tokio::time::timeout(
Duration::from_secs(15),
page.evaluate_runtime_expression_with_await_async(
r#"new Promise((resolve, reject) => {
globalThis.worker = new SharedWorker("/shared.js", "diagnostics");
worker.onerror = () => reject(Error("could not start SharedWorker"));
worker.port.onmessage = event => resolve(event.data);
})"#,
true,
),
)
.await??;
assert_eq!(result["value"], "ready", "{result}");
}
for (page, marker) in [(&mut first, "first"), (&mut second, "second")] {
page.evaluate_runtime_expression_async(&format!("worker.port.postMessage({marker:?})"))
.await?;
let event = tokio::time::timeout(Duration::from_secs(15), diagnostics.recv()).await??;
let DiagnosticEvent::RuntimeException {
source: DiagnosticSource::SharedWorker { instance_id },
message,
filename,
..
} = event.as_ref()
else {
panic!("expected a SharedWorker exception, got {event:?}");
};
assert!(message.contains(marker), "{message}");
assert_eq!(filename, &server.url("/shared.js"));
assert_eq!(*instance.get_or_insert(*instance_id), *instance_id);
}
let result = tokio::time::timeout(
Duration::from_secs(15),
first.evaluate_runtime_expression_with_await_async(
r#"new Promise(resolve => {
globalThis.missingWorker = new SharedWorker("/missing.js");
missingWorker.onerror = () => resolve("error");
})"#,
true,
),
)
.await??;
assert_eq!(result["value"], "error", "{result}");
let failure = diagnostics.try_recv()?;
assert!(
matches!(
failure.as_ref(),
DiagnosticEvent::ScriptLoadFailure {
source: DiagnosticSource::SharedWorker { instance_id },
url,
message,
} if Some(*instance_id) != instance && url == &server.url("/missing.js") && message.contains("404")
),
"{failure:?}"
);
assert_empty(&mut diagnostics);
Ok(())
}
fn assert_empty(diagnostics: &mut DiagnosticsSubscription) {
assert_eq!(
diagnostics.try_recv(),
Err(tokio::sync::broadcast::error::TryRecvError::Empty),
);
}
struct DiagnosticFixtureServer {
origin: String,
task: JoinHandle<()>,
}
impl DiagnosticFixtureServer {
async fn spawn() -> Result<Self> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let origin = format!("http://{}", listener.local_addr()?);
let task = tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let mut stream = BufReader::new(stream);
let mut line = String::new();
stream.read_line(&mut line).await.unwrap();
let (status, content_type, body) = fixture_response(line.split_whitespace().nth(1));
loop {
line.clear();
if stream.read_line(&mut line).await.unwrap() == 0 || line == "\r\n" {
break;
}
}
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len(),
);
stream
.get_mut()
.write_all(response.as_bytes())
.await
.unwrap();
stream.get_mut().shutdown().await.unwrap();
}
});
Ok(Self { origin, task })
}
fn url(&self, path: &str) -> String {
format!("{}{path}", self.origin)
}
}
impl Drop for DiagnosticFixtureServer {
fn drop(&mut self) {
self.task.abort();
}
}
fn fixture_response(path: Option<&str>) -> (&'static str, &'static str, &'static str) {
match path {
Some("/parser") => (
"200 OK",
"text/html",
r#"<!doctype html>
<script>globalThis.scriptEvents = [];</script>
<script src="/blocking.js" onerror="scriptEvents.push('blocking')"></script>
<script defer src="/defer.js" onerror="scriptEvents.push('defer')"></script>
<script>
document.write(`<script src="/written.js" onerror="scriptEvents.push('written')"><\/script>`);
</script>"#,
),
Some("/page") => ("200 OK", "text/html", "<!doctype html>"),
Some("/shared.js") => (
"200 OK",
"text/javascript",
"onconnect = event => {
const port = event.ports[0];
port.onmessage = event => { throw new Error(event.data); };
port.postMessage('ready');
};",
),
_ => ("404 Not Found", "text/plain", "fixture script not found"),
}
}
@@ -5,11 +5,10 @@
window.parserOwnedModuleTlaPayloadOrder = [];
window.addEventListener("error", (event) => {
window.parserOwnedModuleTlaPayloadOrder.push("window-error");
window.parserOwnedModuleTlaPayloadErrorMessageMatches = Boolean(
event.error &&
typeof event.error.message === "string" &&
event.error.message.length > 0,
);
window.parserOwnedModuleTlaPayloadErrorIdentityMatches =
event.error === window.parserOwnedModuleTlaPayloadReason;
window.parserOwnedModuleTlaPayloadErrorMessageMatches =
typeof event.message === "string" && event.message.length > 0;
window.parserOwnedModuleTlaPayloadFilenameMatches =
typeof event.filename === "string" &&
event.filename.includes(
@@ -21,8 +20,8 @@
type="module"
onerror="window.parserOwnedModuleTlaPayloadOrder.push('script-error');"
>
const reason = Object.create(null);
await Promise.reject(reason);
window.parserOwnedModuleTlaPayloadReason = Object.create(null);
await Promise.reject(window.parserOwnedModuleTlaPayloadReason);
</script>
<script type="module">
window.parserOwnedModuleTlaPayloadOrder.push("later-module");
+4
View File
@@ -3902,6 +3902,10 @@ async fn parser_owned_module_tla_exotic_rejection_reports_window_error_payload_w
diagnostic_global(&page, "parserOwnedModuleTlaPayloadContinuation"),
Some(&JsValueSnapshot::Bool(true))
);
assert_eq!(
diagnostic_global(&page, "parserOwnedModuleTlaPayloadErrorIdentityMatches"),
Some(&JsValueSnapshot::Bool(true))
);
assert_eq!(
diagnostic_global(&page, "parserOwnedModuleTlaPayloadErrorMessageMatches"),
Some(&JsValueSnapshot::Bool(true))
+6 -5
View File
@@ -568,11 +568,12 @@ pub(crate) use self::webassembly_runtime::{
};
pub(crate) use self::websocket::{WebSocketDispatchResult, dispatch_websocket_event};
pub(crate) use self::window_events::{
clear_simple_window_event_handler_values, dispatch_window_error_event_with_details,
dispatch_window_promise_rejection_event, dispatch_window_report_error_message,
event_handler_property_is_exposed, install_simple_window_event_handlers,
is_window_event_handler_property, set_window_body_onerror_handler_compiled,
set_window_onerror_handler_value, window_body_onerror_handler_is_compiled,
clear_simple_window_event_handler_values, dispatch_window_error_event,
dispatch_window_error_event_with_details, dispatch_window_promise_rejection_event,
dispatch_window_report_error_message, event_handler_property_is_exposed,
install_simple_window_event_handlers, is_window_event_handler_property,
set_window_body_onerror_handler_compiled, set_window_onerror_handler_value,
window_body_onerror_handler_is_compiled,
};
#[cfg(test)]
pub(crate) use self::window_lazy_surface::window_lazy_surface_diagnostics;
@@ -165,7 +165,8 @@ pub(super) use console::{
};
pub(super) use error::window_report_error_callback;
pub(crate) use error::{
dispatch_window_error_event_with_details, dispatch_window_report_error_message,
dispatch_window_error_event, dispatch_window_error_event_with_details,
dispatch_window_report_error_message,
};
pub(crate) use install::event_handler_property_is_exposed;
pub(super) use install::install_window_global_accessors;
@@ -117,6 +117,49 @@ pub(crate) fn dispatch_window_error_event_with_details<'s>(
colno: u32,
error_value: Option<v8::Local<'s, v8::Value>>,
) -> std::result::Result<(), String> {
let event = dispatch_window_error_event(
scope,
host_ptr,
message,
filename,
lineno,
colno,
error_value,
)?;
if let Some(event) = event {
unsafe { &*host_ptr }.emit_diagnostic(|source| {
let handled =
crate::context_bootstrap::event_bool_attribute(scope, event, "defaultPrevented");
let stack = if handled {
None
} else {
error_value.and_then(|value| {
crate::exception_reporting::captured_exception_stack(scope, value)
})
};
Some(crate::DiagnosticEvent::runtime_exception(
source,
message,
filename,
lineno,
colno,
stack.as_deref(),
handled,
))
});
}
Ok(())
}
pub(crate) fn dispatch_window_error_event<'s>(
scope: &mut v8::PinScope<'s, '_>,
host_ptr: *mut PageScriptHost,
message: &str,
filename: &str,
lineno: u32,
colno: u32,
error_value: Option<v8::Local<'s, v8::Value>>,
) -> std::result::Result<Option<v8::Local<'s, v8::Object>>, String> {
ensure_window_reflecting_body_onerror_handler(scope);
let error_value = error_value.unwrap_or_else(|| v8::null(scope).into());
@@ -146,7 +189,7 @@ pub(crate) fn dispatch_window_error_event_with_details<'s>(
.ok()
.and_then(|ctor| ctor.new_instance(scope, &[event_type.into(), init.into()]));
let Some(event) = event else {
return Ok(());
return Ok(None);
};
mark_event_trusted(scope, event);
@@ -155,7 +198,7 @@ pub(crate) fn dispatch_window_error_event_with_details<'s>(
crate::context_bootstrap::child_browsing_context_handle_for_current_realm_scope(scope)
{
runtime.dispatch_child_window_event(scope, child_handle, "error", event);
return Ok(());
return Ok(Some(event));
}
runtime.dispatch_public_event(scope, host_ptr, EventTargetHandle::Window, event)?;
@@ -171,7 +214,7 @@ pub(crate) fn dispatch_window_error_event_with_details<'s>(
v8str(scope, "currentTarget").into(),
global_value,
);
Ok(())
Ok(Some(event))
}
pub(in crate::context_bootstrap) fn window_report_error_callback<'s>(
@@ -455,6 +455,15 @@ pub(in crate::context_bootstrap) fn worker_constructor_callback<'s>(
) {
Ok(source) => source,
Err(message) => {
nested_context
.worker_context_runtime
.emit_diagnostic(|source| {
crate::DiagnosticEvent::script_load_failure(
source,
resolved_url.as_str(),
&message,
)
});
let _ =
nested_context
.wake_tx
+147
View File
@@ -0,0 +1,147 @@
//! Best-effort diagnostics shared by the Pages and Workers of one Browser.
use std::sync::{Arc, OnceLock};
use tokio::sync::broadcast;
const CAPACITY: usize = 128;
const TEXT_MAX_BYTES: usize = 4 * 1024;
const STACK_MAX_BYTES: usize = 16 * 1024;
/// The Page or Worker that produced a diagnostic.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DiagnosticSource {
Page { page_id: u64 },
DedicatedWorker { instance_id: u64 },
SharedWorker { instance_id: u64 },
ServiceWorker { version_id: u64 },
}
/// A structured, best-effort observation from a Browser.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DiagnosticEvent {
/// A reported script exception or promise rejection.
RuntimeException {
source: DiagnosticSource,
message: String,
filename: String,
/// One-based source line, or zero when unavailable.
lineno: u32,
/// One-based source column, or zero when unavailable.
colno: u32,
/// Native stack frames, when available.
stack: Option<String>,
/// Whether the source realm canceled default reporting.
handled: bool,
},
/// A script whose source could not be loaded.
ScriptLoadFailure {
source: DiagnosticSource,
url: String,
message: String,
},
}
/// A live subscription to future diagnostics in one Browser.
///
/// A slow receiver skips older events and receives a lag error with the number
/// skipped. Dropping the receiver removes this subscription.
pub type DiagnosticsSubscription = broadcast::Receiver<Arc<DiagnosticEvent>>;
impl DiagnosticEvent {
pub(crate) fn runtime_exception(
source: DiagnosticSource,
message: &str,
filename: &str,
lineno: u32,
colno: u32,
stack: Option<&str>,
handled: bool,
) -> Self {
Self::RuntimeException {
source,
message: bounded(message, TEXT_MAX_BYTES),
filename: bounded(filename, TEXT_MAX_BYTES),
lineno,
colno,
stack: stack.map(|stack| bounded(stack, STACK_MAX_BYTES)),
handled,
}
}
pub(crate) fn script_load_failure(source: DiagnosticSource, url: &str, message: &str) -> Self {
Self::ScriptLoadFailure {
source,
url: bounded(url, TEXT_MAX_BYTES),
message: bounded(message, TEXT_MAX_BYTES),
}
}
}
fn bounded(value: &str, max_bytes: usize) -> String {
value[..value.floor_char_boundary(max_bytes)].to_owned()
}
#[derive(Clone, Debug, Default)]
pub(crate) struct DiagnosticEmitter(Arc<OnceLock<broadcast::Sender<Arc<DiagnosticEvent>>>>);
impl DiagnosticEmitter {
pub(crate) fn subscribe(&self) -> DiagnosticsSubscription {
self.0
.get_or_init(|| broadcast::Sender::new(CAPACITY))
.subscribe()
}
pub(crate) fn emit(&self, build: impl FnOnce() -> Option<DiagnosticEvent>) {
if let Some(sender) = self.0.get()
&& sender.receiver_count() != 0
&& let Some(event) = build()
{
let _ = sender.send(Arc::new(event));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn diagnostics_are_lazy_after_the_last_receiver_is_dropped() {
let diagnostics = DiagnosticEmitter::default();
assert!(diagnostics.0.get().is_none());
diagnostics.emit(|| panic!("no receiver"));
let receiver = diagnostics.subscribe();
drop(receiver);
diagnostics.emit(|| panic!("the receiver was dropped"));
}
#[test]
fn slow_diagnostic_receivers_lag_and_messages_are_bounded() {
let diagnostics = DiagnosticEmitter::default();
let mut slow = diagnostics.subscribe();
let mut fast = diagnostics.subscribe();
let message = "€".repeat(TEXT_MAX_BYTES);
for _ in 0..=CAPACITY {
diagnostics.emit(|| {
Some(DiagnosticEvent::script_load_failure(
DiagnosticSource::Page { page_id: 1 },
"https://example.test/missing.js",
&message,
))
});
let event = fast.try_recv().expect("event for fast receiver");
assert!(matches!(
event.as_ref(),
DiagnosticEvent::ScriptLoadFailure { message, .. } if message.len() == 4095
));
}
assert_eq!(
slow.try_recv(),
Err(broadcast::error::TryRecvError::Lagged(1))
);
assert!(slow.try_recv().is_ok());
}
}
@@ -1592,6 +1592,8 @@ impl DocumentRuntime {
}
}
Err(error_message) => {
unsafe { &*host_ptr }
.emit_script_load_failure(start.script.url.as_str(), &error_message);
tracing::debug!(
host_script_handle = start.host_script_handle.as_str(),
url = %start.script.url,
@@ -246,6 +246,10 @@ impl DocumentRuntime {
.current_main_document_resource_loader()
.is_none()
{
unsafe { &*host_ptr }.emit_script_load_failure(
script.url.as_str(),
"script resource loader is unavailable",
);
let task = ScriptEventTask::new(ScriptEventKind::Error, host_script_handle);
if let Err(error) = self.host_dispatch_script_event(scope, host_ptr, &task) {
debug!(
@@ -116,6 +116,77 @@ fn exception_stack_property<'s>(
local_value_to_string(scope, stack).filter(|stack| !stack.is_empty())
}
/// Format V8-captured frames without reading the JavaScript stack property.
pub(crate) fn captured_exception_stack<'s>(
scope: &mut v8::PinScope<'s, '_>,
exception: v8::Local<'s, v8::Value>,
) -> Option<String> {
if !exception.is_native_error() {
return None;
}
let stack = v8::Exception::get_stack_trace(scope, exception)?;
let frames = (0..stack.get_frame_count().min(32))
.filter_map(|index| stack.get_frame(scope, index))
.map(|frame| {
// Source locations come from Message. Some rejection paths do
// not expose a valid Script for their captured frames.
let name = frame
.get_function_name(scope)
.map(|name| name.to_rust_string_lossy(scope))
.unwrap_or_else(|| "<anonymous>".to_owned());
format!("at {}", bounded_log_field(&name, LOG_SOURCE_LINE_MAX_BYTES))
})
.collect::<Vec<_>>();
(!frames.is_empty()).then(|| frames.join("\n"))
}
pub(crate) fn exception_message_details<'s>(
scope: &mut v8::PinScope<'s, '_>,
value: v8::Local<'s, v8::Value>,
) -> (String, String, u32, u32) {
let description = v8::Exception::create_message(scope, value);
let message = description.get(scope).to_rust_string_lossy(scope);
let filename = description
.get_script_resource_name(scope)
.filter(|value| value.is_string())
.map(|value| value.to_rust_string_lossy(scope))
.unwrap_or_default();
let lineno = description
.get_line_number(scope)
.and_then(|line| u32::try_from(line).ok())
.unwrap_or(0);
let colno = description
.get_start_column()
.checked_add(1)
.and_then(|column| u32::try_from(column).ok())
.unwrap_or(0);
(message, filename, lineno, colno)
}
pub(crate) fn diagnostic_from_exception<'s>(
scope: &mut v8::PinScope<'s, '_>,
source: crate::DiagnosticSource,
value: Option<v8::Local<'s, v8::Value>>,
handled: bool,
) -> crate::DiagnosticEvent {
let value = value.unwrap_or_else(|| v8::undefined(scope).into());
let (message, filename, lineno, colno) = exception_message_details(scope, value);
let stack = if handled {
None
} else {
captured_exception_stack(scope, value)
};
crate::DiagnosticEvent::runtime_exception(
source,
&message,
&filename,
lineno,
colno,
stack.as_deref(),
handled,
)
}
/// Module creation must not eagerly read Error.stack or call an author's
/// Error.prepareStackTrace hook while retaining a parse exception.
pub(super) fn build_exception_report_without_stack<'s>(
+2
View File
@@ -50,6 +50,7 @@ mod detached_css_style;
mod detached_dom_surface;
mod detached_event_target;
mod devtools;
mod diagnostics;
mod document_color_scheme;
mod document_cookie_owner;
mod document_language;
@@ -222,6 +223,7 @@ pub(crate) use context_bootstrap::{
form_data_entries_to_string_pairs, form_data_object_from_entries_for_window,
snapshot_form_data_value,
};
pub use diagnostics::{DiagnosticEvent, DiagnosticSource, DiagnosticsSubscription};
pub use document_cookie_owner::{
DocumentCookieBackendConnectionState, DocumentCookieBrowserContextSnapshot,
DocumentCookieGetFreshnessStatus, DocumentCookieOwnerSnapshot,
@@ -1928,7 +1928,7 @@ impl PageScriptHost {
&mut self,
failed: FrameDocumentClassicSourceFailureWork,
) -> FrameDocumentClassicSourceFailureReportApplication {
let (target, _failure, script_element_event) = failed.into_parts();
let (target, failure, script_element_event) = failed.into_parts();
let child_handle = target.child_handle();
let owner = target.task_owner().document_owner();
let runner_owner_current = self.frame_parser_classic_scripts.has_runner(owner);
@@ -1967,6 +1967,7 @@ impl PageScriptHost {
FrameDocumentClassicSourceFailureReportSkipReason::StaleRealm,
);
}
self.emit_script_load_failure(failure.script_url().as_str(), failure.error());
FrameDocumentClassicSourceFailureReportApplication::completed(
FrameDocumentClassicScriptCompletionAction::new(
FrameDocumentClassicScriptCompletionTarget::new(
@@ -131,6 +131,24 @@ impl PageScriptHost {
self.page_script_environment.as_ref()?.upgrade()
}
pub(crate) fn emit_diagnostic(
&self,
build: impl FnOnce(crate::DiagnosticSource) -> Option<crate::DiagnosticEvent>,
) {
self.browser_context_runtime.diagnostics().emit(|| {
let page_id = self.page_script_environment()?.page_id();
build(crate::DiagnosticSource::Page { page_id })
});
}
pub(crate) fn emit_script_load_failure(&self, url: &str, message: &str) {
self.emit_diagnostic(|source| {
Some(crate::DiagnosticEvent::script_load_failure(
source, url, message,
))
});
}
#[cfg(test)]
pub(crate) fn bind_auxiliary_window_for_test(
&mut self,
@@ -172,6 +172,9 @@ impl PageScriptHost {
let mut worker_handle = spawn_worker_with_options(
options
.with_interception_context(context)
.with_diagnostic_source(crate::DiagnosticSource::DedicatedWorker {
instance_id: renderer_instance_id,
})
.with_pause_evaluation_until_debugger(true),
);
self.browser_context_runtime()
@@ -593,12 +596,16 @@ impl PageScriptHost {
if let Some(client_id) = reserved_service_worker_client_id {
spawn_options = spawn_options.with_reserved_service_worker_client_id(client_id);
}
let mut worker_handle = spawn_worker_with_options(spawn_options);
let renderer_instance_id = self
.workers
.get(&worker_id)
.map(|state| state.renderer_instance_id)
.expect("loading DedicatedWorker must retain its renderer instance identity");
let mut worker_handle = spawn_worker_with_options(spawn_options.with_diagnostic_source(
crate::DiagnosticSource::DedicatedWorker {
instance_id: renderer_instance_id,
},
));
self.browser_context_runtime()
.attach_dedicated_worker_control(
renderer_instance_id,
@@ -761,10 +768,17 @@ impl PageScriptHost {
let Some(state) = self.workers.get(&worker_id) else {
return false;
};
let instance_id = state.renderer_instance_id;
self.browser_context_runtime.diagnostics().emit(|| {
Some(crate::DiagnosticEvent::script_load_failure(
crate::DiagnosticSource::DedicatedWorker { instance_id },
&script_url,
&error_message,
))
});
if !state.target_created {
return true;
}
let instance_id = state.renderer_instance_id;
self.append_dedicated_worker_target_lifecycle(
crate::runtime::RendererDedicatedWorkerTargetEvent::ScriptLoadFailed {
instance_id,
@@ -9,6 +9,7 @@ use std::{
rc::{Rc, Weak},
};
use crate::diagnostics::{DiagnosticEmitter, DiagnosticEvent, DiagnosticSource};
use crate::planning::{
PreparedScript, SharedScriptSourceLoadCompleter,
external_script_source_load_outcome_from_result,
@@ -162,6 +163,9 @@ impl RendererProducerRegistrar {
/// the SharedWorker constructor on Window.
#[derive(Clone, Debug)]
pub(crate) struct RendererWorkerContextRuntime {
diagnostics: DiagnosticEmitter,
diagnostic_source: Option<DiagnosticSource>,
next_dedicated_worker_instance_id: Arc<AtomicU64>,
debugger_enabled: bool,
#[cfg(feature = "devtools")]
shared_worker_pause_on_start: Arc<AtomicBool>,
@@ -180,6 +184,7 @@ pub(crate) struct RendererStoragePartitionIdentity {
#[derive(Debug)]
struct RendererBrowserContextRuntimeInner {
diagnostics: DiagnosticEmitter,
debugger_enabled: bool,
id: super::RendererBrowserContextRuntimeId,
// Commit style and representations together, independently of any page's
@@ -194,7 +199,7 @@ struct RendererBrowserContextRuntimeInner {
storage_partition_identity: RendererStoragePartitionIdentity,
next_child_document_loader_id: AtomicU64,
next_detached_parser_script_fetch_id: AtomicU64,
next_dedicated_worker_instance_id: AtomicU64,
next_dedicated_worker_instance_id: Arc<AtomicU64>,
dedicated_worker_targets: Mutex<HashMap<u64, DedicatedWorkerTarget>>,
#[cfg(feature = "devtools")]
dedicated_worker_pause_on_start_for_devtools: AtomicBool,
@@ -592,6 +597,7 @@ impl RendererBrowserContextRuntime {
);
Self {
inner: Arc::new(RendererBrowserContextRuntimeInner {
diagnostics: DiagnosticEmitter::default(),
debugger_enabled,
id,
clipboard_snapshot: Mutex::new(ClipboardSnapshot::default()),
@@ -604,7 +610,7 @@ impl RendererBrowserContextRuntime {
storage_partition_identity,
next_child_document_loader_id: AtomicU64::default(),
next_detached_parser_script_fetch_id: AtomicU64::default(),
next_dedicated_worker_instance_id: AtomicU64::default(),
next_dedicated_worker_instance_id: Arc::default(),
dedicated_worker_targets: Mutex::new(HashMap::new()),
#[cfg(feature = "devtools")]
dedicated_worker_pause_on_start_for_devtools: AtomicBool::new(false),
@@ -774,8 +780,19 @@ impl RendererBrowserContextRuntime {
self.inner.broadcast_channel_registry.clone()
}
pub fn subscribe_diagnostics(&self) -> crate::DiagnosticsSubscription {
self.inner.diagnostics.subscribe()
}
pub(crate) fn diagnostics(&self) -> &DiagnosticEmitter {
&self.inner.diagnostics
}
pub(crate) fn worker_context_runtime(&self) -> RendererWorkerContextRuntime {
RendererWorkerContextRuntime {
diagnostics: self.inner.diagnostics.clone(),
diagnostic_source: None,
next_dedicated_worker_instance_id: self.inner.next_dedicated_worker_instance_id.clone(),
debugger_enabled: self.inner.debugger_enabled,
#[cfg(feature = "devtools")]
shared_worker_pause_on_start: self
@@ -1044,6 +1061,9 @@ impl RendererWorkerContextRuntime {
debugger_enabled: bool,
) -> Self {
Self {
diagnostics: DiagnosticEmitter::default(),
diagnostic_source: None,
next_dedicated_worker_instance_id: Arc::default(),
debugger_enabled,
#[cfg(feature = "devtools")]
shared_worker_pause_on_start: Arc::new(AtomicBool::new(false)),
@@ -1053,6 +1073,23 @@ impl RendererWorkerContextRuntime {
}
}
pub(crate) fn with_diagnostic_source(mut self, source: DiagnosticSource) -> Self {
self.diagnostic_source = Some(source);
self
}
pub(crate) fn for_nested_dedicated_worker(self) -> Self {
let instance_id = self
.next_dedicated_worker_instance_id
.fetch_add(1, Ordering::Relaxed)
.saturating_add(1);
self.with_diagnostic_source(DiagnosticSource::DedicatedWorker { instance_id })
}
pub(crate) fn emit_diagnostic(&self, build: impl FnOnce(DiagnosticSource) -> DiagnosticEvent) {
self.diagnostics.emit(|| self.diagnostic_source.map(build));
}
pub(crate) fn message_port_registry(
&self,
) -> crate::message_port_runtime::SharedMessagePortRegistry {
+29 -7
View File
@@ -497,6 +497,7 @@ enum PageOwnedScriptFailureClassification {
dynamic_kind: crate::dynamic_script_owner::DynamicScriptFailureKind,
module_failure_policy: Option<crate::host::ModuleFailurePolicy>,
error_constructor: Option<ScriptErrorConstructorKind>,
failed_module: Option<crate::module_runtime::ModuleEntryId>,
},
}
@@ -514,6 +515,7 @@ impl PageOwnedScriptFailureClassification {
),
module_failure_policy: error.module_failure_policy(),
error_constructor: error.error_constructor(),
failed_module: None,
},
)
}
@@ -521,8 +523,18 @@ impl PageOwnedScriptFailureClassification {
fn from_module_load_error(
script: &PreparedScript,
error: &crate::module_runtime::ModuleLoadError,
) -> Self {
Self::from_module_error_with_entry(script, error, None)
}
fn from_module_error_with_entry(
script: &PreparedScript,
error: &crate::module_runtime::ModuleLoadError,
root_entry: Option<crate::module_runtime::ModuleEntryId>,
) -> Self {
let module_failure_policy = crate::host::ModuleFailurePolicy::for_module_load_error(error);
let failed_module = root_entry
.filter(|_| error.stage() == crate::module_runtime::ModuleLoadStage::Evaluate);
PageOwnedScriptFailureClassification::Typed {
dynamic_kind: crate::dynamic_script_owner::DynamicScriptOwner::module_load_failure_kind(
script,
@@ -530,6 +542,7 @@ impl PageOwnedScriptFailureClassification {
),
module_failure_policy: Some(module_failure_policy),
error_constructor: error.error_constructor(),
failed_module,
}
}
}
@@ -608,6 +621,7 @@ fn complete_prepared_script_execution_failure(
dynamic_kind,
module_failure_policy,
error_constructor,
..
} => vm.finish_runtime_owned_script_failure_with_kind(
dynamic_script_owner_id,
&script,
@@ -626,19 +640,22 @@ fn complete_prepared_script_execution_failure(
Some(script.url.as_str()),
);
} else if vm.parser_owned_module_reports_failure_immediately(&script) {
let (module_failure_policy, error_constructor) = match failure_classification {
let (module_failure_policy, error_constructor, failed_module) = match failure_classification
{
PageOwnedScriptFailureClassification::Typed {
module_failure_policy,
error_constructor,
failed_module,
..
} => (module_failure_policy, error_constructor),
PageOwnedScriptFailureClassification::LegacyMessageText => (None, None),
} => (module_failure_policy, error_constructor, failed_module),
PageOwnedScriptFailureClassification::LegacyMessageText => (None, None, None),
};
vm.dispatch_parser_owned_module_failure_and_finish_settlement_best_effort(
&script,
&error,
module_failure_policy,
error_constructor,
failed_module,
);
} else {
let (module_failure_policy, error_constructor) = match failure_classification {
@@ -675,6 +692,7 @@ fn complete_page_owned_prepared_script_execution_failure_body(
dynamic_kind,
module_failure_policy,
error_constructor,
..
} => (dynamic_kind, module_failure_policy, error_constructor),
PageOwnedScriptFailureClassification::LegacyMessageText => (
crate::dynamic_script_owner::DynamicScriptOwner::legacy_message_failure_kind(
@@ -693,22 +711,25 @@ fn complete_page_owned_prepared_script_execution_failure_body(
error_constructor,
)
} else if vm.parser_owned_inline_importmap_reports_window_error_immediately(&script) {
vm.report_window_error_body_best_effort(&error, Some(script.url.as_str()), None);
vm.report_window_error_body_best_effort(&error, Some(script.url.as_str()), None, None);
crate::script_vm::ScriptTerminalBodyActivity::EventDispatchAttempted
} else if vm.parser_owned_module_reports_failure_immediately(&script) {
let (module_failure_policy, error_constructor) = match failure_classification {
let (module_failure_policy, error_constructor, failed_module) = match failure_classification
{
PageOwnedScriptFailureClassification::Typed {
module_failure_policy,
error_constructor,
failed_module,
..
} => (module_failure_policy, error_constructor),
PageOwnedScriptFailureClassification::LegacyMessageText => (None, None),
} => (module_failure_policy, error_constructor, failed_module),
PageOwnedScriptFailureClassification::LegacyMessageText => (None, None, None),
};
vm.dispatch_current_prepared_script_error_body_best_effort(
&script,
&error,
module_failure_policy,
error_constructor,
failed_module,
)
} else {
let (module_failure_policy, error_constructor) = match failure_classification {
@@ -2633,6 +2654,7 @@ impl PageVm {
dynamic_kind,
module_failure_policy,
error_constructor,
..
},
) if dynamic_kind.is_deferrable_module() => {
self.vm_mut()
@@ -356,6 +356,10 @@ impl ParserClassicDocumentScriptExecutionHooks
));
}
owner.record_network_result(&failure.script, failure.source_network_result.as_ref());
owner
.page_vm
.vm()
.emit_script_load_failure(failure.script.url.as_str(), &failure.error);
let _ = owner
.page_vm
.vm_mut()
@@ -206,9 +206,10 @@ impl PageVm {
let (error, prepared_activity) = failure.into_parts();
let message = error.message().to_owned();
let failure_classification =
PageOwnedScriptFailureClassification::from_module_load_error(
PageOwnedScriptFailureClassification::from_module_error_with_entry(
&script_continuation.script,
&error,
Some(graph.root_entry),
);
self.complete_module_script_failure_for_terminal_disposition(
script_continuation,
@@ -442,6 +443,7 @@ impl PageVm {
&message,
Some(evaluation.script_continuation.script.url.as_str()),
error_constructor,
Some(evaluation.root_entry),
);
MainParserContinuationTaskEffect::applied(
owner,
@@ -450,6 +452,7 @@ impl PageVm {
} else {
self.vm_mut()
.report_module_tla_rejection_and_finish_reaction_best_effort(
evaluation.root_entry,
&message,
Some(evaluation.script_continuation.script.url.as_str()),
error_constructor,
@@ -501,6 +504,7 @@ impl PageVm {
crate::host::ModuleFailurePolicy::EvaluationFailure,
),
error_constructor,
failed_module: Some(evaluation.root_entry),
},
PreparedScriptBodyActivity::NotEntered,
terminal_disposition,
@@ -307,6 +307,88 @@ async fn main_parser_module_tla_rejection_reports_without_duplicate_completion()
})
.await;
}
#[tokio::test(flavor = "current_thread")]
async fn main_parser_inline_module_tla_rejection_preserves_the_original_error() {
run_page_vm_async_test(async move {
let loader =
crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
for (source, suspends) in [
("await Promise.reject(globalThis.expectedError);", false),
(
"await new Promise((_, reject) => { globalThis.rejectInlineModule = reject; });",
true,
),
] {
let mut page_vm = test_page_vm_with_loader_and_document_url(
&loader,
Vec::new(),
Url::parse("https://example.com/inline-module.html").expect("document URL"),
);
page_vm.vm_mut().eval(
r#"
globalThis.expectedError = new TypeError("inline TLA rejected");
globalThis.inlineModuleErrors = [];
addEventListener("error", event => {
inlineModuleErrors.push(event.error === expectedError);
event.preventDefault();
});
"#,
)?;
let document = &mut page_vm.vm_mut().document_runtime;
let body = document
.snapshot_document()
.document_body_handle()
.expect("body");
let script_node = document
.dom_host_mut()
.create_parser_element_without_attributes(
"script".to_owned(),
"http://www.w3.org/1999/xhtml".to_owned(),
None,
);
assert!(document.dom_host_mut().append_child(body, script_node));
let handle = document.bind_parser_owned_script_handle_for_node(script_node);
let mut script = prepared_inline_module_for_page_vm_test(
&page_vm,
script_node.index() as u32,
source,
);
script.host_script_handle = Some(handle);
let work = install_parser_module_defer_work(&mut page_vm, script);
page_vm
.execute_post_parse_page_owned_task_on_named_owner_lane(&loader, work)
.await?;
if suspends {
assert_eq!(
page_vm
.vm_mut()
.eval("JSON.stringify(inlineModuleErrors)")?,
"[]"
);
page_vm.vm_mut().eval("rejectInlineModule(expectedError)")?;
}
run_parser_module_completion_turns_for_test(
&mut page_vm,
&loader,
usize::from(suspends),
"inline module TLA rejection",
)
.await;
assert_eq!(
page_vm
.vm_mut()
.eval("JSON.stringify(inlineModuleErrors)")?,
"[true]"
);
}
Ok::<_, anyhow::Error>(())
})
.await
.expect("inline module rejection should report the original exception");
}
#[tokio::test(flavor = "current_thread")]
async fn parser_module_graph_failure_leaves_shared_sibling_fetch_for_joined_script_waiter() {
run_page_vm_async_test(async move {
@@ -241,6 +241,12 @@ impl ParserClassicDocumentScriptExecutionHooks
let script_handle = failure.script_handle();
let script_url = failure.script_url().clone();
let error = failure.error().to_owned();
if owner.page_vm.vm().current_main_document_task_owner() == Some(target.owner()) {
owner
.page_vm
.vm()
.emit_script_load_failure(script_url.as_str(), &error);
}
let event = owner
.page_vm
.vm()
@@ -58,7 +58,7 @@ pub(super) fn dispatch_error_and_maybe_propagate<'s>(
// `error` event at the Worker object. Runtime script errors additionally
// propagate to the owning Window when that Worker event is not canceled.
if unhandled && error.phase == crate::worker::WorkerErrorPhase::Runtime {
crate::context_bootstrap::dispatch_window_error_event_with_details(
crate::context_bootstrap::dispatch_window_error_event(
scope,
host_ptr,
error.message,
@@ -129,6 +129,7 @@ impl ScriptVm {
&task.message,
task.filename.as_deref(),
task.error_constructor,
None,
) {
Ok(()) => MainDocumentPostParseCallbackSettlement::Completed,
Err(error) => {
@@ -1082,6 +1082,12 @@ impl ScriptVm {
}
}
}
// A script element owns this internal evaluation promise. Its
// failure is reported through Window's ErrorEvent, rather than
// as an independently unhandled user promise.
if let Some(promise) = promise {
promise.mark_as_handled();
}
if let Err(error) = Self::perform_microtask_checkpoints(&mut scope, None) {
return Ok(Err(ModuleLoadError::new(
ModuleLoadStage::Evaluate,
@@ -507,6 +507,12 @@ impl ScriptVm {
}
}
}
// A script element owns this internal evaluation promise. Its
// failure is reported through Window's ErrorEvent, rather than
// as an independently unhandled user promise.
if let Some(promise) = promise {
promise.mark_as_handled();
}
if let Err(error) = Self::perform_microtask_checkpoints(&mut scope, None) {
return Ok(Err(ModuleLoadError::new(
ModuleLoadStage::Evaluate,
@@ -573,7 +573,7 @@ impl ScriptVm {
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
load_delay_binding: Option<MainDocumentScriptLoadDelayLease>,
) -> Result<FollowupPageTaskDisposition> {
let mut planned_failure_work = self.document_runtime.plan_script_failure_lifecycle_work(
let mut planned_failure_work = self.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
@@ -1210,7 +1210,7 @@ impl ScriptVm {
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
lease: MainDocumentScriptLoadDelayLease,
) {
let work = self.document_runtime.plan_script_failure_lifecycle_work(
let work = self.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
@@ -1261,7 +1261,7 @@ impl ScriptVm {
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
lease: MainDocumentScriptLoadDelayLease,
) -> RuntimeScriptFailureTerminalBodySettlement {
let work = self.document_runtime.plan_script_failure_lifecycle_work(
let work = self.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
@@ -1279,6 +1279,7 @@ impl ScriptVm {
&task.message,
task.filename.as_deref(),
task.error_constructor,
None,
);
activity = crate::script_vm::ScriptTerminalBodyActivity::EventDispatchAttempted;
}
@@ -1459,6 +1460,7 @@ impl ScriptVm {
message,
module_failure_policy,
error_constructor,
None,
);
self.enqueue_immediate_runtime_script_work_if_needed();
return activity;
@@ -170,8 +170,18 @@ fn flush_promise_rejection_state(
if !promise.has_handler() {
remember_reported_promise_rejection(&state.reported, rejection.clone());
}
if matches!(outcome, Ok(true)) {
log_unhandled_promise_rejection(scope, reason);
if let Ok(allows_default) = outcome {
unsafe { &*host_ptr }.emit_diagnostic(|source| {
Some(crate::exception_reporting::diagnostic_from_exception(
scope,
source,
reason,
!allows_default,
))
});
if allows_default {
log_unhandled_promise_rejection(scope, reason);
}
}
});
}
@@ -12,10 +12,43 @@ use crate::context_bootstrap::{
ORIGINAL_WEBASSEMBLY_COMPILE_ERROR_CONSTRUCTOR_SLOT,
ORIGINAL_WEBASSEMBLY_LINK_ERROR_CONSTRUCTOR_SLOT, dispatch_window_error_event_with_details,
};
use crate::host::ScriptEventTask;
use crate::host::{ModuleFailurePolicy, ScriptEventKind, ScriptEventTask};
use crate::module_runtime::ModuleEntryId;
use crate::page_task_queue::PostParseLifecycleWork;
use crate::planning::PreparedScript;
use crate::types::{ScriptErrorConstructorKind, ScriptSourceKind};
use crate::util::{get_private_value, v8_string, v8str};
impl ScriptVm {
pub(crate) fn emit_script_load_failure(&self, url: &str, message: &str) {
self._context_host
.borrow()
.emit_script_load_failure(url, message);
}
pub(super) fn plan_script_failure_lifecycle_work(
&mut self,
script: &PreparedScript,
message: &str,
module_failure_policy: Option<ModuleFailurePolicy>,
error_constructor: Option<ScriptErrorConstructorKind>,
) -> Vec<PostParseLifecycleWork> {
let work = self.document_runtime.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
error_constructor,
);
self._context_host.borrow().emit_diagnostic(|source| {
let reports_source_failure = script.source_kind == ScriptSourceKind::External
&& work.iter().any(|item| matches!(item, PostParseLifecycleWork::DispatchScriptEvent(task) if task.kind == ScriptEventKind::Error));
reports_source_failure.then(|| {
crate::DiagnosticEvent::script_load_failure(source, script.url.as_str(), message)
})
});
work
}
pub(crate) fn dispatch_script_event_body_best_effort(&mut self, task: &ScriptEventTask) {
if let Err(error) = self.dispatch_script_event_body(task) {
self.record_runtime_warning(format_args!(
@@ -39,8 +72,11 @@ impl ScriptVm {
message: &str,
filename: Option<&str>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
) {
if let Err(error) = self.report_window_error_body(message, filename, error_constructor) {
if let Err(error) =
self.report_window_error_body(message, filename, error_constructor, failed_module)
{
self.record_runtime_warning(format_args!(
"window script failure body dispatch failed for `{}`: {error}",
filename.unwrap_or("")
@@ -53,8 +89,37 @@ impl ScriptVm {
message: &str,
filename: Option<&str>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
) -> Result<()> {
// An evaluated module keeps the original thrown value, including a TLA
// rejection, in its V8 module record. Read it only at the existing error
// reporting boundary, after module evaluation has finished unwinding.
let failed_module =
failed_module.and_then(|entry| self.document_runtime.native_compiled_module(entry));
self.with_default_context_scope(|scope, host_ptr| {
if let Some(module) = &failed_module {
let module = v8::Local::new(scope, module);
if module.get_status() == v8::ModuleStatus::Errored {
let reason = module.get_exception();
let (message, source, lineno, colno) =
crate::exception_reporting::exception_message_details(scope, reason);
let filename = if source.is_empty() {
filename.unwrap_or_default()
} else {
&source
};
return dispatch_window_error_event_with_details(
scope,
host_ptr,
&message,
filename,
lineno,
colno,
Some(reason),
)
.map_err(anyhow::Error::msg);
}
}
let global = scope.get_current_context().global(scope);
let message_value = v8_string(scope, message)
.ok_or_else(|| anyhow!("failed to allocate reportError message"))?;
@@ -11,6 +11,7 @@ use anyhow::{Context, Result};
use super::{ScriptTerminalBodyActivity, ScriptVm};
use crate::host::ScriptEventTask;
use crate::module_runtime::ModuleEntryId;
use crate::page_task_queue::{PostParseLifecycleWork, WindowScriptFailureReportTask};
use crate::planning::PreparedScript;
@@ -30,9 +31,10 @@ impl ScriptVm {
message: &str,
filename: Option<&str>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
boundary: &'static str,
) -> Result<()> {
self.report_window_error_body(message, filename, error_constructor)?;
self.report_window_error_body(message, filename, error_constructor, failed_module)?;
self.perform_owner_lane_task_microtask_checkpoints()
.with_context(|| format!("{boundary} checkpoint failed"))
}
@@ -43,9 +45,10 @@ impl ScriptVm {
message: &str,
module_failure_policy: Option<crate::host::ModuleFailurePolicy>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
boundary: &'static str,
) {
let planned_failure_work = self.document_runtime.plan_script_failure_lifecycle_work(
let planned_failure_work = self.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
@@ -61,6 +64,7 @@ impl ScriptVm {
&task.message,
task.filename.as_deref(),
task.error_constructor,
failed_module,
boundary,
),
_ => continue,
@@ -85,6 +89,7 @@ impl ScriptVm {
message,
filename,
None,
None,
"parser import-map failure reporting",
) {
self.record_runtime_warning(format_args!(
@@ -102,12 +107,14 @@ impl ScriptVm {
message: &str,
module_failure_policy: Option<crate::host::ModuleFailurePolicy>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
) {
self.dispatch_planned_script_failure_and_finish_each_synchronous_checkpoint(
script,
message,
module_failure_policy,
error_constructor,
failed_module,
"parser-owned module failure settlement",
);
}
@@ -127,6 +134,7 @@ impl ScriptVm {
message,
module_failure_policy,
error_constructor,
None,
"unclaimed runtime-script terminal",
);
}
@@ -135,6 +143,7 @@ impl ScriptVm {
/// checkpoint. Selected parser continuations use the body-only branch.
pub(crate) fn report_module_tla_rejection_and_finish_reaction_best_effort(
&mut self,
root_entry: ModuleEntryId,
message: &str,
filename: Option<&str>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
@@ -143,6 +152,7 @@ impl ScriptVm {
message,
filename,
error_constructor,
Some(root_entry),
"module TLA rejection reaction",
) {
self.record_runtime_warning(format_args!(
@@ -180,6 +190,7 @@ impl ScriptVm {
&task.message,
task.filename.as_deref(),
task.error_constructor,
None,
"runtime script failure terminal",
) {
self.record_runtime_warning(format_args!(
@@ -196,8 +207,9 @@ impl ScriptVm {
message: &str,
module_failure_policy: Option<crate::host::ModuleFailurePolicy>,
error_constructor: Option<crate::types::ScriptErrorConstructorKind>,
failed_module: Option<ModuleEntryId>,
) -> ScriptTerminalBodyActivity {
let planned_failure_work = self.document_runtime.plan_script_failure_lifecycle_work(
let planned_failure_work = self.plan_script_failure_lifecycle_work(
script,
message,
module_failure_policy,
@@ -215,6 +227,7 @@ impl ScriptVm {
&task.message,
task.filename.as_deref(),
task.error_constructor,
failed_module,
);
activity = ScriptTerminalBodyActivity::EventDispatchAttempted;
}
@@ -260,6 +273,7 @@ impl ScriptVm {
message,
filename,
error_constructor,
None,
"test-only Window error",
) {
self.record_runtime_warning(format_args!(
@@ -248,6 +248,7 @@ fn window_script_failure_error_event_is_trusted_without_trusting_synthetic_event
"trusted browser-generated error",
Some("https://window-error-trusted.test/script.js"),
None,
None,
);
let result = vm
.eval(
@@ -19,6 +19,7 @@ addEventListener("error", () => {
"body-only Window error",
Some("https://script-terminal.test/body.js"),
None,
None,
)
.expect("Window error body should dispatch");
assert_eq!(
@@ -979,6 +979,9 @@ fn spawn_service_worker(
.with_network_policy(params.network_policy)
.with_policy_context(policy_context)
.with_worker_context_runtime(params.worker_context_runtime)
.with_diagnostic_source(crate::DiagnosticSource::ServiceWorker {
version_id: params.run_owner.version_id().as_u64(),
})
.with_service_worker_runtime(service)
.with_global_kind(crate::worker::WorkerGlobalKind::Service {
registration_id: params.registration_id,
@@ -78,6 +78,9 @@ impl RendererSharedWorkerHost {
.with_network_policy(execution_policy.network_policy)
.with_policy_context(policy_context)
.with_worker_context_runtime(execution_policy.worker_context_runtime.clone())
.with_diagnostic_source(crate::DiagnosticSource::SharedWorker {
instance_id: self.instance_id().as_u64(),
})
.with_pause_evaluation_until_debugger(
execution_policy
.worker_context_runtime
@@ -86,6 +86,20 @@ fn finish_loading_with_runtime_service(
match runtime_service.fail_loading_registry_entry(&params, instance_id) {
SharedWorkerLoadFailure::Failed { clients, .. } => {
if let Some(host) = host {
params
.launch_context
.execution_policy
.worker_context_runtime
.with_diagnostic_source(crate::DiagnosticSource::SharedWorker {
instance_id: instance_id.as_u64(),
})
.emit_diagnostic(|source| {
crate::DiagnosticEvent::script_load_failure(
source,
params.key.script_url(),
&message,
)
});
host.close_completed_loading();
host.fail_clients(
clients,
@@ -47,7 +47,7 @@ pub(crate) fn reserve_nested_worker_context(
worker_id,
base_url,
loader: state.loader.clone(),
worker_context_runtime: state.worker_context_runtime.clone(),
worker_context_runtime: state.worker_context_runtime.clone().for_nested_dedicated_worker(),
service_worker_runtime: state.service_worker_runtime.clone(),
service_worker_client_id: state.service_worker_client_id,
storage_key_top_level_site: state.storage_key.top_level_site().to_owned(),
@@ -411,6 +411,14 @@ fn flush_pending_worker_promise_rejections(scope: &mut v8::PinScope<'_, '_>) {
rejection.clone(),
);
}
with_worker_diagnostic(scope, |scope, source| {
crate::exception_reporting::diagnostic_from_exception(
scope,
source,
reason,
!allows_default,
)
});
if allows_default {
log_unhandled_promise_rejection(scope, reason);
}
@@ -3450,6 +3458,18 @@ fn maybe_send_service_worker_periodic_sync_completion(
let _ = parent_tx.send(message);
}
fn with_worker_diagnostic<'s>(
scope: &mut v8::PinScope<'s, '_>,
build: impl FnOnce(&mut v8::PinScope<'s, '_>, crate::DiagnosticSource) -> crate::DiagnosticEvent,
) {
if let Some(state) = get_worker_state(scope) {
state
.borrow()
.worker_context_runtime
.emit_diagnostic(|source| build(scope, source));
}
}
pub(super) fn dispatch_worker_exception<'s>(
scope: &mut v8::PinScope<'s, '_>,
global: v8::Local<'s, v8::Object>,
@@ -3530,6 +3550,30 @@ pub(super) fn dispatch_worker_exception_with_phase_and_source<'s>(
) -> bool {
apply_worker_exception_location_overrides(scope, &mut report, exception);
let handled = dispatch_worker_error_event(scope, global, &report, exception, script_url);
with_worker_diagnostic(scope, |scope, source| {
let stack = if handled {
None
} else {
exception.and_then(|value| {
crate::exception_reporting::captured_exception_stack(scope, value)
})
};
crate::DiagnosticEvent::runtime_exception(
source,
&report.summary,
report.source.as_deref().unwrap_or(script_url),
report
.line
.and_then(|line| u32::try_from(line).ok())
.unwrap_or(0),
report
.column
.and_then(|column| u32::try_from(column).ok())
.unwrap_or(0),
stack.as_deref(),
handled,
)
});
if !handled {
report_exception_to_parent_with_phase_and_source(
&report,
@@ -445,6 +445,11 @@ impl WorkerSpawnOptions {
self
}
pub(crate) fn with_diagnostic_source(mut self, source: crate::DiagnosticSource) -> Self {
self.worker_context_runtime = self.worker_context_runtime.with_diagnostic_source(source);
self
}
pub(crate) fn with_global_kind(mut self, global_kind: WorkerGlobalKind) -> Self {
self.global_kind = global_kind;
self