fix(performance): retain native navigation timing

This commit is contained in:
ldm0
2026-11-24 14:41:29 +08:00
parent ae77825301
commit 4b857b77a4
29 changed files with 1339 additions and 102 deletions
+2 -1
View File
@@ -1423,7 +1423,8 @@ impl Browser {
ResourceRequestClient::from_browser_resource_runtime_with_page_network_policy(
document_fetch_context_seed.browser_resource_runtime(),
document_fetch_context_seed.page_network_policy(),
);
)
.with_navigation_timing_seed(&document_fetch_context_seed);
let response_status = response.status;
let response_headers = response.headers.clone();
let redirected = response.redirected;
+2 -1
View File
@@ -1069,7 +1069,8 @@ impl NavigationEngine {
ResourceRequestClient::from_browser_resource_runtime_with_page_network_policy(
committed_runtime,
seed.page_network_policy(),
),
)
.with_navigation_timing_seed(&seed),
)
}
+2
View File
@@ -6,6 +6,8 @@ mod event_source_resource_timing;
mod font_loading;
#[path = "scripts/integrity.rs"]
mod integrity;
#[path = "scripts/navigation_resource_timing.rs"]
mod navigation_resource_timing;
#[path = "scripts/nested_worker_retirement.rs"]
mod nested_worker_retirement;
#[path = "scripts/worker_event_source.rs"]
@@ -0,0 +1,452 @@
use super::*;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
task::{JoinHandle, JoinSet},
};
struct NavigationTimingServer {
origin: String,
task: JoinHandle<()>,
prefetched_requests: std::sync::Arc<std::sync::atomic::AtomicUsize>,
}
impl Drop for NavigationTimingServer {
fn drop(&mut self) {
self.task.abort();
}
}
fn epoch_millis() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs_f64()
* 1000.0
}
const STATE_WAITER: &str = r#"
async function waitState(worker, state) {
if (worker.state === state) return;
await new Promise(resolve => {
const changed = () => {
if (worker.state === state) {
worker.removeEventListener('statechange', changed); resolve();
}
};
worker.addEventListener('statechange', changed); changed();
});
}
function snapshot(win) {
const nav = win.performance.getEntriesByType('navigation')[0];
return {timeOrigin: win.performance.timeOrigin, nav: nav.toJSON(),
swTimes: win.swTimes || null};
}
"#;
const SERVICE_WORKER: &str = r#"
const times = {};
const epoch = () => performance.timeOrigin + performance.now();
addEventListener('activate', event => {
times.activateStart = epoch();
event.waitUntil(new Promise(resolve => setTimeout(resolve, 500)).then(() => {
times.activateEnd = epoch();
}));
});
addEventListener('fetch', event => {
times.fetchEvent = epoch();
event.respondWith(new Response('<!doctype html><body>controlled<script>globalThis.swTimes=' +
JSON.stringify(times) + '</script>', {headers:{'Content-Type':'text/html'}}));
});
"#;
impl NavigationTimingServer {
async fn spawn() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let origin = format!("http://{}", listener.local_addr().unwrap());
let stream_observed = std::sync::Arc::new(tokio::sync::Notify::new());
let prefetched_requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let request_count = prefetched_requests.clone();
let task = tokio::spawn(async move {
let mut connections = JoinSet::new();
loop {
let (mut socket, _) = listener.accept().await.unwrap();
let stream_observed = stream_observed.clone();
let request_count = request_count.clone();
connections.spawn(async move {
let mut request = Vec::new();
while !request.windows(4).any(|b| b == b"\r\n\r\n") {
let mut buffer = [0; 2048];
let count = socket.read(&mut buffer).await.unwrap();
if count == 0 { return; }
request.extend_from_slice(&buffer[..count]);
}
let request = String::from_utf8(request).unwrap();
let path = request.split_whitespace().nth(1).unwrap();
if let Some(target) = path.strip_prefix("/redirect?to=") {
let head = format!("HTTP/1.1 302 Found\r\nLocation: {target}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
socket.write_all(head.as_bytes()).await.unwrap();
return;
}
if path == "/stream" {
let first = "<!doctype html><body><script>globalThis.savedNav=performance.getEntriesByType('navigation')[0];globalThis.earlyNav=savedNav.toJSON();fetch('/stream-observed');</script>";
let last = "<p>stream completed</p>";
let head = format!("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", first.len()+last.len());
socket.write_all(head.as_bytes()).await.unwrap();
socket.write_all(first.as_bytes()).await.unwrap();
tokio::time::timeout(Duration::from_secs(10), stream_observed.notified()).await.unwrap();
socket.write_all(last.as_bytes()).await.unwrap();
return;
}
if path == "/stream-observed" {
stream_observed.notify_one();
}
if path == "/prefetched" {
request_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
let (mime, body) = match path {
"/prefetch" => ("text/html", format!(r#"<!doctype html><body><script>
{STATE_WAITER}
(async () => {{
const frame=document.createElement('iframe');
await new Promise(resolve => {{frame.onload=resolve;frame.src='/empty';document.body.appendChild(frame);}});
const doc=frame.contentDocument;
await new Promise((resolve,reject) => {{
const link=doc.createElement('link');link.rel='prefetch';link.as='document';link.href='/prefetched';
link.onload=resolve;link.onerror=reject;doc.head.appendChild(link);
}});
await new Promise(resolve => {{frame.onload=resolve;frame.contentWindow.location='/prefetched';}});
globalThis.observation=snapshot(frame.contentWindow);
}})().catch(error => globalThis.caseError=String(error));
</script>"#)),
"/sw.js" => ("text/javascript", SERVICE_WORKER.to_owned()),
"/setup" => ("text/html", format!(r#"<!doctype html><body><script>
{STATE_WAITER}
(async () => {{
const registration = await navigator.serviceWorker.register('/sw.js', {{scope:'/controlled/'}});
await waitState(registration.installing || registration.waiting || registration.active, 'activated');
globalThis.swReady = true;
}})().catch(error => globalThis.caseError = String(error));
</script>"#)),
"/activation" => ("text/html", format!(r#"<!doctype html><body><script>
{STATE_WAITER}
(async () => {{
const registration = await navigator.serviceWorker.register('/sw.js', {{scope:'/controlled/'}});
await waitState(registration.installing || registration.waiting || registration.active, 'activating');
const frame = document.createElement('iframe');
await new Promise(resolve => {{ frame.onload = resolve; frame.src = '/empty'; document.body.appendChild(frame); }});
const beforeNavigate = performance.timeOrigin + performance.now();
await new Promise(resolve => {{ frame.onload = resolve; frame.contentWindow.location = '/controlled/frame'; }});
globalThis.observation = {{beforeNavigate, child:snapshot(frame.contentWindow)}};
}})().catch(error => globalThis.caseError = String(error));
</script>"#)),
"/ownership" => ("text/html", r#"<!doctype html><body><script>
(async () => {
const frame = document.createElement('iframe');
await new Promise(resolve => { frame.onload=resolve; frame.src='/slow'; document.body.appendChild(frame); });
const win=frame.contentWindow;
const old=win.performance.getEntriesByType('navigation')[0];
const before=old.toJSON(), origin=win.performance.timeOrigin;
const getter=Object.getOwnPropertyDescriptor(PerformanceResourceTiming.prototype,'encodedBodySize').get;
const borrowed=getter.call(old);
win.document.open(); win.document.write('<!doctype html><body>replacement stream'); win.document.close();
const opened=old.toJSON(), openOrigin=win.performance.timeOrigin;
await new Promise(resolve => { frame.onload=resolve; frame.src='/empty'; });
globalThis.observation={before,origin,borrowed,opened,openOrigin,retired:old.toJSON(),current:frame.contentWindow.performance.getEntriesByType('navigation')[0].toJSON()};
})().catch(error => globalThis.caseError=String(error));
</script>"#.to_owned()),
"/slow" => {
// Deliberately delay the response, so a context-creation
// time origin cannot masquerade as navigation start.
tokio::time::sleep(Duration::from_millis(100)).await;
("text/html", format!("<!doctype html><body><script>globalThis.responseSent={};</script>", epoch_millis()))
}
_ => ("text/html", "<!doctype html><body>network".to_owned()),
};
let cache_control = if path == "/prefetched" { "max-age=300" } else { "no-store" };
let head = format!("HTTP/1.1 200 OK\r\nContent-Type: {mime}\r\nCache-Control: {cache_control}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
let _ = socket.write_all(head.as_bytes()).await;
let _ = socket.write_all(body.as_bytes()).await;
});
while let Some(result) = connections.try_join_next() {
result.unwrap();
}
}
});
Self {
origin,
task,
prefetched_requests,
}
}
}
async fn read_json(
page: &mut moli_core::page::Page,
expression: &str,
) -> Result<serde_json::Value> {
let result = page
.evaluate_runtime_expression_by_value_async(expression)
.await?;
Ok(serde_json::from_str(
result["value"]
.as_str()
.unwrap_or_else(|| panic!("{result}")),
)?)
}
fn navigation_snapshot() -> String {
format!("(() => {{ {STATE_WAITER}; return JSON.stringify(snapshot(window)); }})()")
}
#[tokio::test(flavor = "multi_thread")]
async fn navigation_time_origin_precedes_the_http_response() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let before = epoch_millis();
let mut page = browser.fetch(&format!("{}/slow", server.origin)).await?;
let result = read_json(&mut page, &format!("(() => {{ {STATE_WAITER}; return JSON.stringify({{...snapshot(window), responseSent}}); }})()")).await?;
let origin = result["timeOrigin"].as_f64().unwrap();
assert!(
origin >= before && origin < result["responseSent"].as_f64().unwrap(),
"{result}"
);
assert_eq!(result["nav"]["responseStatus"], 200, "{result}");
assert!(
result["nav"]["encodedBodySize"].as_u64().unwrap() > 0,
"{result}"
);
let nav = &result["nav"];
assert_eq!(nav["workerStart"], 0);
for names in [
["fetchStart", "requestStart"],
["requestStart", "responseStart"],
["responseStart", "responseEnd"],
] {
assert!(
nav[names[0]].as_f64().unwrap() <= nav[names[1]].as_f64().unwrap(),
"{result}"
);
}
assert!(nav["responseStart"].as_f64().unwrap() > 0.0, "{result}");
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn iframe_navigation_timing_spans_service_worker_activation() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!("{}/activation", server.origin))
.await?;
browser
.wait_for_script_truthy(
&mut page,
"Boolean(globalThis.observation || globalThis.caseError)",
Duration::from_secs(10),
)
.await?;
let result = read_json(
&mut page,
"JSON.stringify({observation:globalThis.observation,error:globalThis.caseError})",
)
.await?;
assert!(result.get("error").is_none(), "{result}");
let observation = &result["observation"];
let child = &observation["child"];
let origin = child["timeOrigin"].as_f64().unwrap();
let activation_end = child["swTimes"]["activateEnd"].as_f64().unwrap();
let fetch_event = child["swTimes"]["fetchEvent"].as_f64().unwrap();
assert!(
origin >= observation["beforeNavigate"].as_f64().unwrap() && origin < activation_end,
"{result}"
);
assert!(
origin + child["nav"]["workerStart"].as_f64().unwrap() < activation_end,
"{result}"
);
assert!(
activation_end < origin + child["nav"]["fetchStart"].as_f64().unwrap(),
"{result}"
);
assert!(
origin + child["nav"]["fetchStart"].as_f64().unwrap() < fetch_event,
"{result}"
);
assert_eq!(child["nav"]["responseStatus"], 200, "{result}");
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn main_navigation_timing_records_the_running_service_worker() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut setup = browser.fetch(&format!("{}/setup", server.origin)).await?;
browser
.wait_for_script_truthy(
&mut setup,
"Boolean(globalThis.swReady || globalThis.caseError)",
Duration::from_secs(10),
)
.await?;
let mut page = browser
.fetch(&format!("{}/controlled/main", server.origin))
.await?;
let result = read_json(&mut page, &navigation_snapshot()).await?;
assert_eq!(result["nav"]["responseStatus"], 200, "{result}");
let origin = result["timeOrigin"].as_f64().unwrap();
assert!(
origin + result["nav"]["workerStart"].as_f64().unwrap()
<= result["swTimes"]["fetchEvent"].as_f64().unwrap(),
"{result}"
);
assert!(
result["nav"]["fetchStart"].as_f64().unwrap() > 0.0,
"{result}"
);
assert!(
result["nav"]["responseStart"].as_f64().unwrap()
>= result["nav"]["fetchStart"].as_f64().unwrap(),
"{result}"
);
assert!(
result["nav"]["decodedBodySize"].as_u64().unwrap() > 0,
"{result}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn cached_navigation_entry_observes_stream_completion() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser.fetch(&format!("{}/stream", server.origin)).await?;
let result = read_json(&mut page, "JSON.stringify({early:earlyNav,late:savedNav.toJSON(),same:savedNav===performance.getEntriesByType('navigation')[0]})").await?;
assert_eq!(result["same"], true, "{result}");
assert_eq!(result["early"]["responseStatus"], 200, "{result}");
assert_eq!(result["early"]["responseEnd"], 0, "{result}");
assert!(
result["early"]["responseStart"].as_f64().unwrap() > 0.0,
"{result}"
);
assert!(
result["late"]["responseEnd"].as_f64().unwrap()
> result["early"]["responseStart"].as_f64().unwrap(),
"{result}"
);
assert!(
result["late"]["encodedBodySize"].as_u64().unwrap() > 0,
"{result}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn cross_origin_navigation_redirect_exposes_only_the_final_response() -> Result<()> {
let first = NavigationTimingServer::spawn().await;
let last = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!(
"{}/redirect?to={}/slow",
first.origin, last.origin
))
.await?;
let result = read_json(&mut page, &navigation_snapshot()).await?;
let nav = &result["nav"];
assert_eq!(nav["redirectStart"], 0, "{result}");
assert_eq!(nav["redirectEnd"], 0, "{result}");
assert_eq!(nav["responseStatus"], 200, "{result}");
assert!(nav["fetchStart"].as_f64().unwrap() > 0.0, "{result}");
assert!(
nav["responseStart"].as_f64().unwrap() > nav["fetchStart"].as_f64().unwrap(),
"{result}"
);
assert!(nav["encodedBodySize"].as_u64().unwrap() > 0, "{result}");
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn navigation_timing_stays_with_its_window_across_open_and_replacement() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!("{}/ownership", server.origin))
.await?;
browser
.wait_for_script_truthy(
&mut page,
"Boolean(globalThis.observation || globalThis.caseError)",
Duration::from_secs(10),
)
.await?;
let result = read_json(
&mut page,
"JSON.stringify({observation:globalThis.observation,error:globalThis.caseError})",
)
.await?;
assert!(result.get("error").is_none(), "{result}");
let observation = &result["observation"];
assert_eq!(observation["origin"], observation["openOrigin"], "{result}");
assert_eq!(
observation["borrowed"], observation["before"]["encodedBodySize"],
"{result}"
);
for name in [
"fetchStart",
"requestStart",
"responseStart",
"responseEnd",
"encodedBodySize",
"responseStatus",
] {
assert_eq!(
observation["before"][name], observation["opened"][name],
"{name}: {result}"
);
assert_eq!(
observation["before"][name], observation["retired"][name],
"{name}: {result}"
);
}
assert_ne!(
observation["current"]["encodedBodySize"], observation["retired"]["encodedBodySize"],
"{result}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn prefetched_navigation_reuses_the_response_and_reports_a_local_transfer() -> Result<()> {
let server = NavigationTimingServer::spawn().await;
let browser = Browser::new(AppConfig::default())?;
let mut page = browser
.fetch(&format!("{}/prefetch", server.origin))
.await?;
browser
.wait_for_script_truthy(
&mut page,
"Boolean(globalThis.observation || globalThis.caseError)",
Duration::from_secs(10),
)
.await?;
let result = read_json(
&mut page,
"JSON.stringify({observation:globalThis.observation,error:globalThis.caseError})",
)
.await?;
assert!(result.get("error").is_none(), "{result}");
assert_eq!(
server
.prefetched_requests
.load(std::sync::atomic::Ordering::SeqCst),
1,
"navigation must reuse the prefetched response: {result}"
);
let nav = &result["observation"]["nav"];
assert_eq!(nav["responseStatus"], 200, "{result}");
assert_eq!(nav["transferSize"], 0, "{result}");
assert!(nav["encodedBodySize"].as_u64().unwrap() > 0, "{result}");
assert!(nav["responseEnd"].as_f64().unwrap() > 0.0, "{result}");
Ok(())
}
+120 -1
View File
@@ -171,6 +171,15 @@ impl ResponseProgress {
CachedResponseBodyTiming(self.clone())
}
pub(crate) fn mark_materialized_response_available(
&self,
sizes: Option<FetchResponseBodySizes>,
) {
self.mark_response_started();
self.inner.timing.lock().body_sizes = sizes;
self.commit();
}
fn is_committed(&self) -> bool {
self.inner.state.load(Ordering::Acquire) == RESPONSE_COMMITTED
}
@@ -188,6 +197,8 @@ impl ResponseProgress {
/// Native response boundaries shared with observers of the selected transfer.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FetchResponseTiming {
service_worker_started_at: Option<Instant>,
service_worker_dispatched_at: Option<Instant>,
fetch_started_at: Option<Instant>,
body_sizes: Option<FetchResponseBodySizes>,
request_started_at: Option<Instant>,
@@ -199,6 +210,14 @@ pub struct FetchResponseTiming {
}
impl FetchResponseTiming {
pub fn service_worker_started_at(self) -> Option<Instant> {
self.service_worker_started_at
}
pub fn service_worker_dispatched_at(self) -> Option<Instant> {
self.service_worker_dispatched_at
}
/// Start of the selected HTTP hop, retained through transparent transport
/// retries. This is not a libcurl attempt's start or a preflight's clock.
pub fn fetch_started_at(self) -> Option<Instant> {
@@ -246,6 +265,9 @@ impl CachedResponseBodyTiming {
struct FetchLifecycleState {
cancellation: CancellationToken,
fetch_hop_started_at: Option<Instant>,
// Worker startup/activation belongs to the request, independently of
// whichever HTTP response is selected after redirects or fallback.
service_worker_timing: Mutex<(Option<Instant>, Option<Instant>)>,
// This lock protects selection, while the selected token arbitrates
// transport completion and consumer cancellation without taking the lock.
response_progress: Mutex<ResponseProgress>,
@@ -386,7 +408,32 @@ impl FetchCancelHandle {
}
pub fn response_timing(&self) -> FetchResponseTiming {
*self.response_progress().inner.timing.lock()
let mut timing = *self.response_progress().inner.timing.lock();
let worker = self.state.service_worker_timing.lock();
timing.service_worker_started_at = worker.0;
timing.service_worker_dispatched_at = worker.1;
timing
}
/// Called after selecting a controlling worker, before activation/startup.
pub fn mark_service_worker_start(&self) {
if !self.is_cancelled() {
self.state
.service_worker_timing
.lock()
.0
.get_or_insert_with(Instant::now);
}
}
/// Called when the selected worker is ready to receive its fetch event.
pub fn mark_service_worker_dispatch(&self) {
if !self.is_cancelled() {
let mut timing = self.state.service_worker_timing.lock();
if timing.0.is_some() {
timing.1.get_or_insert_with(Instant::now);
}
}
}
#[cfg(test)]
@@ -424,6 +471,78 @@ mod tests {
use crate::FetchCurlTiming;
use std::time::{Duration, Instant};
#[test]
fn service_worker_clock_survives_response_selection_without_leaking_to_hops() {
let request = FetchCancelHandle::new();
request.mark_service_worker_start();
let start = request
.response_timing()
.service_worker_started_at()
.unwrap();
assert!(
request
.response_timing()
.service_worker_dispatched_at()
.is_none()
);
let hop = request.child_for_fetch_hop();
assert!(hop.response_timing().service_worker_started_at().is_none());
hop.mark_response_started();
request.mark_service_worker_dispatch();
let dispatch = request
.response_timing()
.service_worker_dispatched_at()
.unwrap();
request.adopt_response_progress(&hop);
let selected = request.response_timing();
assert_eq!(selected.service_worker_started_at(), Some(start));
assert_eq!(selected.service_worker_dispatched_at(), Some(dispatch));
assert_eq!(
selected.response_started_at(),
hop.response_timing().response_started_at()
);
assert!(start <= dispatch && dispatch <= Instant::now());
request.begin_response_progress();
request.mark_service_worker_start();
request.mark_service_worker_dispatch();
assert_eq!(
request.response_timing().service_worker_started_at(),
Some(start)
);
assert_eq!(
request.response_timing().service_worker_dispatched_at(),
Some(dispatch)
);
assert!(request.response_timing().response_started_at().is_none());
}
#[test]
fn cancelled_or_unselected_worker_dispatch_does_not_create_a_clock() {
let request = FetchCancelHandle::new();
request.mark_service_worker_dispatch();
assert!(
request
.response_timing()
.service_worker_dispatched_at()
.is_none()
);
request.cancel();
request.mark_service_worker_start();
request.mark_service_worker_dispatch();
assert!(
request
.response_timing()
.service_worker_started_at()
.is_none()
);
assert!(
request
.response_timing()
.service_worker_dispatched_at()
.is_none()
);
}
#[test]
fn connection_observations_cannot_follow_response_selection_or_reset() {
let selected = FetchCancelHandle::new();
+60
View File
@@ -227,6 +227,28 @@ pub struct StreamingRawResponse {
}
impl StreamingRawResponse {
/// Exposes an already materialized body as a completed local stream.
/// Encoded sizes, when known, belong to the retained representation; this
/// does not record a network request or receipt of new transport bytes.
pub fn from_materialized_body(
head: ResponseHead,
body: Vec<u8>,
body_sizes: Option<crate::FetchResponseBodySizes>,
) -> Self {
let (body_tx, body_rx) = mpsc::unbounded_channel();
if !body.is_empty() {
body_tx.send(body).expect("new body receiver is open");
}
drop(body_tx);
let cancel_handle = FetchCancelHandle::new();
cancel_handle
.response_progress()
.mark_materialized_response_available(body_sizes);
let (completion_tx, completion_rx) = oneshot::channel();
let _ = completion_tx.send(Ok(()));
Self::new_with_head(head, body_rx, cancel_handle, completion_rx)
}
pub fn response_timing(&self) -> crate::FetchResponseTiming {
self.cancel_handle.response_timing()
}
@@ -597,6 +619,44 @@ mod tests {
}
}
#[tokio::test]
async fn materialized_raw_response_records_local_completion_and_retained_sizes() {
for (body, sizes) in [
(
b"decoded body".to_vec(),
Some(crate::FetchResponseBodySizes {
encoded: 7,
decoded: 12,
}),
),
(b"unknown encoded size".to_vec(), None),
(Vec::new(), Some(crate::FetchResponseBodySizes::default())),
] {
let before = std::time::Instant::now();
let response = StreamingRawResponse::from_materialized_body(
sample_response_head(),
body.clone(),
sizes,
);
let after = std::time::Instant::now();
let cancel = response.cancellation_handle();
let timing = response.response_timing();
let start = timing
.response_started_at()
.expect("local response available");
let end = timing.response_end_at().expect("local body complete");
assert!(before <= start && start <= end && end <= after);
assert_eq!(timing.body_sizes(), sizes);
assert_eq!(timing.request_started_at(), None);
assert!(!timing.body_bytes_received());
assert!(!cancel.cancel_if_response_pending());
let materialized = response.into_materialized_raw_response().await.unwrap();
assert_eq!(materialized.body_bytes(), body);
assert_eq!(materialized.body_sizes(), sizes);
assert!(!cancel.is_cancelled());
}
}
struct CompletionOrderLease {
completion_tx: Option<oneshot::Sender<Result<()>>>,
dropped_before_completion_closed: Arc<AtomicBool>,
@@ -295,6 +295,7 @@ pub(crate) fn capture_eager_intrinsic_interfaces<'s>(
moli_webapi::install_realm_callbacks(
scope,
moli_webapi::RealmCallbacks {
refresh_performance_entry: Some(crate::context_bootstrap::performance_runtime::refresh_navigation_timing),
new_interface_instance: Some(|scope, name| super::build_intrinsic_interface_instance(scope, name).ok()),
call_function: Some(crate::util::call_script_visible_function),
is_window_named_properties_object: Some(crate::context_bootstrap::window_template::is_window_named_properties_object),
@@ -13,6 +13,9 @@ mod marks_measures;
use moli_webapi::performance::memory;
use moli_webapi::performance::name;
mod measurement_interfaces;
mod navigation_timing;
pub(in crate::context_bootstrap) use navigation_timing::refresh_navigation_timing;
pub(in crate::context_bootstrap) use name::PerformanceEntryName;
mod resource_buffer;
mod window_state;
@@ -20,7 +20,8 @@ struct PerformanceGetEntriesByNameArgs {
}
pub(in crate::context_bootstrap) use moli_webapi::performance::entries::{
create_performance_entry, initialize_performance_entry_slots, initialize_resource_timing_slots,
create_performance_entry, initialize_performance_entry_slots,
initialize_resource_timing_response_metadata, initialize_resource_timing_slots,
install_performance_entry_template_bindings, performance_entry_slot_number,
performance_entry_slot_string, set_performance_entry_slot_number,
};
@@ -194,4 +195,3 @@ pub(super) fn append_performance_entry<'s>(
};
let _ = entries.set_index(scope, entries.length(), entry.into());
}
@@ -377,6 +377,7 @@ fn create_navigation_performance_entry<'s>(
))
.initialize(scope, entry)
.expect("PerformanceNavigationTiming slot declaration should initialize");
super::navigation_timing::refresh_navigation_timing(scope, entry);
entry
}
@@ -0,0 +1,189 @@
use super::*;
use crate::util::context_host_ptr_from_global_bridge;
/// Refresh the entry in its own Window realm. Borrowed prototype getters must
/// not pick up the caller's navigation or a replacement Window's Document.
pub(in crate::context_bootstrap) fn refresh_navigation_timing<'s>(
scope: &mut v8::PinScope<'s, '_>,
entry: v8::Local<'s, v8::Object>,
) {
if performance_entry_slot_string(scope, entry, PERFORMANCE_ENTRY_TYPE_SLOT).as_deref()
!= Some("navigation")
{
return;
}
let Some(context) = entry.get_creation_context(scope) else {
return;
};
let scope = &mut v8::ContextScope::new(scope, context);
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
return;
};
let host = unsafe { &*host_ptr };
let Some(dispatch) = host.window_dispatch_scope_for_context(scope, context) else {
return;
};
if host
.current_runtime_window_execution_context_identity_for_dispatch_scope(scope, dispatch)
.is_none()
{
return;
}
let Some(snapshot) = host
.document_resource_loader_for_dispatch_scope(dispatch)
.and_then(|loader| loader.navigation_timing())
.and_then(|timing| timing.snapshot())
else {
return;
};
let origin = moli_url::WebOrigin::from_url(&snapshot.head.final_url);
let expose_redirects = !snapshot.head.url_list().has_cross_origin_url(&origin);
// A navigation exposes the final Document's response. Cross-origin hops
// hide redirect timing without hiding that final response's own timing.
let mut final_head = snapshot.head.clone();
final_head.redirect_chain.clear();
let timing =
FetchResourceTiming::from_start("navigation", snapshot.started, snapshot.time_origin);
timing.response_started_at(Some(snapshot.headers_received));
timing.observe_native_timing(snapshot.native);
let mut data = timing.completed(
&snapshot.head.final_url,
&origin,
moli_fetch::RequestMode::Navigate,
&final_head,
snapshot.materialized_body_size.unwrap_or(0),
Some(&moli_fetch_types::FetchResponseType::Basic.into()),
);
let epoch = |instant: std::time::Instant| {
snapshot.time_origin
+ instant
.saturating_duration_since(snapshot.started)
.as_secs_f64()
* 1000.0
};
let worker_start = snapshot.native.service_worker_started_at().map(epoch);
let worker_ready = snapshot.native.service_worker_dispatched_at().map(epoch);
let synthetic = worker_start.is_some() && snapshot.native.response_started_at().is_none();
let fetch_start = if snapshot.head.redirected {
snapshot
.native
.fetch_started_at()
.map(epoch)
.unwrap_or(snapshot.time_origin)
} else {
worker_ready.unwrap_or(snapshot.time_origin)
};
if expose_redirects && snapshot.head.redirected {
data.redirect_start_unix_millis = Some(snapshot.time_origin);
data.redirect_end_unix_millis = Some(fetch_start);
}
if snapshot.head.redirected
&& let Some(connection) = &mut data.connection_timing
{
connection.domain_lookup_start = connection.domain_lookup_start.max(fetch_start);
connection.domain_lookup_end = connection.domain_lookup_end.max(fetch_start);
connection.connect_start = connection.connect_start.max(fetch_start);
connection.connect_end = connection.connect_end.max(fetch_start);
}
let response_end = snapshot.native.response_end_at().map(epoch).or_else(|| {
snapshot
.materialized_body_size
.map(|_| epoch(snapshot.headers_received))
});
if synthetic {
data.connection_timing = Some(ResourceConnectionTiming::at(fetch_start, false));
data.request_start_unix_millis = Some(fetch_start);
data.response_start_unix_millis = Some(epoch(snapshot.headers_received));
data.final_response_headers_start_unix_millis = data.response_start_unix_millis;
data.transfer_size = 0.0;
}
// A streaming document's terminal fields stay zero until the selected
// transfer completes. Cached entry references see the terminal observation.
if response_end.is_none() {
data.transfer_size = 0.0;
data.encoded_body_size = 0.0;
data.decoded_body_size = 0.0;
}
initialize_resource_timing_slots(
scope,
entry,
"navigation",
data.transfer_size,
data.encoded_body_size,
data.decoded_body_size,
"non-blocking",
data.response_status,
&data.content_type,
);
entries::initialize_resource_timing_response_metadata(
scope,
entry,
&data.delivery_type,
&data.content_encoding,
);
for (slot, value) in [
(PERFORMANCE_RESOURCE_WORKER_START_SLOT, worker_start),
(PERFORMANCE_RESOURCE_FETCH_START_SLOT, Some(fetch_start)),
(
PERFORMANCE_RESOURCE_REDIRECT_START_SLOT,
data.redirect_start_unix_millis,
),
(
PERFORMANCE_RESOURCE_REDIRECT_END_SLOT,
data.redirect_end_unix_millis,
),
(
PERFORMANCE_RESOURCE_DOMAIN_LOOKUP_START_SLOT,
data.connection_timing.map(|t| t.domain_lookup_start),
),
(
PERFORMANCE_RESOURCE_DOMAIN_LOOKUP_END_SLOT,
data.connection_timing.map(|t| t.domain_lookup_end),
),
(
PERFORMANCE_RESOURCE_CONNECT_START_SLOT,
data.connection_timing.map(|t| t.connect_start),
),
(
PERFORMANCE_RESOURCE_CONNECT_END_SLOT,
data.connection_timing.map(|t| t.connect_end),
),
(
PERFORMANCE_RESOURCE_SECURE_CONNECTION_START_SLOT,
data.connection_timing
.and_then(|t| t.secure_connection_start),
),
(
PERFORMANCE_RESOURCE_REQUEST_START_SLOT,
data.request_start_unix_millis,
),
(
PERFORMANCE_RESOURCE_RESPONSE_START_SLOT,
data.response_start_unix_millis,
),
(
PERFORMANCE_RESOURCE_FINAL_RESPONSE_HEADERS_START_SLOT,
data.final_response_headers_start_unix_millis,
),
(
PERFORMANCE_RESOURCE_FIRST_INTERIM_RESPONSE_START_SLOT,
data.first_interim_response_start_unix_millis,
),
(PERFORMANCE_RESOURCE_RESPONSE_END_SLOT, response_end),
] {
let value = value
.map(|value| {
moli_time::coarsened_dom_time_millis((value - snapshot.time_origin).max(0.0))
})
.unwrap_or(0.0);
set_performance_entry_slot_number(scope, entry, slot, value);
}
if let Some(protocol) = v8_string(scope, &data.next_hop_protocol) {
set_private_value(
scope,
entry,
PERFORMANCE_RESOURCE_NEXT_HOP_PROTOCOL_SLOT,
protocol.into(),
);
}
}
@@ -126,13 +126,19 @@ fn bind_window_performance_seed_in_current_realm<'s>(
pub(in crate::context_bootstrap) fn install_default_window_performance_seed<'s>(
scope: &mut v8::PinScope<'s, '_>,
window: v8::Local<'s, v8::Object>,
navigation_time_origin: Option<f64>,
) -> Result<()> {
install_performance_observer_runtime_state(
scope,
window,
WINDOW_PERFORMANCE_OBSERVER_SUPPORTED_ENTRY_TYPES,
)?;
bind_window_performance_seed(scope, window, "navigate", unix_epoch_millis())
bind_window_performance_seed(
scope,
window,
"navigate",
navigation_time_origin.unwrap_or_else(unix_epoch_millis),
)
}
pub(in crate::context_bootstrap) fn build_window_performance_for_receiver<'s>(
@@ -1918,7 +1918,11 @@ fn install_window_runtime_state<'s>(
install_trusted_types_runtime_state(scope, global)?;
install_window_crypto_runtime_state(scope, global, secure_context_available)?;
install_css_runtime_state(scope, global)?;
install_default_window_performance_seed(scope, global)?;
install_default_window_performance_seed(
scope,
global,
document_loader.navigation_time_origin(),
)?;
install_chrome_runtime_state(scope, global)?;
install_storage_runtime_state(scope, global)?;
install_public_window_surface_accessors(scope, global)?;
+1
View File
@@ -1462,6 +1462,7 @@ mod tests {
ConnectedLoadParameters::PreloadLikeLink {
url,
options: Arc::new(ConnectedLinkReadinessFetchOptions {
network_partition_key: None,
document_referrer_policy: None,
resource_type: SubresourceResourceType::Stylesheet,
request_resource_type: Some(moli_fetch::RequestResourceType::CssStyleSheet),
@@ -103,6 +103,11 @@ impl ScriptTextCacheKey {
}
impl RawSubresourceCacheKey {
pub(in crate::network) fn allows_response_store(&self, request: &Request) -> bool {
self.resource_type != "navigation-prefetch"
|| request.resource_type == RequestResourceType::LinkPrefetch
}
pub(in crate::network) fn for_page_cache_partition(mut self, partition_id: u64) -> Self {
self.page_cache_partition_id = partition_id;
self
@@ -970,10 +975,13 @@ pub(in crate::network) fn raw_subresource_memory_cache_key(
}
let mut target = request.url.clone();
target.set_fragment(None);
let navigation_prefetch = same_origin_navigation_prefetch(request);
// These policies authorize the same untainted same-origin HTTP hop. Each
// consumer still checks its redirects and response policy, and Vary still
// distinguishes their mode-specific wire headers.
let request_mode = if request.request_mode == RequestMode::Cors
let request_mode = if navigation_prefetch {
RequestMode::Navigate
} else if request.request_mode == RequestMode::Cors
&& request
.request_origin()
.is_some_and(|origin| origin.same_origin_url(&request.url))
@@ -986,21 +994,48 @@ pub(in crate::network) fn raw_subresource_memory_cache_key(
Some(RawSubresourceCacheKey {
page_cache_partition_id: 0,
url: target.into(),
fetch_destination: request
.browser_request_metadata()
.map(BrowserRequestMetadata::fetch_destination),
resource_type: raw_subresource_cache_resource_type_key(request.resource_type),
follow_redirects: request.transport_follows_redirects(),
credentials_mode: request.credentials_mode.as_ref().to_owned(),
fetch_destination: if navigation_prefetch {
Some("document")
} else {
request
.browser_request_metadata()
.map(BrowserRequestMetadata::fetch_destination)
},
resource_type: if navigation_prefetch {
"navigation-prefetch"
} else {
raw_subresource_cache_resource_type_key(request.resource_type)
},
follow_redirects: navigation_prefetch || request.transport_follows_redirects(),
credentials_mode: if navigation_prefetch {
"include".to_owned()
} else {
request.credentials_mode.as_ref().to_owned()
},
request_origin: request
.request_origin()
.map(|origin| origin.ascii_serialization().to_owned()),
request_mode: request_mode.as_ref().to_owned(),
// Policies and explicit Fetch referrers can select different headers
// without changing the origin or cookie initiator in this cache key.
referrer: request.referrer_header_value(&request.url),
referrer: if navigation_prefetch {
None
} else {
request.referrer_header_value(&request.url)
},
network_partition_key: request.network_partition_key().map(str::to_owned),
cookie_context: format!("{:?}", request.cookie_context),
cookie_context: if navigation_prefetch {
let context = &request.cookie_context.browser_context;
let origin = |url: Option<&Url>| url.map(moli_url::origin_ascii_serialization);
format!(
"site:{:?};top:{:?};storage:{:?}",
origin(context.site_for_cookies_url.as_ref()),
origin(context.top_frame_origin_url.as_ref()),
context.storage_access_status
)
} else {
format!("{:?}", request.cookie_context)
},
serialized_origin: request.serialized_origin(),
has_cross_origin_url: request.has_cross_origin_url(&request.url),
})
@@ -1022,6 +1057,49 @@ fn raw_subresource_cache_resource_type_key(resource_type: RequestResourceType) -
}
}
/// Same-origin document prefetches and navigations can reuse one HTTP
/// representation. Keep this namespace separate from script/fetch caches and
/// from cross-origin or credentialless requests. Vary still matches the actual
/// wire headers, including Referer, Sec-Fetch-Mode/Dest and Sec-Purpose.
fn same_origin_navigation_prefetch(request: &Request) -> bool {
(request.resource_type == RequestResourceType::LinkPrefetch
|| (request.request_mode == RequestMode::Navigate
&& request.browser_request_metadata().is_none()
&& matches!(
request.resource_type,
RequestResourceType::Raw | RequestResourceType::Script
)))
&& request
.request_origin()
.is_some_and(|origin| origin.same_origin_url(&request.url))
&& !request.has_cross_origin_url(&request.url)
&& request
.cookie_context
.browser_context
.site_for_cookies_url
.as_ref()
.is_some_and(|site| {
request
.request_origin()
.is_some_and(|origin| origin.same_origin_url(site))
})
&& request
.cookie_context
.browser_context
.top_frame_origin_url
.as_ref()
.is_some_and(|top| {
request
.request_origin()
.is_some_and(|origin| origin.same_origin_url(top))
})
&& request.redirect_chain().is_empty()
&& request.credentials_mode != moli_fetch::RequestCredentialsMode::Omit
&& request
.subresource_request_metadata()
.is_none_or(|metadata| metadata.integrity.is_none())
}
fn raw_subresource_request_is_memory_cacheable(
request: &Request,
request_headers: &RequestHeaders,
@@ -1043,27 +1121,29 @@ fn raw_subresource_request_is_memory_cacheable(
}
fn raw_subresource_memory_cacheable_resource_type(request: &Request) -> bool {
matches!(
request.resource_type,
RequestResourceType::Image
| RequestResourceType::Font
| RequestResourceType::Media
| RequestResourceType::TextTrack
| RequestResourceType::CssStyleSheet
) || matches!(
(request.resource_type, request.browser_request_metadata()),
(
RequestResourceType::Raw,
Some(
BrowserRequestMetadata::Fetch
| BrowserRequestMetadata::JsonModule
| BrowserRequestMetadata::TextModule
| BrowserRequestMetadata::Manifest
| BrowserRequestMetadata::StyleModule
| BrowserRequestMetadata::Xhr
same_origin_navigation_prefetch(request)
|| matches!(
request.resource_type,
RequestResourceType::Image
| RequestResourceType::Font
| RequestResourceType::Media
| RequestResourceType::TextTrack
| RequestResourceType::CssStyleSheet
)
|| matches!(
(request.resource_type, request.browser_request_metadata()),
(
RequestResourceType::Raw,
Some(
BrowserRequestMetadata::Fetch
| BrowserRequestMetadata::JsonModule
| BrowserRequestMetadata::TextModule
| BrowserRequestMetadata::Manifest
| BrowserRequestMetadata::StyleModule
| BrowserRequestMetadata::Xhr
)
)
)
)
}
fn raw_subresource_memory_cacheable_headers(headers: &RequestHeaders) -> bool {
@@ -1105,6 +1185,13 @@ pub(in crate::network) fn raw_subresource_memory_cache_expiry(
request: &Request,
response: &RawResponse,
) -> Option<u64> {
// The shared document-prefetch namespace contains final representations,
// never a manual redirect that an automatic navigation might commit.
if same_origin_navigation_prefetch(request)
&& (response.redirected || !(200..300).contains(&response.status))
{
return None;
}
// This cache retains complete representations, not Content-Range parts.
if response.status == 206 {
return None;
@@ -1430,6 +1517,110 @@ mod tests {
assert_eq!(cache.diagnostics().pending_script_entry_count, 1);
}
fn document_prefetch_request() -> Request {
Request::new_browser(
"GET",
Url::parse("https://example.test/next").unwrap(),
None,
Vec::new(),
moli_url::WebOrigin::from_ascii_serialization("https://example.test"),
)
.with_resource_type(RequestResourceType::LinkPrefetch)
.with_request_mode(RequestMode::NoCors)
.with_site_for_cookies_url(&Url::parse("https://example.test/client").unwrap())
.with_top_frame_origin_url(&Url::parse("https://example.test/client").unwrap())
}
#[test]
fn document_prefetch_cache_preserves_origin_credentials_and_partitions() {
let prefetch = document_prefetch_request();
let navigation = prefetch
.clone()
.with_resource_type(RequestResourceType::Script)
.with_top_level_navigation_cookie_context();
let key =
|request: &Request| raw_subresource_memory_cache_key(request, &request.request_headers);
assert_eq!(key(&prefetch), key(&navigation));
assert!(key(&prefetch).unwrap().allows_response_store(&prefetch));
assert!(!key(&navigation).unwrap().allows_response_store(&navigation));
let child = navigation.clone().with_subframe_navigation_cookie_context();
assert_eq!(key(&prefetch), key(&child));
assert_ne!(
key(&prefetch).unwrap().for_page_cache_partition(1),
key(&navigation).unwrap().for_page_cache_partition(2)
);
for (site, top) in [
(None, Some("https://example.test")),
(Some("https://example.test"), None),
(
Some("https://third-party.test"),
Some("https://example.test"),
),
(
Some("https://example.test"),
Some("https://third-party.test"),
),
] {
let mut isolated = prefetch.clone();
isolated.cookie_context.browser_context.site_for_cookies_url =
site.map(|value| Url::parse(value).unwrap());
isolated.cookie_context.browser_context.top_frame_origin_url =
top.map(|value| Url::parse(value).unwrap());
assert!(
key(&isolated).is_none(),
"unknown or third-party cookie settings cannot share document prefetches"
);
}
let credentialless = prefetch
.clone()
.with_credentials_mode(moli_fetch::RequestCredentialsMode::Omit);
assert!(key(&credentialless).is_none());
let mut cross_origin = prefetch.clone();
cross_origin.url = Url::parse("https://other.test/next").unwrap();
assert!(key(&cross_origin).is_none());
let mut cookie = prefetch.clone();
cookie
.request_headers
.push(("Cookie".to_owned(), b"session=1".to_vec()));
assert!(key(&cookie).is_none());
let partitioned = navigation.with_network_partition_key(Some("isolated-frame".to_owned()));
assert_ne!(key(&prefetch), key(&partitioned));
}
#[test]
fn document_prefetch_cache_matches_vary_against_navigation_wire_headers() {
let mut prefetch = document_prefetch_request();
prefetch
.request_headers
.push(("Sec-Fetch-Mode".to_owned(), b"no-cors".to_vec()));
let mut navigation = prefetch
.clone()
.with_resource_type(RequestResourceType::Script)
.with_top_level_navigation_cookie_context();
navigation.request_headers =
RequestHeaders::from_bytes(vec![("Sec-Fetch-Mode".to_owned(), b"navigate".to_vec())]);
let key = raw_subresource_memory_cache_key(&prefetch, &prefetch.request_headers).unwrap();
assert_eq!(
Some(key.clone()),
raw_subresource_memory_cache_key(&navigation, &navigation.request_headers)
);
let mut response = raw_response("https://example.test/next", b"prefetched");
response
.headers
.push(("vary".to_owned(), b"Sec-Fetch-Mode".to_vec()));
let mut cache = SharedMemoryResourceCache::default();
cache.insert_raw_subresource(key.clone(), response, u64::MAX, &prefetch.request_headers);
assert!(
cache
.lookup_raw_subresource(&key, &navigation, &navigation.request_headers)
.is_none()
);
assert!(matches!(
cache.lookup_raw_subresource(&key, &prefetch, &prefetch.request_headers),
Some(RawSubresourceCacheLookup::Local { .. })
));
}
fn script_request(url: &str) -> Request {
Request::get(url)
.expect("script request URL")
@@ -171,6 +171,7 @@ pub struct DocumentResourceLoader {
creation_url: Arc<url::Url>,
authority: Arc<DocumentResourceLoaderAuthority>,
csp_reports: Arc<crate::content_security_policy::ContentSecurityPolicyReports>,
navigation_timing: Option<crate::network::navigation::NavigationTiming>,
}
/// Inputs that exist before the initial committed Document owner is known.
@@ -183,21 +184,26 @@ pub struct DocumentResourceLoader {
pub(crate) struct DocumentResourceLoaderBootstrap {
request_client: ResourceRequestClient,
task_runner: RendererResourceTaskRunner,
navigation_timing: Option<crate::network::navigation::NavigationTiming>,
}
impl DocumentResourceLoaderBootstrap {
pub(crate) fn new(
request_client: ResourceRequestClient,
mut request_client: ResourceRequestClient,
task_runner: RendererResourceTaskRunner,
) -> Self {
Self {
navigation_timing: request_client.take_navigation_timing_seed(),
request_client,
task_runner,
}
}
pub(crate) fn commit(self, context: DocumentFetchContext) -> DocumentResourceLoader {
DocumentResourceLoader::new(self.request_client, self.task_runner, context)
let mut loader =
DocumentResourceLoader::new(self.request_client, self.task_runner, context);
loader.navigation_timing = self.navigation_timing;
loader
}
pub(crate) fn author_styles_disabled(&self) -> bool {
@@ -277,6 +283,7 @@ impl DocumentResourceLoader {
.with_document_client_policy(client_security_policy),
creation_url,
csp_reports: Default::default(),
navigation_timing: None,
authority,
}
}
@@ -294,12 +301,14 @@ impl DocumentResourceLoader {
if let Some(browser_site_context) = seed.shared_browser_site_context() {
request_client = request_client.with_shared_browser_site_context(browser_site_context);
}
Self::new_with_preloads(
let mut loader = Self::new_with_preloads(
request_client,
seed.resource_task_runner(),
context,
preloads,
)
);
loader.navigation_timing = Some(seed.navigation_timing());
loader
}
pub(crate) fn for_committed_document(
@@ -339,6 +348,16 @@ impl DocumentResourceLoader {
Self::new(self.request_client.clone(), self.task_runner(), context)
}
pub(crate) fn navigation_timing(&self) -> Option<crate::network::navigation::NavigationTiming> {
self.navigation_timing.clone()
}
pub(crate) fn navigation_time_origin(&self) -> Option<f64> {
self.navigation_timing
.as_ref()
.map(|timing| timing.time_origin())
}
pub(crate) fn for_document_open(
context: DocumentFetchContext,
source: DocumentResourceAuthoritySource,
@@ -354,6 +373,7 @@ impl DocumentResourceLoader {
replacement.csp_reports = previous.csp_reports.clone();
replacement.set_client_security_policy(previous.client_security_policy());
replacement.creation_url = previous.creation_url.clone();
replacement.navigation_timing = previous.navigation_timing.clone();
// document.open() replaces the load owner, not the Document. Transfer
// retirement authority along with its one-shot preload map.
previous
@@ -421,6 +441,7 @@ impl DocumentResourceLoader {
authority: Arc::clone(&self.authority),
creation_url: self.creation_url.clone(),
csp_reports: self.csp_reports.clone(),
navigation_timing: self.navigation_timing.clone(),
}
}
@@ -19,6 +19,7 @@ pub struct DocumentFetchContextSeed {
page_network_policy: PageNetworkPolicy,
browser_site_context: Option<Arc<BrowserCookieFacadeContext>>,
resource_task_runner: RendererResourceTaskRunner,
timing: super::NavigationTiming,
}
impl DocumentFetchContextSeed {
@@ -29,6 +30,7 @@ impl DocumentFetchContextSeed {
page_network_policy: PageNetworkPolicy,
browser_site_context: Option<Arc<BrowserCookieFacadeContext>>,
resource_task_runner: RendererResourceTaskRunner,
timing: super::NavigationTiming,
) -> Self {
Self {
requested_url,
@@ -37,6 +39,7 @@ impl DocumentFetchContextSeed {
page_network_policy,
browser_site_context,
resource_task_runner,
timing,
}
}
@@ -44,6 +47,10 @@ impl DocumentFetchContextSeed {
&self.requested_url
}
pub(crate) fn navigation_timing(&self) -> super::NavigationTiming {
self.timing.clone()
}
pub fn final_url(&self) -> &Url {
&self.final_url
}
@@ -39,6 +39,7 @@ struct NavigationResourceLoaderInner {
id: u64,
state: Mutex<NavigationResourceLoaderState>,
cancel: FetchCancelHandle,
timing: super::NavigationTiming,
}
/// The network authority for exactly one main-resource navigation attempt.
@@ -117,6 +118,7 @@ impl NavigationResourceLoader {
.fetch_add(1, Ordering::Relaxed)
.saturating_add(1),
state: Mutex::new(NavigationResourceLoaderState::Created),
timing: super::NavigationTiming::new(cancel.clone()),
cancel,
}),
}
@@ -126,6 +128,16 @@ impl NavigationResourceLoader {
self.inner.id
}
pub(crate) fn cancel_handle(&self) -> FetchCancelHandle {
self.inner.cancel.clone()
}
/// Records a materialized main-resource response, including SW responses
/// whose body does not come from an HTTP transfer.
pub fn observe_materialized_response(&self, head: moli_fetch::ResponseHead, body_size: usize) {
self.inner.timing.observe_response(head, Some(body_size));
}
pub fn state(&self) -> NavigationResourceLoaderState {
*self.inner.state.lock()
}
@@ -180,6 +192,7 @@ impl NavigationResourceLoader {
.await
{
Ok(response) => {
self.inner.timing.observe_response(response.head(), None);
self.finish_response_ready()?;
Ok(response)
}
@@ -204,6 +217,9 @@ impl NavigationResourceLoader {
.await
{
Ok(response) => {
self.inner
.timing
.observe_response(response.response().head(), None);
self.finish_response_ready()?;
Ok(response)
}
@@ -244,6 +260,7 @@ impl NavigationResourceLoader {
.await
{
Ok(mut response) => {
response.share_response_progress(&self.inner.cancel);
let head = response.head();
let mut body = Vec::new();
// A caller-owned redirect must not wait for an unbounded
@@ -270,12 +287,12 @@ impl NavigationResourceLoader {
return Err(error);
}
self.finish_response_ready()?;
if single_hop {
self.inner.cancel.adopt_response_progress(&response_cancel);
}
self.inner
.timing
.observe_response(head.clone(), Some(body.len()));
Ok((
RawResponse::from_head_and_body(head, body),
response_cancel.response_timing(),
self.inner.cancel.response_timing(),
))
}
Err(error) => {
@@ -345,16 +362,13 @@ impl NavigationResourceLoader {
.await
{
Ok(response) => {
response
.response()
.share_response_progress(&self.inner.cancel);
self.inner
.timing
.observe_response(response.response().head(), None);
self.finish_response_ready()?;
if !matches!(response.response().status, 301 | 302 | 303 | 307 | 308)
|| !response
.response()
.headers
.iter()
.any(|(name, _)| name.eq_ignore_ascii_case("location"))
{
self.inner.cancel.adopt_response_progress(&cancellation);
}
Ok(response)
}
Err(error) => {
@@ -388,6 +402,7 @@ impl NavigationResourceLoader {
self.request_client.page_network_policy(),
self.committed_document_browser_site_context.clone(),
self.task_runner.clone(),
self.inner.timing.clone(),
))
}
@@ -1,6 +1,9 @@
mod context;
mod interception;
mod loader;
mod timing;
pub(crate) use timing::NavigationTiming;
pub use context::DocumentFetchContextSeed;
pub use interception::NavigationInterception;
@@ -0,0 +1,72 @@
use std::{sync::Arc, time::Instant};
use moli_fetch::{FetchCancelHandle, FetchResponseTiming, ResponseHead};
use parking_lot::Mutex;
/// Clock and response observations owned by one navigation, transferred to its
/// committed Document. This does not retain the navigation's load authority.
#[derive(Clone, Debug)]
pub(crate) struct NavigationTiming(Arc<NavigationTimingInner>);
#[derive(Debug)]
struct NavigationTimingInner {
started: Instant,
time_origin: f64,
cancel: FetchCancelHandle,
response: Mutex<Option<NavigationTimingResponse>>,
}
#[derive(Clone, Debug)]
struct NavigationTimingResponse {
head: ResponseHead,
headers_received: Instant,
materialized_body_size: Option<usize>,
}
pub(crate) struct NavigationTimingSnapshot {
pub started: Instant,
pub time_origin: f64,
pub native: FetchResponseTiming,
pub head: ResponseHead,
pub headers_received: Instant,
pub materialized_body_size: Option<usize>,
}
impl NavigationTiming {
pub(super) fn new(cancel: FetchCancelHandle) -> Self {
Self(Arc::new(NavigationTimingInner {
started: Instant::now(),
time_origin: moli_time::unix_epoch_millis(),
cancel,
response: Mutex::new(None),
}))
}
pub(crate) fn time_origin(&self) -> f64 {
self.0.time_origin
}
pub(crate) fn started_at(&self) -> Instant {
self.0.started
}
pub(super) fn observe_response(&self, head: ResponseHead, body_size: Option<usize>) {
*self.0.response.lock() = Some(NavigationTimingResponse {
head,
headers_received: Instant::now(),
materialized_body_size: body_size,
});
}
pub(crate) fn snapshot(&self) -> Option<NavigationTimingSnapshot> {
let response = self.0.response.lock().clone()?;
Some(NavigationTimingSnapshot {
started: self.0.started,
time_origin: self.0.time_origin,
native: self.0.cancel.response_timing(),
head: response.head,
headers_received: response.headers_received,
materialized_body_size: response.materialized_body_size,
})
}
}
+42 -26
View File
@@ -68,6 +68,7 @@ impl ClientSecurityPolicy {
#[derive(Clone, Default)]
struct DocumentRequestContext {
navigation_timing_seed: Option<super::navigation::NavigationTiming>,
preloads: super::preloads::DocumentPreloads,
response_links: Option<super::context::DocumentResponseLinkObserver>,
client_security_policy: ClientSecurityPolicy,
@@ -138,6 +139,24 @@ impl ScriptTextLoadExecution {
}
impl ResourceRequestClient {
/// Transfer a committed navigation's clock through initial page bootstrap.
/// The bootstrap consumes this seed before binding the Document client.
pub fn with_navigation_timing_seed(
mut self,
seed: &super::navigation::DocumentFetchContextSeed,
) -> Self {
self.document_request_context_mut().navigation_timing_seed = Some(seed.navigation_timing());
self
}
pub(crate) fn take_navigation_timing_seed(
&mut self,
) -> Option<super::navigation::NavigationTiming> {
self.document_requests
.as_mut()
.and_then(|context| Arc::make_mut(context).navigation_timing_seed.take())
}
// Standalone clients must return their thread-affine lifetime owner; the
// owner dereferences to this request-side handle for existing call sites.
#[allow(clippy::new_ret_no_self)]
@@ -478,10 +497,21 @@ impl ResourceRequestClient {
/// Creates a Document-owned adapter inside this client's Page target.
pub(crate) fn fork_with_isolated_document_network_policy(&self) -> Self {
Self::from_browser_resource_runtime_with_page_network_policy(
let mut client = Self::from_browser_resource_runtime_with_page_network_policy(
self.resource_runtime.clone(),
self.page_network_policy.isolated_same_page_copy(),
)
);
// The new Document gets its own policy, while retaining the clock of
// the navigation being committed. Committed Document clients have
// already consumed this seed and cannot pass it to inherited children.
if let Some(timing) = self
.document_requests
.as_ref()
.and_then(|context| context.navigation_timing_seed.clone())
{
client.document_request_context_mut().navigation_timing_seed = Some(timing);
}
client
}
/// Creates a Worker-owned adapter while retaining the creator Document's
@@ -1343,12 +1373,9 @@ impl ResourceRequestClient {
&cached,
expires_at_unix_ms,
);
if let Some(sizes) = cached.body_sizes() {
cancel_handle.set_response_body_sizes(sizes);
}
return Ok(NetworkFetchResult::without_request_observation(
streaming_raw_response_from_cached_subresource(*cached)?,
));
let response = streaming_raw_response_from_cached_subresource(*cached)?;
response.share_response_progress(&cancel_handle);
return Ok(NetworkFetchResult::without_request_observation(response));
}
Some(RawSubresourceCacheLookup::Revalidate(cached)) => {
let validators = validation_headers_from_headers(&cached.headers);
@@ -1427,6 +1454,7 @@ impl ResourceRequestClient {
cached.body_sizes(),
)?
.with_network_request_extra_info(response.network_request_extra_info().cloned());
response.share_response_progress(&completed.cancellation_handle());
let completed = self.observe_streaming_response_links(&request, completed);
return Ok(NetworkFetchResult::with_observation_journal(
completed,
@@ -1434,6 +1462,10 @@ impl ResourceRequestClient {
));
}
let response = self.observe_streaming_response_links(&request, response);
// A navigation may consume a completed document prefetch. It does not
// produce speculative entries or acquire a cache tee's body task on a
// miss. In particular, standalone navigation keeps its streaming owner.
let cache_key = cache_key.filter(|key| key.allows_response_store(&request));
let response = if let Some(cache_key) = cache_key {
self.tee_raw_subresource_response_for_memory_cache(request, cache_key, response)
} else {
@@ -1985,24 +2017,8 @@ fn streaming_raw_response_from_head_and_body(
body: Vec<u8>,
body_sizes: Option<moli_fetch::FetchResponseBodySizes>,
) -> Result<StreamingRawResponse> {
let (body_tx, body_rx) = tokio::sync::mpsc::unbounded_channel();
let (completion_tx, completion_rx) = tokio::sync::oneshot::channel();
if !body.is_empty() {
body_tx
.send(body)
.map_err(|_| anyhow!("failed to enqueue cached raw subresource body"))?;
}
drop(body_tx);
let _ = completion_tx.send(Ok(()));
let cancel = FetchCancelHandle::new();
if let Some(sizes) = body_sizes {
cancel.set_response_body_sizes(sizes);
}
Ok(StreamingRawResponse::new_with_head(
head,
body_rx,
cancel,
completion_rx,
Ok(StreamingRawResponse::from_materialized_body(
head, body, body_sizes,
))
}
@@ -117,6 +117,12 @@ async fn raw_memory_cache_revalidates_request_controls_and_preserves_wire_observ
let local = fetch(&client, request(&url)?, observe).await?;
assert_eq!(local.0.cache_state, ResponseCacheState::Local);
assert!(local.1.is_empty());
let local_timing = local.2.response_timing();
assert!(local_timing.response_started_at().is_some());
assert!(local_timing.response_end_at().is_some());
assert!(local_timing.request_started_at().is_none());
assert!(!local_timing.body_bytes_received());
assert_eq!(local_timing.body_sizes(), first.body_sizes());
let mut validation = request(&url)?;
if let Some((name, value)) = control {
validation.request_headers = vec![(name.to_owned(), value.to_owned())].into();
@@ -142,6 +148,7 @@ async fn raw_memory_cache_revalidates_request_controls_and_preserves_wire_observ
assert!(cancel.response_timing().response_started_at().is_some());
assert!(cancel.response_timing().response_end_at().is_some());
assert!(!cancel.response_timing().body_bytes_received());
assert_eq!(validated.body_sizes(), first.body_sizes());
if observe {
assert_eq!(journal.exchanges().len(), 1);
assert_eq!(journal.final_response_observation().unwrap().status(), 304);
@@ -144,8 +144,7 @@ impl RendererBrowserContextRuntime {
.fetch_service_worker_main_resource_for_reserved_client(
client_id,
request,
navigation_loader.request_client(),
navigation_loader.task_runner(),
navigation_loader,
completion_tx,
ServiceWorkerRequestDestination::Document,
)
@@ -160,15 +159,13 @@ impl RendererBrowserContextRuntime {
&self,
client_id: ServiceWorkerClientId,
request: &Request,
request_client: &ResourceRequestClient,
resource_task_runner: RendererResourceTaskRunner,
navigation_loader: &NavigationResourceLoader,
completion_tx: crate::page_task_queue::RendererResourceCompletionSender,
) -> Result<Option<crate::protocol_types::NavigationResponse>> {
self.fetch_service_worker_main_resource_for_reserved_client(
client_id,
request,
request_client,
resource_task_runner,
navigation_loader,
completion_tx,
ServiceWorkerRequestDestination::Iframe,
)
@@ -179,8 +176,7 @@ impl RendererBrowserContextRuntime {
&self,
client_id: ServiceWorkerClientId,
request: &Request,
request_client: &ResourceRequestClient,
resource_task_runner: RendererResourceTaskRunner,
navigation_loader: &NavigationResourceLoader,
completion_tx: crate::page_task_queue::RendererResourceCompletionSender,
destination: ServiceWorkerRequestDestination,
) -> Result<Option<crate::protocol_types::NavigationResponse>> {
@@ -228,9 +224,9 @@ impl RendererBrowserContextRuntime {
policy_context: Default::default(),
},
completion_tx,
request_client: request_client.clone(),
resource_task_runner,
cancel_handle: FetchCancelHandle::new(),
request_client: navigation_loader.request_client().clone(),
resource_task_runner: navigation_loader.task_runner(),
cancel_handle: navigation_loader.cancel_handle(),
direct_completion_tx: Some(direct_completion_tx),
};
@@ -249,7 +245,13 @@ impl RendererBrowserContextRuntime {
"navigation requests cannot contain an author stream"
)),
Ok(ServiceWorkerDirectFetchResult::Fallback) => Ok(None),
Ok(ServiceWorkerDirectFetchResult::Response(response)) => Ok(Some(*response.response)),
Ok(ServiceWorkerDirectFetchResult::Response(response)) => {
navigation_loader.observe_materialized_response(
response.response.head(),
response.response.body_bytes().len(),
);
Ok(Some(*response.response))
}
Ok(ServiceWorkerDirectFetchResult::Failure(message)) => Err(anyhow!(message)),
Err(_) => Err(anyhow!(
"service worker main resource fetch completion channel closed"
@@ -421,6 +421,7 @@ impl ServiceWorkerRuntimeService {
};
fetch_job.bind_to_owner(version.run_owner());
if version.lifecycle_state == ServiceWorkerVersionLifecycleState::Activating {
fetch_job.cancel_handle.mark_service_worker_start();
let event_id =
ServiceWorkerEventId(self.inner.next_event_id.fetch_add(1, Ordering::Relaxed));
let event = ServiceWorkerFetchEvent {
@@ -441,6 +442,7 @@ impl ServiceWorkerRuntimeService {
} else {
let event_id =
ServiceWorkerEventId(self.inner.next_event_id.fetch_add(1, Ordering::Relaxed));
fetch_job.cancel_handle.mark_service_worker_start();
Self::begin_version_event_locked(version);
let action = match &version.running_state {
ServiceWorkerVersionRunningState::Running { host } => {
@@ -1463,6 +1465,14 @@ impl ServiceWorkerRuntimeService {
) {
let navigation_preload = self.navigation_preload_dispatch_for_event(&event);
event.navigation_preload_sent = navigation_preload.is_some();
{
let state = self.inner.state.lock();
if let Some(job) = state.pending_fetch_jobs.get(&event.event_id)
&& job.is_bound_to_owner(&event.owner)
{
job.cancel_handle.mark_service_worker_dispatch();
}
}
if host.dispatch_fetch_event(event.clone()) {
if let Some(navigation_preload) = navigation_preload {
self.start_navigation_preload_dispatch(host, navigation_preload);
@@ -1341,6 +1341,7 @@ impl DocumentRuntime {
)
})
.unwrap_or_else(|| ConnectedLinkReadinessFetchOptions {
network_partition_key: None,
resource_type,
request_resource_type: crate::network::request_resource_type_for_subresource(
resource_type,
@@ -1353,6 +1354,17 @@ impl DocumentRuntime {
link_preload: false,
link_fetch_options: StylesheetFetchOptions::default(),
});
if fetch_options.request_resource_type == Some(RequestResourceType::LinkPrefetch)
&& !host_ptr.is_null()
{
let host = unsafe { &*host_ptr };
if let Some(crate::native_bridge::OwnerDispatchScope::Child(frame)) =
host.owner_dispatch_scope_for_node(handle)
{
fetch_options.network_partition_key =
host.child_browsing_context_network_partition_key(frame);
}
}
if fetch_options.script_fetch_metadata.is_some() {
fetch_options.document_referrer_policy = document_referrer_policy.or_else(|| {
if host_ptr.is_null() {
@@ -2616,6 +2628,7 @@ fn preload_like_link_readiness_fetch_options(
RequestCredentialsMode::Include
};
ConnectedLinkReadinessFetchOptions {
network_partition_key: None,
resource_type,
request_resource_type,
script_fetch_metadata,
@@ -2737,6 +2750,7 @@ fn connected_link_readiness_request(
.with_initiator_url(document_url)
.with_request_origin(request_origin.clone());
let mut request = request
.with_network_partition_key(options.network_partition_key.clone())
.with_request_mode(options.request_mode)
.with_credentials_mode(options.credentials_mode);
if options.link_preload {
@@ -5620,6 +5634,7 @@ mod tests {
document_url,
script_url,
ConnectedLinkReadinessFetchOptions {
network_partition_key: None,
document_referrer_policy: None,
resource_type: SubresourceResourceType::Script,
request_resource_type: Some(RequestResourceType::Script),
@@ -376,6 +376,7 @@ impl Eq for InlineStyleImportSource {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(in crate::document_runtime) struct ConnectedLinkReadinessFetchOptions {
pub(in crate::document_runtime) network_partition_key: Option<String>,
pub(in crate::document_runtime) resource_type: SubresourceResourceType,
pub(in crate::document_runtime) request_resource_type: Option<moli_fetch::RequestResourceType>,
pub(in crate::document_runtime) script_fetch_metadata:
+46 -12
View File
@@ -2,6 +2,18 @@
use std::rc::Rc;
type ObjectCallback = for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>);
type ObjectPredicate = for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>) -> bool;
type InterfaceFactory =
for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, &str) -> Option<v8::Local<'s, v8::Object>>;
type ScriptCall = for<'s, 'i> fn(
&mut v8::PinScope<'s, 'i>,
v8::Local<'s, v8::Function>,
v8::Local<'s, v8::Value>,
&[v8::Local<'s, v8::Value>],
&str,
) -> Option<v8::Local<'s, v8::Value>>;
pub type WebIdlCallbackResult<'s> =
Result<Option<v8::Local<'s, v8::Value>>, v8::Local<'s, v8::Value>>;
pub type WebIdlCallbackInvocation<'s> = for<'i> fn(
@@ -14,13 +26,14 @@ pub type WebIdlCallbackInvocation<'s> = for<'i> fn(
/// Bridges value bindings to the embedder without retaining its host or V8 handles.
/// Callbacks execute in the current (callee) realm, including for borrowed methods.
pub struct RealmCallbacks {
pub new_interface_instance: Option<for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, &str) -> Option<v8::Local<'s, v8::Object>>>,
pub call_function: Option<for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Function>, v8::Local<'s, v8::Value>, &[v8::Local<'s, v8::Value>], &str) -> Option<v8::Local<'s, v8::Value>>>,
pub is_window_named_properties_object: Option<for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>) -> bool>,
pub refresh_performance_entry: Option<ObjectCallback>,
pub new_interface_instance: Option<InterfaceFactory>,
pub call_function: Option<ScriptCall>,
pub is_window_named_properties_object: Option<ObjectPredicate>,
/// Synchronizes a live SVG point from its owner before reading or writing it.
pub point_accessed: for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>),
pub point_accessed: ObjectCallback,
/// Writes a live SVG point back to its owner; ordinary points need no action.
pub point_mutated: for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>),
pub point_mutated: ObjectCallback,
/// Reads the native source of a live MediaQueryListEvent without invoking script.
pub media_query_matches:
for<'s, 'i> fn(&mut v8::PinScope<'s, 'i>, v8::Local<'s, v8::Object>) -> Option<bool>,
@@ -94,10 +107,7 @@ pub(crate) fn read_media_query_matches<'s>(
(callbacks.media_query_matches)(scope, list)
}
pub(crate) fn sync_point<'s>(
scope: &mut v8::PinScope<'s, '_>,
point: v8::Local<'s, v8::Object>,
) {
pub(crate) fn sync_point<'s>(scope: &mut v8::PinScope<'s, '_>, point: v8::Local<'s, v8::Object>) {
if let Some(callbacks) = scope.get_current_context().get_slot::<RealmCallbacks>() {
(callbacks.point_accessed)(scope, point);
}
@@ -110,7 +120,11 @@ pub(crate) fn call_script_visible_function<'s>(
args: &[v8::Local<'s, v8::Value>],
action: &str,
) -> Option<v8::Local<'s, v8::Value>> {
if let Some(callback) = scope.get_current_context().get_slot::<RealmCallbacks>().and_then(|callbacks| callbacks.call_function) {
if let Some(callback) = scope
.get_current_context()
.get_slot::<RealmCallbacks>()
.and_then(|callbacks| callbacks.call_function)
{
callback(scope, function, receiver, args, action)
} else {
let callback = match moli_webidl::convert::<moli_webidl::WebIdlCallbackFunction>(
@@ -131,6 +145,26 @@ pub(crate) fn call_script_visible_function<'s>(
}
}
pub(crate) fn is_window_named_properties_object<'s>(scope: &mut v8::PinScope<'s, '_>, object: v8::Local<'s, v8::Object>) -> bool {
scope.get_current_context().get_slot::<RealmCallbacks>().and_then(|callbacks| callbacks.is_window_named_properties_object).is_some_and(|callback| callback(scope, object))
pub(crate) fn is_window_named_properties_object<'s>(
scope: &mut v8::PinScope<'s, '_>,
object: v8::Local<'s, v8::Object>,
) -> bool {
scope
.get_current_context()
.get_slot::<RealmCallbacks>()
.and_then(|callbacks| callbacks.is_window_named_properties_object)
.is_some_and(|callback| callback(scope, object))
}
pub(crate) fn refresh_performance_entry<'s>(
scope: &mut v8::PinScope<'s, '_>,
entry: v8::Local<'s, v8::Object>,
) {
if let Some(callback) = scope
.get_current_context()
.get_slot::<RealmCallbacks>()
.and_then(|callbacks| callbacks.refresh_performance_entry)
{
callback(scope, entry);
}
}
+2
View File
@@ -667,6 +667,7 @@ pub fn resource_timing_json_snapshot<'s>(
scope: &mut v8::PinScope<'s, '_>,
entry: v8::Local<'s, v8::Object>,
) -> Option<v8::Local<'s, v8::Object>> {
crate::embedding::refresh_performance_entry(scope, entry);
let snapshot = PerformanceResourceTimingJsonSnapshotDeclaration::from_entry(scope, entry)?;
Some(
snapshot
@@ -714,6 +715,7 @@ fn performance_resource_timing_attribute_getter_callback<'s>(
args: v8::FunctionCallbackArguments<'s>,
mut rv: v8::ReturnValue<'_, v8::Value>,
) {
crate::embedding::refresh_performance_entry(scope, args.this());
let Some(slot) = callback_data_item(
scope,
&args,
+1
View File
@@ -114,6 +114,7 @@ fn install_values(
install_realm_callbacks(
scope,
RealmCallbacks {
refresh_performance_entry: None,
new_interface_instance: None,
call_function: None,
is_window_named_properties_object: None,