Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(performance): share native clock state with user timing
ldm00ef10319a3f6
diff --git a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rsindex 8bd5b9920..375c2d354 100644--- a/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs+++ b/moli-renderer-v8/src/context_bootstrap/performance_runtime.rs@@ -143,6 +143,15 @@ pub(super) use window_state::{finish_window_performance_materialization, install_default_window_performance_seed,};+pub(in crate::context_bootstrap) fn performance_now<'s>(+ scope: &mut v8::PinScope<'s, '_>,+ performance: v8::Local<'s, v8::Object>,+) -> f64 {+ let time_origin = performance_slot_number(scope, performance, PERFORMANCE_TIME_ORIGIN_SLOT)+ .expect("branded Performance receiver should retain its time origin");+ dom_time_since_origin_millis(time_origin)+}+pub(super) fn ensure_current_performance_for_api<'s>(scope: &mut v8::PinScope<'s, '_>,) -> Option<v8::Local<'s, v8::Object>> {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.rsindex b47b7dbc5..1e676e8de 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@@ -180,11 +180,9 @@ fn prepare_performance_mark<'s>(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)- });+ let start_time = options+ .start_time+ .unwrap_or_else(|| performance_now(scope, performance));if start_time < 0.0 {webidl::throw_type_error(scope,@@ -262,8 +260,6 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(let Some(parsed_measure) = parse_performance_measure_arguments(scope, &args) else {return;};- let now = unix_epoch_millis()- - 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,@@ -276,7 +272,7 @@ pub(in crate::context_bootstrap) fn performance_measure_callback<'s>(Ok(end) => end,Err(()) => return,},- None => now,+ None => performance_now(scope, performance),};let (start_time, end_time) = match parsed_measure.duration {Some(duration) if parsed_measure.start.is_none() => (end - duration, end),diff --git a/moli-renderer-v8/src/context_bootstrap/window_runtime/performance.rs b/moli-renderer-v8/src/context_bootstrap/window_runtime/performance.rsindex edab152d0..23444d431 100644--- a/moli-renderer-v8/src/context_bootstrap/window_runtime/performance.rs+++ b/moli-renderer-v8/src/context_bootstrap/window_runtime/performance.rs@@ -1,7 +1,4 @@-use crate::context_bootstrap::{- PERFORMANCE_TIME_ORIGIN_SLOT, dom_time_since_origin_millis, performance_slot_number,-};-use crate::util::throw_type_error;+use crate::context_bootstrap::performance_runtime::performance_now;use moli_webapi_declare::v8;pub(in crate::context_bootstrap) fn performance_now_callback<'s>(@@ -9,12 +6,6 @@ pub(in crate::context_bootstrap) fn performance_now_callback<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {- let Some(time_origin) =- performance_slot_number(scope, args.this(), PERFORMANCE_TIME_ORIGIN_SLOT)- else {- throw_type_error(scope, "Illegal invocation");- return;- };- let now = dom_time_since_origin_millis(time_origin);+ let now = performance_now(scope, args.this());rv.set(v8::Number::new(scope, now).into());}diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rsindex 6be4cbb0a..496efb726 100644--- a/moli-renderer-v8/src/script_vm/tests/mod.rs+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs@@ -2270,3 +2270,5 @@ mod shadow_frame_unload_discovery;mod file_reader_handlers;mod streams_sync_protocol;++mod performance_user_timing;diff --git a/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rs b/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rsnew file mode 100644index 000000000..c12aaf076--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/performance_user_timing.rs@@ -0,0 +1,24 @@+use super::*;++#[test]+fn user_timing_implicit_timestamps_share_the_performance_now_clock() {+ let mut vm = new_storage_page_task_executor_test_vm("https://user-timing-clock.test/");+ let source = format!(+ r#"(() => {{+ const probe = {};+ const privateStateProbe = {};+ const frame = document.createElement('iframe');+ document.body.appendChild(frame);+ try {{+ const checks = [globalThis, frame.contentWindow]+ .flatMap(owner => [...probe(owner), ...privateStateProbe(owner)]);+ return JSON.stringify({{total: checks.length, failures: checks.filter(row => !row.passed)}});+ }} finally {{ frame.remove(); }}+ }})()"#,+ include_str!("../../../tests/fixtures/user-timing-clock.js"),+ include_str!("../../../tests/fixtures/user-timing-private-state.js"),+ );+ let result: serde_json::Value = serde_json::from_str(&vm.eval(&source).unwrap()).unwrap();+ assert_eq!(result["total"], 400);+ assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");+}diff --git a/moli-renderer-v8/src/worker/thread/tests/mod.rs b/moli-renderer-v8/src/worker/thread/tests/mod.rsindex f30de5d80..0fc133828 100644--- a/moli-renderer-v8/src/worker/thread/tests/mod.rs+++ b/moli-renderer-v8/src/worker/thread/tests/mod.rs@@ -1547,3 +1547,5 @@ mod xhr_failure;mod payment_events;mod performance_handler_order;++mod performance_user_timing;diff --git a/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rs b/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rsnew file mode 100644index 000000000..8f14da8e5--- /dev/null+++ b/moli-renderer-v8/src/worker/thread/tests/performance_user_timing.rs@@ -0,0 +1,23 @@+use super::*;++#[tokio::test]+async fn worker_user_timing_implicit_timestamps_share_the_performance_now_clock() {+ ensure_v8();+ let source = format!(+ r#"const probe = {};+ const privateStateProbe = {};+ const checks = [...probe(), ...privateStateProbe()];+ postMessage({{total: checks.length, failures: checks.filter(row => !row.passed)}});+ close();"#,+ include_str!("../../../../tests/fixtures/user-timing-clock.js"),+ include_str!("../../../../tests/fixtures/user-timing-private-state.js"),+ );+ let mut worker = spawn_worker(source, "test://user_timing_clock".into());+ let message = timeout(TIMEOUT, worker.recv())+ .await+ .expect("timed out")+ .expect("channel closed");+ let result: serde_json::Value = serde_json::from_str(&expect_post_json(message)).unwrap();+ assert_eq!(result["total"], 200);+ assert_eq!(result["failures"], serde_json::json!([]), "{result:#}");+}diff --git a/moli-renderer-v8/tests/fixtures/user-timing-clock.js b/moli-renderer-v8/tests/fixtures/user-timing-clock.jsnew file mode 100644index 000000000..59b6de4ce--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/user-timing-clock.js@@ -0,0 +1,71 @@+(owner = globalThis) => {+ const checks = [];+ const check = (name, passed, details = '') => checks.push({name, passed: !!passed, details});+ const performance = owner.performance;+ const prototype = owner.Performance.prototype;+ const now = prototype.now.bind(performance);+ const mark = prototype.mark.bind(performance);+ const measure = prototype.measure.bind(performance);+ const clearMarks = prototype.clearMarks.bind(performance);+ const clearMeasures = prototype.clearMeasures.bind(performance);+ const prefix = '__userTimingClock:';+ const names = [];+ const name = suffix => {+ const value = prefix + suffix;+ names.push(value);+ return value;+ };+ const rounded = value => Number(value.toFixed(2));+ try {+ const boundaryName = name('boundary');+ mark(boundaryName, {startTime: 123.456789123});+ const samples = [+ ['mark', suffix => mark(name(suffix)), entry => entry.startTime],+ ['constructor', suffix => new owner.PerformanceMark(name(suffix)), entry => entry.startTime],+ ['measure', suffix => measure(name(suffix)), entry => entry.startTime + entry.duration],+ ['empty-options', suffix => measure(name(suffix), {}), entry => entry.startTime + entry.duration],+ ['legacy-start', suffix => measure(name(suffix), boundaryName), entry => entry.startTime + entry.duration],+ ['options-start', suffix => measure(name(suffix), {start: boundaryName}), entry => entry.startTime + entry.duration],+ ];+ for (let index = 0; index < 32; index++) {+ for (const [kind, create, timestamp] of samples) {+ const before = rounded(now());+ const entry = create(`${kind}:${index}`);+ const after = rounded(now());+ const value = rounded(timestamp(entry));+ check(`${kind}:${index}:within-now`, before <= value && value <= after,+ JSON.stringify({before, value, after}));+ }+ }++ const exact = 123.456789123;+ check('explicit-mark-keeps-precision', mark(name('explicit'), {startTime: exact}).startTime === exact);+ check('explicit-constructor-keeps-precision',+ new owner.PerformanceMark(name('explicit-constructor'), {startTime: exact}).startTime === exact);+ const end = 321.987654321;+ const explicit = measure(name('explicit-measure'), {start: exact, end});+ check('explicit-measure-keeps-precision', explicit.startTime === exact && explicit.duration === end - exact);++ let authorNowCalls = 0;+ const ownNow = Object.getOwnPropertyDescriptor(performance, 'now');+ Object.defineProperty(performance, 'now', {configurable: true, value() {+ authorNowCalls++;+ throw new Error('User Timing must use its native clock');+ }});+ try {+ mark(name('native-mark'));+ new owner.PerformanceMark(name('native-constructor'));+ measure(name('native-measure'));+ check('implicit-timestamps-ignore-author-now', authorNowCalls === 0);+ } finally {+ if (ownNow) Object.defineProperty(performance, 'now', ownNow);+ else delete performance.now;+ }+ } finally {+ for (const value of names) {+ clearMarks(value);+ clearMeasures(value);+ }+ }+ return checks;+}diff --git a/moli-renderer-v8/tests/fixtures/user-timing-private-state.js b/moli-renderer-v8/tests/fixtures/user-timing-private-state.jsnew file mode 100644index 000000000..5eca45788--- /dev/null+++ b/moli-renderer-v8/tests/fixtures/user-timing-private-state.js@@ -0,0 +1,36 @@+(owner = globalThis) => {+ const native = owner.performance;+ const constructor = owner.PerformanceMark;+ const key = '__moliWindowPerformance';+ const previous = Object.getOwnPropertyDescriptor(owner, key);+ const checks = [];+ const check = (name, passed, details = '') => checks.push({name, passed: !!passed, details});+ let reads = 0;+ try {+ Object.defineProperty(owner, key, {configurable: true, writable: true, value: {}});+ check('native-performance-after-expando', owner.performance === native);+ try {+ const entry = new constructor('__private_clock_object');+ check('constructor-after-expando', entry instanceof owner.PerformanceMark+ && Number.isFinite(entry.startTime));+ } catch (error) {+ check('constructor-after-expando', false, String(error));+ }+ Object.defineProperty(owner, key, {configurable: true, get() {+ reads++;+ throw new Error('author expando getter');+ }});+ try {+ const entry = new constructor('__private_clock_getter');+ check('constructor-after-expando-getter', entry instanceof owner.PerformanceMark+ && Number.isFinite(entry.startTime));+ } catch (error) {+ check('constructor-after-expando-getter', false, String(error));+ }+ check('no-author-expando-getter', reads === 0, String(reads));+ } finally {+ if (previous) Object.defineProperty(owner, key, previous);+ else delete owner[key];+ }+ return checks;+}