Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(performance): implement User Timing boundaries and PerformanceMark

ldm0826590cdf5f8
diff --git a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
index 05225f73d..34c0d2f57 100644
--- a/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
+++ b/moli-renderer-v8/src/context_bootstrap/assets/constructor_templates.rs
@@ -30,7 +30,9 @@ use super::super::{
message_ports::{message_channel_constructor_callback, message_port_constructor_callback},
navigator_runtime::clipboard_item_constructor_callback,
notification_runtime::notification_constructor_callback,
- performance_runtime::performance_observer_constructor_callback,
+ performance_runtime::{
+ performance_mark_constructor_callback, performance_observer_constructor_callback,
+ },
range_surface::{
build_abstract_range_template, build_range_constructor_template,
build_static_range_constructor_template,
@@ -513,9 +515,13 @@ pub(in crate::context_bootstrap) fn build_constructor_template<'s>(
ConstructorKind::PerformanceObserverEntryList => {
v8::FunctionTemplate::builder(illegal_constructor_callback).build(scope)
}
+ ConstructorKind::PerformanceMark => {
+ v8::FunctionTemplate::builder(performance_mark_constructor_callback)
+ .length(1)
+ .build(scope)
+ }
ConstructorKind::PerformanceEntry
| ConstructorKind::PerformanceNavigationTiming
- | ConstructorKind::PerformanceMark
| ConstructorKind::PerformanceMeasure
| ConstructorKind::PerformanceResourceTiming
| ConstructorKind::EventCounts
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
index 5b943161a..ab96696c2 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs
@@ -118,7 +118,7 @@ pub(crate) use install::{
};
pub(super) use marks_measures::{
performance_clear_marks_callback, performance_clear_measures_callback,
- performance_mark_callback, performance_measure_callback,
+ performance_mark_callback, performance_mark_constructor_callback, performance_measure_callback,
};
pub(crate) use resource_buffer::run_resource_timing_buffer_full_task;
pub(crate) use window_state::bind_window_performance_seed;
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs
index a1f1c4dce..be2620233 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/entries.rs
@@ -563,10 +563,11 @@ fn performance_entry_attribute_getter<'s>(
slot: &'static str,
rv: &mut v8::ReturnValue<'_, v8::Value>,
) {
- rv.set(
- performance_entry_slot_value(scope, object, slot)
- .unwrap_or_else(|| v8::undefined(scope).into()),
- );
+ let Some(value) = performance_entry_slot_value(scope, object, slot) else {
+ throw_type_error(scope, "Illegal invocation");
+ return;
+ };
+ rv.set(value);
}
pub(in crate::context_bootstrap) fn performance_entry_slot_value<'s>(
@@ -702,7 +703,7 @@ pub(super) fn filtered_performance_entries<'s>(
filtered_entry_list_entries(scope, entries, expected_type, expected_name)
}
-pub(super) fn find_latest_performance_entry_start<'s>(
+pub(super) fn find_latest_performance_mark_start<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
name: &str,
@@ -712,8 +713,10 @@ pub(super) fn find_latest_performance_entry_start<'s>(
for index in 0..entries.length() {
let entry = entries.get_index(scope, index)?;
let entry = v8::Local::<v8::Object>::try_from(entry).ok()?;
- if performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT).as_deref()
- == Some(name)
+ if performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_TYPE_SLOT).as_deref()
+ == Some("mark")
+ && performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_NAME_SLOT).as_deref()
+ == Some(name)
{
found = performance_entry_slot_number(scope, entry, PERFORMANCE_ENTRY_START_TIME_SLOT);
}
@@ -754,6 +757,27 @@ pub(super) fn create_performance_entry<'s>(
entry
}
+pub(super) fn initialize_performance_entry_slots<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ entry: v8::Local<'s, v8::Object>,
+ entry_type: &str,
+ name: &str,
+ start_time: f64,
+ duration: f64,
+ detail: Option<v8::Local<'s, v8::Value>>,
+) {
+ let detail = detail.unwrap_or_else(|| v8::null(scope).into());
+ PerformanceEntryObjectDeclaration {
+ name,
+ entry_type,
+ start_time,
+ duration,
+ detail,
+ }
+ .initialize(scope, entry)
+ .expect("PerformanceEntry declaration should initialize object");
+}
+
pub(super) fn push_performance_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
index 724e9f50b..2a010678c 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/install.rs
@@ -1017,6 +1017,13 @@ fn apply_lifecycle_to_navigation_entry<'s>(
}
}
+pub(super) fn is_window_performance<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ performance: v8::Local<'s, v8::Object>,
+) -> bool {
+ get_private_value(scope, performance, PERFORMANCE_NAVIGATION_TYPE_SEED_SLOT).is_some()
+}
+
pub(super) fn performance_navigation_type_seed<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
@@ -1096,10 +1103,10 @@ impl PerformanceTimingSnapshot {
let time_origin = legacy_timing_epoch_millis(time_origin);
Self {
navigation_start: time_origin,
- unload_event_start: time_origin,
- unload_event_end: time_origin,
- redirect_start: time_origin,
- redirect_end: time_origin,
+ unload_event_start: 0,
+ unload_event_end: 0,
+ redirect_start: 0,
+ redirect_end: 0,
fetch_start: time_origin,
domain_lookup_start: time_origin,
domain_lookup_end: time_origin,
@@ -1110,12 +1117,12 @@ impl PerformanceTimingSnapshot {
response_start: time_origin,
response_end: time_origin,
dom_loading: time_origin,
- dom_interactive: time_origin,
- dom_content_loaded_event_start: time_origin,
- dom_content_loaded_event_end: time_origin,
- dom_complete: time_origin,
- load_event_start: time_origin,
- load_event_end: time_origin,
+ dom_interactive: 0,
+ dom_content_loaded_event_start: 0,
+ dom_content_loaded_event_end: 0,
+ dom_complete: 0,
+ load_event_start: 0,
+ load_event_end: 0,
}
}
}
@@ -1217,7 +1224,7 @@ const PERFORMANCE_ATTRIBUTE_SLOTS: &[&str] = &[
PERFORMANCE_EVENT_COUNTS_SLOT,
];
-const PERFORMANCE_TIMING_JSON_KEYS: &[&str] = &[
+pub(super) const PERFORMANCE_TIMING_ATTRIBUTE_NAMES: &[&str] = &[
"navigationStart",
"unloadEventStart",
"unloadEventEnd",
@@ -1566,8 +1573,9 @@ pub(in crate::context_bootstrap) fn performance_to_json_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- let timing = object_property_as_object(scope, args.this(), "timing")
- .map(|timing| object_json_snapshot(scope, timing, PERFORMANCE_TIMING_JSON_KEYS).into());
+ let timing = object_property_as_object(scope, args.this(), "timing").map(|timing| {
+ object_json_snapshot(scope, timing, PERFORMANCE_TIMING_ATTRIBUTE_NAMES).into()
+ });
let navigation =
object_property_as_object(scope, args.this(), "navigation").map(|navigation| {
object_json_snapshot(scope, navigation, PERFORMANCE_NAVIGATION_JSON_KEYS).into()
@@ -1587,7 +1595,7 @@ fn performance_timing_to_json_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- rv.set(object_json_snapshot(scope, args.this(), PERFORMANCE_TIMING_JSON_KEYS).into());
+ rv.set(object_json_snapshot(scope, args.this(), PERFORMANCE_TIMING_ATTRIBUTE_NAMES).into());
}
fn performance_navigation_to_json_callback<'s>(
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs
index 288c3f88a..99bb56124 100644
--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs
+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime/marks_measures.rs
@@ -1,5 +1,9 @@
-use super::entries::{create_performance_entry, find_latest_performance_entry_start};
+use super::entries::{
+ create_performance_entry, find_latest_performance_mark_start,
+ initialize_performance_entry_slots,
+};
use super::*;
+use crate::context_bootstrap::structured_clone_value;
use crate::util::serialize_v8_iter_array;
use crate::webidl;
@@ -10,6 +14,22 @@ struct PerformanceMarkArgs {
name: String,
}
+#[derive(webidl::WebIdlArgs)]
+#[webidl(prefix = "PerformanceMark")]
+struct PerformanceMarkConstructorArgs {
+ #[webidl(required)]
+ name: String,
+}
+
+#[derive(Default, webidl::WebIdlDictionary)]
+#[webidl(prefix = "PerformanceMarkOptions")]
+struct PerformanceMarkOptions<'s> {
+ #[webidl(converter = "raw")]
+ detail: Option<v8::Local<'s, v8::Value>>,
+ #[webidl(name = "startTime", converter = "double")]
+ start_time: Option<f64>,
+}
+
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "Performance.clearMarks")]
struct PerformanceClearMarksArgs {
@@ -23,6 +43,31 @@ struct PerformanceMeasureArgs {
name: String,
}
+#[derive(Default, webidl::WebIdlDictionary)]
+#[webidl(prefix = "PerformanceMeasureOptions")]
+struct PerformanceMeasureOptions<'s> {
+ #[webidl(converter = "raw")]
+ detail: Option<v8::Local<'s, v8::Value>>,
+ #[webidl(converter = "double")]
+ duration: Option<f64>,
+ #[webidl(converter = "raw")]
+ end: Option<v8::Local<'s, v8::Value>>,
+ #[webidl(converter = "raw")]
+ start: Option<v8::Local<'s, v8::Value>>,
+}
+
+enum MeasureBoundary {
+ Mark(String),
+ Timestamp(f64),
+}
+
+struct ParsedPerformanceMeasure<'s> {
+ start: Option<MeasureBoundary>,
+ duration: Option<f64>,
+ end: Option<MeasureBoundary>,
+ detail: Option<v8::Local<'s, v8::Value>>,
+}
+
#[derive(webidl::WebIdlArgs)]
#[webidl(prefix = "Performance.clearMeasures")]
struct PerformanceClearMeasuresArgs {
@@ -34,37 +79,152 @@ pub(in crate::context_bootstrap) fn performance_mark_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
+ let Some(performance) = require_performance_receiver(scope, args.this()) else {
+ return;
+ };
let Some(parsed) = webidl::parse_args::<PerformanceMarkArgs>(scope, &args) else {
return;
};
- let start_time = args
- .get(1)
- .to_object(scope)
- .and_then(|options| options.get(scope, v8str(scope, "startTime").into()))
- .and_then(|value| value.number_value(scope))
- .filter(|value| value.is_finite())
- .unwrap_or_else(|| {
- unix_epoch_millis()
- - performance_slot_number(scope, args.this(), PERFORMANCE_TIME_ORIGIN_SLOT)
- .unwrap_or(0.0)
- });
- let entry = create_performance_entry(scope, "mark", &parsed.name, start_time, 0.0, None);
- push_performance_entry(scope, args.this(), entry);
+ let Some(options) = parse_performance_mark_options(
+ scope,
+ &args,
+ webidl::Context::argument("Performance.mark", 2),
+ ) else {
+ return;
+ };
+ let Some((start_time, detail)) =
+ prepare_performance_mark(scope, performance, &parsed.name, options)
+ else {
+ return;
+ };
+ let entry = create_performance_entry(scope, "mark", &parsed.name, start_time, 0.0, detail);
+ push_performance_entry(scope, performance, entry);
rv.set(entry.into());
}
+pub(in crate::context_bootstrap) fn performance_mark_constructor_callback<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: v8::FunctionCallbackArguments<'s>,
+ mut rv: v8::ReturnValue<'_, v8::Value>,
+) {
+ if !args.is_construct_call() {
+ webidl::throw_type_error(
+ scope,
+ "Failed to construct 'PerformanceMark': Please use the 'new' operator.",
+ );
+ return;
+ }
+ let Some(parsed) = webidl::parse_args::<PerformanceMarkConstructorArgs>(scope, &args) else {
+ return;
+ };
+ let Some(options) = parse_performance_mark_options(
+ scope,
+ &args,
+ webidl::Context::argument("PerformanceMark", 2),
+ ) else {
+ return;
+ };
+ let Some(performance) = ensure_current_performance_for_api(scope) else {
+ webidl::throw_type_error(scope, "Failed to construct 'PerformanceMark'.");
+ return;
+ };
+ let Some((start_time, detail)) =
+ prepare_performance_mark(scope, performance, &parsed.name, options)
+ else {
+ return;
+ };
+ initialize_performance_entry_slots(
+ scope,
+ args.this(),
+ "mark",
+ &parsed.name,
+ start_time,
+ 0.0,
+ detail,
+ );
+ rv.set(args.this().into());
+}
+
+fn parse_performance_mark_options<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+ context: webidl::Context,
+) -> Option<PerformanceMarkOptions<'s>> {
+ match webidl::dictionary_arg(args, 1, context) {
+ Ok(Some(options)) => {
+ match webidl::parse_dictionary_object::<PerformanceMarkOptions>(scope, options) {
+ Ok(options) => Some(options),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ None
+ }
+ }
+ }
+ Ok(None) => Some(PerformanceMarkOptions::default()),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ None
+ }
+ }
+}
+
+fn prepare_performance_mark<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ performance: v8::Local<'s, v8::Object>,
+ name: &str,
+ options: PerformanceMarkOptions<'s>,
+) -> Option<(f64, Option<v8::Local<'s, v8::Value>>)> {
+ let start_time = options.start_time.unwrap_or_else(|| {
+ unix_epoch_millis()
+ - performance_slot_number(scope, performance, PERFORMANCE_TIME_ORIGIN_SLOT)
+ .unwrap_or(0.0)
+ });
+ if start_time < 0.0 {
+ webidl::throw_type_error(
+ scope,
+ &format!("'{name}' cannot have a negative start time."),
+ );
+ return None;
+ }
+ if install::is_window_performance(scope, performance)
+ && install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(&name)
+ {
+ webidl::throw_dom_exception(
+ scope,
+ "SyntaxError",
+ &format!(
+ "'{name}' is part of the PerformanceTiming interface and cannot be used as a mark name."
+ ),
+ );
+ return None;
+ }
+ clone_user_timing_detail(scope, options.detail).map(|detail| (start_time, detail))
+}
+
+fn require_performance_receiver<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ receiver: v8::Local<'s, v8::Object>,
+) -> Option<v8::Local<'s, v8::Object>> {
+ if performance_slot_array(scope, receiver, PERFORMANCE_ENTRIES_SLOT).is_none() {
+ webidl::throw_type_error(scope, "Illegal invocation");
+ return None;
+ }
+ Some(receiver)
+}
+
pub(in crate::context_bootstrap) fn performance_clear_marks_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- let Some(parsed) = webidl::parse_args::<PerformanceClearMarksArgs>(scope, &args) else {
+ let Some(performance) = require_performance_receiver(scope, args.this()) else {
return;
};
- let Some(entries) = performance_slot_array(scope, args.this(), PERFORMANCE_ENTRIES_SLOT) else {
- rv.set_undefined();
+ let Some(parsed) = webidl::parse_args::<PerformanceClearMarksArgs>(scope, &args) else {
return;
};
+ let entries = performance_slot_array(scope, performance, PERFORMANCE_ENTRIES_SLOT)
+ .expect("branded Performance receiver should retain its entries slot");
let mut next = Vec::new();
for index in 0..entries.length() {
let Some(entry) = entries.get_index(scope, index) else {
@@ -93,7 +253,7 @@ pub(in crate::context_bootstrap) fn performance_clear_marks_callback<'s>(
}
}
let next = serialize_v8_iter_array(scope, next).unwrap_or_else(|| v8::Array::new(scope, 0));
- set_performance_slot_value(scope, args.this(), PERFORMANCE_ENTRIES_SLOT, next.into());
+ set_performance_slot_value(scope, performance, PERFORMANCE_ENTRIES_SLOT, next.into());
rv.set_undefined();
}
@@ -102,53 +262,49 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
+ let Some(performance) = require_performance_receiver(scope, args.this()) else {
+ return;
+ };
let Some(parsed) = webidl::parse_args::<PerformanceMeasureArgs>(scope, &args) else {
return;
};
+ let Some(parsed_measure) = parse_performance_measure_arguments(scope, &args) else {
+ return;
+ };
let now = unix_epoch_millis()
- - performance_slot_number(scope, args.this(), PERFORMANCE_TIME_ORIGIN_SLOT).unwrap_or(0.0);
- let (start, end, duration_value, detail) = if args.length() > 1
- && (args.get(1).is_string() || args.get(1).is_number())
- {
- let start = resolve_measure_boundary(scope, args.this(), args.get(1)).unwrap_or(0.0);
- let end = if args.length() > 2 && !args.get(2).is_undefined() {
- resolve_measure_boundary(scope, args.this(), args.get(2))
- } else {
- None
- };
- (start, end, None, None)
- } else {
- let options = args.get(1).to_object(scope);
- let start = options
- .and_then(|options| options.get(scope, v8str(scope, "start").into()))
- .and_then(|value| resolve_measure_boundary(scope, args.this(), value))
- .unwrap_or(0.0);
- let end = options
- .and_then(|options| options.get(scope, v8str(scope, "end").into()))
- .and_then(|value| resolve_measure_boundary(scope, args.this(), value));
- let duration_value = options
- .and_then(|options| options.get(scope, v8str(scope, "duration").into()))
- .and_then(|value| value.number_value(scope))
- .filter(|value| value.is_finite());
- let detail = options.and_then(|options| options.get(scope, v8str(scope, "detail").into()));
- (start, end, duration_value, detail)
- };
-
- let (start_time, duration) = match (end, duration_value) {
- (Some(end_time), Some(duration)) => (end_time - duration, duration),
- (Some(end_time), None) => (start, end_time - start),
- (None, Some(duration)) => (start, duration),
- (None, None) => (start, now - start),
+ - performance_slot_number(scope, performance, PERFORMANCE_TIME_ORIGIN_SLOT).unwrap_or(0.0);
+ let start = match parsed_measure.start.as_ref() {
+ Some(start) => match resolve_measure_boundary(scope, performance, &parsed.name, start) {
+ Ok(start) => start,
+ Err(()) => return,
+ },
+ None => 0.0,
+ };
+ let end = match parsed_measure.end.as_ref() {
+ Some(end) => match resolve_measure_boundary(scope, performance, &parsed.name, end) {
+ Ok(end) => end,
+ Err(()) => return,
+ },
+ None => now,
+ };
+ let (start_time, end_time) = match parsed_measure.duration {
+ Some(duration) if parsed_measure.start.is_none() => (end - duration, end),
+ Some(duration) => (start, start + duration),
+ None => (start, end),
+ };
+ let detail = match clone_user_timing_detail(scope, parsed_measure.detail) {
+ Some(detail) => detail,
+ None => return,
};
let entry = create_performance_entry(
scope,
"measure",
&parsed.name,
- start_time.max(0.0),
- duration.max(0.0),
+ start_time,
+ end_time - start_time,
detail,
);
- push_performance_entry(scope, args.this(), entry);
+ push_performance_entry(scope, performance, entry);
rv.set(entry.into());
}
@@ -157,13 +313,14 @@ pub(in crate::context_bootstrap) fn performance_clear_measures_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
- let Some(parsed) = webidl::parse_args::<PerformanceClearMeasuresArgs>(scope, &args) else {
+ let Some(performance) = require_performance_receiver(scope, args.this()) else {
return;
};
- let Some(entries) = performance_slot_array(scope, args.this(), PERFORMANCE_ENTRIES_SLOT) else {
- rv.set_undefined();
+ let Some(parsed) = webidl::parse_args::<PerformanceClearMeasuresArgs>(scope, &args) else {
return;
};
+ let entries = performance_slot_array(scope, performance, PERFORMANCE_ENTRIES_SLOT)
+ .expect("branded Performance receiver should retain its entries slot");
let mut next = Vec::new();
for index in 0..entries.length() {
let Some(entry) = entries.get_index(scope, index) else {
@@ -192,21 +349,251 @@ pub(in crate::context_bootstrap) fn performance_clear_measures_callback<'s>(
}
}
let next = serialize_v8_iter_array(scope, next).unwrap_or_else(|| v8::Array::new(scope, 0));
- set_performance_slot_value(scope, args.this(), PERFORMANCE_ENTRIES_SLOT, next.into());
+ set_performance_slot_value(scope, performance, PERFORMANCE_ENTRIES_SLOT, next.into());
rv.set_undefined();
}
+fn parse_performance_measure_arguments<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+) -> Option<ParsedPerformanceMeasure<'s>> {
+ let second = (args.length() > 1).then(|| args.get(1));
+ let options = second
+ .filter(|value| !webidl::is_nullish(*value) && value.is_object())
+ .and_then(|value| v8::Local::<v8::Object>::try_from(value).ok());
+
+ if let Some(options) = options {
+ let options =
+ match webidl::parse_dictionary_object::<PerformanceMeasureOptions>(scope, options) {
+ Ok(options) => options,
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return None;
+ }
+ };
+ let end = match options.end {
+ Some(end) => match parse_measure_boundary_value(
+ scope,
+ end,
+ webidl::Context::member("PerformanceMeasureOptions", "end"),
+ ) {
+ Ok(end) => Some(end),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return None;
+ }
+ },
+ None => None,
+ };
+ let start = match options.start {
+ Some(start) => match parse_measure_boundary_value(
+ scope,
+ start,
+ webidl::Context::member("PerformanceMeasureOptions", "start"),
+ ) {
+ Ok(start) => Some(start),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return None;
+ }
+ },
+ None => None,
+ };
+ let legacy_end = parse_optional_legacy_end(scope, args)?;
+ let non_empty = options.detail.is_some()
+ || options.duration.is_some()
+ || start.is_some()
+ || end.is_some();
+ if !non_empty {
+ return Some(ParsedPerformanceMeasure {
+ start: None,
+ duration: None,
+ end: legacy_end.map(MeasureBoundary::Mark),
+ detail: None,
+ });
+ }
+ if legacy_end.is_some() {
+ webidl::throw_type_error(
+ scope,
+ "If a non-empty PerformanceMeasureOptions object was passed, endMark must not be passed.",
+ );
+ return None;
+ }
+ if start.is_none() && end.is_none() {
+ webidl::throw_type_error(
+ scope,
+ "A non-empty PerformanceMeasureOptions object must contain start or end.",
+ );
+ return None;
+ }
+ if start.is_some() && options.duration.is_some() && end.is_some() {
+ webidl::throw_type_error(
+ scope,
+ "PerformanceMeasureOptions must not define start, duration, and end together.",
+ );
+ return None;
+ }
+ return Some(ParsedPerformanceMeasure {
+ start,
+ duration: options.duration,
+ end,
+ detail: options.detail,
+ });
+ }
+
+ let start = match second.filter(|value| !webidl::is_nullish(*value)) {
+ Some(start) => match parse_dom_string(
+ scope,
+ start,
+ webidl::Context::argument("Performance.measure", 2),
+ ) {
+ Ok(start) => Some(MeasureBoundary::Mark(start)),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ return None;
+ }
+ },
+ None => None,
+ };
+ let end = parse_optional_legacy_end(scope, args)?.map(MeasureBoundary::Mark);
+ Some(ParsedPerformanceMeasure {
+ start,
+ duration: None,
+ end,
+ detail: None,
+ })
+}
+
+fn parse_optional_legacy_end<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ args: &v8::FunctionCallbackArguments<'s>,
+) -> Option<Option<String>> {
+ if args.length() <= 2 || webidl::is_nullish(args.get(2)) {
+ return Some(None);
+ }
+ match parse_dom_string(
+ scope,
+ args.get(2),
+ webidl::Context::argument("Performance.measure", 3),
+ ) {
+ Ok(end) => Some(Some(end)),
+ Err(error) => {
+ webidl::throw_error(scope, &error);
+ None
+ }
+ }
+}
+
+fn parse_dom_string<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+) -> Result<String, webidl::WebIdlError> {
+ webidl::convert::<webidl::DomString>(scope, value, context).map(Into::into)
+}
+
+fn parse_measure_boundary_value<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ value: v8::Local<'s, v8::Value>,
+ context: webidl::Context,
+) -> Result<MeasureBoundary, webidl::WebIdlError> {
+ if value.is_number() {
+ return webidl::convert::<webidl::Double>(scope, value, context)
+ .map(|value| MeasureBoundary::Timestamp(value.0));
+ }
+ parse_dom_string(scope, value, context).map(MeasureBoundary::Mark)
+}
+
fn resolve_measure_boundary<'s>(
scope: &mut v8::PinScope<'s, '_>,
performance: v8::Local<'s, v8::Object>,
- value: v8::Local<'s, v8::Value>,
-) -> Option<f64> {
- if let Some(number) = value.number_value(scope).filter(|value| value.is_finite()) {
- return Some(number);
- }
- let name = value.to_string(scope)?.to_rust_string_lossy(scope);
- match name.as_str() {
- "navigationStart" | "fetchStart" => Some(0.0),
- _ => find_latest_performance_entry_start(scope, performance, &name),
+ measure_name: &str,
+ boundary: &MeasureBoundary,
+) -> Result<f64, ()> {
+ match boundary {
+ MeasureBoundary::Timestamp(timestamp) if *timestamp < 0.0 => {
+ webidl::throw_type_error(
+ scope,
+ &format!("'{measure_name}' cannot have a negative time stamp."),
+ );
+ Err(())
+ }
+ MeasureBoundary::Timestamp(timestamp) => Ok(*timestamp),
+ MeasureBoundary::Mark(name) => resolve_named_measure_boundary(scope, performance, name),
+ }
+}
+
+fn resolve_named_measure_boundary<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ performance: v8::Local<'s, v8::Object>,
+ name: &str,
+) -> Result<f64, ()> {
+ if !install::PERFORMANCE_TIMING_ATTRIBUTE_NAMES.contains(&name) {
+ if let Some(start_time) = find_latest_performance_mark_start(scope, performance, name) {
+ return Ok(start_time);
+ }
+ webidl::throw_dom_exception(
+ scope,
+ "SyntaxError",
+ &format!("The mark '{name}' does not exist."),
+ );
+ return Err(());
+ }
+
+ if !install::is_window_performance(scope, performance) {
+ webidl::throw_type_error(
+ scope,
+ "PerformanceTiming names can only be resolved in a Window global.",
+ );
+ return Err(());
+ }
+ let timing = match super::lazy_subobjects::ensure_performance_subobject(
+ scope,
+ performance,
+ super::lazy_subobjects::PerformanceSubobject::Timing,
+ ) {
+ Ok(value) => match v8::Local::<v8::Object>::try_from(value) {
+ Ok(timing) => timing,
+ Err(_) => {
+ webidl::throw_type_error(scope, "Failed to materialize PerformanceTiming.");
+ return Err(());
+ }
+ },
+ Err(error) => {
+ webidl::throw_type_error(scope, &error.to_string());
+ return Err(());
+ }
+ };
+ let Some(key) = v8_string(scope, name) else {
+ return Err(());
+ };
+ let value = timing
+ .get(scope, key.into())
+ .and_then(|value| value.number_value(scope))
+ .filter(|value| value.is_finite())
+ .unwrap_or(0.0);
+ if value == 0.0 {
+ webidl::throw_dom_exception(
+ scope,
+ "InvalidAccessError",
+ &format!("'{name}' is empty because the event has not happened or is unavailable."),
+ );
+ return Err(());
+ }
+ let navigation_start = timing
+ .get(scope, v8str(scope, "navigationStart").into())
+ .and_then(|value| value.number_value(scope))
+ .filter(|value| value.is_finite())
+ .unwrap_or(0.0);
+ Ok(value - navigation_start)
+}
+
+fn clone_user_timing_detail<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ detail: Option<v8::Local<'s, v8::Value>>,
+) -> Option<Option<v8::Local<'s, v8::Value>>> {
+ match detail {
+ Some(detail) => structured_clone_value(scope, detail).map(Some),
+ None => Some(None),
}
}
diff --git a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
index 279eccaec..9a10908a2 100644
--- a/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
+++ b/moli-renderer-v8/src/script_vm/tests/browser_api/navigation.rs
@@ -380,6 +380,13 @@ fn performance_entries_hide_backing_slots_and_ignore_spoofing() {
__moliPerformanceNavigationTimingType: "reload",
__moliPerformanceNavigationTimingLoadEventEnd: 99
};
+ const getterResult = (getter, receiver) => {
+ try {
+ return stringify(getter.call(receiver));
+ } catch (error) {
+ return error.name;
+ }
+ };
return JSON.stringify({
initialNavigationNames,
initialMarkNames,
@@ -427,10 +434,10 @@ fn performance_entries_hide_backing_slots_and_ignore_spoofing() {
navigationDuration: navigation.duration,
byRealMark: performance.getEntriesByName("real-mark", "mark").length,
bySpoofMark: performance.getEntriesByName("spoof", "resource").length,
- fakeName: String(entryNameGetter.call(fake)),
+ fakeName: getterResult(entryNameGetter, fake),
fakeNavigationType: String(navTypeGetter.call(fake)),
fakeLoadEventEnd: String(navLoadGetter.call(fake)),
- fakeResourceValues: resourceGetters.map(getter => getter.call({})).map(stringify).join("|")
+ fakeResourceValues: resourceGetters.map(getter => getterResult(getter, {})).join("|")
});
})()
"#,
@@ -439,7 +446,155 @@ fn performance_entries_hide_backing_slots_and_ignore_spoofing() {
assert_eq!(
result,
- r#"{"initialNavigationNames":[],"initialMarkNames":[],"initialMeasureNames":[],"markName":"real-mark","markEntryType":"mark","markStartSpoofIgnored":true,"markDuration":0,"markDetailNull":true,"measureDetail":"real","entryDescriptors":["name:true:function:get name:0:undefined:true:true:false","entryType:true:function:get entryType:0:undefined:true:true:false","startTime:true:function:get startTime:0:undefined:true:true:false","duration:true:function:get duration:0:undefined:true:true:false"],"detailDescriptors":["detail:true:function:get detail:0:undefined:true:true:false","detail:true:function:get detail:0:undefined:true:true:false"],"resourceDescriptors":["initiatorType:true:function:get initiatorType:0:undefined:true:true:false","nextHopProtocol:true:function:get nextHopProtocol:0:undefined:true:true:false","workerStart:true:function:get workerStart:0:undefined:true:true:false","redirectStart:true:function:get redirectStart:0:undefined:true:true:false","redirectEnd:true:function:get redirectEnd:0:undefined:true:true:false","fetchStart:true:function:get fetchStart:0:undefined:true:true:false","domainLookupStart:true:function:get domainLookupStart:0:undefined:true:true:false","domainLookupEnd:true:function:get domainLookupEnd:0:undefined:true:true:false","connectStart:true:function:get connectStart:0:undefined:true:true:false","connectEnd:true:function:get connectEnd:0:undefined:true:true:false","secureConnectionStart:true:function:get secureConnectionStart:0:undefined:true:true:false","requestStart:true:function:get requestStart:0:undefined:true:true:false","responseStart:true:function:get responseStart:0:undefined:true:true:false","responseEnd:true:function:get responseEnd:0:undefined:true:true:false","transferSize:true:function:get transferSize:0:undefined:true:true:false","encodedBodySize:true:function:get encodedBodySize:0:undefined:true:true:false","decodedBodySize:true:function:get decodedBodySize:0:undefined:true:true:false","renderBlockingStatus:true:function:get renderBlockingStatus:0:undefined:true:true:false","responseStatus:true:function:get responseStatus:0:undefined:true:true:false","contentType:true:function:get contentType:0:undefined:true:true:false"],"navigationType":"navigate","navigationLoadEventEnd":0,"navigationDuration":0,"byRealMark":1,"bySpoofMark":0,"fakeName":"undefined","fakeNavigationType":"undefined","fakeLoadEventEnd":"undefined","fakeResourceValues":"undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined|undefined"}"#
+ r#"{"initialNavigationNames":[],"initialMarkNames":[],"initialMeasureNames":[],"markName":"real-mark","markEntryType":"mark","markStartSpoofIgnored":true,"markDuration":0,"markDetailNull":true,"measureDetail":"real","entryDescriptors":["name:true:function:get name:0:undefined:true:true:false","entryType:true:function:get entryType:0:undefined:true:true:false","startTime:true:function:get startTime:0:undefined:true:true:false","duration:true:function:get duration:0:undefined:true:true:false"],"detailDescriptors":["detail:true:function:get detail:0:undefined:true:true:false","detail:true:function:get detail:0:undefined:true:true:false"],"resourceDescriptors":["initiatorType:true:function:get initiatorType:0:undefined:true:true:false","nextHopProtocol:true:function:get nextHopProtocol:0:undefined:true:true:false","workerStart:true:function:get workerStart:0:undefined:true:true:false","redirectStart:true:function:get redirectStart:0:undefined:true:true:false","redirectEnd:true:function:get redirectEnd:0:undefined:true:true:false","fetchStart:true:function:get fetchStart:0:undefined:true:true:false","domainLookupStart:true:function:get domainLookupStart:0:undefined:true:true:false","domainLookupEnd:true:function:get domainLookupEnd:0:undefined:true:true:false","connectStart:true:function:get connectStart:0:undefined:true:true:false","connectEnd:true:function:get connectEnd:0:undefined:true:true:false","secureConnectionStart:true:function:get secureConnectionStart:0:undefined:true:true:false","requestStart:true:function:get requestStart:0:undefined:true:true:false","responseStart:true:function:get responseStart:0:undefined:true:true:false","responseEnd:true:function:get responseEnd:0:undefined:true:true:false","transferSize:true:function:get transferSize:0:undefined:true:true:false","encodedBodySize:true:function:get encodedBodySize:0:undefined:true:true:false","decodedBodySize:true:function:get decodedBodySize:0:undefined:true:true:false","renderBlockingStatus:true:function:get renderBlockingStatus:0:undefined:true:true:false","responseStatus:true:function:get responseStatus:0:undefined:true:true:false","contentType:true:function:get contentType:0:undefined:true:true:false"],"navigationType":"navigate","navigationLoadEventEnd":0,"navigationDuration":0,"byRealMark":1,"bySpoofMark":0,"fakeName":"TypeError","fakeNavigationType":"undefined","fakeLoadEventEnd":"undefined","fakeResourceValues":"TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError|TypeError"}"#
+ );
+}
+
+#[test]
+fn performance_user_timing_enforces_mark_and_measure_boundaries() {
+ let mut vm = new_storage_test_vm("https://performance-user-timing-boundaries.test/");
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const capture = callback => {
+ try {
+ callback();
+ return "none";
+ } catch (error) {
+ return `${error.name}:${error.code}`;
+ }
+ };
+ performance.mark("later", { startTime: 5 });
+ const sourceDetail = { value: 1 };
+ const cloned = performance.measure("cloned", {
+ start: 1,
+ duration: 2,
+ detail: sourceDetail
+ });
+ sourceDetail.value = 9;
+ const negative = performance.measure(
+ "negative-duration",
+ "later",
+ "navigationStart"
+ );
+ const legacyPendingNames = [
+ "unloadEventStart",
+ "unloadEventEnd",
+ "redirectStart",
+ "redirectEnd",
+ "secureConnectionStart",
+ "domInteractive",
+ "domContentLoadedEventStart",
+ "domContentLoadedEventEnd",
+ "domComplete",
+ "loadEventStart",
+ "loadEventEnd"
+ ];
+ return JSON.stringify({
+ reservedMark: capture(() => performance.mark("navigationStart")),
+ missingMark: capture(() => performance.measure("missing", "does-not-exist")),
+ numericLegacyMark: capture(() => performance.measure("number", 51.15, "later")),
+ unavailableTiming: capture(() => performance.measure("pending", "redirectStart")),
+ detailOnlyOptions: capture(() => performance.measure("detail-only", { detail: 1 })),
+ overSpecifiedOptions: capture(() => performance.measure("all", {
+ start: 1,
+ duration: 2,
+ end: 3
+ })),
+ negativeMark: capture(() => performance.mark("bad-mark", { startTime: -1 })),
+ infiniteMark: capture(() => performance.mark("bad-infinite", { startTime: Infinity })),
+ negativeBoundary: capture(() => performance.measure("bad-boundary", { start: -1 })),
+ negativeDuration: negative.duration,
+ navigationStartTime: performance.measure("from-navigation", "navigationStart").startTime,
+ pendingTimingStartsAtZero: legacyPendingNames.every(name => performance.timing[name] === 0),
+ clonedDetail: `${cloned.detail.value}:${cloned.detail === sourceDetail}`,
+ navigationEntryIsNotMark: capture(() => performance.measure("entry-name", location.href))
+ });
+ })()
+ "#,
+ )
+ .expect("User Timing boundary probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"reservedMark":"SyntaxError:12","missingMark":"SyntaxError:12","numericLegacyMark":"SyntaxError:12","unavailableTiming":"InvalidAccessError:15","detailOnlyOptions":"TypeError:undefined","overSpecifiedOptions":"TypeError:undefined","negativeMark":"TypeError:undefined","infiniteMark":"TypeError:undefined","negativeBoundary":"TypeError:undefined","negativeDuration":-5,"navigationStartTime":0,"pendingTimingStartsAtZero":true,"clonedDetail":"1:false","navigationEntryIsNotMark":"SyntaxError:12"}"#
+ );
+}
+
+#[test]
+fn performance_mark_constructor_creates_detached_structured_entries() {
+ let mut vm = new_storage_test_vm("https://performance-mark-constructor.test/");
+
+ let result = vm
+ .eval(
+ r#"
+ (() => {
+ const capture = callback => {
+ try {
+ callback();
+ return "none";
+ } catch (error) {
+ return `${error.name}:${error.code}`;
+ }
+ };
+ const sourceDetail = { state: "before" };
+ const entry = new PerformanceMark("detached", {
+ startTime: 2,
+ detail: sourceDetail
+ });
+ sourceDetail.state = "after";
+ class DerivedPerformanceMark extends PerformanceMark {}
+ const derived = new DerivedPerformanceMark("derived", { startTime: 3 });
+ return JSON.stringify({
+ shape: [
+ entry instanceof PerformanceEntry,
+ entry instanceof PerformanceMark,
+ Object.prototype.toString.call(entry),
+ entry.name,
+ entry.entryType,
+ entry.startTime,
+ entry.duration
+ ].join(":"),
+ detail: `${entry.detail.state}:${entry.detail === entry.detail}:${entry.detail === sourceDetail}`,
+ timelineEntries: performance.getEntriesByName("detached", "mark").length,
+ derived: [
+ derived instanceof DerivedPerformanceMark,
+ derived instanceof PerformanceMark,
+ Object.getPrototypeOf(derived) === DerivedPerformanceMark.prototype,
+ derived.name,
+ derived.startTime
+ ].join(":"),
+ constructorInheritance:
+ Object.getPrototypeOf(PerformanceMark) === PerformanceEntry
+ && Object.getPrototypeOf(PerformanceMeasure) === PerformanceEntry,
+ detailBrand: capture(() =>
+ Object.getOwnPropertyDescriptor(PerformanceMark.prototype, "detail")
+ .get.call(PerformanceMark.prototype)),
+ methodBrands: [
+ performance.mark,
+ performance.clearMarks,
+ performance.measure,
+ performance.clearMeasures
+ ].map(method => capture(() => method.call(null, "unbound"))).join("|"),
+ withoutNew: capture(() => PerformanceMark("call")),
+ missingName: capture(() => new PerformanceMark()),
+ negativeStart: capture(() => new PerformanceMark("negative", { startTime: -1 })),
+ infiniteStart: capture(() => new PerformanceMark("infinite", { startTime: Infinity })),
+ reservedName: capture(() => new PerformanceMark("navigationStart")),
+ cloneError: capture(() => new PerformanceMark("clone", {
+ detail: { value: Symbol() }
+ }))
+ });
+ })()
+ "#,
+ )
+ .expect("PerformanceMark constructor probe should evaluate");
+
+ assert_eq!(
+ result,
+ r#"{"shape":"true:true:[object PerformanceMark]:detached:mark:2:0","detail":"before:true:false","timelineEntries":0,"derived":"true:true:true:derived:3","constructorInheritance":true,"detailBrand":"TypeError:undefined","methodBrands":"TypeError:undefined|TypeError:undefined|TypeError:undefined|TypeError:undefined","withoutNew":"TypeError:undefined","missingName":"TypeError:undefined","negativeStart":"TypeError:undefined","infiniteStart":"TypeError:undefined","reservedName":"SyntaxError:12","cloneError":"DataCloneError:25"}"#
);
}
diff --git a/moli-wpt-compat/fixtures/wpt/ported/idl/performance-entry-idlharness.html b/moli-wpt-compat/fixtures/wpt/ported/idl/performance-entry-idlharness.html
index 56249ef9f..21e4dd3b8 100644
--- a/moli-wpt-compat/fixtures/wpt/ported/idl/performance-entry-idlharness.html
+++ b/moli-wpt-compat/fixtures/wpt/ported/idl/performance-entry-idlharness.html
@@ -45,7 +45,10 @@ test(function () {
assert_equals(mark.entryType, "mark");
assert_equals(mark.detail, null);
- const measure = performance.measure("moli-performance-entry-idl-sample-measure", { detail: "measure-detail" });
+ const measure = performance.measure("moli-performance-entry-idl-sample-measure", {
+ start: 0,
+ detail: "measure-detail"
+ });
assert_true(measure instanceof PerformanceEntry);
assert_true(measure instanceof PerformanceMeasure);
assert_equals(Object.prototype.toString.call(measure), "[object PerformanceMeasure]");