Skip to content

armgit / moli

Public Imported from GitHub
0

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

fix(navigation): stabilize sequential CDP lifecycle

ldm0f2a209575121
diff --git a/moli-benchmark/moli_benchmark/sequential_navigate.py b/moli-benchmark/moli_benchmark/sequential_navigate.py
new file mode 100644
index 000000000..7cbf1233d
--- /dev/null
+++ b/moli-benchmark/moli_benchmark/sequential_navigate.py
@@ -0,0 +1,1179 @@
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import random
+import re
+import subprocess
+import time
+import urllib.parse
+from dataclasses import asdict, dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Iterable
+
+from .artifacts import write_json
+from .config import REPO_ROOT, chrome_binary, moli_binary
+from .raw_cdp import (
+ RawCdpCommandError,
+ RawCdpError,
+ RawCdpTimeoutError,
+ RecordedCdpMessage,
+ RoutedRawCdpClient,
+ connect_routed_raw_cdp,
+)
+from .target_serve import start_target_serve, stop_target_serve
+
+
+DEFAULT_SEED = 20260809
+DEFAULT_COUNT = 50
+DEFAULT_PINNED_DOMAINS = ("csdn.net", "zol.com.cn")
+DEFAULT_SEED_FILE = REPO_ROOT / "docs" / "chinese-community-top100-websites.md"
+TRACE_METHODS = {
+ "Page.frameStartedNavigating",
+ "Page.frameStartedLoading",
+ "Page.frameNavigated",
+ "Page.domContentEventFired",
+ "Page.loadEventFired",
+ "Page.lifecycleEvent",
+ "Page.frameStoppedLoading",
+}
+NETWORK_EVENT_METHODS = {
+ "Network.requestWillBeSent",
+ "Network.responseReceived",
+ "Network.loadingFinished",
+ "Network.loadingFailed",
+}
+
+
+@dataclass(frozen=True)
+class NavigationIdentity:
+ frame_id: str
+ loader_id: str
+
+
+@dataclass(frozen=True)
+class NavigationProgress:
+ kind: str
+ record: RecordedCdpMessage
+ identity: NavigationIdentity
+
+
+@dataclass(frozen=True)
+class NavigationTimeouts:
+ response: float
+ dcl: float
+ load: float
+ postcheck: float
+
+
+def parse_top_100_domains(markdown: str) -> list[str]:
+ in_top_100 = False
+ domains: list[str] = []
+ for line in markdown.splitlines():
+ if line.strip() == "## Top 100":
+ in_top_100 = True
+ continue
+ if in_top_100 and line.startswith("## "):
+ break
+ if not in_top_100:
+ continue
+ match = re.match(r"^\s*\d+\.\s+`([^`]+)`", line)
+ if match is not None:
+ domains.append(match.group(1).strip())
+ if not domains:
+ raise ValueError("seed document does not contain any domains under `## Top 100`")
+ return domains
+
+
+def normalize_public_url(value: str) -> str:
+ value = value.strip()
+ if not value:
+ raise ValueError("navigation URL cannot be empty")
+ if "://" not in value and not value.startswith("data:"):
+ value = f"https://{value}"
+ parsed = urllib.parse.urlsplit(value)
+ if parsed.scheme not in {"http", "https", "data"}:
+ raise ValueError(f"unsupported navigation URL scheme: {parsed.scheme}")
+ return value
+
+
+def select_seed_urls(
+ domains: Iterable[str],
+ *,
+ seed: int,
+ count: int,
+ pinned_domains: Iterable[str] = DEFAULT_PINNED_DOMAINS,
+) -> list[str]:
+ if count <= 0:
+ raise ValueError("navigation count must be positive")
+ normalized_domains = list(dict.fromkeys(domain.strip() for domain in domains if domain.strip()))
+ pinned = list(dict.fromkeys(domain.strip() for domain in pinned_domains if domain.strip()))
+ selected_pinned = pinned[:count]
+ remaining = [domain for domain in normalized_domains if domain not in set(selected_pinned)]
+ random.Random(seed).shuffle(remaining)
+ selected = (selected_pinned + remaining)[:count]
+ if len(selected) < count:
+ raise ValueError(f"requested {count} URLs but seed set contains only {len(selected)}")
+ return [normalize_public_url(domain) for domain in selected]
+
+
+def make_recovery_url(marker: str) -> str:
+ html = (
+ "<!doctype html><meta charset=utf-8>"
+ f"<title>{marker}</title><body data-recovery-marker=\"{marker}\">{marker}</body>"
+ )
+ return "data:text/html;charset=utf-8," + urllib.parse.quote(html, safe="")
+
+
+def _is_exact_lifecycle_event(
+ payload: dict[str, Any],
+ *,
+ session_id: str,
+ identity: NavigationIdentity,
+ name: str,
+) -> bool:
+ if payload.get("sessionId") != session_id or payload.get("method") != "Page.lifecycleEvent":
+ return False
+ params = payload.get("params")
+ return (
+ isinstance(params, dict)
+ and params.get("name") == name
+ and params.get("frameId") == identity.frame_id
+ and params.get("loaderId") == identity.loader_id
+ )
+
+
+def find_exact_lifecycle_record(
+ records: Iterable[RecordedCdpMessage],
+ *,
+ session_id: str,
+ identity: NavigationIdentity,
+ name: str,
+) -> RecordedCdpMessage | None:
+ return next(
+ (
+ record
+ for record in records
+ if _is_exact_lifecycle_event(
+ record.payload,
+ session_id=session_id,
+ identity=identity,
+ name=name,
+ )
+ ),
+ None,
+ )
+
+
+def _successor_navigation_identity(
+ payload: dict[str, Any],
+ *,
+ session_id: str,
+ identity: NavigationIdentity,
+) -> NavigationIdentity | None:
+ if payload.get("sessionId") != session_id or payload.get("method") != "Page.frameStartedNavigating":
+ return None
+ params = payload.get("params")
+ if not isinstance(params, dict) or params.get("frameId") != identity.frame_id:
+ return None
+ loader_id = params.get("loaderId")
+ if not isinstance(loader_id, str) or not loader_id or loader_id == identity.loader_id:
+ return None
+ return NavigationIdentity(frame_id=identity.frame_id, loader_id=loader_id)
+
+
+def find_navigation_progress_record(
+ records: Iterable[RecordedCdpMessage],
+ *,
+ session_id: str,
+ identity: NavigationIdentity,
+ lifecycle_name: str,
+) -> NavigationProgress | None:
+ for record in records:
+ if _is_exact_lifecycle_event(
+ record.payload,
+ session_id=session_id,
+ identity=identity,
+ name=lifecycle_name,
+ ):
+ return NavigationProgress(
+ kind="lifecycle",
+ record=record,
+ identity=identity,
+ )
+ successor = _successor_navigation_identity(
+ record.payload,
+ session_id=session_id,
+ identity=identity,
+ )
+ if successor is not None:
+ return NavigationProgress(
+ kind="successor",
+ record=record,
+ identity=successor,
+ )
+ return None
+
+
+def navigation_order_violations(
+ response: RecordedCdpMessage,
+ dcl: RecordedCdpMessage,
+ load: RecordedCdpMessage | None,
+) -> list[str]:
+ violations = []
+ if response.sequence >= dcl.sequence:
+ violations.append("DOMContentLoaded was observable before Page.navigate response")
+ if load is not None:
+ if response.sequence >= load.sequence:
+ violations.append("load was observable before Page.navigate response")
+ if dcl.sequence >= load.sequence:
+ violations.append("load was observable before DOMContentLoaded")
+ return violations
+
+
+def _record_elapsed_ms(record: RecordedCdpMessage, started: float) -> float:
+ return round((record.received_monotonic - started) * 1000.0, 3)
+
+
+def _compact_trace_record(record: RecordedCdpMessage, started: float) -> dict[str, Any] | None:
+ payload = record.payload
+ method = payload.get("method")
+ if method not in TRACE_METHODS and "id" not in payload:
+ return None
+ compact: dict[str, Any] = {
+ "sequence": record.sequence,
+ "elapsed_ms": _record_elapsed_ms(record, started),
+ }
+ if isinstance(method, str):
+ compact["method"] = method
+ params = payload.get("params")
+ if isinstance(params, dict):
+ if method == "Page.lifecycleEvent":
+ compact.update(
+ {
+ "name": params.get("name"),
+ "frame_id": params.get("frameId"),
+ "loader_id": params.get("loaderId"),
+ }
+ )
+ elif method == "Page.frameNavigated":
+ frame = params.get("frame")
+ if isinstance(frame, dict):
+ compact.update(
+ {
+ "frame_id": frame.get("id"),
+ "loader_id": frame.get("loaderId"),
+ "url": frame.get("url"),
+ }
+ )
+ else:
+ for source, destination in (
+ ("frameId", "frame_id"),
+ ("loaderId", "loader_id"),
+ ("url", "url"),
+ ):
+ if source in params:
+ compact[destination] = params[source]
+ else:
+ compact["response_id"] = payload.get("id")
+ if "error" in payload:
+ compact["error"] = payload["error"]
+ return compact
+
+
+def _compact_trace(
+ client: RoutedRawCdpClient,
+ *,
+ after_sequence: int,
+ started: float,
+) -> list[dict[str, Any]]:
+ return [
+ compact
+ for record in client.messages_since(after_sequence)
+ if (compact := _compact_trace_record(record, started)) is not None
+ ]
+
+
+def summarize_network_activity(
+ records: Iterable[RecordedCdpMessage],
+ *,
+ session_id: str,
+ started: float,
+) -> dict[str, Any]:
+ requests: dict[str, dict[str, Any]] = {}
+ event_counts = {method: 0 for method in sorted(NETWORK_EVENT_METHODS)}
+ for record in records:
+ payload = record.payload
+ method = payload.get("method")
+ if payload.get("sessionId") != session_id or method not in NETWORK_EVENT_METHODS:
+ continue
+ event_counts[str(method)] += 1
+ params = payload.get("params")
+ if not isinstance(params, dict):
+ continue
+ request_id = params.get("requestId")
+ if not isinstance(request_id, str) or not request_id:
+ continue
+ entry = requests.setdefault(
+ request_id,
+ {
+ "request_id": request_id,
+ "url": None,
+ "type": None,
+ "frame_id": None,
+ "loader_id": None,
+ "initiator_type": None,
+ "started_sequence": None,
+ "started_ms": None,
+ "redirect_count": 0,
+ "response_status": None,
+ "response_mime_type": None,
+ "terminal": None,
+ "terminal_sequence": None,
+ "terminal_ms": None,
+ "error_text": None,
+ "canceled": None,
+ },
+ )
+ if method == "Network.requestWillBeSent":
+ if entry["started_sequence"] is not None:
+ entry["redirect_count"] += 1
+ request = params.get("request")
+ initiator = params.get("initiator")
+ entry.update(
+ {
+ "url": request.get("url") if isinstance(request, dict) else None,
+ "type": params.get("type"),
+ "frame_id": params.get("frameId"),
+ "loader_id": params.get("loaderId"),
+ "initiator_type": (
+ initiator.get("type") if isinstance(initiator, dict) else None
+ ),
+ "started_sequence": record.sequence,
+ "started_ms": _record_elapsed_ms(record, started),
+ "terminal": None,
+ "terminal_sequence": None,
+ "terminal_ms": None,
+ "error_text": None,
+ "canceled": None,
+ }
+ )
+ elif method == "Network.responseReceived":
+ response = params.get("response")
+ entry["type"] = params.get("type", entry["type"])
+ entry["frame_id"] = params.get("frameId", entry["frame_id"])
+ entry["loader_id"] = params.get("loaderId", entry["loader_id"])
+ if isinstance(response, dict):
+ entry["url"] = response.get("url", entry["url"])
+ entry["response_status"] = response.get("status")
+ entry["response_mime_type"] = response.get("mimeType")
+ elif method == "Network.loadingFinished":
+ entry.update(
+ {
+ "terminal": "finished",
+ "terminal_sequence": record.sequence,
+ "terminal_ms": _record_elapsed_ms(record, started),
+ }
+ )
+ elif method == "Network.loadingFailed":
+ entry.update(
+ {
+ "type": params.get("type", entry["type"]),
+ "terminal": "failed",
+ "terminal_sequence": record.sequence,
+ "terminal_ms": _record_elapsed_ms(record, started),
+ "error_text": params.get("errorText"),
+ "canceled": params.get("canceled"),
+ }
+ )
+
+ ordered = sorted(
+ requests.values(),
+ key=lambda entry: (
+ entry["started_sequence"] is None,
+ entry["started_sequence"] or entry["terminal_sequence"] or 0,
+ ),
+ )
+ inflight = [entry for entry in ordered if entry["terminal"] is None]
+ failed = [entry for entry in ordered if entry["terminal"] == "failed"]
+ return {
+ "event_counts": event_counts,
+ "request_count": len(ordered),
+ "finished_count": sum(entry["terminal"] == "finished" for entry in ordered),
+ "failed_count": len(failed),
+ "inflight_count": len(inflight),
+ "requests": ordered,
+ }
+
+
+def network_event_order_violations(
+ records: Iterable[RecordedCdpMessage],
+ *,
+ session_id: str,
+) -> list[dict[str, Any]]:
+ timelines: dict[str, dict[str, Any]] = {}
+ for record in records:
+ payload = record.payload
+ method = payload.get("method")
+ if payload.get("sessionId") != session_id or method not in NETWORK_EVENT_METHODS:
+ continue
+ params = payload.get("params")
+ if not isinstance(params, dict):
+ continue
+ request_id = params.get("requestId")
+ if not isinstance(request_id, str) or not request_id:
+ continue
+ timeline = timelines.setdefault(
+ request_id,
+ {
+ "request_id": request_id,
+ "url": None,
+ "type": None,
+ "start_sequence": None,
+ "response_sequence": None,
+ "terminals": [],
+ },
+ )
+ if method == "Network.requestWillBeSent":
+ request = params.get("request")
+ if isinstance(request, dict):
+ timeline["url"] = request.get("url", timeline["url"])
+ timeline["type"] = params.get("type", timeline["type"])
+ if timeline["start_sequence"] is None:
+ timeline["start_sequence"] = record.sequence
+ elif method == "Network.responseReceived":
+ timeline["type"] = params.get("type", timeline["type"])
+ if timeline["response_sequence"] is None:
+ timeline["response_sequence"] = record.sequence
+ else:
+ timeline["terminals"].append(
+ {"method": method, "sequence": record.sequence}
+ )
+
+ violations: list[dict[str, Any]] = []
+ for timeline in timelines.values():
+ terminals = timeline.pop("terminals")
+ first_start = timeline["start_sequence"]
+ first_response = timeline["response_sequence"]
+ first_terminal = min(
+ terminals,
+ key=lambda terminal: terminal["sequence"],
+ default=None,
+ )
+
+ def report(kind: str, **details: Any) -> None:
+ violations.append({**timeline, "kind": kind, **details})
+
+ if first_response is not None and (
+ first_start is None or first_response < first_start
+ ):
+ report("response_before_start", sequence=first_response)
+ if first_terminal is not None and (
+ first_start is None or first_terminal["sequence"] < first_start
+ ):
+ report(
+ "terminal_before_start",
+ sequence=first_terminal["sequence"],
+ terminal_method=first_terminal["method"],
+ )
+ first_successful_terminal = min(
+ (
+ terminal
+ for terminal in terminals
+ if terminal["method"] == "Network.loadingFinished"
+ ),
+ key=lambda terminal: terminal["sequence"],
+ default=None,
+ )
+ if first_successful_terminal is not None and (
+ first_response is None
+ or first_successful_terminal["sequence"] < first_response
+ ):
+ report(
+ "successful_terminal_before_response",
+ sequence=first_successful_terminal["sequence"],
+ terminal_method=first_successful_terminal["method"],
+ )
+ if len(terminals) > 1:
+ report(
+ "duplicate_terminal",
+ terminal_sequences=[terminal["sequence"] for terminal in terminals],
+ terminal_methods=[terminal["method"] for terminal in terminals],
+ )
+ return violations
+
+
+def _error_detail(error: BaseException) -> dict[str, Any]:
+ detail: dict[str, Any] = {
+ "type": type(error).__name__,
+ "message": str(error),
+ }
+ if isinstance(error, RawCdpCommandError):
+ detail["cdp_error"] = error.error
+ if isinstance(error, RawCdpTimeoutError):
+ detail["method"] = error.method
+ detail["message_id"] = error.message_id
+ return detail
+
+
+def _command_response_record(
+ records: Iterable[RecordedCdpMessage], message_id: int
+) -> RecordedCdpMessage | None:
+ return next((record for record in records if record.payload.get("id") == message_id), None)
+
+
+async def _wait_for_navigation_progress(
+ client: RoutedRawCdpClient,
+ *,
+ after_sequence: int,
+ session_id: str,
+ identity: NavigationIdentity,
+ lifecycle_name: str,
+ timeout: float,
+) -> NavigationProgress:
+ existing = find_navigation_progress_record(
+ client.messages_since(after_sequence),
+ session_id=session_id,
+ identity=identity,
+ lifecycle_name=lifecycle_name,
+ )
+ if existing is not None:
+ return existing
+
+ lifecycle_task = asyncio.create_task(
+ client.wait_for_event(
+ "Page.lifecycleEvent",
+ after_sequence=after_sequence,
+ session_id=session_id,
+ predicate=lambda payload: _is_exact_lifecycle_event(
+ payload,
+ session_id=session_id,
+ identity=identity,
+ name=lifecycle_name,
+ ),
+ timeout=timeout + 1.0,
+ )
+ )
+ successor_task = asyncio.create_task(
+ client.wait_for_event(
+ "Page.frameStartedNavigating",
+ after_sequence=after_sequence,
+ session_id=session_id,
+ predicate=lambda payload: _successor_navigation_identity(
+ payload,
+ session_id=session_id,
+ identity=identity,
+ )
+ is not None,
+ timeout=timeout + 1.0,
+ )
+ )
+ tasks = {lifecycle_task, successor_task}
+ try:
+ done, _ = await asyncio.wait(
+ tasks,
+ timeout=timeout,
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ if not done:
+ raise RawCdpTimeoutError(
+ f"timed out waiting for {lifecycle_name} or a successor navigation",
+ method="Page.lifecycleEvent",
+ messages=[
+ record.json_value() for record in client.messages_since(after_sequence)
+ ],
+ )
+
+ recorded = find_navigation_progress_record(
+ client.messages_since(after_sequence),
+ session_id=session_id,
+ identity=identity,
+ lifecycle_name=lifecycle_name,
+ )
+ if recorded is not None:
+ return recorded
+
+ progress: list[NavigationProgress] = []
+ for task in done:
+ record = task.result()
+ if task is lifecycle_task:
+ progress.append(
+ NavigationProgress(
+ kind="lifecycle",
+ record=record,
+ identity=identity,
+ )
+ )
+ continue
+ successor = _successor_navigation_identity(
+ record.payload,
+ session_id=session_id,
+ identity=identity,
+ )
+ if successor is not None:
+ progress.append(
+ NavigationProgress(
+ kind="successor",
+ record=record,
+ identity=successor,
+ )
+ )
+ if not progress:
+ raise RawCdpError("navigation progress waiter completed without a matching record")
+ return min(progress, key=lambda item: item.record.sequence)
+ finally:
+ for task in tasks:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
+def _runtime_value(response: dict[str, Any]) -> Any:
+ result = response.get("result")
+ if not isinstance(result, dict):
+ return None
+ remote = result.get("result")
+ if not isinstance(remote, dict):
+ return None
+ return remote.get("value")
+
+
+async def navigate_once(
+ client: RoutedRawCdpClient,
+ *,
+ session_id: str,
+ url: str,
+ timeouts: NavigationTimeouts,
+ require_load: bool = True,
+ network_diagnostics: bool = False,
+) -> dict[str, Any]:
+ started = time.perf_counter()
+ start_sequence = client.current_sequence
+ row: dict[str, Any] = {
+ "url": url,
+ "ok": False,
+ "failure_stage": None,
+ "error": None,
+ "navigate_result": None,
+ "identity": None,
+ "effective_identity": None,
+ "supersessions": [],
+ "response_ms": None,
+ "dcl_ms": None,
+ "load_ms": None,
+ "order_violations": [],
+ "document": None,
+ "dom_root": None,
+ "content_kind": None,
+ "network_diagnostics": None,
+ }
+
+ def capture_network_diagnostics() -> None:
+ if network_diagnostics:
+ row["network_diagnostics"] = summarize_network_activity(
+ client.messages_since(start_sequence),
+ session_id=session_id,
+ started=started,
+ )
+
+ def fail(stage: str, error: BaseException | str) -> dict[str, Any]:
+ row["failure_stage"] = stage
+ row["error"] = _error_detail(error) if isinstance(error, BaseException) else {"message": error}
+ row["trace"] = _compact_trace(
+ client,
+ after_sequence=start_sequence,
+ started=started,
+ )
+ row["elapsed_ms"] = round((time.perf_counter() - started) * 1000.0, 3)
+ capture_network_diagnostics()
+ return row
+
+ try:
+ navigation = await client.command(
+ "Page.navigate",
+ {"url": url},
+ session_id=session_id,
+ timeout=timeouts.response,
+ )
+ except (RawCdpError, TimeoutError) as error:
+ return fail("navigate_response", error)
+
+ response_record = _command_response_record(navigation.messages, navigation.message_id)
+ if response_record is None:
+ return fail("navigate_response", "Page.navigate response was not retained in the CDP trace")
+ row["response_ms"] = _record_elapsed_ms(response_record, started)
+ navigate_result = navigation.response.get("result")
+ if not isinstance(navigate_result, dict):
+ return fail("navigate_response", f"Page.navigate returned no result object: {navigation.response}")
+ row["navigate_result"] = navigate_result
+ frame_id = navigate_result.get("frameId")
+ loader_id = navigate_result.get("loaderId")
+ if not isinstance(frame_id, str) or not frame_id or not isinstance(loader_id, str) or not loader_id:
+ return fail(
+ "navigate_identity",
+ f"cross-document Page.navigate returned no exact frameId/loaderId: {navigate_result}",
+ )
+ identity = NavigationIdentity(frame_id=frame_id, loader_id=loader_id)
+ row["identity"] = asdict(identity)
+ row["effective_identity"] = asdict(identity)
+
+ effective_identity = identity
+ progress_after_sequence = start_sequence
+ lifecycle_name = "DOMContentLoaded"
+ dcl_record: RecordedCdpMessage | None = None
+ load_record: RecordedCdpMessage | None = None
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + timeouts.dcl
+ load_budget_started = False
+ while True:
+ remaining = deadline - loop.time()
+ failure_stage = "load" if load_budget_started else "dom_content_loaded"
+ if remaining <= 0:
+ return fail(
+ failure_stage,
+ f"timed out waiting for {lifecycle_name} or a successor navigation",
+ )
+ try:
+ progress = await _wait_for_navigation_progress(
+ client,
+ after_sequence=progress_after_sequence,
+ session_id=session_id,
+ identity=effective_identity,
+ lifecycle_name=lifecycle_name,
+ timeout=remaining,
+ )
+ except (RawCdpError, TimeoutError) as error:
+ return fail(failure_stage, error)
+
+ progress_after_sequence = progress.record.sequence
+ if progress.kind == "successor":
+ params = progress.record.payload.get("params")
+ row["supersessions"].append(
+ {
+ "from_identity": asdict(effective_identity),
+ "to_identity": asdict(progress.identity),
+ "url": params.get("url") if isinstance(params, dict) else None,
+ "during": "load" if load_budget_started else "dom_content_loaded",
+ "sequence": progress.record.sequence,
+ "elapsed_ms": _record_elapsed_ms(progress.record, started),
+ }
+ )
+ effective_identity = progress.identity
+ row["effective_identity"] = asdict(effective_identity)
+ row["dcl_ms"] = None
+ dcl_record = None
+ lifecycle_name = "DOMContentLoaded"
+ continue
+
+ if lifecycle_name == "DOMContentLoaded":
+ dcl_record = progress.record
+ row["dcl_ms"] = _record_elapsed_ms(dcl_record, started)
+ if not require_load:
+ break
+ lifecycle_name = "load"
+ if not load_budget_started:
+ load_budget_started = True
+ deadline = loop.time() + timeouts.load
+ continue
+
+ load_record = progress.record
+ row["load_ms"] = _record_elapsed_ms(load_record, started)
+ break
+
+ if dcl_record is None:
+ return fail("dom_content_loaded", "navigation completed without DOMContentLoaded")
+
+ order_violations = navigation_order_violations(response_record, dcl_record, load_record)
+ row["order_violations"] = order_violations
+ if order_violations:
+ return fail("event_order", "; ".join(order_violations))
+
+ expression = (
+ "(() => ({"
+ "url:String(location.href),"
+ "title:document.title,"
+ "readyState:document.readyState,"
+ "bodyTextLength:document.body?document.body.innerText.length:0,"
+ "htmlLength:document.documentElement?document.documentElement.outerHTML.length:0"
+ "}))()"
+ )
+ try:
+ evaluation = await client.command(
+ "Runtime.evaluate",
+ {"expression": expression, "returnByValue": True},
+ session_id=session_id,
+ timeout=timeouts.postcheck,
+ )
+ except (RawCdpError, TimeoutError) as error:
+ return fail("runtime_evaluate", error)
+ document = _runtime_value(evaluation.response)
+ if not isinstance(document, dict):
+ return fail("runtime_evaluate", f"Runtime.evaluate returned no document value: {evaluation.response}")
+ row["document"] = document
+ expected_ready_states = {"complete"} if require_load else {"interactive", "complete"}
+ if document.get("readyState") not in expected_ready_states:
+ return fail(
+ "document_ready_state",
+ f"lifecycle completed but readyState was {document.get('readyState')!r}",
+ )
+
+ try:
+ dom = await client.command(
+ "DOM.getDocument",
+ {"depth": 1},
+ session_id=session_id,
+ timeout=timeouts.postcheck,
+ )
+ except (RawCdpError, TimeoutError) as error:
+ return fail("dom_get_document", error)
+ dom_result = dom.response.get("result")
+ root = dom_result.get("root") if isinstance(dom_result, dict) else None
+ node_id = root.get("nodeId") if isinstance(root, dict) else None
+ if not isinstance(node_id, int) or node_id <= 0:
+ return fail("dom_get_document", f"DOM.getDocument returned no root node: {dom.response}")
+ row["dom_root"] = {"node_id": node_id, "backend_node_id": root.get("backendNodeId")}
+
+ error_text = navigate_result.get("errorText") if not row["supersessions"] else None
+ final_url = document.get("url")
+ row["content_kind"] = (
+ "network_error_document"
+ if isinstance(error_text, str)
+ or (isinstance(final_url, str) and final_url.startswith("chrome-error://"))
+ else "document"
+ )
+ row["ok"] = True
+ row["trace"] = _compact_trace(
+ client,
+ after_sequence=start_sequence,
+ started=started,
+ )
+ row["elapsed_ms"] = round((time.perf_counter() - started) * 1000.0, 3)
+ capture_network_diagnostics()
+ return row
+
+
+async def _create_page_session(
+ client: RoutedRawCdpClient,
+ timeout: float,
+ *,
+ network_diagnostics: bool,
+) -> tuple[str, str]:
+ target = await client.command(
+ "Target.createTarget",
+ {"url": "about:blank"},
+ timeout=timeout,
+ )
+ target_id = target.response.get("result", {}).get("targetId")
+ if not isinstance(target_id, str) or not target_id:
+ raise RuntimeError(f"Target.createTarget returned no targetId: {target.response}")
+ attached = await client.command(
+ "Target.attachToTarget",
+ {"targetId": target_id, "flatten": True},
+ timeout=timeout,
+ )
+ session_id = attached.response.get("result", {}).get("sessionId")
+ if not isinstance(session_id, str) or not session_id:
+ raise RuntimeError(f"Target.attachToTarget returned no sessionId: {attached.response}")
+ for method, params in (
+ ("Page.enable", None),
+ ("Runtime.enable", None),
+ ("DOM.enable", None),
+ ("Page.setLifecycleEventsEnabled", {"enabled": True}),
+ ):
+ await client.command(method, params, session_id=session_id, timeout=timeout)
+ if network_diagnostics:
+ await client.command("Network.enable", session_id=session_id, timeout=timeout)
+ return target_id, session_id
+
+
+def _git_output(*args: str) -> str | None:
+ result = subprocess.run(
+ ["git", *args],
+ cwd=REPO_ROOT,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ check=False,
+ text=True,
+ )
+ if result.returncode != 0:
+ return None
+ return result.stdout.strip()
+
+
+def repository_state() -> dict[str, Any]:
+ status = _git_output("status", "--porcelain")
+ return {
+ "commit": _git_output("rev-parse", "HEAD"),
+ "dirty": None if status is None else bool(status),
+ }
+
+
+def selected_engines(engine: str) -> tuple[str, ...]:
+ if engine == "both":
+ return ("moli", "chromium")
+ if engine in {"moli", "chromium"}:
+ return (engine,)
+ raise ValueError(f"unsupported engine selection: {engine}")
+
+
+async def run_engine(
+ *,
+ target: str,
+ binary: Path,
+ urls: list[str],
+ timeouts: NavigationTimeouts,
+ startup_timeout: float,
+ recovery_timeout: float,
+ network_diagnostics: bool,
+) -> dict[str, Any]:
+ started_at = datetime.now(UTC).isoformat()
+ serve = start_target_serve(target, binary, startup_timeout)
+ client: RoutedRawCdpClient | None = None
+ session_id: str | None = None
+ rows: list[dict[str, Any]] = []
+ network_order_violations: list[dict[str, Any]] = []
+ aborted_after_index: int | None = None
+ try:
+ client = await connect_routed_raw_cdp(serve.endpoint)
+ target_id, session_id = await _create_page_session(
+ client,
+ startup_timeout,
+ network_diagnostics=network_diagnostics,
+ )
+ for index, url in enumerate(urls, 1):
+ row = await navigate_once(
+ client,
+ session_id=session_id,
+ url=url,
+ timeouts=timeouts,
+ network_diagnostics=network_diagnostics,
+ )
+ row.update({"index": index, "target_id": target_id})
+ if not row["ok"]:
+ marker = f"moli-navigate-recovery-{index}-{time.time_ns()}"
+ recovery_timeouts = NavigationTimeouts(
+ response=recovery_timeout,
+ dcl=recovery_timeout,
+ load=recovery_timeout,
+ postcheck=recovery_timeout,
+ )
+ recovery = await navigate_once(
+ client,
+ session_id=session_id,
+ url=make_recovery_url(marker),
+ timeouts=recovery_timeouts,
+ network_diagnostics=network_diagnostics,
+ )
+ document = recovery.get("document")
+ marker_ok = isinstance(document, dict) and document.get("title") == marker
+ recovery["marker"] = marker
+ recovery["marker_ok"] = marker_ok
+ recovery["ok"] = bool(recovery["ok"] and marker_ok)
+ row["recovery"] = recovery
+ if not recovery["ok"]:
+ aborted_after_index = index
+ rows.append(row)
+ print(
+ json.dumps(
+ {
+ "target": target,
+ "index": index,
+ "url": url,
+ "ok": row["ok"],
+ "failure_stage": row["failure_stage"],
+ "response_ms": row["response_ms"],
+ "dcl_ms": row["dcl_ms"],
+ "load_ms": row["load_ms"],
+ "content_kind": row["content_kind"],
+ "supersessions": len(row["supersessions"]),
+ "network_inflight": (
+ row.get("network_diagnostics") or {}
+ ).get("inflight_count"),
+ "recovery_ok": row.get("recovery", {}).get("ok"),
+ },
+ ensure_ascii=False,
+ ),
+ flush=True,
+ )
+ if aborted_after_index is not None:
+ break
+ finally:
+ if client is not None:
+ if network_diagnostics and session_id is not None:
+ network_order_violations = network_event_order_violations(
+ client.messages_since(0),
+ session_id=session_id,
+ )
+ await client.close()
+ serve_result = stop_target_serve(serve)
+
+ summary = {
+ "planned": len(urls),
+ "attempted": len(rows),
+ "observable_passes": sum(bool(row["ok"]) for row in rows),
+ "failures": sum(not row["ok"] for row in rows),
+ "document_passes": sum(row.get("content_kind") == "document" for row in rows),
+ "network_error_documents": sum(
+ row.get("content_kind") == "network_error_document" for row in rows
+ ),
+ "recovery_attempts": sum("recovery" in row for row in rows),
+ "recovery_passes": sum(row.get("recovery", {}).get("ok") is True for row in rows),
+ "recovery_failures": sum(row.get("recovery", {}).get("ok") is False for row in rows),
+ "order_violations": sum(bool(row.get("order_violations")) for row in rows),
+ "network_order_violations": len(network_order_violations),
+ "superseded_passes": sum(
+ bool(row["ok"] and row.get("supersessions")) for row in rows
+ ),
+ "aborted_after_index": aborted_after_index,
+ }
+ return {
+ "target": target,
+ "binary": str(binary),
+ "started_at": started_at,
+ "finished_at": datetime.now(UTC).isoformat(),
+ "ready_ms": serve.ready_ms,
+ "summary": summary,
+ "network_order_violations": network_order_violations,
+ "rows": rows,
+ "process": serve_result,
+ }
+
+
+def _parse_args(argv: list[str] | None) -> argparse.Namespace:
+ parser = argparse.ArgumentParser(
+ description="Fuzz sequential Page.navigate calls on one CDP target and verify recovery.",
+ )
+ parser.add_argument("--url", action="append", help="Explicit URL; repeat to define exact order.")
+ parser.add_argument("--seed-file", type=Path, default=DEFAULT_SEED_FILE)
+ parser.add_argument("--seed", type=int, default=DEFAULT_SEED)
+ parser.add_argument("--count", type=int, default=DEFAULT_COUNT)
+ parser.add_argument("--rounds", type=int, default=1)
+ parser.add_argument("--pinned-domain", action="append")
+ parser.add_argument("--moli-bin")
+ parser.add_argument("--chrome-bin")
+ parser.add_argument(
+ "--engine",
+ choices=("moli", "chromium", "both"),
+ default="moli",
+ help="Browser engine to run; `both` runs the same URL order sequentially.",
+ )
+ parser.add_argument("--full-resources", action="store_true")
+ parser.add_argument(
+ "--network-diagnostics",
+ action="store_true",
+ help=(
+ "Enable Network events, record compact request terminal-state summaries, "
+ "and audit exact request event order; off by default to keep benchmark "
+ "overhead comparable."
+ ),
+ )
+ parser.add_argument("--startup-timeout", type=float, default=20.0)
+ parser.add_argument("--response-timeout", type=float, default=15.0)
+ parser.add_argument("--dcl-timeout", type=float, default=15.0)
+ parser.add_argument("--load-timeout", type=float, default=20.0)
+ parser.add_argument("--postcheck-timeout", type=float, default=5.0)
+ parser.add_argument("--recovery-timeout", type=float, default=8.0)
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args(argv)
+ for name in (
+ "startup_timeout",
+ "response_timeout",
+ "dcl_timeout",
+ "load_timeout",
+ "postcheck_timeout",
+ "recovery_timeout",
+ ):
+ if getattr(args, name) <= 0:
+ parser.error(f"--{name.replace('_', '-')} must be positive")
+ if args.rounds <= 0:
+ parser.error("--rounds must be positive")
+ if args.count <= 0:
+ parser.error("--count must be positive")
+ return args
+
+
+def _selected_urls(args: argparse.Namespace) -> list[str]:
+ if args.url:
+ base = [normalize_public_url(url) for url in args.url]
+ else:
+ domains = parse_top_100_domains(args.seed_file.read_text(encoding="utf-8"))
+ base = select_seed_urls(
+ domains,
+ seed=args.seed,
+ count=args.count,
+ pinned_domains=args.pinned_domain or DEFAULT_PINNED_DOMAINS,
+ )
+ return base * args.rounds
+
+
+async def _run(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
+ urls = _selected_urls(args)
+ timeouts = NavigationTimeouts(
+ response=args.response_timeout,
+ dcl=args.dcl_timeout,
+ load=args.load_timeout,
+ postcheck=args.postcheck_timeout,
+ )
+ engines: list[tuple[str, Path]] = []
+ for engine in selected_engines(args.engine):
+ if engine == "moli":
+ engines.append(
+ (
+ "moli-full-cdp" if args.full_resources else "moli-cdp",
+ moli_binary(args.moli_bin),
+ )
+ )
+ continue
+ chrome = chrome_binary(args.chrome_bin)
+ if chrome is None:
+ raise RuntimeError("Chromium binary not found; pass --chrome-bin or set CHROME_BIN")
+ engines.append(("chrome-cdp", chrome))
+
+ results = []
+ for target, binary in engines:
+ results.append(
+ await run_engine(
+ target=target,
+ binary=binary,
+ urls=urls,
+ timeouts=timeouts,
+ startup_timeout=args.startup_timeout,
+ recovery_timeout=args.recovery_timeout,
+ network_diagnostics=args.network_diagnostics,
+ )
+ )
+ payload = {
+ "schema_version": 4,
+ "repository": repository_state(),
+ "engine_selection": args.engine,
+ "seed": args.seed,
+ "rounds": args.rounds,
+ "urls": urls,
+ "timeouts": asdict(timeouts),
+ "network_diagnostics": args.network_diagnostics,
+ "results": results,
+ }
+ failed = any(
+ result["summary"]["failures"]
+ or result["summary"]["network_order_violations"]
+ for result in results
+ )
+ return payload, 1 if failed else 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = _parse_args(argv)
+ payload, exit_code = asyncio.run(_run(args))
+ output = args.output
+ if output is None:
+ stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
+ output = REPO_ROOT / "moli-benchmark" / "results" / f"sequential-navigate-{stamp}.json"
+ write_json(output, payload)
+ print(json.dumps({"output": str(output), "exit_code": exit_code}), flush=True)
+ return exit_code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/moli-benchmark/scripts/fuzz-cdp-sequential-navigate.py b/moli-benchmark/scripts/fuzz-cdp-sequential-navigate.py
new file mode 100755
index 000000000..4f6bb20cf
--- /dev/null
+++ b/moli-benchmark/scripts/fuzz-cdp-sequential-navigate.py
@@ -0,0 +1,7 @@
+#!/usr/bin/env python3
+
+from moli_benchmark.sequential_navigate import main
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/moli-benchmark/tests/test_sequential_navigate.py b/moli-benchmark/tests/test_sequential_navigate.py
new file mode 100644
index 000000000..3824a2197
--- /dev/null
+++ b/moli-benchmark/tests/test_sequential_navigate.py
@@ -0,0 +1,349 @@
+from __future__ import annotations
+
+import unittest
+
+from moli_benchmark.raw_cdp import RecordedCdpMessage
+from moli_benchmark.sequential_navigate import (
+ NavigationIdentity,
+ find_exact_lifecycle_record,
+ find_navigation_progress_record,
+ make_recovery_url,
+ network_event_order_violations,
+ navigation_order_violations,
+ normalize_public_url,
+ parse_top_100_domains,
+ select_seed_urls,
+ selected_engines,
+ summarize_network_activity,
+)
+
+
+def record(sequence: int, payload: dict[str, object]) -> RecordedCdpMessage:
+ return RecordedCdpMessage(
+ sequence=sequence,
+ received_monotonic=float(sequence),
+ received_epoch=float(sequence),
+ payload=payload,
+ )
+
+
+def lifecycle(
+ sequence: int,
+ *,
+ frame_id: str,
+ loader_id: str,
+ name: str,
+ session_id: str = "SID-1",
+) -> RecordedCdpMessage:
+ return record(
+ sequence,
+ {
+ "sessionId": session_id,
+ "method": "Page.lifecycleEvent",
+ "params": {
+ "frameId": frame_id,
+ "loaderId": loader_id,
+ "name": name,
+ },
+ },
+ )
+
+
+def navigation_started(
+ sequence: int,
+ *,
+ frame_id: str,
+ loader_id: str,
+ url: str = "https://next.test/",
+ session_id: str = "SID-1",
+) -> RecordedCdpMessage:
+ return record(
+ sequence,
+ {
+ "sessionId": session_id,
+ "method": "Page.frameStartedNavigating",
+ "params": {
+ "frameId": frame_id,
+ "loaderId": loader_id,
+ "url": url,
+ },
+ },
+ )
+
+
+def network_event(
+ sequence: int,
+ *,
+ method: str,
+ request_id: str,
+ session_id: str = "SID-1",
+) -> RecordedCdpMessage:
+ params: dict[str, object] = {"requestId": request_id}
+ if method == "Network.requestWillBeSent":
+ params.update(
+ {
+ "type": "XHR",
+ "request": {"url": f"https://example.test/{request_id}"},
+ }
+ )
+ elif method == "Network.responseReceived":
+ params["type"] = "XHR"
+ return record(
+ sequence,
+ {
+ "sessionId": session_id,
+ "method": method,
+ "params": params,
+ },
+ )
+
+
+class SequentialNavigateTests(unittest.TestCase):
+ def test_url_normalization_preserves_explicit_data_url(self) -> None:
+ url = "data:text/html,<title>fixture</title>"
+
+ self.assertEqual(normalize_public_url(url), url)
+
+ def test_seed_parser_reads_only_top_100_section(self) -> None:
+ markdown = """
+## Earlier
+1. `ignored.example`
+## Top 100
+1. `csdn.net` — CSDN
+2. `zol.com.cn` — ZOL
+## Maintenance
+1. `also-ignored.example`
+"""
+ self.assertEqual(parse_top_100_domains(markdown), ["csdn.net", "zol.com.cn"])
+
+ def test_seed_selection_pins_repros_and_is_deterministic(self) -> None:
+ domains = ["alpha.test", "csdn.net", "beta.test", "zol.com.cn", "gamma.test"]
+ first = select_seed_urls(domains, seed=17, count=4)
+ second = select_seed_urls(domains, seed=17, count=4)
+
+ self.assertEqual(first, second)
+ self.assertEqual(first[:2], ["https://csdn.net", "https://zol.com.cn"])
+ self.assertEqual(len(set(first)), 4)
+
+ def test_lifecycle_match_requires_exact_session_frame_and_loader(self) -> None:
+ identity = NavigationIdentity(frame_id="FRAME-NEW", loader_id="LOADER-NEW")
+ records = [
+ lifecycle(1, frame_id="FRAME-OLD", loader_id="LOADER-OLD", name="DOMContentLoaded"),
+ lifecycle(2, frame_id="FRAME-NEW", loader_id="LOADER-OLD", name="DOMContentLoaded"),
+ lifecycle(
+ 3,
+ frame_id="FRAME-NEW",
+ loader_id="LOADER-NEW",
+ name="DOMContentLoaded",
+ session_id="SID-OLD",
+ ),
+ lifecycle(4, frame_id="FRAME-NEW", loader_id="LOADER-NEW", name="DOMContentLoaded"),
+ ]
+
+ matched = find_exact_lifecycle_record(
+ records,
+ session_id="SID-1",
+ identity=identity,
+ name="DOMContentLoaded",
+ )
+
+ self.assertIsNotNone(matched)
+ self.assertEqual(matched.sequence if matched else None, 4)
+
+ def test_navigation_progress_uses_earliest_lifecycle_or_same_frame_successor(self) -> None:
+ identity = NavigationIdentity(frame_id="FRAME", loader_id="LOADER-INITIAL")
+ successor = navigation_started(
+ 2,
+ frame_id="FRAME",
+ loader_id="LOADER-SUCCESSOR",
+ )
+ records = [
+ navigation_started(1, frame_id="OTHER", loader_id="LOADER-IGNORED"),
+ successor,
+ lifecycle(3, frame_id="FRAME", loader_id="LOADER-INITIAL", name="DOMContentLoaded"),
+ ]
+
+ progress = find_navigation_progress_record(
+ records,
+ session_id="SID-1",
+ identity=identity,
+ lifecycle_name="DOMContentLoaded",
+ )
+
+ self.assertIsNotNone(progress)
+ self.assertEqual(progress.kind if progress else None, "successor")
+ self.assertEqual(progress.record.sequence if progress else None, 2)
+ self.assertEqual(
+ progress.identity if progress else None,
+ NavigationIdentity(frame_id="FRAME", loader_id="LOADER-SUCCESSOR"),
+ )
+
+ def test_navigation_progress_keeps_lifecycle_when_it_precedes_successor(self) -> None:
+ identity = NavigationIdentity(frame_id="FRAME", loader_id="LOADER-INITIAL")
+ records = [
+ lifecycle(1, frame_id="FRAME", loader_id="LOADER-INITIAL", name="DOMContentLoaded"),
+ navigation_started(2, frame_id="FRAME", loader_id="LOADER-SUCCESSOR"),
+ ]
+
+ progress = find_navigation_progress_record(
+ records,
+ session_id="SID-1",
+ identity=identity,
+ lifecycle_name="DOMContentLoaded",
+ )
+
+ self.assertIsNotNone(progress)
+ self.assertEqual(progress.kind if progress else None, "lifecycle")
+ self.assertEqual(progress.record.sequence if progress else None, 1)
+
+ def test_order_check_rejects_lifecycle_before_navigate_response(self) -> None:
+ response = record(3, {"id": 7, "result": {}})
+ dcl = lifecycle(2, frame_id="FRAME", loader_id="LOADER", name="DOMContentLoaded")
+ load = lifecycle(4, frame_id="FRAME", loader_id="LOADER", name="load")
+
+ self.assertEqual(
+ navigation_order_violations(response, dcl, load),
+ ["DOMContentLoaded was observable before Page.navigate response"],
+ )
+
+ def test_order_check_accepts_response_then_dcl_then_load(self) -> None:
+ response = record(2, {"id": 7, "result": {}})
+ dcl = lifecycle(3, frame_id="FRAME", loader_id="LOADER", name="DOMContentLoaded")
+ load = lifecycle(4, frame_id="FRAME", loader_id="LOADER", name="load")
+
+ self.assertEqual(navigation_order_violations(response, dcl, load), [])
+
+ def test_recovery_url_carries_unique_marker(self) -> None:
+ url = make_recovery_url("marker-123")
+
+ self.assertTrue(url.startswith("data:text/html;charset=utf-8,"))
+ self.assertIn("marker-123", url)
+
+ def test_engine_selection_can_run_each_engine_or_both(self) -> None:
+ self.assertEqual(selected_engines("moli"), ("moli",))
+ self.assertEqual(selected_engines("chromium"), ("chromium",))
+ self.assertEqual(selected_engines("both"), ("moli", "chromium"))
+
+ with self.assertRaisesRegex(ValueError, "unsupported engine"):
+ selected_engines("unknown")
+
+ def test_network_summary_reports_terminal_and_inflight_requests(self) -> None:
+ records = [
+ record(
+ 1,
+ {
+ "sessionId": "SID-1",
+ "method": "Network.requestWillBeSent",
+ "params": {
+ "requestId": "REQ-finished",
+ "frameId": "FRAME",
+ "loaderId": "LOADER",
+ "type": "Document",
+ "request": {"url": "https://example.test/"},
+ "initiator": {"type": "other"},
+ },
+ },
+ ),
+ record(
+ 2,
+ {
+ "sessionId": "SID-1",
+ "method": "Network.loadingFinished",
+ "params": {"requestId": "REQ-finished"},
+ },
+ ),
+ record(
+ 3,
+ {
+ "sessionId": "SID-1",
+ "method": "Network.requestWillBeSent",
+ "params": {
+ "requestId": "REQ-inflight",
+ "frameId": "FRAME",
+ "loaderId": "LOADER",
+ "type": "Script",
+ "request": {"url": "https://example.test/blocker.js"},
+ "initiator": {"type": "parser"},
+ },
+ },
+ ),
+ record(
+ 4,
+ {
+ "sessionId": "SID-other",
+ "method": "Network.loadingFailed",
+ "params": {"requestId": "REQ-inflight", "errorText": "ignored"},
+ },
+ ),
+ ]
+
+ summary = summarize_network_activity(records, session_id="SID-1", started=0.0)
+
+ self.assertEqual(summary["request_count"], 2)
+ self.assertEqual(summary["finished_count"], 1)
+ self.assertEqual(summary["failed_count"], 0)
+ self.assertEqual(summary["inflight_count"], 1)
+ self.assertEqual(summary["requests"][1]["request_id"], "REQ-inflight")
+ self.assertEqual(summary["requests"][1]["type"], "Script")
+ self.assertIsNone(summary["requests"][1]["terminal"])
+
+ def test_network_order_audit_accepts_success_failure_and_redirect_order(self) -> None:
+ records = [
+ network_event(1, method="Network.requestWillBeSent", request_id="REQ-ok"),
+ network_event(2, method="Network.requestWillBeSent", request_id="REQ-ok"),
+ network_event(3, method="Network.responseReceived", request_id="REQ-ok"),
+ network_event(4, method="Network.loadingFinished", request_id="REQ-ok"),
+ network_event(5, method="Network.requestWillBeSent", request_id="REQ-fail"),
+ network_event(6, method="Network.loadingFailed", request_id="REQ-fail"),
+ network_event(
+ 7,
+ method="Network.loadingFinished",
+ request_id="REQ-other-session",
+ session_id="SID-other",
+ ),
+ ]
+
+ self.assertEqual(
+ network_event_order_violations(records, session_id="SID-1"),
+ [],
+ )
+
+ def test_network_order_audit_reports_success_terminal_before_start_and_response(self) -> None:
+ records = [
+ network_event(1, method="Network.loadingFinished", request_id="REQ-late"),
+ network_event(2, method="Network.requestWillBeSent", request_id="REQ-late"),
+ network_event(3, method="Network.responseReceived", request_id="REQ-late"),
+ ]
+
+ violations = network_event_order_violations(records, session_id="SID-1")
+
+ self.assertEqual(
+ [violation["kind"] for violation in violations],
+ ["terminal_before_start", "successful_terminal_before_response"],
+ )
+ self.assertTrue(
+ all(violation["request_id"] == "REQ-late" for violation in violations)
+ )
+
+ def test_network_order_audit_reports_response_order_and_duplicate_terminal(self) -> None:
+ records = [
+ network_event(1, method="Network.responseReceived", request_id="REQ-response"),
+ network_event(2, method="Network.requestWillBeSent", request_id="REQ-response"),
+ network_event(3, method="Network.requestWillBeSent", request_id="REQ-duplicate"),
+ network_event(4, method="Network.loadingFailed", request_id="REQ-duplicate"),
+ network_event(5, method="Network.loadingFailed", request_id="REQ-duplicate"),
+ ]
+
+ violations = network_event_order_violations(records, session_id="SID-1")
+
+ self.assertEqual(
+ [(violation["request_id"], violation["kind"]) for violation in violations],
+ [
+ ("REQ-response", "response_before_start"),
+ ("REQ-duplicate", "duplicate_terminal"),
+ ],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/moli-core/src/lib.rs b/moli-core/src/lib.rs
index 43d78c446..4670f9ff1 100644
--- a/moli-core/src/lib.rs
+++ b/moli-core/src/lib.rs
@@ -21,10 +21,11 @@ pub use moli_page_types::{LayoutPolicy, OptionalResourceFetchMask};
pub use moli_renderer_v8::renderer_output_transport_channel;
pub use moli_renderer_v8::{
PageId, RendererBrowserContextRuntimeId, RendererDocumentLifecycleIdentity,
- RendererOutputCursor, RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem,
- RendererOutputPublication, RendererOutputPublicationOrdering, RendererOutputRecord,
- RendererOutputResidenceIdentity, RendererOutputStreamCloseReason, RendererOutputStreamControl,
- RendererOutputStreamEpoch, RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,
+ RendererDocumentTitleChanged, RendererOutputCursor, RendererOutputFence,
+ RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,
+ RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,
+ RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,
+ RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,
RendererOutputTransportMessage, RendererOutputTransportReceiver,
RendererOutputTransportSendError, RendererOutputTransportSender, RendererOwnerAction,
RendererOwnerLocalHostId, RendererOwnerResourceActivitySource,
diff --git a/moli-core/src/page/mod.rs b/moli-core/src/page/mod.rs
index 9b3d165ed..eaaeb0e38 100644
--- a/moli-core/src/page/mod.rs
+++ b/moli-core/src/page/mod.rs
@@ -249,6 +249,14 @@ impl Page {
self.renderer_agent_attachment_id = Some(id);
}
+ #[doc(hidden)]
+ pub fn take_committed_document_post_response_continuation(
+ &mut self,
+ ) -> Option<RendererPageCommandPostResponseContinuation> {
+ self.handle
+ .take_committed_document_post_response_continuation()
+ }
+
/// Deterministically releases this page from the renderer owner.
///
/// Dropping `Page` also schedules a detached best-effort cleanup, but code
diff --git a/moli-core/src/runtime/navigation_engine.rs b/moli-core/src/runtime/navigation_engine.rs
index 7f3b756b6..d6cf2cb75 100644
--- a/moli-core/src/runtime/navigation_engine.rs
+++ b/moli-core/src/runtime/navigation_engine.rs
@@ -9,7 +9,6 @@ use crate::{
RuntimeIsolatedWorldDefinition, SubresourceAuthCredentials, SubresourceResourceType,
ViewportSurface,
},
- parser::{HtmlParser, XmlParser},
renderer::ExternalRawDocumentBodyStream,
renderer::JsRuntime,
renderer::PageVmInitStage,
@@ -78,11 +77,6 @@ pub enum CommittedDocumentResourceSource {
Synthetic,
}
-fn response_headers_indicate_xml_document(headers: &[(String, String)]) -> bool {
- moli_web_mime::response_document_content_type(headers)
- .is_some_and(|mime| moli_web_mime::is_dom_parser_xml_mime(&mime))
-}
-
fn streaming_raw_response_from_navigation_response(
response: NavigationResponse,
) -> Result<StreamingRawResponse> {
@@ -890,11 +884,13 @@ impl NavigationEngine {
&mut self,
cookie_store: SharedBrowserCookieStore,
requested_url: Url,
+ cancel_handle: FetchCancelHandle,
) -> Result<NavigationResourceLoader> {
- Ok(NavigationResourceLoader::new(
+ Ok(NavigationResourceLoader::new_with_cancel_handle(
self.ensure_resource_request_client(cookie_store)?,
requested_url,
moli_renderer_v8::network::RendererResourceTaskRunner::from_current_tokio()?,
+ cancel_handle,
))
}
@@ -932,8 +928,11 @@ impl NavigationEngine {
})
.context("failed to build request")?;
request.set_auth(auth.map(Into::into));
- let navigation_loader =
- self.navigation_resource_loader(cookie_store, request.url.clone())?;
+ let navigation_loader = self.navigation_resource_loader(
+ cookie_store,
+ request.url.clone(),
+ FetchCancelHandle::new(),
+ )?;
navigation_loader
.fetch_with_network_metadata(request)
.await
@@ -978,6 +977,7 @@ impl NavigationEngine {
body: Option<Vec<u8>>,
request_headers: Vec<(String, String)>,
auth: Option<SubresourceAuthCredentials>,
+ cancel_handle: FetchCancelHandle,
) -> Result<NavigationStreamingRawResponse> {
let mut request = Request::new_bytes(method, raw_url, body, request_headers)
.map(|request| {
@@ -995,7 +995,7 @@ impl NavigationEngine {
.context("failed to build request")?;
request.set_auth(auth.map(Into::into));
let navigation_loader =
- self.navigation_resource_loader(cookie_store, request.url.clone())?;
+ self.navigation_resource_loader(cookie_store, request.url.clone(), cancel_handle)?;
let service_worker_fetch = self
.browser_context_runtime()
.fetch_service_worker_main_resource_for_navigation(&request, &navigation_loader)
@@ -1049,6 +1049,7 @@ impl NavigationEngine {
body.map(String::into_bytes),
request_headers,
auth,
+ FetchCancelHandle::new(),
)
.await
}
@@ -1065,6 +1066,7 @@ impl NavigationEngine {
body: Option<Vec<u8>>,
request_headers: Vec<(String, String)>,
auth: Option<SubresourceAuthCredentials>,
+ cancel_handle: FetchCancelHandle,
) -> Result<NavigationStreamingRawResponse> {
let cookie_store = storage.into_cookie_store();
self.fetch_navigation_streaming_raw_response_async(
@@ -1077,6 +1079,7 @@ impl NavigationEngine {
body,
request_headers,
auth,
+ cancel_handle,
)
.await
}
@@ -2121,74 +2124,45 @@ impl NavigationEngine {
options: DocumentPageLoadOptions,
stage: PageVmInitStage,
) -> Result<PreparedDocumentPage> {
- let loader = self.resource_request_client_for_committed_document(
+ let raw_body =
+ ExternalRawDocumentBodyStream::from_bytes(options.response_body.into_bytes());
+ self.prepare_streaming_raw_page_from_external_body_async(
+ page_reservation,
cookie_store,
- &options.final_url,
- options.resource_source.clone(),
- )?;
- loader.set_extra_http_headers(&options.extra_http_headers);
- loader.set_network_offline(options.network_offline);
- loader.set_blocked_url_patterns(&options.blocked_url_patterns);
- let (mut document, parser_document_handoffs) =
- if response_headers_indicate_xml_document(&options.response_headers) {
- XmlParser.parse_top_level_document_with_handoffs(
- options.final_url.clone(),
- options.response_body,
- )
- } else {
- let (dom_host, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
- options.final_url.clone(),
- options.response_body,
- );
- (dom_host.into_dom(), handoffs)
- };
- if let Some(content_type) =
- moli_web_mime::response_document_content_type(&options.response_headers)
- {
- document.set_document_content_type(content_type);
- }
- let (parser_document_handoffs, parser_blocking_stylesheet_inputs) =
- parser_document_handoffs.into_parts();
- let prepared = self
- .js_runtime
- .prepare_document_page_with_inspector_session_restores(
- page_reservation,
- options.requested_url.clone(),
- options.navigation_initiator_url,
- options.redirected,
- options.redirect_count,
- options.response_status,
- options.response_headers,
- &loader,
- web_storage,
- document,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- indexed_db_manager,
- storage_bucket_store,
- options.document_start_scripts,
- options.runtime_bindings,
- options.runtime_inspector_session_restore_snapshots,
- options.extra_http_headers,
- options.locale_override,
- options.timezone_override,
- options.script_execution_disabled,
- options.bypass_content_security_policy,
- options.cpu_throttling_rate,
- options.emulated_media,
- options.viewport_surface,
- options.network_offline,
- options.blocked_url_patterns,
- options.fetch_subresource_interception_enabled,
- options.fetch_subresource_interception_resource_type,
- false,
- stage,
- options.root_frame_id,
- options.main_document_commit,
- )
- .await
- .context("failed to prepare document page")?;
- Ok(PreparedDocumentPage { prepared })
+ web_storage,
+ indexed_db_manager,
+ storage_bucket_store,
+ options.requested_url,
+ options.final_url,
+ options.navigation_initiator_url,
+ options.redirected,
+ options.redirect_count,
+ options.response_status,
+ options.response_headers,
+ raw_body,
+ options.document_start_scripts,
+ options.runtime_bindings,
+ options.runtime_inspector_session_restore_snapshots,
+ options.extra_http_headers,
+ options.locale_override,
+ options.timezone_override,
+ options.script_execution_disabled,
+ options.bypass_content_security_policy,
+ options.cpu_throttling_rate,
+ options.emulated_media,
+ options.viewport_surface,
+ options.network_offline,
+ options.blocked_url_patterns,
+ options.fetch_subresource_interception_enabled,
+ options.fetch_subresource_interception_resource_type,
+ stage,
+ moli_renderer_v8::RendererPageCreationReplyBoundary::LifecycleTarget,
+ options.root_frame_id,
+ options.resource_source,
+ None,
+ options.main_document_commit,
+ )
+ .await
}
async fn build_document_page_from_response_options_best_effort_async(
diff --git a/moli-core/tests/scripts.rs b/moli-core/tests/scripts.rs
index 839bd2cfe..e03d6af4b 100644
--- a/moli-core/tests/scripts.rs
+++ b/moli-core/tests/scripts.rs
@@ -2397,6 +2397,34 @@ async fn document_write_external_split_script_continues_parser_session() -> Resu
Ok(())
}
+#[tokio::test(flavor = "multi_thread")]
+async fn document_write_inserted_external_script_resumes_chunked_root_input() -> Result<()> {
+ let server = FixtureServer::spawn().await?;
+ let browser = Browser::new(AppConfig::default())?;
+
+ let page = tokio::time::timeout(
+ Duration::from_secs(5),
+ browser.fetch(&server.url("/compat/document-write-inserted-external-resumes-chunked-root")),
+ )
+ .await
+ .expect("document.write parser continuation must not spin on queued root input")?;
+
+ assert_eq!(
+ diagnostic_global(&page, "documentWriteInsertedChunkedResult"),
+ Some(&JsValueSnapshot::String(
+ "before-write,after-write,inserted-external,tail-script".to_owned()
+ ))
+ );
+ assert!(
+ page.serialize_html_async()
+ .await?
+ .contains("id=\"document-write-inserted-chunked-tail\"")
+ );
+
+ server.shutdown().await;
+ Ok(())
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn imported_started_child_script_stays_inert_when_appended() -> Result<()> {
let server = FixtureServer::spawn().await?;
diff --git a/moli-dom/src/native/host/document.rs b/moli-dom/src/native/host/document.rs
index d7e24e2fd..3104b4de1 100644
--- a/moli-dom/src/native/host/document.rs
+++ b/moli-dom/src/native/host/document.rs
@@ -53,8 +53,6 @@ impl DomHost {
dom,
dom_version: Cell::new(0),
query_version: Cell::new(0),
- tree_insertion_tracking_depth: Cell::new(0),
- tree_insertion_versions: RefCell::new(HashMap::new()),
shadow_root_binding_version: Cell::new(0),
connected_shadow_roots_version: Cell::new(0),
id_index: RefCell::new(None),
@@ -193,31 +191,6 @@ impl DomHost {
self.query_version.get()
}
- pub fn tree_insertion_version(&self, handle: DomHandle) -> Option<u64> {
- self.tree_insertion_versions.borrow().get(&handle).copied()
- }
-
- pub fn begin_tree_insertion_tracking(&self) {
- let depth = self.tree_insertion_tracking_depth.get();
- if depth == 0 {
- self.tree_insertion_versions.borrow_mut().clear();
- }
- self.tree_insertion_tracking_depth
- .set(depth.saturating_add(1));
- }
-
- pub fn end_tree_insertion_tracking(&self) {
- let depth = self.tree_insertion_tracking_depth.get();
- if depth == 0 {
- return;
- }
- let depth = depth - 1;
- self.tree_insertion_tracking_depth.set(depth);
- if depth == 0 {
- self.tree_insertion_versions.borrow_mut().clear();
- }
- }
-
pub fn dom_version(&self) -> u64 {
self.dom_version.get()
}
@@ -236,17 +209,6 @@ impl DomHost {
}
}
- pub(super) fn record_tree_insertion_roots(&self, roots: &[DomHandle]) {
- if self.tree_insertion_tracking_depth.get() == 0 {
- return;
- }
- let version = self.query_version.get();
- let mut insertion_versions = self.tree_insertion_versions.borrow_mut();
- for root in roots {
- insertion_versions.insert(*root, version);
- }
- }
-
fn record_shadow_root_binding_mutation(&self) {
self.shadow_root_binding_version
.set(self.shadow_root_binding_version.get().saturating_add(1));
@@ -378,7 +340,6 @@ impl DomHost {
self.record_connected_shadow_roots_mutation();
}
self.record_mutation(MutationScope::QueryState);
- self.record_tree_insertion_roots(std::slice::from_ref(&root));
}
pub fn mark_subtree_disconnected_preserving_owner_document(&mut self, root: DomHandle) {
@@ -1761,12 +1722,24 @@ impl DomHost {
let Some(host) = self.shadow_hosts_by_root.borrow().get(&root).copied() else {
return false;
};
- let mut roots = self.shadow_roots_by_host.borrow_mut();
- let Some(state) = roots.get_mut(&host) else {
- return false;
+ let changed = {
+ let mut roots = self.shadow_roots_by_host.borrow_mut();
+ let Some(state) = roots.get_mut(&host) else {
+ return false;
+ };
+ if state.init.reference_target() == reference_target.as_deref() {
+ return false;
+ }
+ state.init.set_reference_target(reference_target);
+ true
};
- state.init.set_reference_target(reference_target);
- true
+ if changed {
+ // Reference-target forwarding changes live `labels` and form-control
+ // resolution even though it is neither a tree nor an attribute
+ // mutation. Keep it in the same query-version invalidation domain.
+ self.record_mutation(MutationScope::QueryState);
+ }
+ changed
}
pub fn shadow_root_host(&self, root: DomHandle) -> Option<DomHandle> {
diff --git a/moli-dom/src/native/host/mutation/tree.rs b/moli-dom/src/native/host/mutation/tree.rs
index 081fcf4ea..c6aa1543a 100644
--- a/moli-dom/src/native/host/mutation/tree.rs
+++ b/moli-dom/src/native/host/mutation/tree.rs
@@ -317,7 +317,6 @@ impl DomHost {
),
);
self.record_mutation(MutationScope::QueryState);
- self.record_tree_insertion_roots(&inserted_roots);
if let Some(document) = old_owner_document {
self.update_document_target_from_url(document);
}
diff --git a/moli-dom/src/native/host/types.rs b/moli-dom/src/native/host/types.rs
index 4c7c5afbc..813479dd4 100644
--- a/moli-dom/src/native/host/types.rs
+++ b/moli-dom/src/native/host/types.rs
@@ -24,8 +24,6 @@ pub struct DomHost {
pub(super) dom: NativeDom,
pub(super) dom_version: Cell<u64>,
pub(super) query_version: Cell<u64>,
- pub(super) tree_insertion_tracking_depth: Cell<usize>,
- pub(super) tree_insertion_versions: RefCell<HashMap<DomHandle, u64>>,
pub(super) shadow_root_binding_version: Cell<u64>,
pub(super) connected_shadow_roots_version: Cell<u64>,
pub(super) id_index: RefCell<Option<NamedElementIndex>>,
diff --git a/moli-dom/src/native/mod.rs b/moli-dom/src/native/mod.rs
index 075845225..d50f567cf 100644
--- a/moli-dom/src/native/mod.rs
+++ b/moli-dom/src/native/mod.rs
@@ -1462,6 +1462,38 @@ mod tests {
assert_eq!(changed[1].assigned_nodes(), &[first, second]);
}
+ #[test]
+ fn shadow_root_reference_target_changes_invalidate_query_state() {
+ let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));
+ let shadow_host = host.create_element("section");
+ let shadow_root = host
+ .attach_shadow_root(shadow_host, "open")
+ .expect("shadow root");
+ let target = host.create_element("input");
+ assert!(host.set_attribute(target, "id", "forwarded"));
+ assert!(host.append_child(host.document_node_id(), shadow_host));
+ assert!(host.append_child(shadow_root, target));
+
+ let before = host.query_version();
+ assert!(host.set_shadow_root_reference_target(shadow_root, Some("forwarded".to_owned())));
+ assert!(host.query_version() > before);
+ assert_eq!(
+ host.resolve_reference_target_chain(shadow_host),
+ Some(target)
+ );
+
+ let after_change = host.query_version();
+ assert!(!host.set_shadow_root_reference_target(shadow_root, Some("forwarded".to_owned())));
+ assert_eq!(host.query_version(), after_change);
+
+ assert!(host.set_shadow_root_reference_target(shadow_root, None));
+ assert!(host.query_version() > after_change);
+ assert_eq!(
+ host.resolve_reference_target_chain(shadow_host),
+ Some(shadow_host)
+ );
+ }
+
#[test]
fn host_child_mutations_report_slot_assignment_snapshots() {
let mut host = DomHost::from_dom(NativeDom::new_html(test_url()));
diff --git a/moli-fetch/src/streaming_response.rs b/moli-fetch/src/streaming_response.rs
index ddb0ebe14..10abf7a39 100644
--- a/moli-fetch/src/streaming_response.rs
+++ b/moli-fetch/src/streaming_response.rs
@@ -261,6 +261,13 @@ impl StreamingRawResponse {
self.network_request_extra_info.as_ref()
}
+ /// Returns cancellation authority for this exact streaming transfer.
+ /// Owners that move the response into another lifecycle boundary can use
+ /// the clone to retire the transport without retaining the response body.
+ pub fn cancellation_handle(&self) -> FetchCancelHandle {
+ self.cancel_handle.clone()
+ }
+
pub fn try_next_chunk(&mut self) -> Option<Vec<u8>> {
// See StreamingHtmlResponse::try_next_chunk.
self.body_chunks.try_recv().ok()
diff --git a/moli-page-types/src/lib.rs b/moli-page-types/src/lib.rs
index dbd4f6b83..c0dca9e50 100644
--- a/moli-page-types/src/lib.rs
+++ b/moli-page-types/src/lib.rs
@@ -1085,6 +1085,7 @@ pub struct SubresourceRequestStarted {
request_headers: Vec<(String, String)>,
request_body: Option<String>,
request_body_bytes: Option<Vec<u8>>,
+ keepalive: bool,
resource_type: SubresourceResourceType,
request_initiator_type: SubresourceRequestInitiatorType,
request_cookie_report: Option<StoredCookieQueryReport>,
@@ -1182,6 +1183,7 @@ impl SubresourceRequestStarted {
request_headers,
request_body,
request_body_bytes,
+ keepalive: false,
resource_type,
request_initiator_type,
request_cookie_report,
@@ -1198,6 +1200,11 @@ impl SubresourceRequestStarted {
self
}
+ pub fn with_keepalive(mut self, keepalive: bool) -> Self {
+ self.keepalive = keepalive;
+ self
+ }
+
pub fn frame_id(&self) -> Option<&str> {
self.frame_id.as_deref()
}
@@ -1226,6 +1233,10 @@ impl SubresourceRequestStarted {
self.request_body_bytes.as_deref()
}
+ pub fn keepalive(&self) -> bool {
+ self.keepalive
+ }
+
pub fn resource_type(&self) -> SubresourceResourceType {
self.resource_type
}
diff --git a/moli-parser/src/html.rs b/moli-parser/src/html.rs
index 9ba443e03..6470b7c59 100644
--- a/moli-parser/src/html.rs
+++ b/moli-parser/src/html.rs
@@ -59,6 +59,12 @@ struct ParserInputState {
pub struct DocumentStream {
inner: HtmlTreeSinkStream,
+ input: HtmlParserInputStream,
+}
+
+#[derive(Debug, Default)]
+struct HtmlParserInputStream {
+ end_segments: VecDeque<String>,
}
#[derive(Debug, Clone)]
@@ -135,45 +141,6 @@ impl ParserScriptHandoff {
}
}
-#[derive(Debug, Default)]
-pub struct ParserDocumentHandoffs {
- ordered_handoffs: Vec<ParserDocumentHandoff>,
- blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
-}
-
-/// A parser-created DOM action whose runtime side effects must retain token order.
-///
-/// Script handoffs and `<link rel=modulepreload>` insertion are intentionally
-/// represented in one sequence. Both can close import-map acquisition or start
-/// module work, so transporting them in separate vectors would allow the
-/// renderer bootstrap to reorder observable module behavior.
-#[derive(Debug, Clone)]
-pub enum ParserDocumentHandoff {
- Script(Box<ParserScriptHandoff>),
- ModulepreloadLink(NativeNodeId),
-}
-
-impl ParserDocumentHandoffs {
- pub(crate) fn new(
- ordered_handoffs: Vec<ParserDocumentHandoff>,
- blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) -> Self {
- Self {
- ordered_handoffs,
- blocking_stylesheet_inputs,
- }
- }
-
- pub fn into_parts(
- self,
- ) -> (
- Vec<ParserDocumentHandoff>,
- Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) {
- (self.ordered_handoffs, self.blocking_stylesheet_inputs)
- }
-}
-
#[derive(Debug, Clone)]
pub struct ParserScriptNoExecutionOutcome {
position: usize,
@@ -376,59 +343,6 @@ impl HtmlParser {
stream.finish_dom_host()
}
- pub fn parse_dom_host_with_script_handoffs(
- &self,
- final_url: Url,
- html: String,
- ) -> (DomHost, Vec<ParserScriptHandoff>) {
- let (dom_host, handoffs) = self.parse_dom_host_with_document_handoffs(final_url, html);
- let (ordered_handoffs, _) = handoffs.into_parts();
- let script_handoffs = ordered_handoffs
- .into_iter()
- .filter_map(|handoff| match handoff {
- ParserDocumentHandoff::Script(script) => Some(*script),
- ParserDocumentHandoff::ModulepreloadLink(_) => None,
- })
- .collect();
- (dom_host, script_handoffs)
- }
-
- pub fn parse_dom_host_with_document_handoffs(
- &self,
- final_url: Url,
- html: String,
- ) -> (DomHost, ParserDocumentHandoffs) {
- let mut stream = self.start_document(final_url);
- let mut handoffs = Vec::new();
- let mut blocking_stylesheet_inputs = Vec::new();
- for chunk in html_chunks(&html) {
- collect_parser_document_handoffs_for_chunk(
- &mut stream,
- chunk,
- &mut handoffs,
- &mut blocking_stylesheet_inputs,
- );
- }
- collect_parser_document_handoffs_for_chunk(
- &mut stream,
- "",
- &mut handoffs,
- &mut blocking_stylesheet_inputs,
- );
- let (dom_host, finish_signals) = stream.finish_dom_host_with_discovery_signals();
- handoffs.extend(
- finish_signals
- .discovered_modulepreload_link_candidates
- .into_iter()
- .map(ParserDocumentHandoff::ModulepreloadLink),
- );
- blocking_stylesheet_inputs.extend(finish_signals.discovered_blocking_stylesheet_inputs);
- (
- dom_host,
- ParserDocumentHandoffs::new(handoffs, blocking_stylesheet_inputs),
- )
- }
-
pub fn parse_without_declarative_shadow_roots(
&self,
final_url: Url,
@@ -574,12 +488,14 @@ impl DocumentStream {
fn new_parser_stream(final_url: Url) -> Self {
Self {
inner: new_parser_stream_html_tree_sink_stream(final_url),
+ input: HtmlParserInputStream::default(),
}
}
fn new_live_document_root(final_url: Url, document_handle: NativeNodeId) -> Self {
Self {
inner: new_live_document_root_html_tree_sink_stream(final_url, document_handle),
+ input: HtmlParserInputStream::default(),
}
}
@@ -602,6 +518,7 @@ impl DocumentStream {
runtime_dom_sinks,
allow_declarative_shadow_roots,
),
+ input: HtmlParserInputStream::default(),
}
}
@@ -683,6 +600,79 @@ impl DocumentStream {
self.inner.feed(chunk)
}
+ /// Append decoded document input to the parser-owned end segment chain.
+ ///
+ /// The tokenizer only receives a bounded prefix when the owner pumps the
+ /// parser. Appending while a script or stylesheet blocks parsing therefore
+ /// cannot advance the DOM commit frontier.
+ pub fn append_to_end(&mut self, chunk: String) {
+ if !chunk.is_empty() {
+ self.input.end_segments.push_back(chunk);
+ }
+ }
+
+ pub fn has_pending_input(&self) -> bool {
+ self.inner.has_script_input()
+ || self.inner.has_buffered_input()
+ || !self.input.end_segments.is_empty()
+ }
+
+ pub fn next_input_len(&self) -> usize {
+ self.inner
+ .next_script_input_len()
+ .or_else(|| {
+ self.inner
+ .has_buffered_input()
+ .then(|| self.inner.buffered_input_len())
+ })
+ .or_else(|| self.input.end_segments.front().map(String::len))
+ .unwrap_or_default()
+ }
+
+ pub fn snapshot_pending_input(&self) -> String {
+ let mut pending = self.inner.snapshot_script_input();
+ pending.push_str(&self.inner.snapshot_buffered_input());
+ for segment in &self.input.end_segments {
+ pending.push_str(segment);
+ }
+ pending
+ }
+
+ pub fn queued_end_segment_count_for_testing(&self) -> usize {
+ self.input.end_segments.len()
+ }
+
+ fn take_next_owned_input(&mut self, max_bytes: usize) -> (String, bool) {
+ if let Some(input) = self.inner.take_next_script_input() {
+ // One parser insertion is an atomic source segment. Splitting it
+ // outside html5ever would let a remainder jump ahead of bytes the
+ // tokenizer retained when it yielded on a script boundary.
+ return (input, true);
+ }
+
+ if self.inner.has_buffered_input() {
+ return (String::new(), false);
+ }
+
+ let Some(input) = self.input.end_segments.pop_front() else {
+ return (String::new(), false);
+ };
+ let (prefix, remainder) = split_parser_input_prefix(input, max_bytes);
+ if let Some(remainder) = remainder {
+ self.input.end_segments.push_front(remainder);
+ }
+ (prefix, false)
+ }
+
+ pub fn pump_next_parser_step(&mut self, max_bytes: usize) -> ParserPumpOutcome {
+ let (chunk, inserted_source) = self.take_next_owned_input(max_bytes);
+ if inserted_source {
+ self.inner.pump_parser_inserted_step(&chunk)
+ } else {
+ self.inner.pump_parser_step(&chunk)
+ }
+ }
+
/// Feed parser input until either the current buffer is exhausted or the parser yields a
/// concrete embedder control-flow boundary.
///
@@ -731,6 +721,25 @@ impl DocumentStream {
self.pump_parser_step_with_runtime_dom_sinks(chunk, sinks)
}
+ pub fn pump_next_parser_step_with_runtime_dom_consumer<T>(
+ &mut self,
+ max_bytes: usize,
+ consumer: &mut T,
+ ) -> ParserPumpOutcome
+ where
+ T: ParserDomReadConsumer
+ + ParserDomMutationConsumer
+ + ParserMutationEffectConsumer
+ + ParserElementCreationConsumer,
+ {
+ // SAFETY: `consumer` stays exclusively borrowed for this call; the
+ // parser-step Drop guard removes every erased callback before return.
+ let sinks = unsafe { ParserRuntimeDomSinks::from_consumer(consumer) };
+ self.inner.enter_runtime_dom_sinks_parse_step(sinks);
+ let mut step = RuntimeDomSinksParserStep { stream: self };
+ step.pump_next_parser_step(max_bytes)
+ }
+
pub fn pump_parser_step_with_runtime_dom_consumer_without_element_creation<T>(
&mut self,
chunk: &str,
@@ -904,22 +913,6 @@ impl DocumentStream {
self.inner.mark_script_already_started(node_id)
}
- pub fn take_buffered_input(&mut self) -> String {
- // html5ever keeps any still-unconsumed bytes in `input_buffer` after yielding a concrete
- // script hand-off. Returning them to runtime lets the embedder re-queue that buffered
- // source behind a fresh scheduling decision instead of being forced to continue under the
- // parser-step policy that was chosen *before* the hand-off changed script ownership.
- self.inner.take_buffered_input()
- }
-
- pub fn prepend_buffered_input(&mut self, input: String) {
- self.inner.prepend_buffered_input(input);
- }
-
- pub fn peek_buffered_input(&mut self) -> String {
- self.inner.peek_buffered_input()
- }
-
pub fn finish(self) -> NativeDom {
self.inner.finish()
}
@@ -927,10 +920,6 @@ impl DocumentStream {
pub fn finish_dom_host(self) -> DomHost {
self.inner.finish_dom_host()
}
-
- fn finish_dom_host_with_discovery_signals(self) -> (DomHost, ParserFinishDiscoverySignals) {
- self.inner.finish_dom_host_with_discovery_signals()
- }
}
struct RuntimeDomSinksParserStep<'a> {
@@ -945,6 +934,28 @@ impl RuntimeDomSinksParserStep<'_> {
fn pump_parser_inserted_step(&mut self, chunk: &str) -> ParserPumpOutcome {
self.stream.inner.pump_parser_inserted_step(chunk)
}
+
+ fn pump_next_parser_step(&mut self, max_bytes: usize) -> ParserPumpOutcome {
+ self.stream.pump_next_parser_step(max_bytes)
+ }
+}
+
+fn split_parser_input_prefix(input: String, max_bytes: usize) -> (String, Option<String>) {
+ if max_bytes == 0 || input.len() <= max_bytes {
+ return (input, None);
+ }
+
+ let mut split = input.len();
+ for (index, character) in input.char_indices() {
+ let end = index + character.len_utf8();
+ if end > max_bytes {
+ split = if index == 0 { end } else { index };
+ break;
+ }
+ }
+ let remainder = input[split..].to_owned();
+ let prefix = input[..split].to_owned();
+ (prefix, (!remainder.is_empty()).then_some(remainder))
}
impl Drop for RuntimeDomSinksParserStep<'_> {
@@ -1091,6 +1102,21 @@ impl ParserInputQueue {
.filter(|html| !html.is_empty())
}
+ pub fn next_script_input_len(&self) -> Option<usize> {
+ self.0.borrow().script_input_queue.front().map(String::len)
+ }
+
+ pub fn snapshot_script_input(&self) -> String {
+ self.0
+ .borrow()
+ .script_input_queue
+ .iter()
+ .fold(String::new(), |mut input, segment| {
+ input.push_str(segment);
+ input
+ })
+ }
+
pub fn has_script_input(&self) -> bool {
!self.0.borrow().script_input_queue.is_empty()
}
@@ -1108,39 +1134,6 @@ impl ParserInputQueue {
}
}
-fn collect_parser_document_handoffs_for_chunk(
- stream: &mut DocumentStream,
- chunk: &str,
- handoffs: &mut Vec<ParserDocumentHandoff>,
- blocking_stylesheet_inputs: &mut Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
-) {
- let mut pending_chunk = chunk;
- loop {
- let ParserPumpOutcome {
- result,
- discovered_modulepreload_link_candidates,
- discovered_blocking_stylesheet_inputs,
- ..
- } = stream.pump_parser_step(pending_chunk);
- blocking_stylesheet_inputs.extend(discovered_blocking_stylesheet_inputs);
- handoffs.extend(
- discovered_modulepreload_link_candidates
- .into_iter()
- .map(ParserDocumentHandoff::ModulepreloadLink),
- );
- match result {
- ParserPumpStep::Yield(ParserYield::Script(handoff)) => {
- handoffs.push(ParserDocumentHandoff::Script(handoff))
- }
- ParserPumpStep::Yield(
- ParserYield::CustomElementConstruction(_) | ParserYield::BlockingStylesheet(_),
- ) => {}
- ParserPumpStep::InputDrained => break,
- }
- pending_chunk = "";
- }
-}
-
impl ParserInputSession {
pub fn enqueue_script_input_html(&self, html: String) {
if html.is_empty() {
@@ -1674,13 +1667,9 @@ impl TreeSink for DocumentSink {
mod tests {
use std::rc::Rc;
- use super::{
- HtmlParser, ParseHandle, ParserDocumentHandoff, ParserInputQueue, ParserScriptHandoff,
- };
+ use super::{HtmlParser, ParseHandle, ParserInputQueue};
use html5ever::{LocalName, Namespace, QualName};
use moli_dom::native::{NativeDom, NativeNodeId};
- use moli_page_types::{ScriptKind, ScriptMode, ScriptSourceKind};
- use moli_stylesheet_blocking::DocumentBlockingStylesheetSignature;
use url::Url;
const HTML_NS: &str = "http://www.w3.org/1999/xhtml";
@@ -1733,8 +1722,8 @@ mod tests {
}
#[test]
- fn template_contents_do_not_publish_document_stylesheet_handoffs() {
- let (document, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
+ fn template_contents_do_not_publish_document_stylesheet_candidates() {
+ let document = HtmlParser.parse_dom_host(
Url::parse("https://template-styles.test/page.html").expect("test URL"),
concat!(
"<!doctype html>",
@@ -1745,12 +1734,6 @@ mod tests {
)
.to_owned(),
);
- let (_, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- assert!(
- blocking_stylesheet_inputs.is_empty(),
- "inert template contents must not publish main Document stylesheet blockers"
- );
assert!(
document
.stylesheet_candidate_handles_for_tree_scope(document.document_node_id())
@@ -1822,156 +1805,6 @@ mod tests {
);
}
- #[test]
- fn parse_dom_host_with_script_handoffs_reports_parser_blocking_classic_scripts() {
- let parser = HtmlParser;
- let (host, handoffs) = parser.parse_dom_host_with_script_handoffs(
- Url::parse("https://parser-handoff.test/page.html").expect("test url"),
- "<!doctype html><html><head><script>window.ran = true;</script></head><body><p>after</p></body></html>"
- .to_owned(),
- );
- let script_handles = host.dom().document_order_script_handles();
- assert_eq!(script_handles.len(), 1);
- assert_eq!(handoffs.len(), 1);
- let ParserScriptHandoff::BlockingClassic {
- node_id,
- start_line,
- script,
- ..
- } = &handoffs[0]
- else {
- panic!("inline parser classic script should produce a blocking classic handoff");
- };
- assert_eq!(*node_id, script_handles[0]);
- assert_eq!(*start_line, 1);
- assert_eq!(script.kind, ScriptKind::Classic);
- assert_eq!(script.mode, ScriptMode::Normal);
- assert_eq!(script.source_kind, ScriptSourceKind::Inline);
- assert!(
- host.dom().serialize_document().contains("<p>after</p>"),
- "parser should continue past the collected script handoff"
- );
- }
-
- #[test]
- fn parse_dom_host_with_document_handoffs_captures_stylesheet_inputs() {
- let (mut host, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
- Url::parse("https://parser-handoff.test/page.html").expect("test URL"),
- concat!(
- "<!doctype html><html><head>",
- "<link rel='stylesheet' href='/before.css'>",
- "<script defer src='/defer.js'></script>",
- "</head><body></body></html>",
- )
- .to_owned(),
- );
- let (script_handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- assert_eq!(script_handoffs.len(), 1);
- assert_eq!(blocking_stylesheet_inputs.len(), 1);
- assert!(matches!(
- blocking_stylesheet_inputs[0].signature(),
- DocumentBlockingStylesheetSignature::Link { url, .. }
- if url.as_str() == "https://parser-handoff.test/before.css"
- ));
- assert!(
- host.dom().serialize_document().contains("/before.css"),
- "document handoff collection must not consume the stylesheet node"
- );
- let link = host
- .elements_by_tag_name(host.document_handle(), "link", false)
- .into_iter()
- .next()
- .expect("parsed stylesheet link");
- let node = host.node(link).expect("parsed stylesheet link node");
- assert!(
- node.flags().parser_created(),
- "generic parser provenance remains available after tree construction"
- );
- assert!(
- !node
- .as_element()
- .is_some_and(moli_dom::native::Element::link_created_by_parser),
- "link-specific parser processing state must be consumed at FinishParsingChildren"
- );
- assert!(host.set_attribute(link, "href", "/dynamic.css"));
- assert!(
- moli_stylesheet_blocking::document_owned_blocking_stylesheet_candidate_for_node(
- &host,
- moli_dom::NodeId::new(link.index()),
- )
- .is_none(),
- "a dynamically reprocessed parser-created link must not become a new parser blocker"
- );
- }
-
- #[test]
- fn parse_dom_host_with_document_handoffs_captures_stylesheet_closed_by_eof() {
- let (_, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
- Url::parse("https://parser-handoff.test/page.html").expect("test URL"),
- "<!doctype html><body><style>@import url('/eof.css')".to_owned(),
- );
- let (_, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- assert_eq!(
- blocking_stylesheet_inputs
- .iter()
- .map(|input| input.signature())
- .collect::<Vec<_>>(),
- vec![
- &DocumentBlockingStylesheetSignature::ParserCreatedStyleImport {
- urls: vec![
- Url::parse("https://parser-handoff.test/eof.css").expect("stylesheet URL"),
- ],
- }
- ],
- "EOF tree-builder completion must publish its final captured parser blocker",
- );
- }
-
- #[test]
- fn parser_document_handoffs_preserve_script_and_modulepreload_token_order() {
- let (host, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
- Url::parse("https://parser-handoff.test/page.html").expect("test URL"),
- concat!(
- "<!doctype html><html><head>",
- "<script type='importmap'>{\"imports\": {}}</script>",
- "<link id='preload' rel='modulepreload' href='/dependency.mjs'>",
- "<script type='module' src='/entry.mjs'></script>",
- "</head><body></body></html>",
- )
- .to_owned(),
- );
- let preload = host
- .element_handle_by_id("preload")
- .expect("modulepreload link");
- let (ordered_handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- assert!(blocking_stylesheet_inputs.is_empty());
- assert_eq!(ordered_handoffs.len(), 3);
- let ParserDocumentHandoff::Script(import_map) = &ordered_handoffs[0] else {
- panic!("first handoff should be the import map");
- };
- assert!(matches!(
- import_map.as_ref(),
- ParserScriptHandoff::ImportMap { .. }
- ));
- assert!(matches!(
- ordered_handoffs[1],
- ParserDocumentHandoff::ModulepreloadLink(handle) if handle == preload
- ));
- let ParserDocumentHandoff::Script(module) = &ordered_handoffs[2] else {
- panic!("third handoff should be the module script");
- };
- assert!(matches!(
- module.as_ref(),
- ParserScriptHandoff::NonAsyncPostParse {
- script,
- ..
- } if script.kind == ScriptKind::Module
- ));
- }
-
#[test]
fn parser_input_session_keeps_insertion_preload_html_separate_from_script_input() {
let queue = ParserInputQueue::default();
diff --git a/moli-parser/src/lib.rs b/moli-parser/src/lib.rs
index c065abf96..5d8b8795c 100644
--- a/moli-parser/src/lib.rs
+++ b/moli-parser/src/lib.rs
@@ -10,6 +10,7 @@ mod session;
mod stream;
mod stylesheet_blocking;
mod xml;
+mod xml_stream;
mod xml_tree_viewer;
use std::collections::{HashMap, HashSet, VecDeque};
@@ -22,11 +23,10 @@ use moli_stylesheet_blocking::{
pub use html::{
DocumentStream, HtmlParser, ParserBlockingStylesheetPause,
- ParserCustomElementConstructionHandoff, ParserDocumentHandoff, ParserDocumentHandoffs,
- ParserFinishDiscoverySignals, ParserInputContext, ParserInputQueue, ParserInputSession,
- ParserPumpOutcome, ParserPumpStep, ParserScriptElementStateTransition, ParserScriptHandoff,
- ParserScriptNoExecutionOutcome, ParserScriptPreparationFailure, ParserStreamDocumentSnapshot,
- ParserYield,
+ ParserCustomElementConstructionHandoff, ParserFinishDiscoverySignals, ParserInputContext,
+ ParserInputQueue, ParserInputSession, ParserPumpOutcome, ParserPumpStep,
+ ParserScriptElementStateTransition, ParserScriptHandoff, ParserScriptNoExecutionOutcome,
+ ParserScriptPreparationFailure, ParserStreamDocumentSnapshot, ParserYield,
};
pub use live_target::{
ParserDomMutation, ParserDomMutationConsumer, ParserDomReadConsumer,
@@ -39,6 +39,7 @@ pub use script_planning::{
classify_parser_script,
};
pub use xml::XmlParser;
+pub use xml_stream::XmlDocumentStream;
const STREAM_CHUNK_BYTES: usize = 8 * 1024;
diff --git a/moli-parser/src/live_target.rs b/moli-parser/src/live_target.rs
index c0f94a4ee..5986ed1e9 100644
--- a/moli-parser/src/live_target.rs
+++ b/moli-parser/src/live_target.rs
@@ -59,6 +59,17 @@ impl ParserMutationEffectSink {
}
pub trait ParserDomReadConsumer {
+ /// Returns a read-only snapshot of the parser's current executable
+ /// Document when the embedding runtime can provide one.
+ ///
+ /// Most parser turns only need narrow node reads. The snapshot is reserved
+ /// for end-of-document algorithms, such as Chromium-compatible unstyled
+ /// XML presentation, which must inspect the complete tree before applying
+ /// mutations back through the live parser mutation sink.
+ fn snapshot_parser_document(&mut self) -> Option<NativeDom> {
+ None
+ }
+
fn node_exists(&mut self, node_id: NativeNodeId) -> bool;
fn is_connected(&mut self, node_id: NativeNodeId) -> bool;
@@ -140,6 +151,7 @@ pub trait ParserDomReadConsumer {
#[derive(Clone, Copy)]
struct ParserDomReadSink {
data: NonNull<()>,
+ snapshot_parser_document: unsafe fn(NonNull<()>) -> Option<NativeDom>,
node_exists: unsafe fn(NonNull<()>, NativeNodeId) -> bool,
is_connected: unsafe fn(NonNull<()>, NativeNodeId) -> bool,
is_text_node: unsafe fn(NonNull<()>, NativeNodeId) -> bool,
@@ -163,6 +175,14 @@ struct ParserDomReadSink {
impl ParserDomReadSink {
unsafe fn from_consumer_unchecked<T: ParserDomReadConsumer>(consumer: &mut T) -> Self {
+ unsafe fn snapshot_parser_document_impl<T: ParserDomReadConsumer>(
+ data: NonNull<()>,
+ ) -> Option<NativeDom> {
+ // SAFETY: ParserDomReadSink::from_consumer_unchecked requires the pointed-to
+ // consumer to remain live and exclusive for the pump step.
+ unsafe { data.cast::<T>().as_mut() }.snapshot_parser_document()
+ }
+
unsafe fn node_exists_impl<T: ParserDomReadConsumer>(
data: NonNull<()>,
node_id: NativeNodeId,
@@ -315,6 +335,7 @@ impl ParserDomReadSink {
Self {
data: NonNull::from(consumer).cast(),
+ snapshot_parser_document: snapshot_parser_document_impl::<T>,
node_exists: node_exists_impl::<T>,
is_connected: is_connected_impl::<T>,
is_text_node: is_text_node_impl::<T>,
@@ -337,6 +358,12 @@ impl ParserDomReadSink {
}
}
+ fn snapshot_parser_document(self) -> Option<NativeDom> {
+ // SAFETY: construction ties the raw pointer and callback to the same
+ // consumer remains live for the current parser operation.
+ unsafe { (self.snapshot_parser_document)(self.data) }
+ }
+
fn node_exists(self, node_id: NativeNodeId) -> bool {
// SAFETY: construction ties the raw pointer and callback to the same
// consumer remains live for the current runtime-DOM sink step.
@@ -520,6 +547,8 @@ pub trait ParserDomMutationConsumer {
fn create_processing_instruction(&mut self, target: String, data: String) -> NativeNodeId;
+ fn create_cdata_section(&mut self, data: String) -> NativeNodeId;
+
fn create_document_type(
&mut self,
name: String,
@@ -555,12 +584,13 @@ pub trait ParserDomMutationConsumer {
struct ParserDomMutationSink {
data: NonNull<()>,
apply: unsafe fn(NonNull<()>, ParserDomMutation),
- create_parser_element_without_attributes:
- unsafe fn(NonNull<()>, String, String, Option<String>) -> NativeNodeId,
+ create_parser_element_for_document_without_attributes:
+ unsafe fn(NonNull<()>, NativeNodeId, String, String, Option<String>) -> NativeNodeId,
add_attrs_if_missing_for_parser: unsafe fn(NonNull<()>, NativeNodeId, Vec<NativeAttribute>),
create_text_node: unsafe fn(NonNull<()>, String) -> NativeNodeId,
create_comment: unsafe fn(NonNull<()>, String) -> NativeNodeId,
create_processing_instruction: unsafe fn(NonNull<()>, String, String) -> NativeNodeId,
+ create_cdata_section: unsafe fn(NonNull<()>, String) -> NativeNodeId,
create_document_type: unsafe fn(NonNull<()>, String, String, String) -> NativeNodeId,
prepend_text_to_text_node: unsafe fn(NonNull<()>, NativeNodeId, String),
append_text_to_text_node: unsafe fn(NonNull<()>, NativeNodeId, String),
@@ -584,8 +614,11 @@ impl ParserDomMutationSink {
// pointed-to consumer to remain live and exclusive for the pump step.
unsafe { data.cast::<T>().as_mut() }.apply_parser_dom_mutation(mutation);
}
- unsafe fn create_parser_element_without_attributes_impl<T: ParserDomMutationConsumer>(
+ unsafe fn create_parser_element_for_document_without_attributes_impl<
+ T: ParserDomMutationConsumer,
+ >(
data: NonNull<()>,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
@@ -593,7 +626,12 @@ impl ParserDomMutationSink {
// SAFETY: ParserDomMutationSink::from_consumer_unchecked requires the
// pointed-to consumer to remain live and exclusive for the pump step.
unsafe { data.cast::<T>().as_mut() }
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ .create_parser_element_for_document_without_attributes(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
unsafe fn add_attrs_if_missing_for_parser_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
@@ -629,6 +667,14 @@ impl ParserDomMutationSink {
// pointed-to consumer to remain live and exclusive for the pump step.
unsafe { data.cast::<T>().as_mut() }.create_processing_instruction(target, data_text)
}
+ unsafe fn create_cdata_section_impl<T: ParserDomMutationConsumer>(
+ data: NonNull<()>,
+ cdata: String,
+ ) -> NativeNodeId {
+ // SAFETY: ParserDomMutationSink::from_consumer_unchecked requires the
+ // pointed-to consumer to remain live and exclusive for the pump step.
+ unsafe { data.cast::<T>().as_mut() }.create_cdata_section(cdata)
+ }
unsafe fn create_document_type_impl<T: ParserDomMutationConsumer>(
data: NonNull<()>,
name: String,
@@ -724,13 +770,13 @@ impl ParserDomMutationSink {
Self {
data: NonNull::from(consumer).cast(),
apply: apply_impl::<T>,
- create_parser_element_without_attributes: create_parser_element_without_attributes_impl::<
- T,
- >,
+ create_parser_element_for_document_without_attributes:
+ create_parser_element_for_document_without_attributes_impl::<T>,
add_attrs_if_missing_for_parser: add_attrs_if_missing_for_parser_impl::<T>,
create_text_node: create_text_node_impl::<T>,
create_comment: create_comment_impl::<T>,
create_processing_instruction: create_processing_instruction_impl::<T>,
+ create_cdata_section: create_cdata_section_impl::<T>,
create_document_type: create_document_type_impl::<T>,
prepend_text_to_text_node: prepend_text_to_text_node_impl::<T>,
append_text_to_text_node: append_text_to_text_node_impl::<T>,
@@ -750,8 +796,9 @@ impl ParserDomMutationSink {
unsafe { (self.apply)(self.data, mutation) };
}
- fn create_parser_element_without_attributes(
+ fn create_parser_element_for_document_without_attributes(
self,
+ document_handle: NativeNodeId,
local_name: String,
namespace: String,
prefix: Option<String>,
@@ -759,8 +806,12 @@ impl ParserDomMutationSink {
// SAFETY: construction ties the raw pointer and callback to the same
// consumer remains live for the current runtime-DOM sink step.
unsafe {
- (self.create_parser_element_without_attributes)(
- self.data, local_name, namespace, prefix,
+ (self.create_parser_element_for_document_without_attributes)(
+ self.data,
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
)
}
}
@@ -789,6 +840,12 @@ impl ParserDomMutationSink {
unsafe { (self.create_processing_instruction)(self.data, target, data) }
}
+ fn create_cdata_section(self, data: String) -> NativeNodeId {
+ // SAFETY: construction ties the raw pointer and callback to the same
+ // consumer remains live for the current runtime-DOM sink step.
+ unsafe { (self.create_cdata_section)(self.data, data) }
+ }
+
fn create_document_type(
self,
name: String,
@@ -1322,6 +1379,12 @@ impl ParserDomMutationConsumer for TestMutationEffectCollector<'_> {
unsafe { &mut *self.host }.create_processing_instruction(&target, &data)
}
+ fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ // SAFETY: tests keep the borrowed DomHost pointer alive and route the
+ // parser pump through this collector for the duration of the step.
+ unsafe { &mut *self.host }.create_cdata_section(&data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -1656,6 +1719,12 @@ impl ParserDomMutationConsumer for TestReadTrackingCollector<'_> {
unsafe { &mut *self.host }.create_processing_instruction(&target, &data)
}
+ fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ // SAFETY: tests keep the borrowed DomHost pointer alive and route the
+ // parser pump through this collector for the duration of the step.
+ unsafe { &mut *self.host }.create_cdata_section(&data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -1847,7 +1916,44 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
+ pub(super) fn new_xml(final_url: Url) -> Self {
+ let dom_host = DomHost::from_dom(NativeDom::new_xml(final_url.clone()));
+ let document_handle = dom_host.document_handle();
+ Self {
+ owned_dom_host: Some(dom_host),
+ parser_document_handle: Some(document_handle),
+ parser_document_url: Some(final_url),
+ runtime_dom_sinks: None,
+ next_insertion_is_template_contents: false,
+ open_template_element_depth: 0,
+ pending_open_parser_element: None,
+ open_parser_elements: Vec::new(),
+ allow_declarative_shadow_roots: false,
+ pending_null_custom_element_registry_elements: Vec::new(),
+ state: HtmlTreeSinkState::default(),
+ }
+ }
+
pub(super) fn new_live_document_root(final_url: Url, document_handle: NativeNodeId) -> Self {
+ Self::new_live_document_root_with_declarative_shadow_roots(final_url, document_handle, true)
+ }
+
+ pub(super) fn new_live_xml_document_root(
+ final_url: Url,
+ document_handle: NativeNodeId,
+ ) -> Self {
+ Self::new_live_document_root_with_declarative_shadow_roots(
+ final_url,
+ document_handle,
+ false,
+ )
+ }
+
+ fn new_live_document_root_with_declarative_shadow_roots(
+ final_url: Url,
+ document_handle: NativeNodeId,
+ allow_declarative_shadow_roots: bool,
+ ) -> Self {
Self {
owned_dom_host: None,
parser_document_handle: Some(document_handle),
@@ -1857,7 +1963,7 @@ impl ParserStreamHtmlTreeSinkTarget {
open_template_element_depth: 0,
pending_open_parser_element: None,
open_parser_elements: Vec::new(),
- allow_declarative_shadow_roots: true,
+ allow_declarative_shadow_roots,
pending_null_custom_element_registry_elements: Vec::new(),
state: HtmlTreeSinkState::default(),
}
@@ -1912,6 +2018,14 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
+ pub(super) fn snapshot_current_parser_document(&self) -> Option<NativeDom> {
+ if let Some(owner) = &self.runtime_dom_sinks {
+ owner.dom_read_sink().snapshot_parser_document()
+ } else {
+ Some(self.dom_host().snapshot_document())
+ }
+ }
+
fn read_is_connected(&self, node_id: NativeNodeId) -> bool {
if let Some(owner) = &self.runtime_dom_sinks {
owner.dom_read_sink().is_connected(node_id)
@@ -2045,7 +2159,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- fn parser_document_node_id(&self) -> NativeNodeId {
+ pub(super) fn parser_document_node_id(&self) -> NativeNodeId {
self.parser_document_handle
.expect("parser stream should record its parser document/root handle")
}
@@ -2170,6 +2284,16 @@ impl ParserStreamHtmlTreeSinkTarget {
self.mutation_effect_delivery(effects)
}
+ pub(super) fn append_existing_node(&mut self, parent: NativeNodeId, child: NativeNodeId) {
+ self.record_parser_dom_mutation(ParserDomMutation::AppendChild { parent, child })
+ .consume();
+ }
+
+ pub(super) fn remove_existing_node(&mut self, parent: NativeNodeId, child: NativeNodeId) {
+ self.record_parser_dom_mutation(ParserDomMutation::RemoveChild { parent, child })
+ .consume();
+ }
+
fn note_parser_element_appended(&mut self, handle: &ParseHandle) {
let Some(node_id) = handle.dom_node_id() else {
return;
@@ -2344,23 +2468,34 @@ impl ParserStreamHtmlTreeSinkTarget {
svg_script.then_some(node_id)
}
- fn create_parser_element_without_attributes(
+ pub(super) fn create_parser_element_without_attributes(
&mut self,
local_name: String,
namespace: String,
prefix: Option<String>,
) -> NativeNodeId {
+ let document_handle = self.parser_document_node_id();
if let Some(owner) = &self.runtime_dom_sinks {
owner
.dom_mutation_sink()
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ .create_parser_element_for_document_without_attributes(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
} else {
self.dom_host_mut()
- .create_parser_element_without_attributes(local_name, namespace, prefix)
+ .create_parser_element_without_attributes_for_document(
+ document_handle,
+ local_name,
+ namespace,
+ prefix,
+ )
}
}
- fn add_attrs_if_missing_for_parser(
+ pub(super) fn add_attrs_if_missing_for_parser(
&mut self,
node_id: NativeNodeId,
attrs: Vec<NativeAttribute>,
@@ -2375,7 +2510,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- fn create_text_node(&mut self, text: String) -> NativeNodeId {
+ pub(super) fn create_text_node(&mut self, text: String) -> NativeNodeId {
if let Some(owner) = &self.runtime_dom_sinks {
owner.dom_mutation_sink().create_text_node(text)
} else {
@@ -2383,7 +2518,7 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- fn create_comment_node(&mut self, text: String) -> NativeNodeId {
+ pub(super) fn create_comment_node(&mut self, text: String) -> NativeNodeId {
if let Some(owner) = &self.runtime_dom_sinks {
owner.dom_mutation_sink().create_comment(text)
} else {
@@ -2391,7 +2526,11 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- fn create_processing_instruction_node(&mut self, target: String, data: String) -> NativeNodeId {
+ pub(super) fn create_processing_instruction_node(
+ &mut self,
+ target: String,
+ data: String,
+ ) -> NativeNodeId {
if let Some(owner) = &self.runtime_dom_sinks {
owner
.dom_mutation_sink()
@@ -2402,7 +2541,17 @@ impl ParserStreamHtmlTreeSinkTarget {
}
}
- fn create_document_type_node(
+ pub(super) fn create_cdata_section_node(&mut self, data: String) -> NativeNodeId {
+ let document_handle = self.parser_document_node_id();
+ if let Some(owner) = &self.runtime_dom_sinks {
+ owner.dom_mutation_sink().create_cdata_section(data)
+ } else {
+ self.dom_host_mut()
+ .create_cdata_section_for_document(document_handle, &data)
+ }
+ }
+
+ pub(super) fn create_document_type_node(
&mut self,
name: String,
public_id: String,
@@ -2892,6 +3041,10 @@ impl ParserStreamHtmlTreeSinkTarget {
ParseHandle::new(self.create_processing_instruction_node(target, data), None)
}
+ pub(super) fn create_cdata_section(&mut self, data: String) -> ParseHandle {
+ ParseHandle::new(self.create_cdata_section_node(data), None)
+ }
+
pub(super) fn append(
&mut self,
parent_id: NativeNodeId,
diff --git a/moli-parser/src/session.rs b/moli-parser/src/session.rs
index eef091ebf..c55e32bca 100644
--- a/moli-parser/src/session.rs
+++ b/moli-parser/src/session.rs
@@ -24,6 +24,7 @@ pub(super) struct HtmlTreeSinkSession {
pub(super) struct HtmlParserSession {
tokenizer: Tokenizer<EmbedderPausingTreeBuilder>,
input_buffer: BufferQueue,
+ suspended_input_buffers: Vec<BufferQueue>,
}
struct EmbedderPausingTreeBuilder {
@@ -132,6 +133,7 @@ impl HtmlParserSession {
Self {
tokenizer: Tokenizer::new(tree_builder, opts.tokenizer),
input_buffer: BufferQueue::default(),
+ suspended_input_buffers: Vec::new(),
}
}
@@ -154,6 +156,7 @@ impl HtmlParserSession {
Self {
tokenizer: Tokenizer::new(tree_builder, tokenizer_options),
input_buffer: BufferQueue::default(),
+ suspended_input_buffers: Vec::new(),
}
}
@@ -171,24 +174,63 @@ impl HtmlParserSession {
self.input_buffer.push_back(input);
}
- pub(super) fn push_inserted_back(&mut self, input: StrTendril) {
+ pub(super) fn begin_inserted_input(&mut self, input: StrTendril) {
+ if input.is_empty() {
+ return;
+ }
// Without segment provenance from html5ever, any later token can span
- // inserted input and the original tail. Prefer permanent unknown
- // locations over reporting plausible but incorrect document lines.
+ // inserted input and the original tail after this insertion frame is
+ // restored. Prefer permanent unknown locations over reporting
+ // plausible but incorrect document lines.
self.tokenizer.sink.sink().mark_source_positions_unknown();
+ let parent = std::mem::take(&mut self.input_buffer);
+ self.suspended_input_buffers.push(parent);
self.input_buffer.push_back(input);
}
- pub(super) fn push_front(&mut self, input: StrTendril) {
- self.input_buffer.push_front(input);
+ pub(super) fn has_buffered_input(&self) -> bool {
+ !self.input_buffer.is_empty()
+ || self
+ .suspended_input_buffers
+ .iter()
+ .any(|input| !input.is_empty())
}
- pub(super) fn pop_front(&mut self) -> Option<StrTendril> {
- self.input_buffer.pop_front()
+ pub(super) fn buffered_input_len(&self) -> usize {
+ let mut len = 0usize;
+ for input in
+ std::iter::once(&self.input_buffer).chain(self.suspended_input_buffers.iter().rev())
+ {
+ let input = input.clone();
+ while let Some(chunk) = input.pop_front() {
+ len = len.saturating_add(chunk.len());
+ }
+ }
+ len
}
- pub(super) fn feed(&self) -> TokenizerResult<ParseHandle> {
- self.tokenizer.feed(&self.input_buffer)
+ pub(super) fn snapshot_buffered_input(&self) -> String {
+ let mut buffered = String::new();
+ for input in
+ std::iter::once(&self.input_buffer).chain(self.suspended_input_buffers.iter().rev())
+ {
+ let input = input.clone();
+ while let Some(chunk) = input.pop_front() {
+ buffered.push_str(&chunk);
+ }
+ }
+ buffered
+ }
+
+ pub(super) fn feed(&mut self) -> TokenizerResult<ParseHandle> {
+ let result = self.tokenizer.feed(&self.input_buffer);
+ if matches!(result, TokenizerResult::Done)
+ && self.input_buffer.is_empty()
+ && let Some(parent) = self.suspended_input_buffers.pop()
+ {
+ self.input_buffer = parent;
+ }
+ result
}
pub(super) fn sink(&self) -> &DocumentSink {
@@ -198,8 +240,10 @@ impl HtmlParserSession {
pub(super) fn finish(self) -> ParserStreamHtmlTreeSinkTarget {
let Self {
tokenizer,
- input_buffer,
+ mut input_buffer,
+ mut suspended_input_buffers,
} = self;
+ restore_all_suspended_input(&mut input_buffer, &mut suspended_input_buffers);
while let TokenizerResult::Script(_) = tokenizer.feed(&input_buffer) {
tokenizer
.sink
@@ -219,8 +263,10 @@ impl HtmlParserSession {
pub(super) fn finish_live_runtime_dom_sink_parser(self) -> ParserFinishDiscoverySignals {
let Self {
tokenizer,
- input_buffer,
+ mut input_buffer,
+ mut suspended_input_buffers,
} = self;
+ restore_all_suspended_input(&mut input_buffer, &mut suspended_input_buffers);
while let TokenizerResult::Script(_) = tokenizer.feed(&input_buffer) {
tokenizer
.sink
@@ -259,6 +305,17 @@ impl HtmlParserSession {
}
}
+fn restore_all_suspended_input(
+ input_buffer: &mut BufferQueue,
+ suspended_input_buffers: &mut Vec<BufferQueue>,
+) {
+ while let Some(parent) = suspended_input_buffers.pop() {
+ while let Some(chunk) = parent.pop_front() {
+ input_buffer.push_back(chunk);
+ }
+ }
+}
+
pub(super) fn new_html_tree_sink_session(
target: ParserStreamHtmlTreeSinkTarget,
) -> HtmlTreeSinkSession {
diff --git a/moli-parser/src/stream.rs b/moli-parser/src/stream.rs
index 6db8e281e..26a0f1ffc 100644
--- a/moli-parser/src/stream.rs
+++ b/moli-parser/src/stream.rs
@@ -474,6 +474,14 @@ impl HtmlTreeSinkStream {
self.script_input.take_next_script_input()
}
+ pub fn next_script_input_len(&self) -> Option<usize> {
+ self.script_input.next_script_input_len()
+ }
+
+ pub fn snapshot_script_input(&self) -> String {
+ self.script_input.snapshot_script_input()
+ }
+
pub fn has_script_input(&self) -> bool {
self.script_input.has_script_input()
}
@@ -499,6 +507,14 @@ impl HtmlTreeSinkStream {
}
pub fn pump_parser_inserted_step(&mut self, chunk: &str) -> ParserPumpOutcome {
+ if chunk.is_empty() {
+ return ParserPumpOutcome {
+ result: ParserPumpStep::InputDrained,
+ discovered_async_prefetch_scripts: Vec::new(),
+ discovered_modulepreload_link_candidates: Vec::new(),
+ discovered_blocking_stylesheet_inputs: Vec::new(),
+ };
+ }
self.pump_parser_step_with_source(chunk, true)
}
@@ -509,7 +525,7 @@ impl HtmlTreeSinkStream {
) -> ParserPumpOutcome {
if !chunk.is_empty() {
if inserted_source {
- self.parser.push_inserted_back(StrTendril::from(chunk));
+ self.parser.begin_inserted_input(StrTendril::from(chunk));
} else {
self.parser.push_back(StrTendril::from(chunk));
}
@@ -799,32 +815,16 @@ impl HtmlTreeSinkStream {
self.parser.sink().mark_script_already_started(node_id);
}
- pub fn take_buffered_input(&mut self) -> String {
- let mut buffered = String::new();
- while let Some(chunk) = self.parser.pop_front() {
- buffered.push_str(&chunk);
- }
- buffered
+ pub fn has_buffered_input(&self) -> bool {
+ self.parser.has_buffered_input()
}
- pub fn prepend_buffered_input(&mut self, input: String) {
- if input.is_empty() {
- return;
- }
- self.parser.push_front(StrTendril::from(input));
+ pub fn buffered_input_len(&self) -> usize {
+ self.parser.buffered_input_len()
}
- pub fn peek_buffered_input(&mut self) -> String {
- let mut buffered = String::new();
- let mut drained = Vec::new();
- while let Some(chunk) = self.parser.pop_front() {
- buffered.push_str(&chunk);
- drained.push(chunk);
- }
- for chunk in drained {
- self.parser.push_back(chunk);
- }
- buffered
+ pub fn snapshot_buffered_input(&self) -> String {
+ self.parser.snapshot_buffered_input()
}
pub fn finish(self) -> NativeDom {
@@ -1051,6 +1051,11 @@ mod tests {
unsafe { &mut *self.host }.create_processing_instruction(&target, &data)
}
+ fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ // SAFETY: the test keeps the DomHost alive for this parser pump step.
+ unsafe { &mut *self.host }.create_cdata_section(&data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -1636,8 +1641,6 @@ mod tests {
outer.result,
ParserPumpStep::Yield(ParserYield::Script(_))
));
- let original_tail = stream.take_buffered_input();
-
let inserted = stream.pump_parser_inserted_step("\n <script>inserted()</script>\n");
let ParserPumpStep::Yield(ParserYield::Script(handoff)) = inserted.result else {
panic!("expected inserted parser script handoff");
@@ -1653,10 +1656,9 @@ mod tests {
assert_eq!((start_line, start_column), (0, 0));
assert!(matches!(
- stream.pump_parser_inserted_step("").result,
+ stream.pump_parser_step("").result,
ParserPumpStep::InputDrained
));
- stream.prepend_buffered_input(original_tail);
let original = stream.pump_parser_step("");
let ParserPumpStep::Yield(ParserYield::Script(handoff)) = original.result else {
@@ -1686,13 +1688,10 @@ mod tests {
outer.result,
ParserPumpStep::Yield(ParserYield::Script(_))
));
- let original_tail = stream.take_buffered_input();
-
assert!(matches!(
stream.pump_parser_inserted_step("<scr").result,
ParserPumpStep::InputDrained
));
- stream.prepend_buffered_input(original_tail);
let cross_source = stream.pump_parser_step("");
let ParserPumpStep::Yield(ParserYield::Script(handoff)) = cross_source.result else {
@@ -1790,13 +1789,10 @@ mod tests {
outer.result,
ParserPumpStep::Yield(ParserYield::Script(_))
));
- let original_tail = stream.take_buffered_input();
-
assert!(matches!(
stream.pump_parser_inserted_step("").result,
ParserPumpStep::InputDrained
));
- stream.prepend_buffered_input(original_tail);
let original = stream.pump_parser_step("");
let ParserPumpStep::Yield(ParserYield::Script(handoff)) = original.result else {
diff --git a/moli-parser/src/stylesheet_blocking.rs b/moli-parser/src/stylesheet_blocking.rs
index 5414dc9ee..4aefcae94 100644
--- a/moli-parser/src/stylesheet_blocking.rs
+++ b/moli-parser/src/stylesheet_blocking.rs
@@ -62,7 +62,7 @@ mod tests {
document_owned_blocking_stylesheet_candidate_for_node, preload_like_link_loads_stylesheet,
stylesheet_link_disposition,
};
- use crate::HtmlParser;
+ use crate::{HtmlParser, ParserPumpStep};
use moli_dom::native::Node;
#[test]
@@ -95,12 +95,21 @@ mod tests {
#[test]
fn parser_created_link_blocker_is_captured_before_link_processing_state_is_consumed() {
let parser = HtmlParser;
- let (document, handoffs) = parser.parse_dom_host_with_document_handoffs(
- url::Url::parse("https://example.com/").unwrap(),
+ let mut stream = parser.start_document(url::Url::parse("https://example.com/").unwrap());
+ stream.append_to_end(
"<!doctype html><html><head><link rel=stylesheet href='/slow.css'><script>window.x = 1;</script></head></html>".to_owned(),
);
+ let mut captured_blockers = Vec::new();
+ while stream.has_pending_input() {
+ let outcome = stream.pump_next_parser_step(0);
+ captured_blockers.extend(outcome.discovered_blocking_stylesheet_inputs);
+ if matches!(outcome.result, ParserPumpStep::InputDrained) && !stream.has_pending_input()
+ {
+ break;
+ }
+ }
+ let document = stream.finish();
let script = document.script_handles()[0];
- let (_, captured_blockers) = handoffs.into_parts();
let blockers = collect_document_owned_blocking_stylesheet_nodes_before(
&document,
diff --git a/moli-parser/src/xml.rs b/moli-parser/src/xml.rs
index 75b45cf83..49fc02299 100644
--- a/moli-parser/src/xml.rs
+++ b/moli-parser/src/xml.rs
@@ -18,20 +18,11 @@ use xmlparser::{
ElementEnd as XmlElementEnd, Token as XmlTokenizerToken, Tokenizer as XmlTokenizer,
};
+use super::{html_chunks, xml_tree_viewer::transform_document_to_xml_tree_view};
use moli_dom::native::{Attribute as NativeAttribute, DomHost, NativeDom, NativeNodeId, Node};
-use moli_stylesheet_blocking::{
- DocumentOwnedBlockingStylesheetDiscoveryInput, collect_document_owned_blocking_stylesheets,
- link_rel_includes_token,
-};
-
-use super::{
- ParserDocumentHandoff, ParserDocumentHandoffs, html_chunks,
- stream::prepare_parser_script_handoff_for_static_document,
- xml_tree_viewer::transform_document_to_xml_tree_view,
-};
-const CDATA_MARKER_PI_TARGET: &str = "moli-cdata";
-const XMLNS_NAMESPACE: &str = "http://www.w3.org/2000/xmlns/";
+pub(super) const CDATA_MARKER_PI_TARGET: &str = "moli-cdata";
+pub(super) const XMLNS_NAMESPACE: &str = "http://www.w3.org/2000/xmlns/";
#[derive(Debug, Clone, Default)]
pub struct XmlParser;
@@ -77,68 +68,32 @@ struct XmlLiveTreeSinkTarget<'a> {
document_handle: NativeNodeId,
cdata_sections: Vec<String>,
namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
- ordered_runtime_handoffs: Vec<XmlParserRuntimeHandoff>,
source_has_unclosed_element_at_eof: bool,
}
-struct XmlNamespaceDeclaration {
- ordinary_attributes_before: usize,
- attribute: NativeAttribute,
-}
-
-#[derive(Clone, Copy)]
-enum XmlParserRuntimeHandoff {
- Script(NativeNodeId),
- ModulepreloadLink(NativeNodeId),
+pub(super) struct XmlNamespaceDeclaration {
+ pub(super) ordinary_attributes_before: usize,
+ pub(super) attribute: NativeAttribute,
}
impl XmlParser {
pub fn parse(&self, final_url: Url, xml: String) -> NativeDom {
- self.parse_with_script_handoffs(final_url, xml).0
- }
-
- pub fn parse_with_script_handoffs(
- &self,
- final_url: Url,
- xml: String,
- ) -> (NativeDom, Vec<super::ParserScriptHandoff>) {
- let (document, handoffs) = self.parse_with_document_handoffs(final_url, xml);
- let (ordered_handoffs, _) = handoffs.into_parts();
- let script_handoffs = ordered_handoffs
- .into_iter()
- .filter_map(|handoff| match handoff {
- ParserDocumentHandoff::Script(script) => Some(*script),
- ParserDocumentHandoff::ModulepreloadLink(_) => None,
- })
- .collect();
- (document, script_handoffs)
- }
-
- pub fn parse_with_document_handoffs(
- &self,
- final_url: Url,
- xml: String,
- ) -> (NativeDom, ParserDocumentHandoffs) {
- self.parse_with_document_handoffs_and_presentation(final_url, xml, false)
+ self.parse_with_presentation(final_url, xml, false)
}
/// Parses a top-level XML navigation and applies Chromium's source-tree
/// presentation when the document has no associated style information.
/// DOMParser and child-document callers must use the raw parser entry point.
- pub fn parse_top_level_document_with_handoffs(
- &self,
- final_url: Url,
- xml: String,
- ) -> (NativeDom, ParserDocumentHandoffs) {
- self.parse_with_document_handoffs_and_presentation(final_url, xml, true)
+ pub fn parse_top_level_document(&self, final_url: Url, xml: String) -> NativeDom {
+ self.parse_with_presentation(final_url, xml, true)
}
- fn parse_with_document_handoffs_and_presentation(
+ fn parse_with_presentation(
&self,
final_url: Url,
xml: String,
present_unstyled_xml: bool,
- ) -> (NativeDom, ParserDocumentHandoffs) {
+ ) -> NativeDom {
let source_has_unclosed_element_at_eof = xml_source_has_unclosed_element_at_eof(&xml);
let namespace_declarations = xml_namespace_declarations(&xml);
let (xml, cdata_sections) = xml_with_cdata_markers(&xml);
@@ -152,45 +107,25 @@ impl XmlParser {
for chunk in html_chunks(&xml) {
parser.process(XmlStrTendril::from(chunk));
}
- let (mut document, ordered_runtime_handoffs) = parser.finish().finish_document();
+ let mut document = parser.finish().finish_document();
if present_unstyled_xml {
document = transform_document_to_xml_tree_view(document);
}
- let ordered_handoffs = ordered_runtime_handoffs
- .into_iter()
- .map(|handoff| match handoff {
- XmlParserRuntimeHandoff::Script(node_id) => {
- ParserDocumentHandoff::Script(Box::new(
- prepare_parser_script_handoff_for_static_document(&document, node_id, 1, 0),
- ))
- }
- XmlParserRuntimeHandoff::ModulepreloadLink(node_id) => {
- ParserDocumentHandoff::ModulepreloadLink(node_id)
- }
- })
- .collect();
- let blocking_stylesheet_inputs = collect_document_owned_blocking_stylesheets(&document)
- .iter()
- .map(DocumentOwnedBlockingStylesheetDiscoveryInput::from)
- .collect();
- (
- document,
- ParserDocumentHandoffs::new(ordered_handoffs, blocking_stylesheet_inputs),
- )
+ document
}
- /// Parses an XML tree directly into an empty XML Document that already
- /// belongs to `dom_host`.
+ /// Parses an inert XML tree directly into an empty XML Document that
+ /// already belongs to `dom_host`.
///
/// The mutable borrow is retained by the tree sink for exactly this
- /// synchronous parser call. Returned script handles are discovery facts;
- /// the caller remains responsible for parser-script ordering and execution.
- pub fn parse_tree_into_document(
+ /// synchronous parser call. Script elements remain inert; executable
+ /// top-level and child Documents must use `XmlDocumentStream` instead.
+ pub fn parse_inert_tree_into_document(
&self,
dom_host: &mut DomHost,
document_handle: NativeNodeId,
xml: &str,
- ) -> Option<Vec<NativeNodeId>> {
+ ) -> Option<()> {
let source_has_unclosed_element_at_eof = xml_source_has_unclosed_element_at_eof(xml);
let namespace_declarations = xml_namespace_declarations(xml);
let target = XmlLiveTreeSinkTarget::new_borrowed(dom_host, document_handle)?
@@ -202,7 +137,8 @@ impl XmlParser {
for chunk in html_chunks(&xml) {
parser.process(XmlStrTendril::from(chunk));
}
- Some(parser.finish().finish_live_tree())
+ parser.finish().finish_live_tree();
+ Some(())
}
}
@@ -210,7 +146,7 @@ impl XmlParser {
// on EOF and therefore does not report a still-open element. Keep this check
// deliberately narrower than a second well-formedness parser: tokenizer errors
// and mismatched tags defer to xml5ever's own parse-error reporting.
-fn xml_source_has_unclosed_element_at_eof(source: &str) -> bool {
+pub(super) fn xml_source_has_unclosed_element_at_eof(source: &str) -> bool {
let mut open_elements = Vec::<(String, String)>::new();
let mut pending_element = None::<(String, String)>;
@@ -300,7 +236,7 @@ fn xml_with_cdata_markers(xml: &str) -> (String, Vec<String>) {
/// however, exposes `xmlns` declarations as Attr nodes in the XMLNS namespace.
/// Capture them in element-creation order and merge them at the tree-sink
/// boundary.
-fn xml_namespace_declarations(xml: &str) -> VecDeque<Vec<XmlNamespaceDeclaration>> {
+pub(super) fn xml_namespace_declarations(xml: &str) -> VecDeque<Vec<XmlNamespaceDeclaration>> {
let mut declarations = VecDeque::new();
let mut current = None::<(usize, Vec<XmlNamespaceDeclaration>)>;
@@ -436,18 +372,17 @@ impl XmlLiveTreeSinkTarget<'static> {
document_handle,
cdata_sections,
namespace_declarations,
- ordered_runtime_handoffs: Vec::new(),
source_has_unclosed_element_at_eof,
}
}
- fn finish_document(mut self) -> (NativeDom, Vec<XmlParserRuntimeHandoff>) {
+ fn finish_document(mut self) -> NativeDom {
self.record_unclosed_source_element_error();
self.restore_cdata_marker_processing_instructions();
let XmlDomHost::Owned(dom_host) = self.dom_host else {
unreachable!("owned XML parsing must finish with an owned DOM host")
};
- (dom_host.snapshot_document(), self.ordered_runtime_handoffs)
+ dom_host.snapshot_document()
}
}
@@ -466,7 +401,6 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
document_handle,
cdata_sections: Vec::new(),
namespace_declarations: VecDeque::new(),
- ordered_runtime_handoffs: Vec::new(),
source_has_unclosed_element_at_eof: false,
})
}
@@ -492,16 +426,9 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
self
}
- fn finish_live_tree(mut self) -> Vec<NativeNodeId> {
+ fn finish_live_tree(mut self) {
self.record_unclosed_source_element_error();
self.restore_cdata_marker_processing_instructions();
- self.ordered_runtime_handoffs
- .into_iter()
- .filter_map(|handoff| match handoff {
- XmlParserRuntimeHandoff::Script(node_id) => Some(node_id),
- XmlParserRuntimeHandoff::ModulepreloadLink(_) => None,
- })
- .collect()
}
fn record_unclosed_source_element_error(&mut self) {
@@ -556,27 +483,6 @@ impl<'a> XmlLiveTreeSinkTarget<'a> {
);
self.dom_host
.add_attrs_if_missing_for_parser(node_id, attributes);
- if self
- .dom_host
- .node(node_id)
- .is_some_and(|node| node.is_html_element_named("script"))
- {
- self.ordered_runtime_handoffs
- .push(XmlParserRuntimeHandoff::Script(node_id));
- } else if self
- .dom_host
- .node(node_id)
- .and_then(Node::as_element)
- .is_some_and(|element| {
- element.is_html_element("link")
- && element
- .attribute("rel")
- .is_some_and(|rel| link_rel_includes_token(rel, "modulepreload"))
- })
- {
- self.ordered_runtime_handoffs
- .push(XmlParserRuntimeHandoff::ModulepreloadLink(node_id));
- }
XmlParseHandle::new(node_id, Some(element_name))
}
@@ -978,9 +884,7 @@ impl<'host> XmlTreeSink for XmlDocumentSink<'host> {
#[cfg(test)]
mod tests {
use super::{XmlParser, xml_source_has_unclosed_element_at_eof};
- use crate::ParserScriptHandoff;
use moli_dom::native::{DomHost, NativeDom, NativeNodeId, Node, NodeType};
- use moli_page_types::ScriptMode;
use url::Url;
#[test]
@@ -1061,8 +965,8 @@ mod tests {
let child_url = Url::parse("https://child.example.test/document.xml").unwrap();
let child_document = host.create_detached_xml_document_with_url(child_url.clone());
- let script_handles = parser
- .parse_tree_into_document(
+ parser
+ .parse_inert_tree_into_document(
&mut host,
child_document,
concat!(
@@ -1074,12 +978,21 @@ mod tests {
"</root>"
),
)
- .expect("empty XML document accepts a direct parse");
+ .expect("empty XML document accepts a direct inert parse");
assert_eq!(host.child_handles(parent_document).count(), 0);
- assert_eq!(script_handles.len(), 1);
+ let mut descendants = Vec::new();
+ collect_descendants(&host, child_document, &mut descendants);
+ let script_handle = descendants
+ .iter()
+ .copied()
+ .find(|node_id| {
+ host.node(*node_id)
+ .is_some_and(|node| node.is_html_element_named("script"))
+ })
+ .expect("XHTML script element");
assert_eq!(
- host.node(script_handles[0]).and_then(Node::owner_document),
+ host.node(script_handle).and_then(Node::owner_document),
Some(child_document)
);
assert_eq!(
@@ -1089,8 +1002,6 @@ mod tests {
Some(&child_url)
);
- let mut descendants = Vec::new();
- collect_descendants(&host, child_document, &mut descendants);
assert!(
descendants
.iter()
@@ -1122,7 +1033,7 @@ mod tests {
assert!(
parser
- .parse_tree_into_document(&mut host, html_document, "<root />")
+ .parse_inert_tree_into_document(&mut host, html_document, "<root />")
.is_none()
);
assert_eq!(host.child_handles(html_document).count(), 0);
@@ -1130,13 +1041,13 @@ mod tests {
let xml_document = host.create_detached_xml_document();
assert!(
parser
- .parse_tree_into_document(&mut host, xml_document, "<root />")
+ .parse_inert_tree_into_document(&mut host, xml_document, "<root />")
.is_some()
);
let children_before_retry = host.child_handles(xml_document).collect::<Vec<_>>();
assert!(
parser
- .parse_tree_into_document(&mut host, xml_document, "<replacement />")
+ .parse_inert_tree_into_document(&mut host, xml_document, "<replacement />")
.is_none()
);
assert_eq!(
@@ -1155,7 +1066,7 @@ mod tests {
let child_document = host.create_detached_xml_document_with_url(child_url.clone());
parser
- .parse_tree_into_document(
+ .parse_inert_tree_into_document(
&mut host,
child_document,
concat!(
@@ -1346,41 +1257,4 @@ mod tests {
.find(|node_id| dom.node(*node_id).is_some_and(|node| node.is_element()))
.expect("document element")
}
-
- #[test]
- fn xml_parser_prepares_xhtml_scripts_from_recorded_tree_builder_handles() {
- let (_, handoffs) = XmlParser.parse_with_script_handoffs(
- Url::parse("https://example.test/page.xhtml").unwrap(),
- concat!(
- "<html xmlns='http://www.w3.org/1999/xhtml'><head>",
- "<script type='importmap'>{\"imports\":{\"dep\":\"/dep.js\"}}</script>",
- "<script defer='defer' src='data:text/javascript,globalThis.deferRan=1'></script>",
- "<script type='module'>export const value = 1;</script>",
- "<script async='async' src='data:text/javascript,globalThis.asyncRan=1'></script>",
- "</head><body /></html>",
- )
- .to_owned(),
- );
-
- assert_eq!(handoffs.len(), 4);
- assert!(matches!(
- &handoffs[0],
- ParserScriptHandoff::ImportMap { import_map, .. } if import_map.position == 0
- ));
- assert!(matches!(
- &handoffs[1],
- ParserScriptHandoff::NonAsyncPostParse { script, .. }
- if script.position == 1 && script.mode == ScriptMode::Defer
- ));
- assert!(matches!(
- &handoffs[2],
- ParserScriptHandoff::NonAsyncPostParse { script, .. }
- if script.position == 2 && script.mode == ScriptMode::ModuleDefer
- ));
- assert!(matches!(
- &handoffs[3],
- ParserScriptHandoff::AsyncPostParse { script, .. }
- if script.position == 3 && script.mode == ScriptMode::Async
- ));
- }
}
diff --git a/moli-parser/src/xml_stream.rs b/moli-parser/src/xml_stream.rs
new file mode 100644
index 000000000..424d681bf
--- /dev/null
+++ b/moli-parser/src/xml_stream.rs
@@ -0,0 +1,1209 @@
+use std::{
+ borrow::Cow,
+ cell::{Cell, RefCell},
+ collections::VecDeque,
+ rc::Rc,
+};
+
+use html5ever::{
+ Attribute as HtmlAttribute, LocalName as HtmlLocalName, Namespace as HtmlNamespace,
+ Prefix as HtmlPrefix, QualName as HtmlQualName,
+ tendril::StrTendril as HtmlStrTendril,
+ tree_builder::{ElementFlags as HtmlElementFlags, NodeOrText as HtmlNodeOrText},
+};
+use moli_dom::native::{DomHost, NativeDom, NativeNodeId};
+use url::Url;
+use xml5ever::{
+ Attribute as XmlAttribute, ExpandedName, LocalName as XmlLocalName, Namespace as XmlNamespace,
+ Prefix as XmlPrefix, QualName as XmlQualName, TokenizerResult,
+ buffer_queue::BufferQueue,
+ driver::XmlParseOpts,
+ interface::{ElementFlags as XmlElementFlags, QuirksMode as XmlQuirksMode},
+ tendril::StrTendril,
+ tokenizer::{ProcessResult, Token, TokenSink, XmlTokenizer},
+ tree_builder::{NodeOrText as XmlNodeOrText, TreeSink, XmlTreeBuilder},
+};
+
+use crate::{
+ ParserBlockingStylesheetPause, ParserDomMutationConsumer, ParserDomReadConsumer,
+ ParserElementCreationConsumer, ParserFinishDiscoverySignals, ParserMutationEffectConsumer,
+ ParserPlanningReadView, ParserPumpOutcome, ParserPumpStep, ParserScriptHandoff, ParserYield,
+ PreparedScript,
+ html::ParseHandle,
+ live_target::{ParserRuntimeDomSinks, ParserStreamHtmlTreeSinkTarget},
+ stream::prepare_parser_script_handoff_for_static_document,
+ xml::{
+ CDATA_MARKER_PI_TARGET, XmlNamespaceDeclaration, xml_namespace_declarations,
+ xml_source_has_unclosed_element_at_eof,
+ },
+ xml_tree_viewer::transform_parser_target_to_xml_tree_view,
+};
+
+/// Incremental XML backend for an executable Document.
+///
+/// Unlike xml5ever's high-level `XmlParser` driver, this owner surfaces
+/// `TokenizerResult::Script` instead of immediately feeding through it. The
+/// tokenizer, tree builder, unconsumed input, and live-DOM target therefore
+/// remain in one parser session across script and stylesheet suspension.
+pub struct XmlDocumentStream {
+ parser: XmlParserSession,
+ input: XmlParserInputStream,
+ preprocessor: XmlInputPreprocessor,
+ raw_source: String,
+ scanned_namespace_element_count: usize,
+ eof_declared: bool,
+}
+
+#[derive(Default)]
+struct XmlParserInputStream {
+ end_segments: VecDeque<String>,
+}
+
+struct XmlParserSession {
+ tokenizer: XmlTokenizer<EmbedderPausingXmlTreeBuilder>,
+ input_buffer: BufferQueue,
+}
+
+struct EmbedderPausingXmlTreeBuilder {
+ inner: XmlTreeBuilder<XmlStreamParseHandle, XmlStreamDocumentSink>,
+}
+
+struct XmlStreamDocumentSink {
+ target: RefCell<XmlParserStreamTarget>,
+ quirks_mode: Cell<XmlQuirksMode>,
+}
+
+struct XmlParserStreamTarget {
+ common: ParserStreamHtmlTreeSinkTarget,
+ namespace_declarations: VecDeque<Vec<XmlNamespaceDeclaration>>,
+ cdata_sections: Vec<String>,
+ source_has_unclosed_element_at_eof: bool,
+ present_unstyled_top_level_document: bool,
+}
+
+#[derive(Debug, Clone)]
+struct XmlStreamParseHandle {
+ inner: ParseHandle,
+ element_name: Option<Rc<XmlQualName>>,
+ suppress_append: bool,
+}
+
+#[derive(Default)]
+struct XmlInputPreprocessor {
+ pending: String,
+ next_cdata_index: usize,
+ completed_cdata_sections: Vec<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum RawXmlParserStep {
+ Script(NativeNodeId),
+ BlockingStylesheet(NativeNodeId),
+ InputDrained,
+}
+
+impl XmlDocumentStream {
+ /// Starts a raw XML stream. This is suitable for parser tests and inert
+ /// consumers; executable top-level navigation uses
+ /// `new_top_level_document` explicitly.
+ pub fn new(final_url: Url) -> Self {
+ Self::from_target(ParserStreamHtmlTreeSinkTarget::new_xml(final_url), false)
+ }
+
+ pub fn new_top_level_document(final_url: Url) -> Self {
+ Self::from_target(ParserStreamHtmlTreeSinkTarget::new_xml(final_url), true)
+ }
+
+ pub fn new_live_document_root(final_url: Url, document_handle: NativeNodeId) -> Self {
+ Self::from_target(
+ ParserStreamHtmlTreeSinkTarget::new_live_xml_document_root(final_url, document_handle),
+ false,
+ )
+ }
+
+ fn from_target(
+ common: ParserStreamHtmlTreeSinkTarget,
+ present_unstyled_top_level_document: bool,
+ ) -> Self {
+ let target = XmlParserStreamTarget {
+ common,
+ namespace_declarations: VecDeque::new(),
+ cdata_sections: Vec::new(),
+ source_has_unclosed_element_at_eof: false,
+ present_unstyled_top_level_document,
+ };
+ Self {
+ parser: XmlParserSession::new(target, XmlParseOpts::default()),
+ input: XmlParserInputStream::default(),
+ preprocessor: XmlInputPreprocessor::default(),
+ raw_source: String::new(),
+ scanned_namespace_element_count: 0,
+ eof_declared: false,
+ }
+ }
+
+ /// Appends decoded XML bytes to the parser-owned end segment chain.
+ /// Appending does not run the tokenizer or mutate the DOM.
+ pub fn append_to_end(&mut self, chunk: String) {
+ assert!(!self.eof_declared, "cannot append XML input after EOF");
+ if chunk.is_empty() {
+ return;
+ }
+ self.raw_source.push_str(&chunk);
+ self.refresh_namespace_declarations();
+ let transformed = self.preprocessor.push(&chunk, false);
+ self.transfer_completed_cdata_sections();
+ if !transformed.is_empty() {
+ self.input.end_segments.push_back(transformed);
+ }
+ }
+
+ /// Declares source EOF and flushes any prefix retained by the CDATA
+ /// boundary preprocessor. Calling this more than once is a no-op.
+ pub fn declare_eof(&mut self) {
+ if self.eof_declared {
+ return;
+ }
+ self.eof_declared = true;
+ self.refresh_namespace_declarations();
+ let trailing = self.preprocessor.push("", true);
+ self.transfer_completed_cdata_sections();
+ if !trailing.is_empty() {
+ self.input.end_segments.push_back(trailing);
+ }
+ self.parser
+ .sink()
+ .borrow_mut()
+ .source_has_unclosed_element_at_eof =
+ xml_source_has_unclosed_element_at_eof(&self.raw_source);
+ }
+
+ pub fn has_pending_input(&self) -> bool {
+ self.parser.has_buffered_input() || !self.input.end_segments.is_empty()
+ }
+
+ pub fn next_input_len(&self) -> usize {
+ if self.parser.has_buffered_input() {
+ self.parser.buffered_input_len()
+ } else {
+ self.input
+ .end_segments
+ .front()
+ .map(String::len)
+ .unwrap_or_default()
+ }
+ }
+
+ pub fn snapshot_pending_input(&self) -> String {
+ let mut pending = self.parser.snapshot_buffered_input();
+ for segment in &self.input.end_segments {
+ pending.push_str(segment);
+ }
+ pending.push_str(&self.preprocessor.pending);
+ pending
+ }
+
+ pub fn pump_next_parser_step(&mut self, max_bytes: usize) -> ParserPumpOutcome {
+ let chunk = self.take_next_owned_input(max_bytes);
+ self.parser.pump_parser_step(&chunk)
+ }
+
+ pub fn pump_next_parser_step_with_runtime_dom_consumer<T>(
+ &mut self,
+ max_bytes: usize,
+ consumer: &mut T,
+ ) -> ParserPumpOutcome
+ where
+ T: ParserDomReadConsumer
+ + ParserDomMutationConsumer
+ + ParserMutationEffectConsumer
+ + ParserElementCreationConsumer,
+ {
+ // SAFETY: `consumer` remains exclusively borrowed until the scoped
+ // guard clears every erased callback at the end of this parser step.
+ let sinks = unsafe { ParserRuntimeDomSinks::from_consumer(consumer) };
+ self.parser.enter_runtime_dom_sinks_parse_step(sinks);
+ let step = RuntimeXmlDomSinksParserStep { stream: self };
+ step.stream.pump_next_parser_step(max_bytes)
+ }
+
+ pub fn snapshot_parser_stream_document(&self) -> NativeDom {
+ self.parser
+ .sink()
+ .borrow()
+ .common
+ .snapshot_parser_stream_document()
+ }
+
+ pub fn snapshot_parser_stream_dom_host(&self) -> DomHost {
+ self.parser
+ .sink()
+ .borrow()
+ .common
+ .snapshot_parser_stream_dom_host()
+ }
+
+ pub fn take_parser_stream_dom_host(&mut self) -> DomHost {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .common
+ .take_parser_stream_document()
+ }
+
+ pub fn restore_parser_stream_dom_host(&mut self, dom_host: DomHost) {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .common
+ .restore_parser_stream_dom_host(dom_host);
+ }
+
+ pub fn set_document_content_type(&mut self, content_type: String) {
+ let mut dom_host = self.take_parser_stream_dom_host();
+ let document_handle = dom_host.document_handle();
+ let _ = dom_host.set_document_content_type_for_handle(document_handle, content_type);
+ self.restore_parser_stream_dom_host(dom_host);
+ }
+
+ pub fn with_parser_stream_dom_host_for_bootstrap<R>(
+ &mut self,
+ f: impl FnOnce(DomHost) -> std::result::Result<R, Box<(anyhow::Error, DomHost)>>,
+ ) -> anyhow::Result<R> {
+ let bootstrap_document = self.take_parser_stream_dom_host();
+ match f(bootstrap_document) {
+ Ok(result) => Ok(result),
+ Err(error) => {
+ let (error, bootstrap_document) = *error;
+ self.restore_parser_stream_dom_host(bootstrap_document);
+ Err(error)
+ }
+ }
+ }
+
+ pub fn take_parser_stream_null_custom_element_registry_elements(
+ &mut self,
+ ) -> Vec<NativeNodeId> {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .common
+ .take_parser_stream_null_custom_element_registry_elements()
+ }
+
+ pub fn with_stylesheet_blocking_read_view<R>(
+ &self,
+ f: impl FnOnce(&dyn moli_stylesheet_blocking::StylesheetBlockingReadView) -> R,
+ ) -> R {
+ let target = self.parser.sink().borrow();
+ f(&target.common)
+ }
+
+ pub fn drain_discovered_parser_meta_csp_candidates(&mut self) -> Vec<NativeNodeId> {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .common
+ .drain_discovered_parser_meta_csp_candidates()
+ }
+
+ pub fn mark_script_already_started(&mut self, node_id: NativeNodeId) {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .common
+ .mark_script_already_started(node_id);
+ }
+
+ pub fn finish_with_runtime_dom_consumer<T>(
+ mut self,
+ consumer: &mut T,
+ ) -> ParserFinishDiscoverySignals
+ where
+ T: ParserDomReadConsumer
+ + ParserDomMutationConsumer
+ + ParserMutationEffectConsumer
+ + ParserElementCreationConsumer,
+ {
+ self.declare_eof();
+ assert!(
+ !self.has_pending_input(),
+ "XML parser must drain all source before finish"
+ );
+ // SAFETY: `consumer` remains exclusively borrowed for the consuming
+ // finish operation. The unwind guard clears callbacks if finish panics.
+ let sinks = unsafe { ParserRuntimeDomSinks::from_consumer(consumer) };
+ self.parser.enter_runtime_dom_sinks_parse_step(sinks);
+ let mut finish = RuntimeXmlDomSinksParserFinish {
+ parser: Some(self.parser),
+ };
+ finish.finish()
+ }
+
+ pub fn finish(mut self) -> NativeDom {
+ self.declare_eof();
+ while self.has_pending_input() {
+ let _ = self.pump_next_parser_step(0);
+ }
+ self.parser.finish_owned().finish_dom_host().into_dom()
+ }
+
+ fn refresh_namespace_declarations(&mut self) {
+ let declarations = xml_namespace_declarations(&self.raw_source);
+ if declarations.len() <= self.scanned_namespace_element_count {
+ return;
+ }
+ let newly_complete = declarations
+ .into_iter()
+ .skip(self.scanned_namespace_element_count)
+ .collect::<VecDeque<_>>();
+ self.scanned_namespace_element_count = self
+ .scanned_namespace_element_count
+ .saturating_add(newly_complete.len());
+ self.parser
+ .sink()
+ .borrow_mut()
+ .namespace_declarations
+ .extend(newly_complete);
+ }
+
+ fn transfer_completed_cdata_sections(&mut self) {
+ let sections = std::mem::take(&mut self.preprocessor.completed_cdata_sections);
+ if !sections.is_empty() {
+ self.parser
+ .sink()
+ .borrow_mut()
+ .cdata_sections
+ .extend(sections);
+ }
+ }
+
+ fn take_next_owned_input(&mut self, max_bytes: usize) -> String {
+ if self.parser.has_buffered_input() {
+ return String::new();
+ }
+ let Some(input) = self.input.end_segments.pop_front() else {
+ return String::new();
+ };
+ let (prefix, remainder) = split_xml_parser_input_prefix(input, max_bytes);
+ if let Some(remainder) = remainder {
+ self.input.end_segments.push_front(remainder);
+ }
+ prefix
+ }
+}
+
+impl XmlParserSession {
+ fn new(target: XmlParserStreamTarget, opts: XmlParseOpts) -> Self {
+ let sink = XmlStreamDocumentSink {
+ target: RefCell::new(target),
+ quirks_mode: Cell::new(XmlQuirksMode::NoQuirks),
+ };
+ let tree_builder = XmlTreeBuilder::new(sink, opts.tree_builder);
+ let tokenizer = XmlTokenizer::new(
+ EmbedderPausingXmlTreeBuilder {
+ inner: tree_builder,
+ },
+ opts.tokenizer,
+ );
+ Self {
+ tokenizer,
+ input_buffer: BufferQueue::default(),
+ }
+ }
+
+ fn sink(&self) -> &RefCell<XmlParserStreamTarget> {
+ &self.tokenizer.sink.inner.sink.target
+ }
+
+ fn has_buffered_input(&self) -> bool {
+ !self.input_buffer.is_empty()
+ }
+
+ fn buffered_input_len(&self) -> usize {
+ let input = self.input_buffer.clone();
+ let mut len = 0usize;
+ while let Some(chunk) = input.pop_front() {
+ len = len.saturating_add(chunk.len());
+ }
+ len
+ }
+
+ fn snapshot_buffered_input(&self) -> String {
+ let input = self.input_buffer.clone();
+ let mut buffered = String::new();
+ while let Some(chunk) = input.pop_front() {
+ buffered.push_str(&chunk);
+ }
+ buffered
+ }
+
+ fn enter_runtime_dom_sinks_parse_step(&mut self, sinks: ParserRuntimeDomSinks) {
+ self.sink()
+ .borrow_mut()
+ .common
+ .enter_runtime_dom_sinks_parse_step(sinks);
+ }
+
+ fn clear_runtime_dom_sinks_after_parse_step(&mut self) {
+ self.sink()
+ .borrow_mut()
+ .common
+ .clear_runtime_dom_sinks_after_parse_step();
+ }
+
+ fn pump_parser_step(&mut self, chunk: &str) -> ParserPumpOutcome {
+ if !chunk.is_empty() {
+ self.input_buffer.push_back(StrTendril::from(chunk));
+ }
+
+ let raw_step = loop {
+ match self.tokenizer.feed(&self.input_buffer) {
+ TokenizerResult::Done => break RawXmlParserStep::InputDrained,
+ TokenizerResult::EncodingIndicator(_) => continue,
+ TokenizerResult::Script(handle) => {
+ let node_id = handle.inner.node_id();
+ let target = self.sink().borrow();
+ if target.common.front_pending_blocking_stylesheet_pause() == Some(node_id) {
+ break RawXmlParserStep::BlockingStylesheet(node_id);
+ }
+ if ParserPlanningReadView::parser_script_read(&target.common, node_id).is_some()
+ {
+ break RawXmlParserStep::Script(node_id);
+ }
+ // xml5ever yields on every local-name `script`, including
+ // non-HTML namespaces. Those nodes are not executable and
+ // therefore do not suspend an executable Document parser.
+ }
+ }
+ };
+
+ let mut target = self.sink().borrow_mut();
+ let async_candidate_ids = target.common.drain_discovered_async_prefetch_candidates();
+ let discovered_async_prefetch_scripts = async_candidate_ids
+ .iter()
+ .filter_map(|node_id| {
+ match prepare_parser_script_handoff_for_static_document(
+ &target.common,
+ *node_id,
+ 0,
+ 0,
+ ) {
+ ParserScriptHandoff::AsyncPostParse { script, .. } => Some(script),
+ _ => None,
+ }
+ })
+ .collect::<Vec<PreparedScript>>();
+ let discovered_modulepreload_link_candidates = target
+ .common
+ .drain_discovered_modulepreload_link_candidates();
+ let discovered_blocking_stylesheet_inputs =
+ target.common.drain_discovered_blocking_stylesheet_inputs();
+
+ let result = match raw_step {
+ RawXmlParserStep::Script(node_id) => {
+ let handoff = prepare_parser_script_handoff_for_static_document(
+ &target.common,
+ node_id,
+ 0,
+ 0,
+ );
+ ParserPumpStep::Yield(ParserYield::Script(Box::new(handoff)))
+ }
+ RawXmlParserStep::BlockingStylesheet(node_id) => {
+ let pending = target.common.pop_pending_blocking_stylesheet_pause();
+ assert_eq!(pending, Some(node_id));
+ ParserPumpStep::Yield(ParserYield::BlockingStylesheet(
+ ParserBlockingStylesheetPause { node_id },
+ ))
+ }
+ RawXmlParserStep::InputDrained => ParserPumpStep::InputDrained,
+ };
+
+ ParserPumpOutcome {
+ result,
+ discovered_async_prefetch_scripts,
+ discovered_modulepreload_link_candidates,
+ discovered_blocking_stylesheet_inputs,
+ }
+ }
+
+ fn finish_owned(self) -> ParserStreamHtmlTreeSinkTarget {
+ let Self {
+ tokenizer,
+ input_buffer,
+ } = self;
+ debug_assert!(input_buffer.is_empty());
+ tokenizer.end();
+ let mut target = tokenizer.sink.inner.sink.finish();
+ target.record_unclosed_source_element_error();
+ target.present_unstyled_top_level_document_if_needed();
+ target.common
+ }
+
+ fn finish_live_runtime_dom_sink_parser(self) -> ParserFinishDiscoverySignals {
+ let Self {
+ tokenizer,
+ input_buffer,
+ } = self;
+ debug_assert!(input_buffer.is_empty());
+ tokenizer.end();
+ let mut target = tokenizer.sink.inner.sink.target.borrow_mut();
+ target.record_unclosed_source_element_error();
+ target.present_unstyled_top_level_document_if_needed();
+ ParserFinishDiscoverySignals {
+ parser_created_null_registry_elements: target
+ .common
+ .take_parser_stream_null_custom_element_registry_elements(),
+ discovered_modulepreload_link_candidates: target
+ .common
+ .drain_discovered_modulepreload_link_candidates(),
+ discovered_parser_meta_csp_candidates: target
+ .common
+ .drain_discovered_parser_meta_csp_candidates(),
+ discovered_blocking_stylesheet_inputs: target
+ .common
+ .drain_discovered_blocking_stylesheet_inputs(),
+ }
+ }
+}
+
+impl TokenSink for EmbedderPausingXmlTreeBuilder {
+ type Handle = XmlStreamParseHandle;
+
+ fn process_token(&self, token: Token) -> ProcessResult<Self::Handle> {
+ let result = self.inner.process_token(token);
+ if !matches!(result, ProcessResult::Continue) {
+ return result;
+ }
+ let pending_stylesheet = self
+ .inner
+ .sink
+ .target
+ .borrow()
+ .common
+ .front_pending_blocking_stylesheet_pause();
+ if let Some(node_id) = pending_stylesheet {
+ return ProcessResult::Script(XmlStreamParseHandle::new(ParseHandle::new(
+ node_id, None,
+ )));
+ }
+ ProcessResult::Continue
+ }
+
+ fn end(&self) {
+ self.inner.end();
+ }
+}
+
+impl XmlParserStreamTarget {
+ fn merge_namespace_declarations(&mut self, attributes: &mut Vec<XmlAttribute>) {
+ for (declaration_index, declaration) in self
+ .namespace_declarations
+ .pop_front()
+ .unwrap_or_default()
+ .into_iter()
+ .enumerate()
+ {
+ let attribute = &declaration.attribute;
+ let xml_attribute = XmlAttribute {
+ name: XmlQualName::new(
+ attribute.prefix().map(XmlPrefix::from),
+ XmlNamespace::from(attribute.namespace()),
+ XmlLocalName::from(attribute.local_name()),
+ ),
+ value: StrTendril::from(attribute.value()),
+ };
+ let insertion_index = declaration
+ .ordinary_attributes_before
+ .saturating_add(declaration_index)
+ .min(attributes.len());
+ attributes.insert(insertion_index, xml_attribute);
+ }
+ }
+
+ fn record_unclosed_source_element_error(&mut self) {
+ if self.source_has_unclosed_element_at_eof {
+ self.common
+ .push_parse_error("Unexpected EOF with an unclosed XML element".to_owned());
+ }
+ }
+
+ fn present_unstyled_top_level_document_if_needed(&mut self) {
+ if self.present_unstyled_top_level_document {
+ transform_parser_target_to_xml_tree_view(&mut self.common);
+ }
+ }
+}
+
+impl XmlStreamParseHandle {
+ fn new(inner: ParseHandle) -> Self {
+ Self {
+ inner,
+ element_name: None,
+ suppress_append: false,
+ }
+ }
+
+ fn element(inner: ParseHandle, element_name: Rc<XmlQualName>) -> Self {
+ Self {
+ inner,
+ element_name: Some(element_name),
+ suppress_append: false,
+ }
+ }
+
+ fn suppressed(inner: ParseHandle) -> Self {
+ Self {
+ inner,
+ element_name: None,
+ suppress_append: true,
+ }
+ }
+}
+
+impl PartialEq for XmlStreamParseHandle {
+ fn eq(&self, other: &Self) -> bool {
+ self.inner == other.inner
+ }
+}
+
+impl Eq for XmlStreamParseHandle {}
+
+impl TreeSink for XmlStreamDocumentSink {
+ type Handle = XmlStreamParseHandle;
+ type Output = XmlParserStreamTarget;
+ type ElemName<'a>
+ = ExpandedName<'a>
+ where
+ Self: 'a;
+
+ fn finish(self) -> Self::Output {
+ self.target.into_inner()
+ }
+
+ fn parse_error(&self, error: Cow<'static, str>) {
+ self.target
+ .borrow_mut()
+ .common
+ .push_parse_error(error.into_owned());
+ }
+
+ fn get_document(&self) -> Self::Handle {
+ XmlStreamParseHandle::new(self.target.borrow().common.document_handle())
+ }
+
+ fn elem_name<'a>(&'a self, target: &'a Self::Handle) -> Self::ElemName<'a> {
+ target
+ .element_name
+ .as_deref()
+ .expect("xml5ever requested the name of a non-element node")
+ .expanded()
+ }
+
+ fn create_element(
+ &self,
+ name: XmlQualName,
+ mut attrs: Vec<XmlAttribute>,
+ flags: XmlElementFlags,
+ ) -> Self::Handle {
+ let mut target = self.target.borrow_mut();
+ target.merge_namespace_declarations(&mut attrs);
+ let element_name = Rc::new(name.clone());
+ let html_name = xml_name_to_html(&name);
+ let html_attrs = attrs.into_iter().map(xml_attribute_to_html).collect();
+ let mut html_flags = HtmlElementFlags::default();
+ html_flags.template = flags.template;
+ html_flags.mathml_annotation_xml_integration_point =
+ flags.mathml_annotation_xml_integration_point;
+ XmlStreamParseHandle::element(
+ target
+ .common
+ .create_element(html_name, html_attrs, html_flags),
+ element_name,
+ )
+ }
+
+ fn create_comment(&self, text: StrTendril) -> Self::Handle {
+ XmlStreamParseHandle::new(
+ self.target
+ .borrow_mut()
+ .common
+ .create_comment(text.to_string()),
+ )
+ }
+
+ fn create_pi(&self, target: StrTendril, data: StrTendril) -> Self::Handle {
+ let target_text = target.to_string();
+ let data_text = data.to_string();
+ let mut parser_target = self.target.borrow_mut();
+ if target_text == CDATA_MARKER_PI_TARGET
+ && let Ok(index) = data_text.trim().parse::<usize>()
+ && let Some(cdata) = parser_target.cdata_sections.get(index).cloned()
+ {
+ return XmlStreamParseHandle::new(parser_target.common.create_cdata_section(cdata));
+ }
+ let handle = parser_target
+ .common
+ .create_processing_instruction(target_text.clone(), data_text);
+ if target_text.eq_ignore_ascii_case("xml") {
+ XmlStreamParseHandle::suppressed(handle)
+ } else {
+ XmlStreamParseHandle::new(handle)
+ }
+ }
+
+ fn append(&self, parent: &Self::Handle, child: XmlNodeOrText<Self::Handle>) {
+ let child = match child {
+ XmlNodeOrText::AppendNode(handle) if handle.suppress_append => return,
+ XmlNodeOrText::AppendNode(handle) => HtmlNodeOrText::AppendNode(handle.inner),
+ XmlNodeOrText::AppendText(text) => {
+ HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))
+ }
+ };
+ self.target
+ .borrow_mut()
+ .common
+ .append(parent.inner.node_id(), child)
+ .consume();
+ }
+
+ fn append_before_sibling(&self, sibling: &Self::Handle, child: XmlNodeOrText<Self::Handle>) {
+ let child = match child {
+ XmlNodeOrText::AppendNode(handle) if handle.suppress_append => return,
+ XmlNodeOrText::AppendNode(handle) => HtmlNodeOrText::AppendNode(handle.inner),
+ XmlNodeOrText::AppendText(text) => {
+ HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))
+ }
+ };
+ self.target
+ .borrow_mut()
+ .common
+ .append_before_sibling(sibling.inner.node_id(), child)
+ .consume();
+ }
+
+ fn append_based_on_parent_node(
+ &self,
+ element: &Self::Handle,
+ prev_element: &Self::Handle,
+ child: XmlNodeOrText<Self::Handle>,
+ ) {
+ let child = match child {
+ XmlNodeOrText::AppendNode(handle) if handle.suppress_append => return,
+ XmlNodeOrText::AppendNode(handle) => HtmlNodeOrText::AppendNode(handle.inner),
+ XmlNodeOrText::AppendText(text) => {
+ HtmlNodeOrText::AppendText(HtmlStrTendril::from(text.as_ref()))
+ }
+ };
+ self.target
+ .borrow_mut()
+ .common
+ .append_based_on_parent_node(
+ element.inner.node_id(),
+ prev_element.inner.node_id(),
+ child,
+ )
+ .consume();
+ }
+
+ fn append_doctype_to_document(
+ &self,
+ name: StrTendril,
+ public_id: StrTendril,
+ system_id: StrTendril,
+ ) {
+ self.target
+ .borrow_mut()
+ .common
+ .append_doctype(
+ name.to_string(),
+ public_id.to_string(),
+ system_id.to_string(),
+ )
+ .consume();
+ }
+
+ fn mark_script_already_started(&self, node: &Self::Handle) {
+ self.target
+ .borrow_mut()
+ .common
+ .mark_script_already_started(node.inner.node_id());
+ }
+
+ fn pop(&self, node: &Self::Handle) {
+ let is_script = node.inner.element_name.as_ref().is_some_and(|name| {
+ name.local.as_ref() == "script"
+ && matches!(
+ name.ns.as_ref(),
+ "http://www.w3.org/1999/xhtml" | "http://www.w3.org/2000/svg"
+ )
+ });
+ self.target
+ .borrow_mut()
+ .common
+ .note_node_closed(node.inner.node_id(), is_script);
+ }
+
+ fn get_template_contents(&self, target: &Self::Handle) -> Self::Handle {
+ self.target
+ .borrow_mut()
+ .common
+ .template_contents_handle(target.inner.node_id())
+ .map(XmlStreamParseHandle::new)
+ .unwrap_or_else(|| target.clone())
+ }
+
+ fn same_node(&self, left: &Self::Handle, right: &Self::Handle) -> bool {
+ left == right
+ }
+
+ fn set_quirks_mode(&self, mode: XmlQuirksMode) {
+ self.quirks_mode.set(mode);
+ }
+
+ fn add_attrs_if_missing(&self, target: &Self::Handle, attrs: Vec<XmlAttribute>) {
+ self.target.borrow_mut().common.add_attrs_if_missing(
+ target.inner.node_id(),
+ attrs.into_iter().map(xml_attribute_to_html).collect(),
+ );
+ }
+
+ fn remove_from_parent(&self, target: &Self::Handle) {
+ self.target
+ .borrow_mut()
+ .common
+ .remove_from_parent(target.inner.node_id())
+ .consume();
+ }
+
+ fn reparent_children(&self, node: &Self::Handle, new_parent: &Self::Handle) {
+ self.target
+ .borrow_mut()
+ .common
+ .reparent_children(node.inner.node_id(), new_parent.inner.node_id())
+ .consume();
+ }
+}
+
+fn xml_name_to_html(name: &XmlQualName) -> HtmlQualName {
+ HtmlQualName::new(
+ name.prefix
+ .as_ref()
+ .map(|prefix| HtmlPrefix::from(prefix.as_ref())),
+ HtmlNamespace::from(name.ns.as_ref()),
+ HtmlLocalName::from(name.local.as_ref()),
+ )
+}
+
+fn xml_attribute_to_html(attribute: XmlAttribute) -> HtmlAttribute {
+ HtmlAttribute {
+ name: xml_name_to_html(&attribute.name),
+ value: HtmlStrTendril::from(attribute.value.as_ref()),
+ }
+}
+
+impl XmlInputPreprocessor {
+ fn push(&mut self, input: &str, eof: bool) -> String {
+ const CDATA_OPEN: &str = "<![CDATA[";
+ const CDATA_CLOSE: &str = "]]>";
+
+ self.pending.push_str(input);
+ let mut output = String::new();
+ loop {
+ let Some(start) = self.pending.find(CDATA_OPEN) else {
+ if eof {
+ output.push_str(&self.pending);
+ self.pending.clear();
+ } else {
+ let keep = longest_suffix_prefix_len(&self.pending, CDATA_OPEN);
+ let emit_len = self.pending.len().saturating_sub(keep);
+ output.push_str(&self.pending[..emit_len]);
+ self.pending.drain(..emit_len);
+ }
+ break;
+ };
+ output.push_str(&self.pending[..start]);
+ self.pending.drain(..start);
+ let content_start = CDATA_OPEN.len();
+ let Some(relative_end) = self.pending[content_start..].find(CDATA_CLOSE) else {
+ if eof {
+ output.push_str(&self.pending);
+ self.pending.clear();
+ }
+ break;
+ };
+ let content_end = content_start + relative_end;
+ let cdata = self.pending[content_start..content_end].to_owned();
+ output.push_str("<?");
+ output.push_str(CDATA_MARKER_PI_TARGET);
+ output.push(' ');
+ output.push_str(&self.next_cdata_index.to_string());
+ output.push_str("?>");
+ self.completed_cdata_sections.push(cdata);
+ self.next_cdata_index = self.next_cdata_index.saturating_add(1);
+ self.pending.drain(..(content_end + CDATA_CLOSE.len()));
+ }
+ output
+ }
+}
+
+fn longest_suffix_prefix_len(value: &str, prefix: &str) -> usize {
+ let max = value.len().min(prefix.len().saturating_sub(1));
+ (1..=max)
+ .rev()
+ .find(|length| value.ends_with(&prefix[..*length]))
+ .unwrap_or_default()
+}
+
+fn split_xml_parser_input_prefix(input: String, max_bytes: usize) -> (String, Option<String>) {
+ if max_bytes == 0 || input.len() <= max_bytes {
+ return (input, None);
+ }
+ let mut split = input.len();
+ for (index, character) in input.char_indices() {
+ let end = index + character.len_utf8();
+ if end > max_bytes {
+ split = if index == 0 { end } else { index };
+ break;
+ }
+ }
+ let remainder = input[split..].to_owned();
+ let prefix = input[..split].to_owned();
+ (prefix, (!remainder.is_empty()).then_some(remainder))
+}
+
+struct RuntimeXmlDomSinksParserStep<'a> {
+ stream: &'a mut XmlDocumentStream,
+}
+
+impl Drop for RuntimeXmlDomSinksParserStep<'_> {
+ fn drop(&mut self) {
+ self.stream
+ .parser
+ .clear_runtime_dom_sinks_after_parse_step();
+ }
+}
+
+struct RuntimeXmlDomSinksParserFinish {
+ parser: Option<XmlParserSession>,
+}
+
+impl RuntimeXmlDomSinksParserFinish {
+ fn finish(&mut self) -> ParserFinishDiscoverySignals {
+ self.parser
+ .take()
+ .map(XmlParserSession::finish_live_runtime_dom_sink_parser)
+ .unwrap_or_default()
+ }
+}
+
+impl Drop for RuntimeXmlDomSinksParserFinish {
+ fn drop(&mut self) {
+ if let Some(parser) = &mut self.parser {
+ parser.clear_runtime_dom_sinks_after_parse_step();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use moli_dom::native::{Node, NodeType};
+ use url::Url;
+
+ use crate::{ParserPumpStep, ParserYield, XmlDocumentStream};
+
+ fn test_url() -> Url {
+ Url::parse("https://example.test/page.xhtml").expect("test URL")
+ }
+
+ fn element_by_id(
+ document: &moli_dom::native::NativeDom,
+ id: &str,
+ ) -> Option<moli_dom::native::NativeNodeId> {
+ document
+ .nodes()
+ .find(|node| {
+ node.as_element()
+ .and_then(|element| element.attribute("id"))
+ == Some(id)
+ })
+ .map(Node::id)
+ }
+
+ #[test]
+ fn incremental_xml_stops_before_future_dom_at_parser_script() {
+ let mut stream = XmlDocumentStream::new(test_url());
+ stream.append_to_end(
+ concat!(
+ "<html xmlns='http://www.w3.org/1999/xhtml'><body>",
+ "<div id='before'/><script>globalThis.hit = true;</script>",
+ "<div id='future'/></body></html>"
+ )
+ .to_owned(),
+ );
+ stream.declare_eof();
+
+ let first = stream.pump_next_parser_step(0);
+ let ParserPumpStep::Yield(ParserYield::Script(handoff)) = first.result else {
+ panic!("expected an executable XML parser script handoff");
+ };
+ let crate::ParserScriptHandoff::BlockingClassic { script, .. } = *handoff else {
+ panic!("inline XHTML script must use the parser-blocking classic lane");
+ };
+ assert!(matches!(
+ script.source,
+ crate::ScriptSource::Inline(ref source)
+ if source == "globalThis.hit = true;"
+ ));
+ let paused = stream.snapshot_parser_stream_dom_host();
+ assert!(paused.element_handle_by_id("before").is_some());
+ assert!(
+ paused.element_handle_by_id("future").is_none(),
+ "XML future nodes must not be materialized past a parser script"
+ );
+
+ let second = stream.pump_next_parser_step(0);
+ assert!(matches!(second.result, ParserPumpStep::InputDrained));
+ let resumed = stream.snapshot_parser_stream_dom_host();
+ assert!(resumed.element_handle_by_id("future").is_some());
+ }
+
+ #[test]
+ fn incremental_xml_preserves_chunked_cdata_and_namespace_declarations() {
+ let mut stream = XmlDocumentStream::new(test_url());
+ for chunk in [
+ "<root data-before='1' xml",
+ "ns:m='urn:meta'><child><![CDA",
+ "TA[ < > & ]]></child></root>",
+ ] {
+ stream.append_to_end(chunk.to_owned());
+ while stream.has_pending_input() {
+ let outcome = stream.pump_next_parser_step(3);
+ assert!(matches!(outcome.result, ParserPumpStep::InputDrained));
+ }
+ }
+ stream.declare_eof();
+ while stream.has_pending_input() {
+ let outcome = stream.pump_next_parser_step(3);
+ assert!(matches!(outcome.result, ParserPumpStep::InputDrained));
+ }
+
+ let document = stream.finish();
+ let root = document
+ .document_element_node_id()
+ .expect("document element");
+ let attributes = document
+ .node(root)
+ .and_then(Node::as_element)
+ .expect("root element")
+ .attributes();
+ assert_eq!(
+ attributes
+ .iter()
+ .map(|attribute| attribute.name())
+ .collect::<Vec<_>>(),
+ ["data-before", "xmlns:m"]
+ );
+ let child = document
+ .child_ids(root)
+ .find(|node_id| document.node(*node_id).is_some_and(Node::is_element))
+ .expect("child element");
+ let cdata = document.child_ids(child).next().expect("CDATA child");
+ assert_eq!(
+ document.node(cdata).map(Node::node_type),
+ Some(NodeType::CDataSection)
+ );
+ assert_eq!(
+ document
+ .node(cdata)
+ .and_then(Node::as_cdata_section)
+ .map(|section| section.data()),
+ Some(" < > & ")
+ );
+ }
+
+ #[test]
+ fn incremental_xml_does_not_suspend_for_non_executable_script_namespace() {
+ let mut stream = XmlDocumentStream::new(test_url());
+ stream.append_to_end("<root><script>not executable</script><tail/></root>".to_owned());
+ stream.declare_eof();
+
+ let outcome = stream.pump_next_parser_step(0);
+ assert!(matches!(outcome.result, ParserPumpStep::InputDrained));
+ assert_eq!(
+ stream
+ .snapshot_parser_stream_document()
+ .elements_by_tag_name(
+ stream.snapshot_parser_stream_document().document_node_id(),
+ "tail",
+ false,
+ )
+ .len(),
+ 1
+ );
+ }
+
+ #[test]
+ fn incremental_top_level_unstyled_xml_builds_viewer_on_the_same_source_nodes() {
+ let mut stream = XmlDocumentStream::new_top_level_document(test_url());
+ stream.append_to_end(
+ "<semantic-root id='source'><child>ready</child></semantic-root>".to_owned(),
+ );
+ stream.declare_eof();
+ while stream.has_pending_input() {
+ let outcome = stream.pump_next_parser_step(2);
+ assert!(matches!(outcome.result, ParserPumpStep::InputDrained));
+ }
+ let source_root = stream
+ .snapshot_parser_stream_dom_host()
+ .element_handle_by_id("source")
+ .expect("source XML root before viewer conversion");
+
+ let document = stream.finish();
+ let document_element = document
+ .document_element_handle()
+ .and_then(|handle| document.node(handle))
+ .and_then(Node::as_element)
+ .expect("viewer document element");
+ assert_eq!(document_element.local_name(), "html");
+ assert_eq!(document_element.namespace(), "http://www.w3.org/1999/xhtml");
+ let source_container = element_by_id(&document, "webkit-xml-viewer-source-xml")
+ .expect("viewer source container");
+ assert_eq!(
+ document
+ .child_ids(source_container)
+ .find(|handle| document.node(*handle).is_some_and(Node::is_element)),
+ Some(source_root),
+ "viewer conversion must move rather than clone the parsed XML source root"
+ );
+ }
+
+ #[test]
+ fn incremental_top_level_xhtml_keeps_its_xml_tree() {
+ let mut stream = XmlDocumentStream::new_top_level_document(test_url());
+ stream.append_to_end(
+ "<html xmlns='http://www.w3.org/1999/xhtml'><body id='body'/></html>".to_owned(),
+ );
+ let document = stream.finish();
+ assert!(element_by_id(&document, "body").is_some());
+ assert!(element_by_id(&document, "webkit-xml-viewer-source-xml").is_none());
+ }
+
+ #[test]
+ fn incremental_top_level_malformed_xml_does_not_build_viewer() {
+ let mut stream = XmlDocumentStream::new_top_level_document(test_url());
+ stream.append_to_end("<semantic-root>".to_owned());
+ let document = stream.finish();
+ assert!(!document.parse_errors().is_empty());
+ assert_eq!(
+ document
+ .document_element_handle()
+ .and_then(|handle| document.node(handle))
+ .and_then(Node::as_element)
+ .map(|element| element.local_name()),
+ Some("semantic-root")
+ );
+ assert!(element_by_id(&document, "webkit-xml-viewer-source-xml").is_none());
+ }
+}
diff --git a/moli-parser/src/xml_tree_viewer.rs b/moli-parser/src/xml_tree_viewer.rs
index 01d197594..4c0f2c36f 100644
--- a/moli-parser/src/xml_tree_viewer.rs
+++ b/moli-parser/src/xml_tree_viewer.rs
@@ -1,6 +1,10 @@
-use moli_dom::native::{DomHost, NativeDom, NativeNodeId, NodeData, NodeType};
+use std::collections::{HashMap, HashSet};
+
+use moli_dom::native::{DomHost, NativeDom, NativeNodeId, Node, NodeData, NodeType};
use xmlparser::{ElementEnd, Token, Tokenizer};
+use crate::live_target::ParserStreamHtmlTreeSinkTarget;
+
const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
const MATHML_NAMESPACE: &str = "http://www.w3.org/1998/Math/MathML";
@@ -78,6 +82,116 @@ pub(super) fn transform_document_to_xml_tree_view(document: NativeDom) -> Native
host.into_dom()
}
+/// Applies the XML viewer conversion to the parser's current DOM owner.
+///
+/// The snapshot is used only to decide and plan the Chromium-compatible tree
+/// shape. Every structural change is replayed through the parser target, so a
+/// bootstrapped renderer keeps one live `Document`, stable node identities for
+/// the source XML subtree, and the normal mutation/runtime bookkeeping.
+pub(super) fn transform_parser_target_to_xml_tree_view(
+ target: &mut ParserStreamHtmlTreeSinkTarget,
+) {
+ let Some(source_document) = target.snapshot_current_parser_document() else {
+ return;
+ };
+ if !should_transform(&source_document) {
+ return;
+ }
+
+ let parser_document = target.parser_document_node_id();
+ if source_document.document_node_id() != parser_document {
+ return;
+ }
+ let original_handles = source_document
+ .nodes()
+ .map(Node::id)
+ .collect::<HashSet<_>>();
+ let original_document_children = source_document
+ .child_ids(parser_document)
+ .collect::<Vec<_>>();
+ let transformed_document = transform_document_to_xml_tree_view(source_document);
+ let desired_document_children = transformed_document
+ .child_ids(transformed_document.document_node_id())
+ .collect::<Vec<_>>();
+
+ for child in original_document_children {
+ target.remove_existing_node(parser_document, child);
+ }
+
+ let mut materialized_handles = HashMap::new();
+ for desired_child in desired_document_children {
+ let child = materialize_transformed_viewer_node(
+ target,
+ &transformed_document,
+ &original_handles,
+ &mut materialized_handles,
+ desired_child,
+ );
+ target.append_existing_node(parser_document, child);
+ }
+}
+
+fn materialize_transformed_viewer_node(
+ target: &mut ParserStreamHtmlTreeSinkTarget,
+ transformed: &NativeDom,
+ original_handles: &HashSet<NativeNodeId>,
+ materialized_handles: &mut HashMap<NativeNodeId, NativeNodeId>,
+ source_handle: NativeNodeId,
+) -> NativeNodeId {
+ if original_handles.contains(&source_handle) {
+ return source_handle;
+ }
+ if let Some(handle) = materialized_handles.get(&source_handle) {
+ return *handle;
+ }
+
+ let data = transformed
+ .node(source_handle)
+ .unwrap_or_else(|| panic!("XML viewer plan references missing node {source_handle:?}"))
+ .data()
+ .clone();
+ let materialized = match data {
+ NodeData::Element(element) => {
+ let handle = target.create_parser_element_without_attributes(
+ element.local_name().to_owned(),
+ element.namespace().to_owned(),
+ element.prefix().map(str::to_owned),
+ );
+ target.add_attrs_if_missing_for_parser(handle, element.attributes().to_vec());
+ handle
+ }
+ NodeData::Text(text) => target.create_text_node(text.data().to_owned()),
+ NodeData::CDataSection(cdata) => target.create_cdata_section_node(cdata.data().to_owned()),
+ NodeData::Comment(comment) => target.create_comment_node(comment.data().to_owned()),
+ NodeData::ProcessingInstruction(instruction) => target.create_processing_instruction_node(
+ instruction.target().to_owned(),
+ instruction.data().to_owned(),
+ ),
+ NodeData::DocumentType(document_type) => target.create_document_type_node(
+ document_type.name().to_owned(),
+ document_type.public_id().to_owned(),
+ document_type.system_id().to_owned(),
+ ),
+ NodeData::Document(_) | NodeData::DocumentFragment(_) => {
+ panic!("XML viewer plan cannot materialize a document container node")
+ }
+ };
+ materialized_handles.insert(source_handle, materialized);
+
+ let children = transformed.child_ids(source_handle).collect::<Vec<_>>();
+ for child in children {
+ let child = materialize_transformed_viewer_node(
+ target,
+ transformed,
+ original_handles,
+ materialized_handles,
+ child,
+ );
+ target.append_existing_node(materialized, child);
+ }
+ materialized
+}
+
fn should_transform(document: &NativeDom) -> bool {
if !document.parse_errors().is_empty() || document.document_element_handle().is_none() {
return false;
@@ -359,12 +473,10 @@ mod tests {
use url::Url;
fn parse_top_level(source: &str) -> NativeDom {
- XmlParser
- .parse_top_level_document_with_handoffs(
- Url::parse("https://example.test/document.xml").unwrap(),
- source.to_owned(),
- )
- .0
+ XmlParser.parse_top_level_document(
+ Url::parse("https://example.test/document.xml").unwrap(),
+ source.to_owned(),
+ )
}
fn document_element(document: &NativeDom) -> NativeNodeId {
diff --git a/moli-protocol-webdriver-bidi/src/network.rs b/moli-protocol-webdriver-bidi/src/network.rs
index 1a04a10cb..ae7990b6c 100644
--- a/moli-protocol-webdriver-bidi/src/network.rs
+++ b/moli-protocol-webdriver-bidi/src/network.rs
@@ -427,7 +427,10 @@ fn network_request_event_cdp_params(event: &NetworkRequestEvent, method: &str) -
"type": event.request_initiator_type.as_deref().unwrap_or("other")
},
"redirectHasExtraInfo": event.redirect_has_extra_info,
- "type": event.resource_type.as_deref().unwrap_or_default(),
+ "type": event
+ .resource_type
+ .map(|resource_type| resource_type.as_cdp_type())
+ .unwrap_or_default(),
"frameId": event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or_default(),
"hasUserGesture": false,
});
@@ -462,7 +465,10 @@ fn network_request_event_cdp_params(event: &NetworkRequestEvent, method: &str) -
"requestId": event.request_id.as_str(),
"loaderId": event.loader_id.as_ref().map(|id| id.as_str()).unwrap_or_default(),
"timestamp": event.timestamp.unwrap_or_default(),
- "type": event.resource_type.as_deref().unwrap_or_default(),
+ "type": event
+ .resource_type
+ .map(|resource_type| resource_type.as_cdp_type())
+ .unwrap_or_default(),
"frameId": event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or_default(),
"response": {
"url": event.url,
@@ -488,7 +494,10 @@ fn network_request_event_cdp_params(event: &NetworkRequestEvent, method: &str) -
"Network.loadingFailed" => json!({
"requestId": event.request_id.as_str(),
"timestamp": event.timestamp.unwrap_or_default(),
- "type": event.resource_type.as_deref().unwrap_or_default(),
+ "type": event
+ .resource_type
+ .map(|resource_type| resource_type.as_cdp_type())
+ .unwrap_or_default(),
"errorText": event.error_text.as_deref().unwrap_or_default(),
"canceled": event.loading_failed_canceled,
}),
@@ -1171,7 +1180,7 @@ fn json_number_as_u64(value: &Value) -> Option<u64> {
mod tests {
use moli_protocol::devtools_runtime::{
AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsNetworkInterceptId,
- DevToolsRequestId, DevToolsTargetId, NetworkRequestEvent,
+ DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId, NetworkRequestEvent,
};
use serde_json::json;
@@ -1307,7 +1316,7 @@ mod tests {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(1.25),
wall_time: None,
status: Some(200),
@@ -1355,7 +1364,7 @@ mod tests {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(1.25),
wall_time: None,
status: Some(200),
diff --git a/moli-protocol-webdriver-bidi/src/tests.rs b/moli-protocol-webdriver-bidi/src/tests.rs
index e25b539d1..592cdf660 100644
--- a/moli-protocol-webdriver-bidi/src/tests.rs
+++ b/moli-protocol-webdriver-bidi/src/tests.rs
@@ -1,12 +1,12 @@
use moli_protocol::devtools_runtime::{
AutomationEvent, BrowserDownloadProgressEvent, BrowserDownloadWillBeginEvent,
DevToolsBrowserContextId, DevToolsFrameId, DevToolsLoaderId, DevToolsNavigationId,
- DevToolsNetworkInterceptId, DevToolsRealmId, DevToolsRemoteValue, DevToolsRequestId,
- DevToolsStackCallFrame, DevToolsStackTrace, DevToolsTargetId, DevToolsTargetInfo,
- DevToolsTargetKind, LogEntryEvent, NavigationFrameEvent, NavigationFrameEventKind,
- NavigationLifecycleEvent, NetworkAuthChallengeEvent, NetworkRequestEvent,
- PageFileChooserOpenedEvent, PageJavaScriptDialogOpeningEvent, RuntimeConsoleEvent,
- RuntimeExecutionContextEvent, RuntimeExecutionContextsClearedEvent,
+ DevToolsNetworkInterceptId, DevToolsNetworkResourceType, DevToolsRealmId, DevToolsRemoteValue,
+ DevToolsRequestId, DevToolsStackCallFrame, DevToolsStackTrace, DevToolsTargetId,
+ DevToolsTargetInfo, DevToolsTargetKind, LogEntryEvent, NavigationFrameEvent,
+ NavigationFrameEventKind, NavigationLifecycleEvent, NetworkAuthChallengeEvent,
+ NetworkRequestEvent, PageFileChooserOpenedEvent, PageJavaScriptDialogOpeningEvent,
+ RuntimeConsoleEvent, RuntimeExecutionContextEvent, RuntimeExecutionContextsClearedEvent,
SameDocumentNavigationEvent, ScriptMessageEvent, TargetLifecycleEvent, UserPromptClosedEvent,
webdriver_bidi_node_shared_id_for_backend_node_id,
};
@@ -2783,7 +2783,7 @@ fn session_subscribe_serializes_blocked_network_automation_events() {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(1.0),
wall_time: Some(1.0),
status: None,
@@ -2819,7 +2819,7 @@ fn session_subscribe_serializes_blocked_network_automation_events() {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(1.25),
wall_time: None,
status: Some(200),
@@ -2984,7 +2984,7 @@ fn session_subscribe_serializes_auth_required_network_automation_event() {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(3.0),
wall_time: Some(3.0),
status: None,
diff --git a/moli-protocol/src/conn.rs b/moli-protocol/src/conn.rs
index 35fc9342e..0ea066f52 100644
--- a/moli-protocol/src/conn.rs
+++ b/moli-protocol/src/conn.rs
@@ -512,7 +512,10 @@ pub(crate) use runtime_load::{
};
use scheduler_hooks::CdpSchedulerHooks;
use scheduler_state::CdpConnectionSchedulerState;
-pub use scheduler_state::{BackgroundNavigationGateKey, CdpSchedulerEvent, CdpTurnOutcome};
+pub use scheduler_state::{
+ BackgroundNavigationCancellation, BackgroundNavigationGateKey, CdpSchedulerEvent,
+ CdpTurnOutcome,
+};
#[cfg(test)]
pub(crate) use site_data_manager_surface::{
BrowserContextReservedSiteDataOwnerState, BrowserContextSiteDataManagerOwnerState,
@@ -1422,10 +1425,14 @@ impl CdpConnection {
&mut self,
token: &DocumentNavigationToken,
state: &NavigationDispatchState,
+ cancellation: BackgroundNavigationCancellation,
) {
let key = BackgroundNavigationGateKey::for_navigation(token, state);
self.scheduler_state
- .push_scheduler_event(CdpSchedulerEvent::BackgroundNavigationStarted { key });
+ .push_scheduler_event(CdpSchedulerEvent::BackgroundNavigationStarted {
+ key,
+ cancellation,
+ });
}
pub fn has_pending_document_navigation_for_session_owner(
@@ -1537,11 +1544,27 @@ impl CdpConnection {
.and_then(|slot| slot.current_document_loader_id().map(str::to_owned))
}
+ #[cfg(test)]
pub(crate) fn ingest_renderer_network_output_item_and_prepare_live_delivery_for_session_owner(
&mut self,
session_id: Option<&str>,
source_document: moli_core::RendererDocumentLifecycleIdentity,
item: &moli_core::page::ScriptNetworkOutputItem,
+ ) -> Option<crate::domains::network::TargetNetworkBacklogPreparedDelivery> {
+ self.ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(
+ session_id,
+ None,
+ source_document,
+ item,
+ )
+ }
+
+ pub(crate) fn ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(
+ &mut self,
+ session_id: Option<&str>,
+ source_renderer_page: Option<RendererPageResidenceIdentity>,
+ source_document: moli_core::RendererDocumentLifecycleIdentity,
+ item: &moli_core::page::ScriptNetworkOutputItem,
) -> Option<crate::domains::network::TargetNetworkBacklogPreparedDelivery> {
let primary_session_id = self.runtime_session_owner_primary_session_id(session_id);
let mut request_id_allocator = std::mem::take(&mut self.network_request_id_allocator);
@@ -1550,6 +1573,7 @@ impl CdpConnection {
.ok()
.and_then(|slot| {
slot.ingest_renderer_network_output_item_and_prepare_live_delivery(
+ source_renderer_page,
source_document,
item,
session_id,
diff --git a/moli-protocol/src/conn/browser_context/fetch_owner.rs b/moli-protocol/src/conn/browser_context/fetch_owner.rs
index bdde2f477..2d4b25e61 100644
--- a/moli-protocol/src/conn/browser_context/fetch_owner.rs
+++ b/moli-protocol/src/conn/browser_context/fetch_owner.rs
@@ -11,7 +11,7 @@ use crate::conn::{
PendingFetchResponseBodyStreamReadStart, PendingSubresourceFetchAuthRequest,
PendingSubresourceFetchRequest, PendingSubresourceFetchResponseRequest, TargetRuntimeSlot,
};
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use crate::domains::network::TargetIoStreamRead;
pub(crate) type SessionOwnerPendingFetchState = (
@@ -903,7 +903,7 @@ impl CdpConnection {
&self,
target_id: &str,
request_stage: FetchRequestStage,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &url::Url,
) -> Vec<DevToolsNetworkInterceptId> {
self.target_fetch_config_for_target(target_id)
diff --git a/moli-protocol/src/conn/browser_context/target_session_owner.rs b/moli-protocol/src/conn/browser_context/target_session_owner.rs
index d2165933a..b8b91b2a0 100644
--- a/moli-protocol/src/conn/browser_context/target_session_owner.rs
+++ b/moli-protocol/src/conn/browser_context/target_session_owner.rs
@@ -17,7 +17,7 @@ use crate::conn::{
PendingFetchNavigation, PendingSubresourceFetchAuthRequest, PendingSubresourceFetchRequest,
PendingSubresourceFetchResponseRequest, RuntimeBindingDefinition,
};
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use moli_cookie_jar::{StoredCookieQueryReport, StoredCookieSetReport};
#[cfg(test)]
use moli_core::page::RendererServiceWorkerVersionStatus;
@@ -1556,6 +1556,29 @@ impl<'a> TargetSessionOwnerMut<'a> {
}
}
+ pub(super) fn apply_renderer_document_title(&mut self, title: String) -> Option<bool> {
+ match self {
+ Self::ActiveTarget {
+ browser_context, ..
+ } => Some(
+ browser_context
+ .active_target
+ .owner_state
+ .commit_document_title(title),
+ ),
+ Self::BackgroundTarget {
+ browser_context,
+ target_id,
+ ..
+ } => Some(
+ browser_context.mutate_parked_target_owner_state(target_id, |owner_state| {
+ owner_state.commit_document_title(title)
+ }),
+ ),
+ Self::NoLoadedBrowserContext => None,
+ }
+ }
+
pub(super) fn navigation_history_entry_url(&mut self, entry_id: i32) -> Option<String> {
match self {
Self::ActiveTarget {
@@ -1833,7 +1856,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
fetch_snapshot
.matching_request_stage_pause_sessions(
default_session_id.as_deref(),
- "Document",
+ DevToolsNetworkResourceType::Document,
requested_url,
)
.into_iter()
@@ -1845,7 +1868,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
fetch_snapshot
.matching_response_stage_pause_sessions(
default_session_id.as_deref(),
- "Document",
+ DevToolsNetworkResourceType::Document,
requested_url,
)
.into_iter()
@@ -1956,7 +1979,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
fetch_snapshot
.matching_request_stage_pause_sessions(
target_session_id.as_deref(),
- "Document",
+ DevToolsNetworkResourceType::Document,
requested_url,
)
.into_iter()
@@ -1968,7 +1991,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
fetch_snapshot
.matching_response_stage_pause_sessions(
target_session_id.as_deref(),
- "Document",
+ DevToolsNetworkResourceType::Document,
requested_url,
)
.into_iter()
@@ -2234,6 +2257,8 @@ impl<'a> TargetSessionOwnerMut<'a> {
target_id,
..
} => {
+ let committed_document_post_response_continuation =
+ page.take_committed_document_post_response_continuation();
let previous_page_owner = TargetPageResidenceIdentity::new(
browser_context.id.clone(),
Some(target_id.clone()),
@@ -2246,11 +2271,28 @@ impl<'a> TargetSessionOwnerMut<'a> {
.background_target(target_id)?
.session_id()
.map(str::to_owned);
+ let previous_title = browser_context
+ .parked_target_owner_state(target_id)
+ .and_then(|owner_state| {
+ owner_state.committed_document_title().map(str::to_owned)
+ })
+ .or_else(|| {
+ browser_context
+ .background_target(target_id)?
+ .runtime_slot()
+ .loaded_page()
+ .map(Page::document_title)
+ });
+ let committed_document_title = page.document_title();
let page_snapshot = (history_url.to_string(), page.document_title());
browser_context.mutate_parked_target_owner_state(target_id, |owner_state| {
owner_state.mark_initial_empty_document_exited();
+ if let Some(previous_title) = previous_title {
+ owner_state.refresh_current_navigation_history_title(previous_title);
+ }
owner_state.record_loaded_page_navigation_history(page_snapshot);
owner_state.clear_committed_document_navigation_state();
+ owner_state.commit_document_title(committed_document_title);
});
browser_context.mutate_parked_page_session_state(target_id, |state| {
clear_parked_page_loaded_document_session_state(state);
@@ -2321,6 +2363,7 @@ impl<'a> TargetSessionOwnerMut<'a> {
}
Some(Ok(LoadedNavigationPageCommit {
replaced_page_owner,
+ committed_document_post_response_continuation,
}))
}
Self::NoLoadedBrowserContext => None,
@@ -3358,6 +3401,19 @@ impl CdpConnection {
.navigation_history_snapshot()
}
+ pub(crate) fn apply_renderer_document_title_for_session_owner(
+ &mut self,
+ session_id: Option<&str>,
+ change: &moli_core::RendererDocumentTitleChanged,
+ ) -> Option<bool> {
+ self.target_root_document_protocol_attachment_identity_for_session(
+ session_id,
+ change.source_document,
+ )?;
+ self.target_session_owner_mut(session_id)?
+ .apply_renderer_document_title(change.title.clone())
+ }
+
pub(crate) fn target_session_owner_navigation_history_entry_url(
&mut self,
session_id: Option<&str>,
diff --git a/moli-protocol/src/conn/dispatch_tests.rs b/moli-protocol/src/conn/dispatch_tests.rs
index 3e6e40bf4..690d2fc5a 100644
--- a/moli-protocol/src/conn/dispatch_tests.rs
+++ b/moli-protocol/src/conn/dispatch_tests.rs
@@ -71,18 +71,8 @@ async fn execute_direct_devtools_command_through_renderer_fence_for_test(
ctx: &mut crate::testing::TestContext,
command: DevToolsCommand,
) -> Result<DevToolsCommandResult, crate::devtools_runtime::DevToolsError> {
- let (result, scheduler_events, protocol_events, renderer_output_predecessor) = ctx
- .conn
- .execute_devtools_command(command)
+ ctx.execute_devtools_command_through_renderer_fence_for_test(command)
.await
- .into_complete_parts();
- if let Some(predecessor) = renderer_output_predecessor {
- ctx.route_direct_command_renderer_predecessor_for_test(predecessor)
- .await;
- }
- ctx.route_direct_command_output_for_test(protocol_events, scheduler_events)
- .await;
- result
}
async fn evaluate_string_through_renderer_fence_for_test(
@@ -144,7 +134,7 @@ async fn create_target_in_browser_context_through_renderer_fence_for_test(
}
async fn materialize_bidi_target_node_for_test(
- conn: &mut CdpConnection,
+ ctx: &mut crate::testing::TestContext,
html: &str,
selector: &str,
) -> (DevToolsCommandContext, DevToolsRemoteHandleId, u32) {
@@ -154,15 +144,16 @@ async fn materialize_bidi_target_node_for_test(
target_id: None,
browser_context_id: None,
};
- let (create_result, _, _, _) = conn
- .execute_devtools_command(DevToolsCommand::CreateTarget(DevToolsCreateTargetCommand {
- context: context.clone(),
- url: "about:blank".to_owned(),
- browser_context_id: None,
- activate: false,
- }))
- .await
- .into_complete_parts();
+ let create_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CreateTarget(
+ DevToolsCreateTargetCommand {
+ context: context.clone(),
+ url: "about:blank".to_owned(),
+ browser_context_id: None,
+ activate: false,
+ },
+ ))
+ .await;
let DevToolsCommandResult::CreateTarget(create_result) =
create_result.expect("create target should succeed")
else {
@@ -173,19 +164,20 @@ async fn materialize_bidi_target_node_for_test(
..context
};
- let (navigate_result, _, _, _) = conn
- .execute_devtools_command(DevToolsCommand::Navigate(DevToolsNavigateCommand {
- context: target_context.clone(),
- url: format!("data:text/html,{html}"),
- referrer: None,
- wait: DevToolsNavigationWait::Load,
- }))
- .await
- .into_complete_parts();
+ let navigate_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::Navigate(
+ DevToolsNavigateCommand {
+ context: target_context.clone(),
+ url: format!("data:text/html,{html}"),
+ referrer: None,
+ wait: DevToolsNavigationWait::Load,
+ },
+ ))
+ .await;
navigate_result.expect("navigate should succeed");
- let (evaluate_result, _, _, _) = conn
- .execute_devtools_command(DevToolsCommand::EvaluateScript(
+ let evaluate_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::EvaluateScript(
DevToolsEvaluateScriptCommand {
context: target_context.clone(),
realm_id: None,
@@ -200,8 +192,7 @@ async fn materialize_bidi_target_node_for_test(
serialization_options: None,
},
))
- .await
- .into_complete_parts();
+ .await;
let DevToolsCommandResult::Script(evaluate_result) =
evaluate_result.expect("node evaluate should succeed")
else {
@@ -220,10 +211,10 @@ async fn materialize_bidi_target_node_for_test(
}
async fn materialize_bidi_target_input_node_for_test(
- conn: &mut CdpConnection,
+ ctx: &mut crate::testing::TestContext,
html: &str,
) -> (DevToolsCommandContext, DevToolsRemoteHandleId, u32) {
- materialize_bidi_target_node_for_test(conn, html, "#target").await
+ materialize_bidi_target_node_for_test(ctx, html, "#target").await
}
async fn ensure_initial_document_for_target_id_for_test(
@@ -3889,10 +3880,10 @@ async fn devtools_call_function_node_shared_id_failure_precedes_handle() {
#[tokio::test]
async fn bidi_node_remote_value_registers_renderer_shared_node_binding() {
- let mut conn = CdpConnection::new();
+ let mut ctx = crate::testing::TestContext::from_conn(CdpConnection::new());
let (_target_context, shared_id, backend_node_id) =
materialize_bidi_target_input_node_for_test(
- &mut conn,
+ &mut ctx,
"<input id='target' data-state='ready'>",
)
.await;
@@ -3901,9 +3892,11 @@ async fn bidi_node_remote_value_registers_renderer_shared_node_binding() {
"BiDi node remote value should carry renderer-owned backend id"
);
- conn.clear_runtime_remote_object_tracking_for_session_owner(None);
+ ctx.conn
+ .clear_runtime_remote_object_tracking_for_session_owner(None);
- let renderer_binding = conn
+ let renderer_binding = ctx
+ .conn
.document_bidi_node_binding_for_session_owner_async(None, shared_id.as_str())
.await
.expect("renderer BiDi shared-node binding lookup should run");
@@ -4019,16 +4012,16 @@ async fn bidi_node_remote_value_reuses_renderer_frontend_node_id() {
#[tokio::test]
async fn bidi_node_remote_value_registers_child_shared_node_bindings() {
- let mut conn = CdpConnection::new();
+ let mut ctx = crate::testing::TestContext::from_conn(CdpConnection::new());
let (target_context, _shared_id, _backend_node_id) = materialize_bidi_target_node_for_test(
- &mut conn,
+ &mut ctx,
"<section id='target'><a id='inside'>Inside</a></section>",
"#target",
)
.await;
- let (evaluate_result, _) = conn
- .execute_devtools_command(DevToolsCommand::EvaluateScript(
+ let evaluate_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::EvaluateScript(
DevToolsEvaluateScriptCommand {
context: target_context.clone(),
realm_id: None,
@@ -4047,8 +4040,7 @@ async fn bidi_node_remote_value_registers_child_shared_node_bindings() {
}),
},
))
- .await
- .into_parts();
+ .await;
let remote_value = expect_script_value_result(
evaluate_result.expect("node evaluate should succeed"),
"expected node script result",
@@ -4061,9 +4053,11 @@ async fn bidi_node_remote_value_registers_child_shared_node_bindings() {
.unwrap_or_else(|| panic!("serialized child should expose sharedId: {node_value}"))
.to_owned();
- conn.clear_runtime_remote_object_tracking_for_session_owner(None);
+ ctx.conn
+ .clear_runtime_remote_object_tracking_for_session_owner(None);
- let renderer_binding = conn
+ let renderer_binding = ctx
+ .conn
.document_bidi_node_binding_for_session_owner_async(None, &child_shared_id)
.await
.expect("child shared-node binding lookup should run");
@@ -4075,29 +4069,30 @@ async fn bidi_node_remote_value_registers_child_shared_node_bindings() {
"renderer DOM agent should register child sharedId bindings: {renderer_binding:?}"
);
- let (call_result, _) = conn
- .execute_devtools_command(DevToolsCommand::CallFunction(DevToolsCallFunctionCommand {
- context: target_context,
- realm_id: None,
- world_name: None,
- object_id: None,
- this_parameter: None,
- function_declaration: "(node) => `${node.localName}:${node.id}`".to_owned(),
- arguments: vec![json!({
- "type": "node",
- "sharedId": child_shared_id
- })],
- await_promise: false,
- user_gesture: false,
- webdriver_bidi_file_prompt_handler: None,
- result_ownership: DevToolsResultOwnership::None,
- object_group: None,
- preserve_remote_metadata: false,
- materialize_bidi_script_result: false,
- serialization_options: None,
- }))
- .await
- .into_parts();
+ let call_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CallFunction(
+ DevToolsCallFunctionCommand {
+ context: target_context,
+ realm_id: None,
+ world_name: None,
+ object_id: None,
+ this_parameter: None,
+ function_declaration: "(node) => `${node.localName}:${node.id}`".to_owned(),
+ arguments: vec![json!({
+ "type": "node",
+ "sharedId": child_shared_id
+ })],
+ await_promise: false,
+ user_gesture: false,
+ webdriver_bidi_file_prompt_handler: None,
+ result_ownership: DevToolsResultOwnership::None,
+ object_group: None,
+ preserve_remote_metadata: false,
+ materialize_bidi_script_result: false,
+ serialization_options: None,
+ },
+ ))
+ .await;
let remote_value = expect_script_value_result(
call_result.expect("callFunction should resolve child sharedId via renderer binding"),
"expected callFunction value result",
@@ -4107,24 +4102,25 @@ async fn bidi_node_remote_value_registers_child_shared_node_bindings() {
#[tokio::test]
async fn set_file_input_files_shared_id_uses_renderer_binding_without_protocol_registry() {
- let mut conn = CdpConnection::new();
+ let mut ctx = crate::testing::TestContext::from_conn(CdpConnection::new());
let (target_context, _shared_id, backend_node_id) =
- materialize_bidi_target_input_node_for_test(&mut conn, "<input id='target' type='file'>")
+ materialize_bidi_target_input_node_for_test(&mut ctx, "<input id='target' type='file'>")
.await;
let fake_shared_id =
crate::devtools_runtime::webdriver_bidi_node_shared_id_for_backend_node_id(backend_node_id);
- conn.register_document_bidi_node_binding_for_session_owner_async(
- None,
- fake_shared_id.as_str(),
- backend_node_id,
- )
- .await
- .expect("renderer fake shared-node binding registration should run");
+ ctx.conn
+ .register_document_bidi_node_binding_for_session_owner_async(
+ None,
+ fake_shared_id.as_str(),
+ backend_node_id,
+ )
+ .await
+ .expect("renderer fake shared-node binding registration should run");
let upload_bytes = b"from renderer registry";
- let (set_result, _) = conn
- .execute_devtools_command(DevToolsCommand::SetFileInputFiles(
- DevToolsSetFileInputFilesCommand {
+ let set_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::SetFileInputFiles(DevToolsSetFileInputFilesCommand {
context: target_context.clone(),
object_id: fake_shared_id,
files: vec![moli_core::page::SelectedFile {
@@ -4134,14 +4130,13 @@ async fn set_file_input_files_shared_id_uses_renderer_binding_without_protocol_r
last_modified: 0.0,
}],
append: false,
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
set_result.expect("setFileInputFiles should use renderer shared-node binding");
- let (evaluate_result, _) = conn
- .execute_devtools_command(DevToolsCommand::EvaluateScript(
+ let evaluate_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::EvaluateScript(
DevToolsEvaluateScriptCommand {
context: target_context,
realm_id: None,
@@ -4156,8 +4151,7 @@ async fn set_file_input_files_shared_id_uses_renderer_binding_without_protocol_r
serialization_options: None,
},
))
- .await
- .into_parts();
+ .await;
let remote_value = expect_script_value_result(
evaluate_result.expect("file input state evaluate should succeed"),
"expected file input state script result",
@@ -4170,37 +4164,39 @@ async fn set_file_input_files_shared_id_uses_renderer_binding_without_protocol_r
#[tokio::test]
async fn locate_nodes_start_node_shared_id_uses_renderer_binding_without_protocol_registry() {
- let mut conn = CdpConnection::new();
+ let mut ctx = crate::testing::TestContext::from_conn(CdpConnection::new());
let (target_context, _shared_id, backend_node_id) = materialize_bidi_target_node_for_test(
- &mut conn,
+ &mut ctx,
"<section id='target'><a id='inside'>Inside</a></section><a id='outside'>Outside</a>",
"#target",
)
.await;
let fake_shared_id =
crate::devtools_runtime::webdriver_bidi_node_shared_id_for_backend_node_id(backend_node_id);
- conn.register_document_bidi_node_binding_for_session_owner_async(
- None,
- fake_shared_id.as_str(),
- backend_node_id,
- )
- .await
- .expect("renderer fake shared-node binding registration should run");
-
- let (locate_result, _) = conn
- .execute_devtools_command(DevToolsCommand::LocateNodes(DevToolsLocateNodesCommand {
- context: target_context,
- locator: DevToolsLocateNodesLocator::Css("a".to_owned()),
- max_node_count: None,
- start_nodes: vec![json!({
- "type": "node",
- "sharedId": fake_shared_id.as_str()
- })],
- start_node_references: Vec::new(),
- serialization_options: None,
- }))
+ ctx.conn
+ .register_document_bidi_node_binding_for_session_owner_async(
+ None,
+ fake_shared_id.as_str(),
+ backend_node_id,
+ )
.await
- .into_parts();
+ .expect("renderer fake shared-node binding registration should run");
+
+ let locate_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::LocateNodes(
+ DevToolsLocateNodesCommand {
+ context: target_context,
+ locator: DevToolsLocateNodesLocator::Css("a".to_owned()),
+ max_node_count: None,
+ start_nodes: vec![json!({
+ "type": "node",
+ "sharedId": fake_shared_id.as_str()
+ })],
+ start_node_references: Vec::new(),
+ serialization_options: None,
+ },
+ ))
+ .await;
let DevToolsCommandResult::LocateNodes(locate_result) =
locate_result.expect("locateNodes should use renderer shared-node binding")
else {
@@ -4216,46 +4212,49 @@ async fn locate_nodes_start_node_shared_id_uses_renderer_binding_without_protoco
#[tokio::test]
async fn call_function_shared_id_uses_renderer_binding_without_protocol_registry() {
- let mut conn = CdpConnection::new();
+ let mut ctx = crate::testing::TestContext::from_conn(CdpConnection::new());
let (target_context, _shared_id, backend_node_id) = materialize_bidi_target_node_for_test(
- &mut conn,
+ &mut ctx,
"<section id='target'><a id='inside'>Inside</a></section>",
"#target",
)
.await;
let fake_shared_id =
crate::devtools_runtime::webdriver_bidi_node_shared_id_for_backend_node_id(backend_node_id);
- conn.register_document_bidi_node_binding_for_session_owner_async(
- None,
- fake_shared_id.as_str(),
- backend_node_id,
- )
- .await
- .expect("renderer fake shared-node binding registration should run");
-
- let (call_result, _) = conn
- .execute_devtools_command(DevToolsCommand::CallFunction(DevToolsCallFunctionCommand {
- context: target_context,
- realm_id: None,
- world_name: None,
- object_id: None,
- this_parameter: None,
- function_declaration: "(node) => `${node.id}:${node.querySelector('a').id}`".to_owned(),
- arguments: vec![json!({
- "type": "node",
- "sharedId": fake_shared_id.as_str()
- })],
- await_promise: false,
- user_gesture: false,
- webdriver_bidi_file_prompt_handler: None,
- result_ownership: DevToolsResultOwnership::None,
- object_group: None,
- preserve_remote_metadata: false,
- materialize_bidi_script_result: false,
- serialization_options: None,
- }))
+ ctx.conn
+ .register_document_bidi_node_binding_for_session_owner_async(
+ None,
+ fake_shared_id.as_str(),
+ backend_node_id,
+ )
.await
- .into_parts();
+ .expect("renderer fake shared-node binding registration should run");
+
+ let call_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CallFunction(
+ DevToolsCallFunctionCommand {
+ context: target_context,
+ realm_id: None,
+ world_name: None,
+ object_id: None,
+ this_parameter: None,
+ function_declaration: "(node) => `${node.id}:${node.querySelector('a').id}`"
+ .to_owned(),
+ arguments: vec![json!({
+ "type": "node",
+ "sharedId": fake_shared_id.as_str()
+ })],
+ await_promise: false,
+ user_gesture: false,
+ webdriver_bidi_file_prompt_handler: None,
+ result_ownership: DevToolsResultOwnership::None,
+ object_group: None,
+ preserve_remote_metadata: false,
+ materialize_bidi_script_result: false,
+ serialization_options: None,
+ },
+ ))
+ .await;
let remote_value = expect_script_value_result(
call_result.expect("callFunction should use renderer shared-node binding"),
"expected callFunction value result",
@@ -4790,7 +4789,7 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
loader_id.as_str(),
)
.await;
- let mut conn = ctx.conn;
+ let conn = &mut ctx.conn;
let (single_result, _) = conn
.execute_devtools_command(DevToolsCommand::QuerySelector(
@@ -5005,35 +5004,38 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
);
assert!(object_geometry_result.quads.is_empty());
- let (resolved_property_result, _) = conn
- .execute_devtools_command(DevToolsCommand::CallFunction(DevToolsCallFunctionCommand {
- context: DevToolsCommandContext {
- target_id: Some(target_id.clone()),
- ..context.clone()
+ let _ = conn;
+ let resolved_property_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CallFunction(
+ DevToolsCallFunctionCommand {
+ context: DevToolsCommandContext {
+ target_id: Some(target_id.clone()),
+ ..context.clone()
+ },
+ realm_id: None,
+ world_name: None,
+ object_id: Some(DevToolsRemoteHandleId::from(resolved_object_id)),
+ this_parameter: None,
+ function_declaration: "function() { return this.id; }".to_owned(),
+ arguments: Vec::new(),
+ await_promise: false,
+ user_gesture: false,
+ webdriver_bidi_file_prompt_handler: None,
+ result_ownership: DevToolsResultOwnership::ByValue,
+ object_group: None,
+ preserve_remote_metadata: false,
+ materialize_bidi_script_result: false,
+ serialization_options: None,
},
- realm_id: None,
- world_name: None,
- object_id: Some(DevToolsRemoteHandleId::from(resolved_object_id)),
- this_parameter: None,
- function_declaration: "function() { return this.id; }".to_owned(),
- arguments: Vec::new(),
- await_promise: false,
- user_gesture: false,
- webdriver_bidi_file_prompt_handler: None,
- result_ownership: DevToolsResultOwnership::ByValue,
- object_group: None,
- preserve_remote_metadata: false,
- materialize_bidi_script_result: false,
- serialization_options: None,
- }))
- .await
- .into_parts();
+ ))
+ .await;
let resolved_property = expect_script_value_result(
resolved_property_result.expect("resolved call function should succeed"),
"expected resolved call function value",
);
assert_eq!(resolved_property.value, json!("target"));
+ let conn = &mut ctx.conn;
let (scroll_result, _) = conn
.execute_devtools_command(DevToolsCommand::ScrollIntoViewIfNeeded(
DevToolsScrollIntoViewIfNeededCommand {
@@ -5099,20 +5101,22 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
assert_eq!(multiple_result.node_ids.len(), 2);
assert!(multiple_result.multiple);
- let (xpath_result, _) = conn
- .execute_devtools_command(DevToolsCommand::LocateNodes(DevToolsLocateNodesCommand {
- context: DevToolsCommandContext {
- target_id: Some(target_id.clone()),
- ..context.clone()
+ let _ = conn;
+ let xpath_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::LocateNodes(
+ DevToolsLocateNodesCommand {
+ context: DevToolsCommandContext {
+ target_id: Some(target_id.clone()),
+ ..context.clone()
+ },
+ locator: DevToolsLocateNodesLocator::XPath("//main[@id='target']".to_owned()),
+ max_node_count: Some(1),
+ start_nodes: Vec::new(),
+ start_node_references: Vec::new(),
+ serialization_options: None,
},
- locator: DevToolsLocateNodesLocator::XPath("//main[@id='target']".to_owned()),
- max_node_count: Some(1),
- start_nodes: Vec::new(),
- start_node_references: Vec::new(),
- serialization_options: None,
- }))
- .await
- .into_parts();
+ ))
+ .await;
let DevToolsCommandResult::LocateNodes(xpath_result) =
xpath_result.expect("xpath locate nodes should succeed")
else {
@@ -5128,23 +5132,24 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
);
assert_eq!(xpath_result.node_ids, vec![target_node_id]);
- let (link_result, _) = conn
- .execute_devtools_command(DevToolsCommand::LocateNodes(DevToolsLocateNodesCommand {
- context: DevToolsCommandContext {
- target_id: Some(target_id.clone()),
- ..context.clone()
- },
- locator: DevToolsLocateNodesLocator::LinkText {
- value: "Top Link".to_owned(),
- match_type: DevToolsLocateNodesTextMatch::Full,
+ let link_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::LocateNodes(
+ DevToolsLocateNodesCommand {
+ context: DevToolsCommandContext {
+ target_id: Some(target_id.clone()),
+ ..context.clone()
+ },
+ locator: DevToolsLocateNodesLocator::LinkText {
+ value: "Top Link".to_owned(),
+ match_type: DevToolsLocateNodesTextMatch::Full,
+ },
+ max_node_count: Some(1),
+ start_nodes: Vec::new(),
+ start_node_references: Vec::new(),
+ serialization_options: None,
},
- max_node_count: Some(1),
- start_nodes: Vec::new(),
- start_node_references: Vec::new(),
- serialization_options: None,
- }))
- .await
- .into_parts();
+ ))
+ .await;
let DevToolsCommandResult::LocateNodes(link_result) =
link_result.expect("link text locate nodes should succeed")
else {
@@ -5152,8 +5157,8 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
};
assert_eq!(link_result.node_ids.len(), 1);
- let (root_result, _) = conn
- .execute_devtools_command(DevToolsCommand::QuerySelector(
+ let root_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::QuerySelector(
DevToolsQuerySelectorCommand {
context: DevToolsCommandContext {
target_id: Some(target_id.clone()),
@@ -5164,8 +5169,7 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
multiple: false,
},
))
- .await
- .into_parts();
+ .await;
let DevToolsCommandResult::QuerySelector(root_result) =
root_result.expect("root query selector should succeed")
else {
@@ -5173,8 +5177,9 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
};
let root_node_id = root_result.node_ids[0];
- let (rooted_query_result, _, rooted_query_events) = conn
- .execute_devtools_command_with_protocol_events(DevToolsCommand::QuerySelector(
+ let sent_before_rooted_query = ctx.sent.len();
+ let rooted_query_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::QuerySelector(
DevToolsQuerySelectorCommand {
context: DevToolsCommandContext {
target_id: Some(target_id.clone()),
@@ -5185,12 +5190,11 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
multiple: false,
},
))
- .await
- .into_parts_with_protocol_events();
+ .await;
assert!(
- rooted_query_events
+ ctx.sent[sent_before_rooted_query..]
.iter()
- .all(|event| event.protocol_message().is_none()),
+ .all(|message| message.get("id").is_none()),
"direct rooted DOM.querySelector must not route child-node sidecars as protocol events"
);
let DevToolsCommandResult::QuerySelector(rooted_query_result) =
@@ -5201,23 +5205,24 @@ async fn devtools_command_executes_dom_query_selector_for_document_root() {
assert_eq!(rooted_query_result.node_ids.len(), 1);
assert_ne!(rooted_query_result.node_ids[0], link_result.node_ids[0]);
- let (root_link_result, _) = conn
- .execute_devtools_command(DevToolsCommand::LocateNodes(DevToolsLocateNodesCommand {
- context: DevToolsCommandContext {
- target_id: Some(target_id),
- ..context
- },
- locator: DevToolsLocateNodesLocator::LinkText {
- value: "Link".to_owned(),
- match_type: DevToolsLocateNodesTextMatch::Partial,
+ let root_link_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::LocateNodes(
+ DevToolsLocateNodesCommand {
+ context: DevToolsCommandContext {
+ target_id: Some(target_id),
+ ..context
+ },
+ locator: DevToolsLocateNodesLocator::LinkText {
+ value: "Link".to_owned(),
+ match_type: DevToolsLocateNodesTextMatch::Partial,
+ },
+ max_node_count: None,
+ start_nodes: Vec::new(),
+ start_node_references: vec![DevToolsDomNodeReference::FrontendNodeId(root_node_id)],
+ serialization_options: None,
},
- max_node_count: None,
- start_nodes: Vec::new(),
- start_node_references: vec![DevToolsDomNodeReference::FrontendNodeId(root_node_id)],
- serialization_options: None,
- }))
- .await
- .into_parts();
+ ))
+ .await;
let DevToolsCommandResult::LocateNodes(root_link_result) =
root_link_result.expect("rooted link text locate nodes should succeed")
else {
@@ -5565,9 +5570,8 @@ async fn devtools_command_executes_input_key_command_without_cdp_sidecar() {
"direct input key dispatch must not emit CDP-shaped sidecar messages: {protocol_events:?}"
);
- let (value_result, _) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::EvaluateScript(
+ let value_result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::EvaluateScript(
DevToolsEvaluateScriptCommand {
context: target_context,
realm_id: None,
@@ -5582,8 +5586,7 @@ async fn devtools_command_executes_input_key_command_without_cdp_sidecar() {
serialization_options: None,
},
))
- .await
- .into_parts();
+ .await;
let value_result = expect_script_value_result(
value_result.expect("value evaluation should succeed"),
"expected script value",
diff --git a/moli-protocol/src/conn/fetch_support.rs b/moli-protocol/src/conn/fetch_support.rs
index 7114e2b74..c0fa9e6d2 100644
--- a/moli-protocol/src/conn/fetch_support.rs
+++ b/moli-protocol/src/conn/fetch_support.rs
@@ -8,7 +8,7 @@ use super::{
CapturedBody, CapturedBodyWriter, CdpConnection, DocumentNavigationToken,
NavigationDispatchState, NavigationLoadOutcome, PausedResponsePreparedDocument,
};
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use crate::domains::network::MainDocumentBodyProgressSource;
use moli_cookie_jar::StoredCookieQueryReport;
use moli_core::page::{
@@ -45,16 +45,16 @@ pub struct FetchInterceptionPattern {
}
impl FetchInterceptionPattern {
- pub fn matches_request(&self, resource_type: &str, url: &Url) -> bool {
+ pub fn matches_request(&self, resource_type: DevToolsNetworkResourceType, url: &Url) -> bool {
self.resource_type_filter
- .is_none_or(|filter| filter.matches_cdp_type(resource_type))
+ .is_none_or(|filter| filter.matches_resource_type(resource_type))
&& url_pattern_matches(&self.url_pattern, url.as_str())
}
}
pub fn matching_fetch_pattern<'a>(
patterns: &'a [FetchInterceptionPattern],
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<&'a FetchInterceptionPattern> {
patterns
@@ -90,12 +90,28 @@ impl FetchResourceTypeFilter {
self.into()
}
- pub fn matches_cdp_type(self, resource_type: &str) -> bool {
+ pub fn matches_resource_type(self, resource_type: DevToolsNetworkResourceType) -> bool {
match self {
Self::Fetch | Self::EventSource | Self::Xhr => {
- matches!(resource_type, "Fetch" | "EventSource" | "XHR")
+ matches!(
+ resource_type,
+ DevToolsNetworkResourceType::Fetch
+ | DevToolsNetworkResourceType::EventSource
+ | DevToolsNetworkResourceType::Xhr
+ )
+ }
+ Self::Document => resource_type == DevToolsNetworkResourceType::Document,
+ Self::Script => resource_type == DevToolsNetworkResourceType::Script,
+ Self::Stylesheet => resource_type == DevToolsNetworkResourceType::Stylesheet,
+ Self::Image => resource_type == DevToolsNetworkResourceType::Image,
+ Self::Media => resource_type == DevToolsNetworkResourceType::Media,
+ Self::TextTrack => resource_type == DevToolsNetworkResourceType::TextTrack,
+ Self::Ping => resource_type == DevToolsNetworkResourceType::Ping,
+ Self::CspViolationReport => {
+ resource_type == DevToolsNetworkResourceType::CspViolationReport
}
- _ => self.label() == resource_type,
+ Self::WebSocket => resource_type == DevToolsNetworkResourceType::WebSocket,
+ Self::Other => resource_type == DevToolsNetworkResourceType::Other,
}
}
@@ -144,6 +160,7 @@ mod tests {
FetchInterceptionPattern, FetchRequestStage, FetchResourceTypeFilter,
fetch_subresource_interception_config_for_patterns, matching_fetch_pattern,
};
+ use crate::devtools_runtime::DevToolsNetworkResourceType;
use moli_core::page::SubresourceResourceType;
use url::Url;
@@ -186,7 +203,12 @@ mod tests {
.expect("CDP Fetch resourceType token should parse");
assert_eq!(parsed, expected);
assert_eq!(parsed.label(), raw);
- assert!(parsed.matches_cdp_type(raw));
+ assert!(
+ parsed.matches_resource_type(
+ DevToolsNetworkResourceType::from_cdp_type(raw)
+ .expect("supported Fetch filter should be a CDP network resource type"),
+ )
+ );
}
assert!(FetchResourceTypeFilter::parse("xhr").is_none());
}
@@ -207,11 +229,17 @@ mod tests {
];
let url = Url::parse("https://example.test/api").unwrap();
- let matched = matching_fetch_pattern(&patterns, "Fetch", &url).unwrap();
+ let matched =
+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Fetch, &url).unwrap();
assert_eq!(matched.request_stage, FetchRequestStage::Response);
- assert!(matching_fetch_pattern(&patterns, "Image", &url).is_none());
+ assert!(
+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Image, &url).is_none()
+ );
let script_url = Url::parse("https://example.test/script.js").unwrap();
- assert!(matching_fetch_pattern(&patterns, "Script", &script_url).is_some());
+ assert!(
+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Script, &script_url,)
+ .is_some()
+ );
}
#[test]
@@ -221,10 +249,17 @@ mod tests {
FetchResourceTypeFilter::EventSource,
FetchResourceTypeFilter::Xhr,
] {
- for resource_type in ["Fetch", "EventSource", "XHR"] {
- assert!(filter.matches_cdp_type(resource_type), "{filter:?}");
+ for resource_type in [
+ DevToolsNetworkResourceType::Fetch,
+ DevToolsNetworkResourceType::EventSource,
+ DevToolsNetworkResourceType::Xhr,
+ ] {
+ assert!(filter.matches_resource_type(resource_type), "{filter:?}");
}
- assert!(!filter.matches_cdp_type("Script"), "{filter:?}");
+ assert!(
+ !filter.matches_resource_type(DevToolsNetworkResourceType::Script),
+ "{filter:?}"
+ );
}
}
@@ -237,7 +272,10 @@ mod tests {
}];
let url = Url::parse("https://example.test/style.css").unwrap();
- assert!(matching_fetch_pattern(&patterns, "Stylesheet", &url).is_some());
+ assert!(
+ matching_fetch_pattern(&patterns, DevToolsNetworkResourceType::Stylesheet, &url)
+ .is_some()
+ );
}
#[test]
diff --git a/moli-protocol/src/conn/output.rs b/moli-protocol/src/conn/output.rs
index cecbf53f1..b622319f7 100644
--- a/moli-protocol/src/conn/output.rs
+++ b/moli-protocol/src/conn/output.rs
@@ -1,11 +1,11 @@
use crate::devtools_runtime::{
AutomationEvent, BrowserDownloadProgressEvent, BrowserDownloadWillBeginEvent, DevToolsFrameId,
- DevToolsRealmId, DevToolsRemoteHandleId, DevToolsTargetInfo, DomSetChildNodesEvent,
- LogEntryEvent, NavigationFrameEvent, NavigationFrameEventKind, NavigationLifecycleEvent,
- PageFileChooserOpenedEvent, PageJavaScriptDialogOpeningEvent, PageLifecycleEvent,
- RuntimeConsoleEvent, RuntimeExecutionContextEvent, RuntimeExecutionContextsClearedEvent,
- SameDocumentNavigationEvent, ScriptExceptionEvent, TargetAttachmentEvent,
- TargetDetachmentEvent, TargetLifecycleEvent, UserPromptClosedEvent,
+ DevToolsNetworkResourceType, DevToolsRealmId, DevToolsRemoteHandleId, DevToolsTargetInfo,
+ DomSetChildNodesEvent, LogEntryEvent, NavigationFrameEvent, NavigationFrameEventKind,
+ NavigationLifecycleEvent, PageFileChooserOpenedEvent, PageJavaScriptDialogOpeningEvent,
+ PageLifecycleEvent, RuntimeConsoleEvent, RuntimeExecutionContextEvent,
+ RuntimeExecutionContextsClearedEvent, SameDocumentNavigationEvent, ScriptExceptionEvent,
+ TargetAttachmentEvent, TargetDetachmentEvent, TargetLifecycleEvent, UserPromptClosedEvent,
};
use moli_core::{
RendererRuntimeInspectorAsyncCompletion,
@@ -2049,7 +2049,7 @@ impl ProtocolDeliveryEnvelope {
let Some(resource_type) = self.network_resource_type() else {
return false;
};
- resource_type != "Document"
+ resource_type != DevToolsNetworkResourceType::Document
}
/// Returns whether this event is an already-produced CDP Network-domain
@@ -2070,7 +2070,7 @@ impl ProtocolDeliveryEnvelope {
return false;
};
message.get("method").and_then(Value::as_str) == Some("Network.responseReceived")
- && self.network_resource_type() == Some("Document")
+ && self.network_resource_type() == Some(DevToolsNetworkResourceType::Document)
}
pub fn trace_network_summary(
@@ -2142,7 +2142,13 @@ impl ProtocolDeliveryEnvelope {
.or_else(|| params.pointer("/response/url"))
.or_else(|| params.get("documentURL"))
.and_then(Value::as_str);
- Some((method, self.network_resource_type(), request_id, url))
+ Some((
+ method,
+ self.network_resource_type()
+ .map(DevToolsNetworkResourceType::as_cdp_type),
+ request_id,
+ url,
+ ))
}
fn is_fetch_interception_control_path_event(&self) -> bool {
@@ -2183,14 +2189,14 @@ impl ProtocolDeliveryEnvelope {
.is_some_and(|blocked_intercepts| !blocked_intercepts.is_empty())
}
- fn network_resource_type(&self) -> Option<&str> {
+ fn network_resource_type(&self) -> Option<DevToolsNetworkResourceType> {
if let Some(resource_type) = self.automation_event_network_resource_type() {
return Some(resource_type);
}
self.protocol_message_network_resource_type()
}
- fn automation_event_network_resource_type(&self) -> Option<&str> {
+ fn automation_event_network_resource_type(&self) -> Option<DevToolsNetworkResourceType> {
let BackgroundProtocolEventPayload::Protocol(event) = &self.payload else {
return None;
};
@@ -2200,21 +2206,29 @@ impl ProtocolDeliveryEnvelope {
| AutomationEvent::NetworkResponseCompleted(event)
| AutomationEvent::NetworkFetchError(event)
| AutomationEvent::NetworkAuthRequired(event)
- | AutomationEvent::RequestPaused(event) => event.resource_type.as_deref(),
+ | AutomationEvent::RequestPaused(event) => event.resource_type,
_ => None,
}
}
- fn protocol_message_network_resource_type(&self) -> Option<&str> {
+ fn protocol_message_network_resource_type(&self) -> Option<DevToolsNetworkResourceType> {
let message = self.protocol_message()?;
let method = message.get("method")?.as_str()?;
let params = message.get("params")?;
match method {
"Network.requestWillBeSent" | "Network.responseReceived" | "Network.loadingFailed" => {
- params.get("type")?.as_str()
+ params
+ .get("type")?
+ .as_str()
+ .and_then(DevToolsNetworkResourceType::from_cdp_type)
+ }
+ "Network.webSocketFrameError" | "Network.webSocketClosed" => {
+ Some(DevToolsNetworkResourceType::WebSocket)
}
- "Network.webSocketFrameError" | "Network.webSocketClosed" => Some("WebSocket"),
- "Fetch.requestPaused" | "Fetch.authRequired" => params.get("resourceType")?.as_str(),
+ "Fetch.requestPaused" | "Fetch.authRequired" => params
+ .get("resourceType")?
+ .as_str()
+ .and_then(DevToolsNetworkResourceType::from_cdp_type),
_ => None,
}
}
@@ -4265,10 +4279,11 @@ pub fn build_event(method: &str, params: Value, session_id: Option<&str>) -> Val
mod tests {
use crate::devtools_runtime::{
AutomationEvent, DevToolsBrowserContextId, DevToolsFrameId, DevToolsLoaderId,
- DevToolsSessionId, DevToolsTargetId, DevToolsTargetInfo, DevToolsTargetKind,
- NavigationFrameEvent, NavigationFrameEventKind, NavigationLifecycleEvent,
- RuntimeExecutionContextEvent, RuntimeExecutionContextsClearedEvent, TargetAttachmentEvent,
- TargetDetachmentEvent, TargetLifecycleEvent, UserPromptClosedEvent,
+ DevToolsNetworkResourceType, DevToolsSessionId, DevToolsTargetId, DevToolsTargetInfo,
+ DevToolsTargetKind, NavigationFrameEvent, NavigationFrameEventKind,
+ NavigationLifecycleEvent, RuntimeExecutionContextEvent,
+ RuntimeExecutionContextsClearedEvent, TargetAttachmentEvent, TargetDetachmentEvent,
+ TargetLifecycleEvent, UserPromptClosedEvent,
};
use serde_json::{Value, json};
@@ -5441,7 +5456,7 @@ mod tests {
fn background_event_waits_for_navigation_completion_only_for_non_document_network() {
use crate::devtools_runtime::{DevToolsRequestId, NetworkRequestEvent};
- let network_event = |resource_type: Option<&str>| {
+ let network_event = |resource_type: Option<DevToolsNetworkResourceType>| {
AutomationEvent::NetworkResponseStarted(NetworkRequestEvent {
target_id: DevToolsTargetId::from("TID-nav"),
frame_id: Some(DevToolsFrameId::from("TID-nav")),
@@ -5457,7 +5472,7 @@ mod tests {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: resource_type.map(str::to_owned),
+ resource_type,
timestamp: Some(1.0),
wall_time: None,
status: Some(200),
@@ -5479,11 +5494,11 @@ mod tests {
let document = BackgroundProtocolEvent::immediate_automation_event(
json!({"method": "Network.responseReceived"}),
- network_event(Some("Document")),
+ network_event(Some(DevToolsNetworkResourceType::Document)),
);
let script = BackgroundProtocolEvent::immediate_automation_event(
json!({"method": "Network.responseReceived"}),
- network_event(Some("Script")),
+ network_event(Some(DevToolsNetworkResourceType::Script)),
);
let lifecycle = BackgroundProtocolEvent::immediate_automation_event(
json!({"method": "Page.frameStartedLoading"}),
diff --git a/moli-protocol/src/conn/page_state/loaded.rs b/moli-protocol/src/conn/page_state/loaded.rs
index 4bb6da374..c7e04cc65 100644
--- a/moli-protocol/src/conn/page_state/loaded.rs
+++ b/moli-protocol/src/conn/page_state/loaded.rs
@@ -5,11 +5,13 @@ use super::super::state::{
};
use super::super::{BackgroundTarget, BrowserContext, TargetRuntimeSlot};
use crate::conn::TargetPageResidenceIdentity;
-use moli_core::page::Page;
+use moli_core::page::{Page, RendererPageCommandPostResponseContinuation};
use url::Url;
pub(crate) struct LoadedNavigationPageCommit {
pub(crate) replaced_page_owner: Option<TargetPageResidenceIdentity>,
+ pub(crate) committed_document_post_response_continuation:
+ Option<RendererPageCommandPostResponseContinuation>,
}
pub(crate) enum LoadedNavigationRendererAttachmentCommit {
@@ -171,6 +173,17 @@ impl BrowserContext {
}
fn record_loaded_page_navigation_history(&mut self, page: &Page, history_url: &Url) {
+ let previous_title = self
+ .active_target
+ .owner_state
+ .committed_document_title()
+ .map(str::to_owned)
+ .or_else(|| self.loaded_page().map(Page::document_title));
+ if let Some(previous_title) = previous_title {
+ self.active_target
+ .owner_state
+ .refresh_current_navigation_history_title(previous_title);
+ }
self.active_target
.owner_state
.record_loaded_page_navigation_history((
@@ -235,6 +248,8 @@ impl BrowserContext {
renderer_attachment_commit: LoadedNavigationRendererAttachmentCommit,
history_url: &Url,
) -> anyhow::Result<LoadedNavigationPageCommit> {
+ let committed_document_post_response_continuation =
+ page.take_committed_document_post_response_continuation();
let previous_page_owner = TargetPageResidenceIdentity::new(
self.id.clone(),
self.active_target_id_owned(),
@@ -273,6 +288,7 @@ impl BrowserContext {
.runtime_slot
.install_pending_renderer_call_replacements(replacements);
}
+ let committed_document_title = page.document_title();
self.record_loaded_page_navigation_history(&page, history_url);
let previous = self.replace_loaded_page(Some(page));
self.reset_subresource_network_cursor();
@@ -280,6 +296,9 @@ impl BrowserContext {
self.active_target
.owner_state
.clear_committed_document_navigation_state();
+ self.active_target
+ .owner_state
+ .commit_document_title(committed_document_title);
self.clear_active_target_runtime_remote_object_tracking();
let replaced_page_owner = previous.as_ref().map(|_| previous_page_owner);
if let Some(page) = previous {
@@ -287,6 +306,7 @@ impl BrowserContext {
}
Ok(LoadedNavigationPageCommit {
replaced_page_owner,
+ committed_document_post_response_continuation,
})
}
diff --git a/moli-protocol/src/conn/page_state/parked.rs b/moli-protocol/src/conn/page_state/parked.rs
index 49c2435b9..f250cc783 100644
--- a/moli-protocol/src/conn/page_state/parked.rs
+++ b/moli-protocol/src/conn/page_state/parked.rs
@@ -1354,8 +1354,11 @@ impl BrowserContext {
target_id: Some(DevToolsTargetId::from(target_id)),
kind: DevToolsTargetKind::Page,
title: self
- .loaded_page()
- .map(|page| page.document_title())
+ .active_target
+ .owner_state
+ .committed_document_title()
+ .map(str::to_owned)
+ .or_else(|| self.loaded_page().map(|page| page.document_title()))
.unwrap_or_default(),
url: self.target_url().to_owned(),
attached,
@@ -1393,9 +1396,11 @@ impl BrowserContext {
Some(DevToolsTargetInfo {
target_id: Some(DevToolsTargetId::from(target.target_id())),
kind: DevToolsTargetKind::Page,
- title: target
- .loaded_page()
- .map(|page| page.document_title())
+ title: self
+ .parked_target_owner_state(target.target_id())
+ .and_then(|owner_state| owner_state.committed_document_title())
+ .map(str::to_owned)
+ .or_else(|| target.loaded_page().map(|page| page.document_title()))
.unwrap_or_default(),
url: target.target_url().to_owned(),
attached,
diff --git a/moli-protocol/src/conn/protocol_output.rs b/moli-protocol/src/conn/protocol_output.rs
index 74f41bb7c..f289c8c95 100644
--- a/moli-protocol/src/conn/protocol_output.rs
+++ b/moli-protocol/src/conn/protocol_output.rs
@@ -37,6 +37,32 @@ impl CdpConnection {
self.scheduler_state
.renderer_output_ingress
.close(stream, last_published_sequence);
+ if let Some(renderer_page) =
+ super::RendererPageResidenceIdentity::from_residence(stream.residence())
+ {
+ self.finish_renderer_page_output_retirement(renderer_page);
+ }
+ }
+ }
+ }
+
+ fn finish_renderer_page_output_retirement(
+ &mut self,
+ renderer_page: super::RendererPageResidenceIdentity,
+ ) {
+ for browser_context in self
+ .browser_context
+ .iter_mut()
+ .chain(self.inactive_browser_contexts.iter_mut())
+ {
+ browser_context
+ .active_target
+ .runtime_slot
+ .finish_renderer_page_output_retirement(renderer_page);
+ for target in &mut browser_context.background_targets {
+ target
+ .runtime_slot
+ .finish_renderer_page_output_retirement(renderer_page);
}
}
}
diff --git a/moli-protocol/src/conn/runtime_eval.rs b/moli-protocol/src/conn/runtime_eval.rs
index 16a6d45f1..29648a2a1 100644
--- a/moli-protocol/src/conn/runtime_eval.rs
+++ b/moli-protocol/src/conn/runtime_eval.rs
@@ -5973,20 +5973,15 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn document_node_snapshot_for_backend_node_id_reads_live_renderer_snapshot() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<html><body><article id='target'>live</article></body></html>",
- )
- .await
- .expect("test page should load");
let mut browser_context = BrowserContext::new("BID-runtime-node-snapshot".to_owned());
browser_context.set_active_target_id("TID-runtime-node-snapshot".to_owned());
- let _ = browser_context
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
ctx.conn.browser_context = Some(browser_context);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><body><article id='target'>live</article></body></html>",
+ None,
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1,
diff --git a/moli-protocol/src/conn/runtime_load.rs b/moli-protocol/src/conn/runtime_load.rs
index 5870871b9..0af9f22b7 100644
--- a/moli-protocol/src/conn/runtime_load.rs
+++ b/moli-protocol/src/conn/runtime_load.rs
@@ -694,6 +694,7 @@ fn spawn_captured_body_replay(
pub(crate) struct BackgroundNavigationLoadJob {
engine: NavigationEngine,
page_reservation: RendererPageReservationToken,
+ cancellation: BackgroundNavigationCancellation,
early_result: Option<BackgroundNavigationEarlyResult>,
load_inputs: TargetNavigationLoadInputs,
method: String,
@@ -807,6 +808,10 @@ impl BackgroundNavigationEarlyResult {
}
impl BackgroundNavigationLoadJob {
+ pub(crate) fn cancellation(&self) -> BackgroundNavigationCancellation {
+ self.cancellation.clone()
+ }
+
fn emit_early_result_for_successful_document(
early_result: &mut Option<BackgroundNavigationEarlyResult>,
navigation: &Result<NavigationLoadOutcome, String>,
@@ -899,6 +904,7 @@ impl BackgroundNavigationLoadJob {
self.body,
self.request_headers.clone(),
None,
+ self.cancellation.fetch_cancel_handle(),
)
.await;
let navigation_response = match navigation_response {
@@ -2124,7 +2130,8 @@ impl CdpConnection {
&mut self,
raw_url: &str,
) -> Result<LoadedNavigation, String> {
- self.load_navigation_via_runtime_for_session_owner_async(None, raw_url)
+ let load_inputs = self.navigation_load_inputs_for_session_owner(None);
+ self.load_navigation_via_runtime_with_load_inputs_async(None, raw_url, load_inputs)
.await
}
@@ -2135,25 +2142,44 @@ impl CdpConnection {
/// inserting it later. The latter cannot model renderer output ownership:
/// the Page stream is opened while the page is built and must already be
/// bound to its target before any concrete publication is consumed.
+ #[cfg(test)]
pub(crate) async fn load_navigation_via_runtime_for_session_owner_async(
&mut self,
session_id: Option<&str>,
raw_url: &str,
) -> Result<LoadedNavigation, String> {
- let request_headers = self
- .navigation_load_inputs_for_session_owner(session_id)
- .extra_http_headers;
+ let load_inputs = self.navigation_fixture_load_inputs_for_session_owner(session_id)?;
+ self.load_navigation_via_runtime_with_load_inputs_async(session_id, raw_url, load_inputs)
+ .await
+ }
+
+ async fn load_navigation_via_runtime_with_load_inputs_async(
+ &mut self,
+ session_id: Option<&str>,
+ raw_url: &str,
+ load_inputs: TargetNavigationLoadInputs,
+ ) -> Result<LoadedNavigation, String> {
+ let request_headers = load_inputs.extra_http_headers.clone();
let navigation = self
- .load_navigation_request_via_runtime_with_network_events_async(
+ .load_navigation_request_via_runtime_with_network_events_and_load_inputs_async(
session_id,
+ load_inputs,
"GET",
raw_url,
None,
request_headers,
MainDocumentBodyProgressSource::default(),
- NavigationRequestLoadPolicy::DocumentInitiated,
)
.await?;
+ self.commit_navigation_load_outcome_for_session_owner_async(session_id, navigation)
+ .await
+ }
+
+ async fn commit_navigation_load_outcome_for_session_owner_async(
+ &mut self,
+ session_id: Option<&str>,
+ navigation: NavigationLoadOutcome,
+ ) -> Result<LoadedNavigation, String> {
match navigation {
NavigationLoadOutcome::ResponseCommitReady(navigation) => {
let navigation = *navigation;
@@ -2365,6 +2391,7 @@ impl CdpConnection {
BackgroundNavigationLoadJob {
engine,
page_reservation,
+ cancellation: BackgroundNavigationCancellation::new(),
early_result,
load_inputs,
method: navigation.request_method.clone(),
@@ -2696,18 +2723,24 @@ impl CdpConnection {
response_headers: Vec<(String, String)>,
response_body: String,
) -> Result<LoadedNavigation, String> {
- self.build_loaded_navigation_from_buffered_response_for_session_owner_async(
- None,
+ let load_inputs = self.navigation_load_inputs_for_session_owner(None);
+ let initial_request_cookie_report =
+ load_inputs.request_cookie_report_for_navigation(&requested_url, &request_method, true);
+ self.build_loaded_navigation_from_buffered_response_with_request_cookie_report_async(
+ &load_inputs,
requested_url,
request_method,
request_headers,
response_status,
response_headers,
response_body,
+ None,
+ initial_request_cookie_report,
)
.await
}
+ #[cfg(test)]
pub(crate) async fn build_loaded_navigation_from_buffered_response_for_session_owner_async(
&mut self,
session_id: Option<&str>,
@@ -2718,21 +2751,45 @@ impl CdpConnection {
response_headers: Vec<(String, String)>,
response_body: String,
) -> Result<LoadedNavigation, String> {
- let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);
+ let load_inputs = self.navigation_fixture_load_inputs_for_session_owner(session_id)?;
let initial_request_cookie_report =
load_inputs.request_cookie_report_for_navigation(&requested_url, &request_method, true);
- self.build_loaded_navigation_from_buffered_response_with_request_cookie_report_async(
- &load_inputs,
- requested_url,
- request_method,
- request_headers,
- response_status,
- response_headers,
- response_body,
- None,
- initial_request_cookie_report,
- )
- .await
+ let navigation = self
+ .build_navigation_from_buffered_body_source_with_load_inputs_async(
+ session_id,
+ &load_inputs,
+ requested_url.clone(),
+ requested_url,
+ request_method,
+ request_headers,
+ response_status,
+ response_headers,
+ CapturedBody::from_string(response_body),
+ initial_request_cookie_report,
+ NetworkObservationJournal::default(),
+ MainDocumentBodyProgressSource::default(),
+ )
+ .await?;
+ self.commit_navigation_load_outcome_for_session_owner_async(session_id, navigation)
+ .await
+ }
+
+ #[cfg(test)]
+ fn navigation_fixture_load_inputs_for_session_owner(
+ &self,
+ session_id: Option<&str>,
+ ) -> Result<TargetNavigationLoadInputs, String> {
+ let load_inputs = self.navigation_load_inputs_for_session_owner(session_id);
+ let frame_id = load_inputs.root_frame_id.clone().ok_or_else(|| {
+ "navigation fixture requires an installed target root frame".to_owned()
+ })?;
+ Ok(load_inputs.with_main_document_commit_seed(
+ RendererMainDocumentCommitSeed::from_navigation_fixture(
+ frame_id,
+ DEFAULT_LOADER_ID.to_owned(),
+ monotonic_timestamp_seconds(),
+ ),
+ ))
}
/// Replays an already-buffered document response into the phase-one parser
diff --git a/moli-protocol/src/conn/scheduler_state.rs b/moli-protocol/src/conn/scheduler_state.rs
index 7cc0f852b..d98245bde 100644
--- a/moli-protocol/src/conn/scheduler_state.rs
+++ b/moli-protocol/src/conn/scheduler_state.rs
@@ -7,6 +7,39 @@ use serde_json::{Value, json};
const RECENT_ACTIVITY_TRACE_LIMIT: usize = 128;
+/// Transport cancellation authority for one exact background main-resource
+/// navigation.
+///
+/// The protocol scheduler keeps this beside the navigation gate so starting a
+/// replacement in the same frame can abort the superseded fetch immediately,
+/// matching the lifetime of Chromium's frame-owned `NavigationRequest`.
+#[derive(Clone, Debug, Default)]
+pub struct BackgroundNavigationCancellation {
+ handle: moli_fetch::FetchCancelHandle,
+}
+
+impl BackgroundNavigationCancellation {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn cancel(&self) {
+ self.handle.cancel();
+ }
+
+ pub fn is_cancelled(&self) -> bool {
+ self.handle.is_cancelled()
+ }
+
+ pub(crate) fn fetch_cancel_handle(&self) -> moli_fetch::FetchCancelHandle {
+ self.handle.clone()
+ }
+
+ pub(crate) fn from_fetch_cancel_handle(handle: moli_fetch::FetchCancelHandle) -> Self {
+ Self { handle }
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BackgroundNavigationGateKey {
target_id: Option<String>,
@@ -38,6 +71,25 @@ impl BackgroundNavigationGateKey {
}
}
+ /// Whether a newly-started navigation owns the same browsing-context
+ /// lane as an older in-flight navigation.
+ ///
+ /// Session identity is intentionally not part of a target-backed lane:
+ /// two DevTools sessions can address the same frame, but a cross-document
+ /// navigation from either session still supersedes the frame's previous
+ /// navigation. The exact loader/request fields remain part of equality so
+ /// a late completion cannot retire the replacement gate.
+ pub fn supersedes(&self, pending: &Self) -> bool {
+ if self.frame_id != pending.frame_id {
+ return false;
+ }
+ match (&self.target_id, &pending.target_id) {
+ (Some(target_id), Some(pending_target_id)) => target_id == pending_target_id,
+ (None, None) => self.session_id == pending.session_id,
+ (Some(_), None) | (None, Some(_)) => false,
+ }
+ }
+
#[cfg(feature = "test-support")]
pub(crate) fn from_test_parts(
target_id: Option<String>,
@@ -60,6 +112,7 @@ impl BackgroundNavigationGateKey {
pub enum CdpSchedulerEvent {
BackgroundNavigationStarted {
key: BackgroundNavigationGateKey,
+ cancellation: BackgroundNavigationCancellation,
},
ProtocolWorkPublished {
work: crate::domains::activity::ProtocolSchedulerWork,
diff --git a/moli-protocol/src/conn/state/fetch.rs b/moli-protocol/src/conn/state/fetch.rs
index f4cc2b763..e28af8dde 100644
--- a/moli-protocol/src/conn/state/fetch.rs
+++ b/moli-protocol/src/conn/state/fetch.rs
@@ -18,7 +18,7 @@ pub(super) use super::super::fetch_support::{
};
use super::navigation_outcome::NavigationDispatchState;
use super::runtime_slot::TargetRuntimeSlot;
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use moli_fetch::url_pattern_matches;
#[derive(Debug, Default)]
@@ -1112,7 +1112,7 @@ impl TargetFetchConfig {
#[cfg(test)]
pub(crate) fn matching_request_stage(
&self,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<FetchRequestStage> {
if !self.enabled {
@@ -1124,7 +1124,7 @@ impl TargetFetchConfig {
#[cfg(test)]
pub(crate) fn matching_document_request_stage(&self, url: &Url) -> Option<FetchRequestStage> {
- self.matching_request_stage("Document", url)
+ self.matching_request_stage(DevToolsNetworkResourceType::Document, url)
}
pub(crate) fn matches_auth_required(&self, url: &Url) -> bool {
@@ -1141,7 +1141,7 @@ impl TargetFetchConfig {
pub(crate) fn matching_network_intercepts(
&self,
request_stage: FetchRequestStage,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<DevToolsNetworkInterceptId> {
if !self.enabled {
@@ -1154,9 +1154,9 @@ impl TargetFetchConfig {
self.enabled
&& self.patterns.iter().any(|pattern| {
pattern.request_stage == FetchRequestStage::Response
- && pattern
- .resource_type_filter
- .is_none_or(|filter| filter.matches_cdp_type("Document"))
+ && pattern.resource_type_filter.is_none_or(|filter| {
+ filter.matches_resource_type(DevToolsNetworkResourceType::Document)
+ })
})
}
@@ -1326,7 +1326,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_request_stage(
&self,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<FetchRequestStage> {
if !self.enabled {
@@ -1339,7 +1339,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_fetch_request_stage_sessions(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<TargetFetchRequestStageSession> {
if !self.enabled {
@@ -1374,7 +1374,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_request_stage_pause_sessions(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<TargetFetchRequestStageSession> {
let mut sessions = self
@@ -1393,7 +1393,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
fn matching_network_request_stage_session(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<TargetFetchRequestStageSession> {
if !self.enabled {
@@ -1420,7 +1420,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_fetch_response_stage_sessions(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<TargetFetchResponseStageSession> {
if !self.enabled {
@@ -1446,7 +1446,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_response_stage_pause_sessions(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<TargetFetchResponseStageSession> {
let mut sessions =
@@ -1462,7 +1462,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
fn matching_network_response_stage_session(
&self,
default_session_id: Option<&str>,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<TargetFetchResponseStageSession> {
if !self.enabled {
@@ -1552,7 +1552,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn response_stage_owner_kind(
&self,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Option<PendingSubresourceFetchOwnerKind> {
if !self.enabled {
@@ -1576,7 +1576,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn response_stage_candidate_owner_kind(
&self,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
) -> Option<PendingSubresourceFetchOwnerKind> {
if !self.enabled {
return None;
@@ -1586,7 +1586,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pattern.request_stage == FetchRequestStage::Response
&& pattern
.resource_type_filter
- .is_none_or(|filter| filter.matches_cdp_type(resource_type))
+ .is_none_or(|filter| filter.matches_resource_type(resource_type))
})
}) {
return Some(PendingSubresourceFetchOwnerKind::Fetch);
@@ -1598,7 +1598,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pattern.request_stage == FetchRequestStage::Response
&& pattern
.resource_type_filter
- .is_none_or(|filter| filter.matches_cdp_type(resource_type))
+ .is_none_or(|filter| filter.matches_resource_type(resource_type))
})
})
.then_some(PendingSubresourceFetchOwnerKind::NetworkOrBidi)
@@ -1622,7 +1622,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
pub(crate) fn matching_network_intercepts(
&self,
request_stage: FetchRequestStage,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<DevToolsNetworkInterceptId> {
if !self.enabled {
@@ -1642,17 +1642,24 @@ impl TargetFetchSubresourceInterceptionSnapshot {
matching_auth_required_network_intercepts(&self.network_intercepts, url)
}
- pub(crate) fn has_response_stage_candidate(&self, resource_type: &str) -> bool {
+ pub(crate) fn has_response_stage_candidate(
+ &self,
+ resource_type: DevToolsNetworkResourceType,
+ ) -> bool {
self.enabled
&& self.patterns.iter().any(|pattern| {
pattern.request_stage == FetchRequestStage::Response
&& pattern
.resource_type_filter
- .is_none_or(|filter| filter.matches_cdp_type(resource_type))
+ .is_none_or(|filter| filter.matches_resource_type(resource_type))
})
}
- pub(crate) fn matches_response_stage(&self, resource_type: &str, url: &Url) -> bool {
+ pub(crate) fn matches_response_stage(
+ &self,
+ resource_type: DevToolsNetworkResourceType,
+ url: &Url,
+ ) -> bool {
self.enabled
&& self.patterns.iter().any(|pattern| {
pattern.request_stage == FetchRequestStage::Response
@@ -1664,7 +1671,7 @@ impl TargetFetchSubresourceInterceptionSnapshot {
fn matching_network_intercepts(
intercepts: &BTreeMap<String, TargetNetworkInterceptConfig>,
request_stage: FetchRequestStage,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &Url,
) -> Vec<DevToolsNetworkInterceptId> {
intercepts
diff --git a/moli-protocol/src/conn/state/navigation.rs b/moli-protocol/src/conn/state/navigation.rs
index 44bb8a705..ffb14ded2 100644
--- a/moli-protocol/src/conn/state/navigation.rs
+++ b/moli-protocol/src/conn/state/navigation.rs
@@ -126,6 +126,20 @@ impl TargetNavigationHistoryState {
.map(|entry| entry.url.clone())
}
+ pub(crate) fn refresh_current_entry_title(&mut self, title: String) -> bool {
+ let Some(current_entry) = self
+ .current_index
+ .and_then(|current_index| self.entries.get_mut(current_index))
+ else {
+ return false;
+ };
+ if current_entry.title == title {
+ return false;
+ }
+ current_entry.title = title;
+ true
+ }
+
pub(crate) fn snapshot(&self) -> (usize, Vec<PageNavigationHistoryEntry>) {
(self.current_index.unwrap_or(0), self.entries.clone())
}
@@ -316,4 +330,32 @@ mod tests {
));
assert_eq!(history.snapshot(), before);
}
+
+ #[test]
+ fn title_refresh_updates_only_current_entry_metadata() {
+ let mut history = TargetNavigationHistoryState::default();
+ let first_id = history.allocate_entry_id();
+ history.seed_entry(PageNavigationHistoryEntry {
+ id: first_id,
+ url: "https://example.test/a".to_owned(),
+ user_typed_url: "https://example.test/a".to_owned(),
+ title: String::new(),
+ transition_type: "typed".to_owned(),
+ document_sequence_number: None,
+ });
+ let before = history.snapshot().1[0].clone();
+
+ assert!(history.refresh_current_entry_title("A".to_owned()));
+ assert!(!history.refresh_current_entry_title("A".to_owned()));
+
+ let refreshed = &history.snapshot().1[0];
+ assert_eq!(refreshed.title, "A");
+ assert_eq!(refreshed.id, before.id);
+ assert_eq!(refreshed.url, before.url);
+ assert_eq!(refreshed.user_typed_url, before.user_typed_url);
+ assert_eq!(
+ refreshed.document_sequence_number,
+ before.document_sequence_number
+ );
+ }
}
diff --git a/moli-protocol/src/conn/state/navigation_outcome.rs b/moli-protocol/src/conn/state/navigation_outcome.rs
index b7980a161..74259aaf9 100644
--- a/moli-protocol/src/conn/state/navigation_outcome.rs
+++ b/moli-protocol/src/conn/state/navigation_outcome.rs
@@ -96,6 +96,25 @@ impl RendererMainDocumentCommitSeed {
}
}
+ /// Freezes the same renderer commit identity for a test navigation that
+ /// starts from an already-installed target without creating a synthetic
+ /// `NavigationDispatchState` or mutating the target's request counters.
+ #[cfg(test)]
+ pub(crate) fn from_navigation_fixture(
+ frame_id: String,
+ loader_id: String,
+ timestamp: f64,
+ ) -> Self {
+ let source_document_security = NavigationSourceDocumentSecurityContext::default();
+ Self {
+ frame_id,
+ loader_id,
+ timestamp,
+ inherited_security_origin: source_document_security.security_origin,
+ inherited_secure_context_type: source_document_security.secure_context_type,
+ }
+ }
+
pub(crate) fn resolve(
&self,
final_url: &Url,
@@ -359,9 +378,15 @@ impl<'a> TargetInfo<'a> {
kind: "page",
title: bc
.active_target
- .runtime_slot
- .loaded_page()
- .map(|page| page.document_title())
+ .owner_state
+ .committed_document_title()
+ .map(str::to_owned)
+ .or_else(|| {
+ bc.active_target
+ .runtime_slot
+ .loaded_page()
+ .map(|page| page.document_title())
+ })
.unwrap_or_default(),
url: bc.target_url(),
attached,
diff --git a/moli-protocol/src/conn/state/parking.rs b/moli-protocol/src/conn/state/parking.rs
index a97947e13..329124c03 100644
--- a/moli-protocol/src/conn/state/parking.rs
+++ b/moli-protocol/src/conn/state/parking.rs
@@ -881,6 +881,7 @@ impl TargetInitialEmptyDocumentState {
#[derive(Debug, Clone, Default)]
pub(crate) struct TargetOwnerState {
pub(crate) initial_empty_document: Option<TargetInitialEmptyDocumentState>,
+ pub(crate) committed_document_title: Option<String>,
pub(crate) next_document_start_script_id: u32,
pub(crate) document_start_scripts: Vec<(String, DocumentStartScript)>,
pub(crate) isolated_worlds: Vec<IsolatedWorldDefinition>,
@@ -897,6 +898,18 @@ pub(crate) struct TargetOwnerState {
}
impl TargetOwnerState {
+ pub(crate) fn committed_document_title(&self) -> Option<&str> {
+ self.committed_document_title.as_deref()
+ }
+
+ pub(crate) fn commit_document_title(&mut self, title: String) -> bool {
+ let changed = self.committed_document_title.as_deref().unwrap_or_default() != title;
+ self.committed_document_title = Some(title.clone());
+ self.navigation_history_state
+ .refresh_current_entry_title(title);
+ changed
+ }
+
pub(crate) fn has_bidi_channel_preload_script(&self) -> bool {
self.document_start_scripts
.iter()
@@ -1047,17 +1060,31 @@ impl TargetOwnerState {
}
}
- fn ensure_navigation_history_seeded(&mut self, page_snapshot: Option<(String, String)>) {
- if !self.navigation_history_state.is_empty() {
+ fn reconcile_navigation_history_page_snapshot(
+ &mut self,
+ page_snapshot: Option<(String, String)>,
+ ) {
+ let Some(mut page_snapshot) = page_snapshot else {
return;
+ };
+ if let Some(title) = self.committed_document_title() {
+ page_snapshot.1 = title.to_owned();
}
- let Some(page_snapshot) = page_snapshot else {
+ if !self.navigation_history_state.is_empty() {
+ let (_, title) = page_snapshot;
+ self.navigation_history_state
+ .refresh_current_entry_title(title);
return;
- };
+ }
let entry = self.navigation_history_entry_for_page_snapshot(page_snapshot);
self.navigation_history_state.seed_entry(entry);
}
+ pub(crate) fn refresh_current_navigation_history_title(&mut self, title: String) -> bool {
+ self.navigation_history_state
+ .refresh_current_entry_title(title)
+ }
+
pub(crate) fn mark_next_navigation_history_replace_current(&mut self) {
self.navigation_history_state.mark_replace_current();
}
@@ -1081,7 +1108,7 @@ impl TargetOwnerState {
page_snapshot: Option<(String, String)>,
entry_id: i32,
) -> Option<String> {
- self.ensure_navigation_history_seeded(page_snapshot);
+ self.reconcile_navigation_history_page_snapshot(page_snapshot);
self.navigation_history_state.entry_url(entry_id)
}
@@ -1089,7 +1116,7 @@ impl TargetOwnerState {
&mut self,
page_snapshot: Option<(String, String)>,
) -> (usize, Vec<PageNavigationHistoryEntry>) {
- self.ensure_navigation_history_seeded(page_snapshot);
+ self.reconcile_navigation_history_page_snapshot(page_snapshot);
self.navigation_history_state.snapshot()
}
@@ -1097,7 +1124,7 @@ impl TargetOwnerState {
&mut self,
page_snapshot: Option<(String, String)>,
) -> bool {
- self.ensure_navigation_history_seeded(page_snapshot);
+ self.reconcile_navigation_history_page_snapshot(page_snapshot);
self.navigation_history_state.prune_all_but_current()
}
@@ -1105,7 +1132,7 @@ impl TargetOwnerState {
&mut self,
page_snapshot: Option<(String, String)>,
) -> bool {
- self.ensure_navigation_history_seeded(page_snapshot);
+ self.reconcile_navigation_history_page_snapshot(page_snapshot);
self.navigation_history_state.can_prune_all_but_current()
}
@@ -1122,6 +1149,7 @@ impl TargetOwnerState {
}
pub(crate) fn clear_committed_document_navigation_state(&mut self) {
+ self.committed_document_title = None;
self.clear_observable_output_state();
self.clear_loaded_document_context_state();
}
@@ -1130,10 +1158,13 @@ impl TargetOwnerState {
&mut self,
page_snapshot: Option<(String, String)>,
url: String,
- title: String,
+ mut title: String,
history_update: moli_core::page::SameDocumentHistoryUpdate,
) {
- self.ensure_navigation_history_seeded(page_snapshot);
+ self.reconcile_navigation_history_page_snapshot(page_snapshot);
+ if let Some(committed_title) = self.committed_document_title() {
+ title = committed_title.to_owned();
+ }
let _ =
self.navigation_history_state
.record_same_document_update(url, title, history_update);
@@ -1190,6 +1221,7 @@ impl TargetOwnerState {
pub(crate) fn is_default(&self) -> bool {
self.initial_empty_document.is_none()
+ && self.committed_document_title.is_none()
&& self.next_document_start_script_id == 0
&& self.document_start_scripts.is_empty()
&& self.isolated_worlds.is_empty()
diff --git a/moli-protocol/src/conn/state/runtime_slot.rs b/moli-protocol/src/conn/state/runtime_slot.rs
index 535e54656..f4e8091e7 100644
--- a/moli-protocol/src/conn/state/runtime_slot.rs
+++ b/moli-protocol/src/conn/state/runtime_slot.rs
@@ -12,8 +12,9 @@ use crate::{
log_output_state::{TargetLogOutputQueueState, TargetNetworkLogEntry},
network::{
CapturedRequestBody, CapturedResponseBody, NetworkBacklogPreferredRequestId,
- PendingNetworkBacklogDeliverySnapshot, TargetIoStreamRead, TargetNetworkAgentState,
- TargetNetworkArtifacts, TargetNetworkBacklogPreparedDelivery,
+ PendingNetworkBacklogDeliverySnapshot, RetiringTargetNetworkAgentState,
+ TargetIoStreamRead, TargetNetworkAgentState, TargetNetworkArtifacts,
+ TargetNetworkBacklogPreparedDelivery,
},
observable_output::{
TargetRuntimeObservableQueueState, TargetRuntimeObservableSourceOutput,
@@ -38,6 +39,14 @@ pub(crate) struct FinishedRendererDocumentNavigation {
pub(crate) renderer_call_replacements: Option<PreparedRendererCallReplacements>,
}
+#[derive(Debug)]
+struct RetiringRendererDocumentOutput {
+ renderer_page: RendererPageResidenceIdentity,
+ loaded_page_generation: u64,
+ binding: CommittedRendererDocumentBinding,
+ network_agent: RetiringTargetNetworkAgentState,
+}
+
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(in crate::conn::state) struct TargetNetworkRequestCounters {
pub(in crate::conn::state) next_fetch_request_id: u32,
@@ -51,6 +60,7 @@ pub(crate) struct TargetRuntimeSlot {
pending_renderer_call_replacements: PreparedRendererCallReplacements,
javascript_dialog_scope: TargetJavaScriptDialogScope,
network_agent: TargetNetworkAgentState,
+ retiring_renderer_document_outputs: Vec<RetiringRendererDocumentOutput>,
log_output_queue: TargetLogOutputQueueState,
observable_queue: TargetRuntimeObservableQueueState,
request_counters: TargetNetworkRequestCounters,
@@ -199,9 +209,35 @@ impl TargetRuntimeSlot {
pub(crate) fn replace_loaded_page(&mut self, page: Option<Page>) -> Option<Page> {
self.javascript_dialog_scope.retire();
let mut page = page;
+ let retiring_document = self
+ .page_slot
+ .loaded_page()
+ .zip(self.page_slot.renderer_document_lifecycle_binding())
+ .map(|(loaded_page, binding)| {
+ (
+ RendererPageResidenceIdentity::from_page(loaded_page),
+ self.page_slot.loaded_page_generation(),
+ binding.clone(),
+ )
+ });
+ let retiring_document =
+ retiring_document.map(|(renderer_page, loaded_page_generation, binding)| {
+ RetiringRendererDocumentOutput {
+ renderer_page,
+ loaded_page_generation,
+ binding,
+ network_agent: self.network_agent.rotate_document_for_replacement(),
+ }
+ });
self.ensure_renderer_attachment_for_replacement(page.as_mut());
let previous = self.page_slot.replace_loaded_page(page);
- self.reset_document_output_state();
+ if let Some(retiring_document) = retiring_document {
+ self.retiring_renderer_document_outputs
+ .push(retiring_document);
+ self.reset_replacement_document_output_state();
+ } else {
+ self.reset_document_output_state();
+ }
self.ingest_owner_page_observable_output_updates();
previous
}
@@ -227,6 +263,10 @@ impl TargetRuntimeSlot {
/// retain response bodies nor rediscover errors from an older Document.
fn reset_document_output_state(&mut self) {
self.network_agent.reset_output_queue();
+ self.reset_replacement_document_output_state();
+ }
+
+ fn reset_replacement_document_output_state(&mut self) {
self.log_output_queue.reset();
self.observable_queue.reset_output_queue();
}
@@ -432,11 +472,47 @@ impl TargetRuntimeSlot {
self.devtools_renderer_channel.current()
}
- pub(crate) fn routes_renderer_page(
+ pub(crate) fn routes_current_renderer_page_owner(
+ &self,
+ renderer_page: RendererPageResidenceIdentity,
+ loaded_page_generation: u64,
+ ) -> bool {
+ self.page_slot.loaded_page_generation() == loaded_page_generation
+ && self.page_slot.routes_renderer_page(renderer_page)
+ }
+
+ pub(crate) fn routes_retiring_renderer_page_owner(
&self,
renderer_page: RendererPageResidenceIdentity,
+ loaded_page_generation: u64,
) -> bool {
- self.page_slot.routes_renderer_page(renderer_page)
+ self.retiring_renderer_document_outputs.iter().any(|entry| {
+ entry.renderer_page == renderer_page
+ && entry.loaded_page_generation == loaded_page_generation
+ })
+ }
+
+ pub(crate) fn finish_renderer_page_output_retirement(
+ &mut self,
+ renderer_page: RendererPageResidenceIdentity,
+ ) {
+ self.retiring_renderer_document_outputs.retain(|entry| {
+ if entry.renderer_page != renderer_page {
+ return true;
+ }
+ let unterminated_requests = entry
+ .network_agent
+ .unterminated_document_bound_request_diagnostics();
+ if !unterminated_requests.is_empty() {
+ tracing::warn!(
+ ?renderer_page,
+ renderer_document = ?entry.binding.renderer_document_identity(),
+ ?unterminated_requests,
+ "retired renderer Page closed before all subresource terminals reached protocol ingress"
+ );
+ }
+ false
+ });
}
pub(crate) fn attach_page_renderer_agent_as_current(
@@ -640,6 +716,7 @@ impl TargetRuntimeSlot {
/// merely because it occupies the same Page residence.
pub(crate) fn ingest_renderer_network_output_item_and_prepare_live_delivery(
&mut self,
+ source_renderer_page: Option<RendererPageResidenceIdentity>,
source_document: RendererDocumentLifecycleIdentity,
item: &ScriptNetworkOutputItem,
trigger_session_id: Option<&str>,
@@ -647,20 +724,47 @@ impl TargetRuntimeSlot {
preferred_request_id: Option<NetworkBacklogPreferredRequestId<'_>>,
network_request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,
) -> Option<TargetNetworkBacklogPreparedDelivery> {
- let binding = self.page_slot.renderer_document_lifecycle_binding()?;
- if binding.renderer_document_identity() != source_document {
- return None;
+ let current_renderer_page = self
+ .page_slot
+ .loaded_page()
+ .map(RendererPageResidenceIdentity::from_page);
+ if let Some(binding) = self.page_slot.renderer_document_lifecycle_binding()
+ && binding.renderer_document_identity() == source_document
+ && source_renderer_page.is_none_or(|page| Some(page) == current_renderer_page)
+ {
+ let loader_id = binding.loader_id.clone();
+ self.log_output_queue
+ .ingest_renderer_network_output_item(item);
+ return Some(
+ self.network_agent
+ .ingest_renderer_output_item_and_prepare_live_delivery(
+ item,
+ &loader_id,
+ trigger_session_id,
+ primary_session_id,
+ preferred_request_id,
+ network_request_id_allocator,
+ ),
+ );
}
- let loader_id = binding.loader_id.clone();
- self.log_output_queue
- .ingest_renderer_network_output_item(item);
+
+ let event_session_ids = self
+ .network_agent
+ .event_session_ids(trigger_session_id, primary_session_id);
+ let retiring = self
+ .retiring_renderer_document_outputs
+ .iter_mut()
+ .find(|entry| {
+ entry.binding.renderer_document_identity() == source_document
+ && source_renderer_page.is_none_or(|page| entry.renderer_page == page)
+ })?;
Some(
- self.network_agent
+ retiring
+ .network_agent
.ingest_renderer_output_item_and_prepare_live_delivery(
item,
- &loader_id,
- trigger_session_id,
- primary_session_id,
+ &retiring.binding.loader_id,
+ event_session_ids,
preferred_request_id,
network_request_id_allocator,
),
@@ -668,6 +772,10 @@ impl TargetRuntimeSlot {
}
pub(crate) fn renderer_subresources_are_idle(&self) -> bool {
+ // The armed network-idle lifecycle binding belongs to the current
+ // loader. A predecessor queue is retained only to deliver its final
+ // protocol facts; detached keepalive work from that Document must not
+ // hold the successor loader's network-idle milestone.
self.network_agent.renderer_subresources_are_idle()
}
@@ -1253,7 +1361,12 @@ impl TargetRuntimeSlot {
#[cfg(test)]
mod tests {
- use moli_core::page::RendererDevToolsAgentToken;
+ use moli_core::page::{
+ RendererDevToolsAgentToken, RendererDocumentToken, RendererFrameToken,
+ RendererLifecycleEpoch, ScriptNetworkOutputItem, SubresourceRequestInitiatorType,
+ SubresourceRequestStarted, SubresourceResourceType,
+ };
+ use url::Url;
use super::*;
@@ -1282,4 +1395,65 @@ mod tests {
"reusing the physical active slot for a new target must allocate a fresh channel"
);
}
+
+ #[test]
+ fn successor_network_idle_ignores_retained_predecessor_delivery_state() {
+ let page_id = moli_core::PageId::new_for_testing(41);
+ let handle = SubresourceNetworkRequestHandle::new(7);
+ let document_url = Url::parse("https://old.example/").expect("document URL should parse");
+ let request_url =
+ Url::parse("https://old.example/keepalive").expect("request URL should parse");
+ let started = ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(
+ SubresourceRequestStarted::new(
+ handle,
+ None,
+ document_url,
+ request_url,
+ "POST".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Fetch,
+ SubresourceRequestInitiatorType::Script,
+ None,
+ ),
+ ));
+ let mut predecessor_agent = TargetNetworkAgentState::default();
+ predecessor_agent.ingest_renderer_output_item(&started, "LOADER-old");
+ let retiring_agent = predecessor_agent.rotate_document_for_replacement();
+ assert_eq!(
+ retiring_agent
+ .unterminated_document_bound_request_diagnostics()
+ .len(),
+ 1
+ );
+
+ let mut slot = TargetRuntimeSlot::default();
+ slot.retiring_renderer_document_outputs
+ .push(RetiringRendererDocumentOutput {
+ renderer_page: RendererPageResidenceIdentity::new(
+ moli_core::RendererOwnerLocalHostId::new_for_testing(3),
+ page_id,
+ ),
+ loaded_page_generation: 1,
+ binding: CommittedRendererDocumentBinding {
+ renderer_frame: RendererFrameToken { page_id },
+ renderer_document: RendererDocumentToken {
+ page_id,
+ generation: 1,
+ },
+ renderer_epoch: RendererLifecycleEpoch(1),
+ navigation: None,
+ frame_id: "FRAME-old".to_owned(),
+ loader_id: "LOADER-old".to_owned(),
+ page_attachment_id: TargetPageAttachmentId::from_raw_for_test(1),
+ document_open_replacement_epoch: None,
+ },
+ network_agent: retiring_agent,
+ });
+
+ assert!(
+ slot.renderer_subresources_are_idle(),
+ "predecessor delivery state must not hold the current loader's network-idle milestone"
+ );
+ }
}
diff --git a/moli-protocol/src/conn/state/tests.rs b/moli-protocol/src/conn/state/tests.rs
index 94e0ecf02..1ad454427 100644
--- a/moli-protocol/src/conn/state/tests.rs
+++ b/moli-protocol/src/conn/state/tests.rs
@@ -1,3 +1,4 @@
+use crate::devtools_runtime::DevToolsNetworkResourceType;
use moli_cookie_jar::new_shared_browser_cookie_store;
use moli_core::page::{SameDocumentHistoryUpdate, SubresourceResourceType};
@@ -163,11 +164,17 @@ fn target_fetch_owner_projects_config_without_exposing_slots() {
"subresource snapshot preserves the event session id"
);
assert_eq!(
- snapshot.matching_request_stage("Fetch", &Url::parse("https://example.test/api").unwrap()),
+ snapshot.matching_request_stage(
+ DevToolsNetworkResourceType::Fetch,
+ &Url::parse("https://example.test/api").unwrap(),
+ ),
Some(FetchRequestStage::Response)
);
assert_eq!(
- snapshot.matching_request_stage("WebSocket", &Url::parse("wss://example.test/ws").unwrap()),
+ snapshot.matching_request_stage(
+ DevToolsNetworkResourceType::WebSocket,
+ &Url::parse("wss://example.test/ws").unwrap(),
+ ),
Some(FetchRequestStage::Request)
);
assert_eq!(
@@ -229,7 +236,10 @@ fn target_fetch_owner_projects_config_without_exposing_slots() {
assert_eq!(
owner
.subresource_interception_snapshot()
- .matching_request_stage("Document", &Url::parse("https://example.test/doc").unwrap()),
+ .matching_request_stage(
+ DevToolsNetworkResourceType::Document,
+ &Url::parse("https://example.test/doc").unwrap(),
+ ),
None
);
}
@@ -402,7 +412,11 @@ fn target_fetch_owner_appends_network_intercept_after_fetch_request_stage_sessio
let pause_sessions = owner
.config_snapshot()
.subresource_interception_snapshot()
- .matching_request_stage_pause_sessions(Some("SID-z"), "Fetch", &api_url)
+ .matching_request_stage_pause_sessions(
+ Some("SID-z"),
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ )
.into_iter()
.map(|session| (session.session_id, session.owner_kind))
.collect::<Vec<_>>();
@@ -463,7 +477,11 @@ fn target_fetch_owner_appends_network_intercept_after_fetch_response_stage_sessi
let pause_sessions = owner
.config_snapshot()
.subresource_interception_snapshot()
- .matching_response_stage_pause_sessions(Some("SID-z"), "Fetch", &api_url)
+ .matching_response_stage_pause_sessions(
+ Some("SID-z"),
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ )
.into_iter()
.map(|session| (session.session_id, session.owner_kind))
.collect::<Vec<_>>();
@@ -572,7 +590,11 @@ fn target_fetch_owner_network_request_stage_survives_earlier_fetch_response_patt
let pause_sessions = owner
.config_snapshot()
.subresource_interception_snapshot()
- .matching_request_stage_pause_sessions(Some("SID-fetch"), "Fetch", &api_url);
+ .matching_request_stage_pause_sessions(
+ Some("SID-fetch"),
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ );
assert_eq!(pause_sessions.len(), 1);
assert_eq!(pause_sessions[0].session_id.as_deref(), Some("BIDI-SID"));
@@ -601,7 +623,7 @@ fn target_fetch_owner_keeps_dormant_network_intercept_removable() {
.config_snapshot()
.matching_network_intercepts(
FetchRequestStage::Request,
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
&Url::parse("https://example.test/api").unwrap(),
)
.is_empty()
@@ -649,8 +671,11 @@ fn target_fetch_owner_reports_matching_network_intercept_ids_by_stage() {
let api_url = Url::parse("https://example.test/api").unwrap();
let config = owner.config_snapshot();
- let request_intercepts =
- config.matching_network_intercepts(FetchRequestStage::Request, "Fetch", &api_url);
+ let request_intercepts = config.matching_network_intercepts(
+ FetchRequestStage::Request,
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ );
assert_eq!(
request_intercepts
.iter()
@@ -660,7 +685,11 @@ fn target_fetch_owner_reports_matching_network_intercept_ids_by_stage() {
);
assert_eq!(
config
- .matching_network_intercepts(FetchRequestStage::Response, "Fetch", &api_url)
+ .matching_network_intercepts(
+ FetchRequestStage::Response,
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ )
.iter()
.map(|intercept| intercept.as_str())
.collect::<Vec<_>>(),
@@ -668,7 +697,11 @@ fn target_fetch_owner_reports_matching_network_intercept_ids_by_stage() {
);
assert_eq!(
config
- .matching_network_intercepts(FetchRequestStage::Response, "XHR", &api_url)
+ .matching_network_intercepts(
+ FetchRequestStage::Response,
+ DevToolsNetworkResourceType::Xhr,
+ &api_url,
+ )
.iter()
.map(|intercept| intercept.as_str())
.collect::<Vec<_>>(),
@@ -676,7 +709,11 @@ fn target_fetch_owner_reports_matching_network_intercept_ids_by_stage() {
);
assert_eq!(
config
- .matching_network_intercepts(FetchRequestStage::Request, "XHR", &api_url)
+ .matching_network_intercepts(
+ FetchRequestStage::Request,
+ DevToolsNetworkResourceType::Xhr,
+ &api_url,
+ )
.iter()
.map(|intercept| intercept.as_str())
.collect::<Vec<_>>(),
@@ -688,7 +725,11 @@ fn target_fetch_owner_reports_matching_network_intercept_ids_by_stage() {
owner
.config_snapshot()
.subresource_interception_snapshot()
- .matching_network_intercepts(FetchRequestStage::Request, "Fetch", &api_url)
+ .matching_network_intercepts(
+ FetchRequestStage::Request,
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ )
.iter()
.map(|intercept| intercept.as_str())
.collect::<Vec<_>>(),
@@ -720,7 +761,10 @@ fn target_fetch_owner_reports_matching_auth_required_network_intercepts() {
assert_eq!(owner.subresource_interception_config(), (true, None));
assert!(config.matches_auth_required(&matching_url));
assert!(config.matches_auth_required(&other_url));
- assert_eq!(config.matching_request_stage("Fetch", &matching_url), None);
+ assert_eq!(
+ config.matching_request_stage(DevToolsNetworkResourceType::Fetch, &matching_url),
+ None
+ );
assert_eq!(
config
.matching_auth_required_network_intercepts(&matching_url)
diff --git a/moli-protocol/src/conn/tests/resource_runtime.rs b/moli-protocol/src/conn/tests/resource_runtime.rs
index 393f5685d..0e2060aea 100644
--- a/moli-protocol/src/conn/tests/resource_runtime.rs
+++ b/moli-protocol/src/conn/tests/resource_runtime.rs
@@ -2534,6 +2534,10 @@ async fn direct_console_routes_to_inactive_active_owner_without_promoting_slot()
ctx.conn.inactive_browser_contexts.push(inactive);
ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-B"))
.await;
+ ctx.wait_for_scheduler_message("inactive console fixture load", |message| {
+ message["method"] == json!("Page.loadEventFired") && message["sessionId"] == json!("SID-B")
+ })
+ .await;
ctx.sent.clear();
ctx.process_and_wait_for_response_async(json!({
diff --git a/moli-protocol/src/devtools_runtime.rs b/moli-protocol/src/devtools_runtime.rs
index e94d5f2d5..38b35b47f 100644
--- a/moli-protocol/src/devtools_runtime.rs
+++ b/moli-protocol/src/devtools_runtime.rs
@@ -7,7 +7,9 @@
use std::{fmt, str::FromStr, sync::Arc};
use moli_cookie_jar::{StoredCookiePartitionKey, StoredCookieQueryReport};
-use moli_core::page::{DomScrollIntoViewRect, SelectedFile, is_renderer_backend_node_id};
+use moli_core::page::{
+ DomScrollIntoViewRect, SelectedFile, SubresourceResourceType, is_renderer_backend_node_id,
+};
use moli_protocol_cdp::{CdpTargetKindWire, CdpTargetType};
use serde_json::{Value, json};
@@ -2192,6 +2194,185 @@ pub struct NetworkAuthChallengeEvent {
pub realm: String,
}
+/// The resource classification carried by protocol-neutral network events.
+///
+/// Renderer and fetch internals keep their more precise loader-facing enums.
+/// This enum represents the observable DevTools classification and is only
+/// converted to a CDP token when an event is serialized at the protocol edge.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum DevToolsNetworkResourceType {
+ Document,
+ Stylesheet,
+ Image,
+ Media,
+ Font,
+ Script,
+ TextTrack,
+ Xhr,
+ Fetch,
+ Prefetch,
+ EventSource,
+ WebSocket,
+ Manifest,
+ SignedExchange,
+ Ping,
+ CspViolationReport,
+ Preflight,
+ FedCm,
+ Other,
+}
+
+impl DevToolsNetworkResourceType {
+ pub const fn as_cdp_type(self) -> &'static str {
+ match self {
+ Self::Document => "Document",
+ Self::Stylesheet => "Stylesheet",
+ Self::Image => "Image",
+ Self::Media => "Media",
+ Self::Font => "Font",
+ Self::Script => "Script",
+ Self::TextTrack => "TextTrack",
+ Self::Xhr => "XHR",
+ Self::Fetch => "Fetch",
+ Self::Prefetch => "Prefetch",
+ Self::EventSource => "EventSource",
+ Self::WebSocket => "WebSocket",
+ Self::Manifest => "Manifest",
+ Self::SignedExchange => "SignedExchange",
+ Self::Ping => "Ping",
+ Self::CspViolationReport => "CSPViolationReport",
+ Self::Preflight => "Preflight",
+ Self::FedCm => "FedCM",
+ Self::Other => "Other",
+ }
+ }
+
+ pub fn from_cdp_type(value: &str) -> Option<Self> {
+ Some(match value {
+ "Document" => Self::Document,
+ "Stylesheet" => Self::Stylesheet,
+ "Image" => Self::Image,
+ "Media" => Self::Media,
+ "Font" => Self::Font,
+ "Script" => Self::Script,
+ "TextTrack" => Self::TextTrack,
+ "XHR" => Self::Xhr,
+ "Fetch" => Self::Fetch,
+ "Prefetch" => Self::Prefetch,
+ "EventSource" => Self::EventSource,
+ "WebSocket" => Self::WebSocket,
+ "Manifest" => Self::Manifest,
+ "SignedExchange" => Self::SignedExchange,
+ "Ping" => Self::Ping,
+ "CSPViolationReport" => Self::CspViolationReport,
+ "Preflight" => Self::Preflight,
+ "FedCM" => Self::FedCm,
+ "Other" => Self::Other,
+ _ => return None,
+ })
+ }
+
+ pub fn from_fetch_interception_type(value: SubresourceResourceType) -> Self {
+ match value {
+ SubresourceResourceType::Fetch
+ | SubresourceResourceType::EventSource
+ | SubresourceResourceType::Xhr => Self::Xhr,
+ _ => value.into(),
+ }
+ }
+}
+
+impl From<SubresourceResourceType> for DevToolsNetworkResourceType {
+ fn from(value: SubresourceResourceType) -> Self {
+ match value {
+ SubresourceResourceType::Script => Self::Script,
+ SubresourceResourceType::Stylesheet => Self::Stylesheet,
+ SubresourceResourceType::Image => Self::Image,
+ SubresourceResourceType::Font => Self::Font,
+ SubresourceResourceType::Audio
+ | SubresourceResourceType::Video
+ | SubresourceResourceType::Media => Self::Media,
+ SubresourceResourceType::TextTrack => Self::TextTrack,
+ SubresourceResourceType::Fetch => Self::Fetch,
+ SubresourceResourceType::EventSource => Self::EventSource,
+ SubresourceResourceType::Xhr => Self::Xhr,
+ SubresourceResourceType::Ping => Self::Ping,
+ SubresourceResourceType::CspReport => Self::CspViolationReport,
+ SubresourceResourceType::Dictionary => Self::Other,
+ SubresourceResourceType::Manifest => Self::Manifest,
+ SubresourceResourceType::WebSocket => Self::WebSocket,
+ }
+ }
+}
+
+#[cfg(test)]
+mod network_resource_type_tests {
+ use super::{DevToolsNetworkResourceType, SubresourceResourceType};
+
+ #[test]
+ fn devtools_network_resource_types_round_trip_cdp_tokens() {
+ for (resource_type, token) in [
+ (DevToolsNetworkResourceType::Document, "Document"),
+ (DevToolsNetworkResourceType::Stylesheet, "Stylesheet"),
+ (DevToolsNetworkResourceType::Image, "Image"),
+ (DevToolsNetworkResourceType::Media, "Media"),
+ (DevToolsNetworkResourceType::Font, "Font"),
+ (DevToolsNetworkResourceType::Script, "Script"),
+ (DevToolsNetworkResourceType::TextTrack, "TextTrack"),
+ (DevToolsNetworkResourceType::Xhr, "XHR"),
+ (DevToolsNetworkResourceType::Fetch, "Fetch"),
+ (DevToolsNetworkResourceType::Prefetch, "Prefetch"),
+ (DevToolsNetworkResourceType::EventSource, "EventSource"),
+ (DevToolsNetworkResourceType::WebSocket, "WebSocket"),
+ (DevToolsNetworkResourceType::Manifest, "Manifest"),
+ (
+ DevToolsNetworkResourceType::SignedExchange,
+ "SignedExchange",
+ ),
+ (DevToolsNetworkResourceType::Ping, "Ping"),
+ (
+ DevToolsNetworkResourceType::CspViolationReport,
+ "CSPViolationReport",
+ ),
+ (DevToolsNetworkResourceType::Preflight, "Preflight"),
+ (DevToolsNetworkResourceType::FedCm, "FedCM"),
+ (DevToolsNetworkResourceType::Other, "Other"),
+ ] {
+ assert_eq!(resource_type.as_cdp_type(), token);
+ assert_eq!(
+ DevToolsNetworkResourceType::from_cdp_type(token),
+ Some(resource_type)
+ );
+ }
+ assert_eq!(
+ DevToolsNetworkResourceType::from_cdp_type("FutureResourceType"),
+ None
+ );
+ }
+
+ #[test]
+ fn subresource_resource_types_convert_without_stringly_typed_intermediate_state() {
+ assert_eq!(
+ DevToolsNetworkResourceType::from(SubresourceResourceType::Audio),
+ DevToolsNetworkResourceType::Media
+ );
+ assert_eq!(
+ DevToolsNetworkResourceType::from(SubresourceResourceType::Dictionary),
+ DevToolsNetworkResourceType::Other
+ );
+ for resource_type in [
+ SubresourceResourceType::Fetch,
+ SubresourceResourceType::EventSource,
+ SubresourceResourceType::Xhr,
+ ] {
+ assert_eq!(
+ DevToolsNetworkResourceType::from_fetch_interception_type(resource_type),
+ DevToolsNetworkResourceType::Xhr
+ );
+ }
+ }
+}
+
#[derive(Debug, Clone, PartialEq)]
pub struct NetworkRequestEvent {
pub target_id: DevToolsTargetId,
@@ -2209,7 +2390,7 @@ pub struct NetworkRequestEvent {
pub redirect_response: Option<NetworkRedirectResponseEvent>,
pub redirect_has_extra_info: bool,
pub request_cookie_report: Option<StoredCookieQueryReport>,
- pub resource_type: Option<String>,
+ pub resource_type: Option<DevToolsNetworkResourceType>,
pub timestamp: Option<f64>,
pub wall_time: Option<f64>,
pub status: Option<u16>,
diff --git a/moli-protocol/src/domains/accessibility/tests.rs b/moli-protocol/src/domains/accessibility/tests.rs
index d1510a5cf..0471b221a 100644
--- a/moli-protocol/src/domains/accessibility/tests.rs
+++ b/moli-protocol/src/domains/accessibility/tests.rs
@@ -73,6 +73,7 @@ async fn accessibility_top_frame_snapshot_commands_use_explicit_dispatch() {
"<!doctype html><html><body><button id='go'>Go</button></body></html>",
)
.await;
+ ctx.sent.clear();
let full_tree_raw = json!({
"id": 1,
@@ -148,6 +149,7 @@ async fn accessibility_get_full_tree_rejects_while_main_document_navigation_is_p
"<!doctype html><html><body><button>previous</button></body></html>",
)
.await;
+ ctx.sent.clear();
let browser_context = ctx
.conn
.browser_context
@@ -409,26 +411,22 @@ fn renderer_backed_ax_node_id(node: &Value) -> String {
#[tokio::test(flavor = "multi_thread")]
async fn accessibility_loaded_page_methods_target_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<html><body><p>Intro</p><button>Owner</button></body></html>",
- )
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><body><p>Intro</p><button>Owner</button></body></html>",
+ Some("SID-background"),
+ )
+ .await;
ctx.process_async(json!({
"id": 201,
@@ -452,7 +450,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
"method": "Accessibility.getRootAXNode"
}))
.await;
- let root = ctx.take_one();
+ let root = ctx.take_response_by_id(202);
assert_eq!(root["sessionId"], "SID-background");
assert_eq!(root["result"]["node"]["role"]["value"], "RootWebArea");
@@ -463,7 +461,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
"params": { "id": button_ax_id }
}))
.await;
- let children = ctx.take_one();
+ let children = ctx.take_response_by_id(203);
assert_eq!(children["sessionId"], "SID-background");
assert!(
children["result"]["nodes"]
@@ -480,7 +478,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
"params": { "backendNodeId": button_backend_id }
}))
.await;
- let chain = ctx.take_one();
+ let chain = ctx.take_response_by_id(204);
assert_eq!(chain["sessionId"], "SID-background");
assert_eq!(
chain["result"]["nodes"]
@@ -502,7 +500,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
}
}))
.await;
- let query = ctx.take_one();
+ let query = ctx.take_response_by_id(205);
assert_eq!(query["sessionId"], "SID-background");
assert_eq!(query["result"]["nodes"][0]["nodeId"], button_ax_id);
@@ -516,7 +514,7 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
}
}))
.await;
- let partial = ctx.take_one();
+ let partial = ctx.take_response_by_id(206);
assert_eq!(partial["sessionId"], "SID-background");
assert_eq!(partial["result"]["nodes"][0]["nodeId"], button_ax_id);
@@ -532,14 +530,6 @@ async fn accessibility_loaded_page_methods_target_background_owner_without_promo
#[tokio::test(flavor = "multi_thread")]
async fn accessibility_loaded_page_methods_target_inactive_owner_without_activation() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<html><body><button>Inactive</button></body></html>",
- )
- .await
- .expect("inactive page should load");
-
let mut active = BrowserContext::new("BID-active".to_owned());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active".to_owned());
@@ -547,10 +537,14 @@ async fn accessibility_loaded_page_methods_target_inactive_owner_without_activat
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
+ inactive.set_target_url("about:blank".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.replace_loaded_page(Some(page));
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><body><button>Inactive</button></body></html>",
+ Some("SID-inactive"),
+ )
+ .await;
ctx.process_async(json!({
"id": 211,
diff --git a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs
index f261bb7cb..74f0b9841 100644
--- a/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs
+++ b/moli-protocol/src/domains/activity/output_ingress/prepared_outputs.rs
@@ -43,12 +43,14 @@ impl PreparedProtocolOutputs {
pub(in crate::domains::activity) fn from_renderer_network_observation(
conn: &mut CdpConnection,
session_id: Option<&str>,
+ source_renderer_page: Option<crate::conn::RendererPageResidenceIdentity>,
source_document: moli_core::RendererDocumentLifecycleIdentity,
item: &moli_core::page::ScriptNetworkOutputItem,
) -> Option<Self> {
let renderer_live = conn
- .ingest_renderer_network_output_item_and_prepare_live_delivery_for_session_owner(
+ .ingest_renderer_page_network_output_item_and_prepare_live_delivery_for_session_owner(
session_id,
+ source_renderer_page,
source_document,
item,
)?;
@@ -78,6 +80,12 @@ impl PreparedProtocolOutputs {
&mut prepared,
);
}
+ RendererProtocolObservation::DocumentTitleChanged(change) => {
+ crate::domains::page::PagePreparedOutputs::from_renderer_document_title_change(
+ change.clone(),
+ )
+ .append_to_document_title_output_sink(&mut prepared);
+ }
RendererProtocolObservation::DocumentLifecycle(event) => {
crate::domains::page::PagePreparedOutputs::from_renderer_document_lifecycle_event(
*event,
diff --git a/moli-protocol/src/domains/activity/output_ingress/renderer.rs b/moli-protocol/src/domains/activity/output_ingress/renderer.rs
index 90ee874c4..8b92e93ba 100644
--- a/moli-protocol/src/domains/activity/output_ingress/renderer.rs
+++ b/moli-protocol/src/domains/activity/output_ingress/renderer.rs
@@ -3,6 +3,7 @@ use serde_json::json;
use std::collections::VecDeque;
use super::super::publication_route::RendererPublicationOwner;
+use super::super::publication_route::RendererPublicationProjection;
use super::super::publication_route::RendererPublicationRoute;
use super::super::runtime_command_barrier::RuntimeCommandOutputBarriers;
use super::prepared_outputs::PreparedProtocolOutputs;
@@ -92,24 +93,32 @@ async fn ingest_renderer_output_publication(
};
let records = publication.into_records();
match route {
- RendererPublicationRoute::AttachedSession { session_id } => {
+ RendererPublicationRoute::AttachedSession {
+ session_id,
+ projection,
+ } => {
project_renderer_output_records_for_route(
conn,
Some(&session_id),
records,
cursor,
+ projection,
barriers,
command_context,
)
.await;
}
- RendererPublicationRoute::UnattachedOwner { owner_route } => {
+ RendererPublicationRoute::UnattachedOwner {
+ owner_route,
+ projection,
+ } => {
let mut route_scope = conn.scoped_none_session_owner_route_override(owner_route);
project_renderer_output_records_for_route(
route_scope.conn_mut(),
None,
records,
cursor,
+ projection,
barriers,
command_context,
)
@@ -123,11 +132,22 @@ async fn project_renderer_output_records_for_route(
session_id: Option<&str>,
records: Vec<moli_core::RendererOutputRecord>,
cursor: moli_core::RendererOutputCursor,
+ projection: RendererPublicationProjection,
barriers: &mut RuntimeCommandOutputBarriers,
command_context: &mut CommandDispatchContext,
) {
for record in records {
let (renderer_cause, item) = record.into_parts();
+ if projection == RendererPublicationProjection::RetiringNetworkOnly
+ && !matches!(
+ &item,
+ RendererOutputItem::Observation(
+ moli_core::RendererProtocolObservation::Network { .. }
+ )
+ )
+ {
+ continue;
+ }
match item {
RendererOutputItem::OwnerAction(action) => {
let outputs =
@@ -153,6 +173,9 @@ async fn project_renderer_output_records_for_route(
let Some(outputs) = PreparedProtocolOutputs::from_renderer_network_observation(
conn,
session_id,
+ crate::conn::RendererPageResidenceIdentity::from_residence(
+ cursor.stream().residence(),
+ ),
*source_document,
item,
) else {
diff --git a/moli-protocol/src/domains/activity/output_slot.rs b/moli-protocol/src/domains/activity/output_slot.rs
index aef74cbca..3f6e5c321 100644
--- a/moli-protocol/src/domains/activity/output_slot.rs
+++ b/moli-protocol/src/domains/activity/output_slot.rs
@@ -51,6 +51,7 @@ pub(in crate::domains) enum ProtocolOutputSlot {
RuntimeInspectorMessages,
RuntimeInspectorPostResponseMessages,
MainDocumentCommit,
+ DocumentTitleChanged,
DocumentLifecycle,
RuntimeObservable,
DomStorage,
@@ -86,6 +87,7 @@ impl ProtocolOutputSlot {
| Self::RuntimeBindingCalls
| Self::DomMutations
| Self::MainDocumentCommit
+ | Self::DocumentTitleChanged
| Self::DocumentLifecycle
| Self::DomStorage => ProtocolOutputDelivery::ProtocolObservation,
}
@@ -97,7 +99,6 @@ impl ProtocolOutputSlot {
match self {
Self::TopLevelLocationNavigation
| Self::TopLevelHistoryTraversal
- | Self::FileChooser
| Self::Download
| Self::SharedWorkerTargetLifecycle
| Self::ServiceWorkerTargetLifecycle
@@ -106,6 +107,11 @@ impl ProtocolOutputSlot {
ProtocolOutputResponseOrder::AfterResponse
}
Self::PendingSubresourceContinueEvents
+ // Blink's file-input activation probe queues
+ // Page.fileChooserOpened synchronously. A script may continue into
+ // document.open(), but Chromium still flushes the chooser event
+ // before the invoking Runtime.evaluate response.
+ | Self::FileChooser
| Self::JavascriptDialog
| Self::WindowOpen
| Self::Popup
@@ -124,6 +130,7 @@ impl ProtocolOutputSlot {
| Self::DomMutations
| Self::RuntimeInspectorMessages
| Self::MainDocumentCommit
+ | Self::DocumentTitleChanged
| Self::DocumentLifecycle
| Self::RuntimeObservable
| Self::DomStorage
@@ -218,6 +225,7 @@ impl ProtocolOutputSlot {
| Self::JavascriptDialog
| Self::WindowOpen
| Self::Popup
+ | Self::DocumentTitleChanged
| Self::DocumentLifecycle
| Self::ChildFrameActivity
| Self::SameDocumentNavigation
@@ -265,7 +273,7 @@ mod tests {
),
(TopLevelLocationNavigation, OwnerAction, AfterResponse),
(TopLevelHistoryTraversal, OwnerAction, AfterResponse),
- (FileChooser, OwnerAction, AfterResponse),
+ (FileChooser, OwnerAction, BeforeResponse),
(Download, OwnerAction, AfterResponse),
(JavascriptDialog, OwnerAction, BeforeResponse),
(WindowOpen, ProtocolObservation, BeforeResponse),
@@ -291,6 +299,7 @@ mod tests {
AfterResponse,
),
(MainDocumentCommit, ProtocolObservation, BeforeResponse),
+ (DocumentTitleChanged, ProtocolObservation, BeforeResponse),
(DocumentLifecycle, ProtocolObservation, BeforeResponse),
(RuntimeObservable, OwnerAction, BeforeResponse),
(DomStorage, ProtocolObservation, BeforeResponse),
diff --git a/moli-protocol/src/domains/activity/publication_route.rs b/moli-protocol/src/domains/activity/publication_route.rs
index cd03a911a..b22ee8ca2 100644
--- a/moli-protocol/src/domains/activity/publication_route.rs
+++ b/moli-protocol/src/domains/activity/publication_route.rs
@@ -31,8 +31,23 @@ pub(crate) enum RendererPublicationOwner {
/// no output payload and grants no renderer execution authority.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum RendererPublicationRoute {
- AttachedSession { session_id: String },
- UnattachedOwner { owner_route: CdpSessionRoute },
+ AttachedSession {
+ session_id: String,
+ projection: RendererPublicationProjection,
+ },
+ UnattachedOwner {
+ owner_route: CdpSessionRoute,
+ projection: RendererPublicationProjection,
+ },
+}
+
+/// A current Page can project its complete renderer stream. A replaced Page
+/// remains routable only for final Network facts whose request correlations
+/// are retained by the target; every other historical record is stale.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum RendererPublicationProjection {
+ CurrentPage,
+ RetiringNetworkOnly,
}
impl RendererPublicationRoute {
@@ -40,9 +55,13 @@ impl RendererPublicationRoute {
browser_context_id: String,
target_id: Option<String>,
session_id: Option<String>,
+ projection: RendererPublicationProjection,
) -> Self {
if let Some(session_id) = session_id {
- return Self::AttachedSession { session_id };
+ return Self::AttachedSession {
+ session_id,
+ projection,
+ };
}
let owner_route = match target_id {
Some(target_id) => CdpSessionRoute::BackgroundTarget {
@@ -54,7 +73,10 @@ impl RendererPublicationRoute {
target_id: None,
},
};
- Self::UnattachedOwner { owner_route }
+ Self::UnattachedOwner {
+ owner_route,
+ projection,
+ }
}
}
@@ -111,6 +133,7 @@ impl RendererPublicationOwner {
browser_context_id: browser_context.id.clone(),
target_id: None,
},
+ projection: RendererPublicationProjection::CurrentPage,
})
}
Self::PageTarget {
@@ -142,16 +165,25 @@ impl RendererPublicationOwner {
target.session_id().map(str::to_owned),
)
};
- (runtime_slot.routes_renderer_page(*renderer_page)
- && runtime_slot.loaded_page_generation()
- == page_owner.loaded_page_generation())
- .then(|| {
- RendererPublicationRoute::for_target(
- browser_context.id.clone(),
- route_target_id,
- session_id,
- )
- })
+ let projection = if runtime_slot.routes_current_renderer_page_owner(
+ *renderer_page,
+ page_owner.loaded_page_generation(),
+ ) {
+ RendererPublicationProjection::CurrentPage
+ } else if runtime_slot.routes_retiring_renderer_page_owner(
+ *renderer_page,
+ page_owner.loaded_page_generation(),
+ ) {
+ RendererPublicationProjection::RetiringNetworkOnly
+ } else {
+ return None;
+ };
+ Some(RendererPublicationRoute::for_target(
+ browser_context.id.clone(),
+ route_target_id,
+ session_id,
+ projection,
+ ))
}),
}
}
diff --git a/moli-protocol/src/domains/activity/subresource.rs b/moli-protocol/src/domains/activity/subresource.rs
index bc6eb7190..7d258b3d4 100644
--- a/moli-protocol/src/domains/activity/subresource.rs
+++ b/moli-protocol/src/domains/activity/subresource.rs
@@ -162,7 +162,7 @@ async fn flush_prepared_subresource_continue_action_background_events_async(
.target_fetch_subresource_interception_snapshot_for_session_owner(session_id)
.is_some_and(|snapshot| {
snapshot.matches_response_stage(
- response_info.resource_type.as_cdp_type(),
+ response_info.resource_type.into(),
&response_info.final_url,
)
})
@@ -191,7 +191,7 @@ async fn flush_prepared_subresource_continue_action_background_events_async(
.map(|snapshot| {
snapshot.matching_network_intercepts(
FetchRequestStage::Response,
- response_info.resource_type.as_cdp_type(),
+ response_info.resource_type.into(),
&response_info.final_url,
)
})
@@ -203,7 +203,7 @@ async fn flush_prepared_subresource_continue_action_background_events_async(
conn.target_fetch_matching_network_intercepts_for_target(
&in_flight.pending.frame_id,
FetchRequestStage::Response,
- response_info.resource_type.as_cdp_type(),
+ response_info.resource_type.into(),
&response_info.final_url,
)
} else {
@@ -224,7 +224,7 @@ async fn flush_prepared_subresource_continue_action_background_events_async(
.map(|snapshot| {
snapshot.matching_response_stage_pause_sessions(
session_id,
- response_info.resource_type.as_cdp_type(),
+ response_info.resource_type.into(),
&response_info.final_url,
)
})
diff --git a/moli-protocol/src/domains/autofill.rs b/moli-protocol/src/domains/autofill.rs
index 2ba342cf9..57e57c631 100644
--- a/moli-protocol/src/domains/autofill.rs
+++ b/moli-protocol/src/domains/autofill.rs
@@ -171,16 +171,13 @@ mod tests {
browser_context.set_target_url("data:text/html,autofill-test".to_owned());
browser_context.set_active_target_id("TID-1".to_owned());
browser_context.attach_active_session("SID-1".to_owned());
- let page = ctx
- .conn
- .load_page_via_runtime_async(&format!("data:text/html,{html}"))
- .await
- .expect("Autofill test page should load");
- let _ = browser_context
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
ctx.conn.browser_context = Some(browser_context);
+ ctx.install_navigation_fixture_for_session_owner(
+ &format!("data:text/html,{html}"),
+ Some("SID-1"),
+ )
+ .await;
+ ctx.sent.clear();
}
async fn backend_node_id_for_expression(
diff --git a/moli-protocol/src/domains/command_output.rs b/moli-protocol/src/domains/command_output.rs
index e00e1a761..3068ec47a 100644
--- a/moli-protocol/src/domains/command_output.rs
+++ b/moli-protocol/src/domains/command_output.rs
@@ -5,9 +5,9 @@ use crate::devtools_runtime::{
AutomationEvent, BrowserDownloadProgressEvent, BrowserDownloadWillBeginEvent,
DevToolsCommandResult, DevToolsError, DevToolsErrorKind, DevToolsFetchRequestId,
DevToolsFrameId, DevToolsLoaderId, DevToolsNetworkDataBytesType, DevToolsNetworkInterceptId,
- DevToolsRealmId, DevToolsRemoteValue, DevToolsRequestId, DevToolsScriptException,
- DevToolsScriptResult, DevToolsStackTrace, DevToolsTargetId, DevToolsTargetInfo,
- NavigationFrameEvent, NavigationFrameEventKind, NetworkAuthChallengeEvent,
+ DevToolsNetworkResourceType, DevToolsRealmId, DevToolsRemoteValue, DevToolsRequestId,
+ DevToolsScriptException, DevToolsScriptResult, DevToolsStackTrace, DevToolsTargetId,
+ DevToolsTargetInfo, NavigationFrameEvent, NavigationFrameEventKind, NetworkAuthChallengeEvent,
NetworkRedirectResponseEvent, NetworkRequestEvent, PageFileChooserOpenedEvent,
PageJavaScriptDialogOpeningEvent, PageLifecycleEvent, RuntimeConsoleEvent,
RuntimeExecutionContextEvent, SameDocumentNavigationEvent, ScriptExceptionEvent,
@@ -1078,7 +1078,7 @@ fn network_request_event_from_cdp_params(params: &Value, request_id: &str) -> Ne
.get("type")
.or_else(|| params.get("resourceType"))
.and_then(Value::as_str)
- .map(str::to_owned),
+ .and_then(DevToolsNetworkResourceType::from_cdp_type),
timestamp: params.get("timestamp").and_then(Value::as_f64),
wall_time: params.get("wallTime").and_then(Value::as_f64),
status: params
diff --git a/moli-protocol/src/domains/css.rs b/moli-protocol/src/domains/css.rs
index 5ca417c69..de9f02ed2 100644
--- a/moli-protocol/src/domains/css.rs
+++ b/moli-protocol/src/domains/css.rs
@@ -972,26 +972,23 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn css_loaded_page_methods_target_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<html><head><style title='owner'>body { color: red; }</style></head><body><div id='target' style='display:flex;width:123px;color:blue'></div></body></html>",
- )
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><head><style title='owner'>body { color: red; }</style></head><body><div id='target' style='display:flex;width:123px;color:blue'></div></body></html>",
+ Some("SID-background"),
+ )
+ .await;
+ ctx.sent.clear();
let style_sheet_id =
inline_style_sheet_id_for_session_async(&mut ctx, Some("SID-background")).await;
@@ -1106,14 +1103,6 @@ mod tests {
#[tokio::test(flavor = "multi_thread")]
async fn css_loaded_page_methods_target_inactive_owner_without_activation() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<html><head><style title='inactive'>main { color: red; }</style></head><body><main id='target' style='display:block;height:77px'></main></body></html>",
- )
- .await
- .expect("inactive page should load");
-
let mut active = BrowserContext::new("BID-active".to_owned());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active".to_owned());
@@ -1121,10 +1110,15 @@ mod tests {
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
+ inactive.set_target_url("about:blank".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.replace_loaded_page(Some(page));
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><head><style title='inactive'>main { color: red; }</style></head><body><main id='target' style='display:block;height:77px'></main></body></html>",
+ Some("SID-inactive"),
+ )
+ .await;
+ ctx.sent.clear();
let style_sheet_id =
inline_style_sheet_id_for_session_async(&mut ctx, Some("SID-inactive")).await;
diff --git a/moli-protocol/src/domains/debugger.rs b/moli-protocol/src/domains/debugger.rs
index 12441ebbb..84b6f6829 100644
--- a/moli-protocol/src/domains/debugger.rs
+++ b/moli-protocol/src/domains/debugger.rs
@@ -364,6 +364,18 @@ mod tests {
navigate["result"]["frameId"].as_str().is_some(),
"{navigate:?}"
);
+ let parsed = ctx
+ .wait_for_scheduler_message(
+ "instrumented replacement scriptParsed after Page.navigate response",
+ |message| {
+ message["method"] == json!("Debugger.scriptParsed")
+ && message["params"]["url"]
+ == json!(
+ "data:text/html,<script>globalThis.__instrumentedNavigation = true</script>"
+ )
+ },
+ )
+ .await;
let created = ctx
.sent
@@ -371,14 +383,10 @@ mod tests {
.find(|message| message["method"] == json!("Runtime.executionContextCreated"))
.expect("replacement default context must precede its instrumentation pause");
assert_eq!(created["params"]["context"]["origin"], json!("://"));
- assert!(
- ctx.sent.iter().any(|message| {
- message["method"] == json!("Debugger.scriptParsed")
- && message["params"]["url"]
- == json!("data:text/html,<script>globalThis.__instrumentedNavigation = true</script>")
- }),
- "the instrumented replacement script must reach V8: {:?}",
- ctx.sent
+ assert_eq!(
+ parsed["params"]["url"],
+ json!("data:text/html,<script>globalThis.__instrumentedNavigation = true</script>"),
+ "the instrumented replacement script must reach V8"
);
}
diff --git a/moli-protocol/src/domains/dom/tests/frames.rs b/moli-protocol/src/domains/dom/tests/frames.rs
index 8281e490d..b979b0dcf 100644
--- a/moli-protocol/src/domains/dom/tests/frames.rs
+++ b/moli-protocol/src/domains/dom/tests/frames.rs
@@ -3671,8 +3671,7 @@ async fn protocol_neutral_query_selector_targets_child_frame_context() {
let child_frame_id = child_frame_id_for_single_iframe_async(&mut ctx, 2).await;
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::QuerySelector(
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::QuerySelector(
DevToolsQuerySelectorCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverClassic,
@@ -3686,8 +3685,6 @@ async fn protocol_neutral_query_selector_targets_child_frame_context() {
},
))
.await
- .into_parts()
- .0
.expect("child frame query selector should run");
let DevToolsCommandResult::QuerySelector(result) = result else {
@@ -4143,8 +4140,7 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
};
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::QuerySelector(
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::QuerySelector(
DevToolsQuerySelectorCommand {
context: context.clone(),
root: None,
@@ -4153,8 +4149,6 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
},
))
.await
- .into_parts()
- .0
.expect("child frame query selector should run");
let DevToolsCommandResult::QuerySelector(result) = result else {
@@ -4347,28 +4341,28 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
.unwrap_or_else(|| panic!("expected child frame node object id: {:?}", result.object));
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::CallFunction(DevToolsCallFunctionCommand {
- context: context.clone(),
- realm_id: None,
- world_name: None,
- object_id: Some(DevToolsRemoteHandleId::from(object_id.clone())),
- this_parameter: None,
- function_declaration:
- "function() { return this.id + ':' + getComputedStyle(this).display; }".to_owned(),
- arguments: Vec::new(),
- await_promise: false,
- user_gesture: false,
- webdriver_bidi_file_prompt_handler: None,
- result_ownership: DevToolsResultOwnership::None,
- object_group: None,
- preserve_remote_metadata: false,
- materialize_bidi_script_result: false,
- serialization_options: None,
- }))
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CallFunction(
+ DevToolsCallFunctionCommand {
+ context: context.clone(),
+ realm_id: None,
+ world_name: None,
+ object_id: Some(DevToolsRemoteHandleId::from(object_id.clone())),
+ this_parameter: None,
+ function_declaration:
+ "function() { return this.id + ':' + getComputedStyle(this).display; }"
+ .to_owned(),
+ arguments: Vec::new(),
+ await_promise: false,
+ user_gesture: false,
+ webdriver_bidi_file_prompt_handler: None,
+ result_ownership: DevToolsResultOwnership::None,
+ object_group: None,
+ preserve_remote_metadata: false,
+ materialize_bidi_script_result: false,
+ serialization_options: None,
+ },
+ ))
.await
- .into_parts()
- .0
.expect("child frame callFunctionOn should run");
let DevToolsCommandResult::Script(result) = result else {
@@ -4526,28 +4520,28 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
});
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::CallFunction(DevToolsCallFunctionCommand {
- context: context.clone(),
- realm_id: None,
- world_name: None,
- object_id: Some(DevToolsRemoteHandleId::from(high_backend_object_id)),
- this_parameter: None,
- function_declaration:
- "function() { return this.id + ':' + getComputedStyle(this).display; }".to_owned(),
- arguments: Vec::new(),
- await_promise: false,
- user_gesture: false,
- webdriver_bidi_file_prompt_handler: None,
- result_ownership: DevToolsResultOwnership::None,
- object_group: None,
- preserve_remote_metadata: false,
- materialize_bidi_script_result: false,
- serialization_options: None,
- }))
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::CallFunction(
+ DevToolsCallFunctionCommand {
+ context: context.clone(),
+ realm_id: None,
+ world_name: None,
+ object_id: Some(DevToolsRemoteHandleId::from(high_backend_object_id)),
+ this_parameter: None,
+ function_declaration:
+ "function() { return this.id + ':' + getComputedStyle(this).display; }"
+ .to_owned(),
+ arguments: Vec::new(),
+ await_promise: false,
+ user_gesture: false,
+ webdriver_bidi_file_prompt_handler: None,
+ result_ownership: DevToolsResultOwnership::None,
+ object_group: None,
+ preserve_remote_metadata: false,
+ materialize_bidi_script_result: false,
+ serialization_options: None,
+ },
+ ))
.await
- .into_parts()
- .0
.expect("child frame high backend callFunctionOn should run");
let DevToolsCommandResult::Script(result) = result else {
panic!("expected script result");
@@ -4558,15 +4552,14 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
assert_eq!(value.value, json!("inside-frame:grid"));
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::DomGeometry(DevToolsDomGeometryCommand {
- context: context.clone(),
- reference: DevToolsDomNodeReference::BackendNodeId(renderer_backend_node_id),
- operation: DevToolsDomGeometryOperation::GetBoxModel,
- }))
+ .execute_devtools_command_through_renderer_fence_for_test(DevToolsCommand::DomGeometry(
+ DevToolsDomGeometryCommand {
+ context: context.clone(),
+ reference: DevToolsDomNodeReference::BackendNodeId(renderer_backend_node_id),
+ operation: DevToolsDomGeometryOperation::GetBoxModel,
+ },
+ ))
.await
- .into_parts()
- .0
.expect("child frame high backend geometry should run");
let DevToolsCommandResult::DomGeometry(result) = result else {
panic!("expected child high backend geometry result");
@@ -4581,19 +4574,16 @@ async fn protocol_neutral_resolve_node_targets_child_frame_context() {
assert!(result.quads.is_empty());
let result = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::ScrollIntoViewIfNeeded(
- DevToolsScrollIntoViewIfNeededCommand {
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::ScrollIntoViewIfNeeded(DevToolsScrollIntoViewIfNeededCommand {
context,
reference: Some(DevToolsDomNodeReference::BackendNodeId(
renderer_backend_node_id,
)),
rect: None,
- },
- ))
+ }),
+ )
.await
- .into_parts()
- .0
.expect("child frame high backend scrollIntoViewIfNeeded should run");
assert!(matches!(result, DevToolsCommandResult::Empty));
}
diff --git a/moli-protocol/src/domains/dom/tests/geometry.rs b/moli-protocol/src/domains/dom/tests/geometry.rs
index edce7d827..f966c0bac 100644
--- a/moli-protocol/src/domains/dom/tests/geometry.rs
+++ b/moli-protocol/src/domains/dom/tests/geometry.rs
@@ -57,6 +57,12 @@ async fn dom_resolve_geometry_and_mutation_target_loaded_background_owner_withou
Some("SID-background"),
)
.await;
+ ctx.wait_for_scheduler_message("background fixture load", |message| {
+ message["sessionId"] == json!("SID-background")
+ && message["method"] == json!("Page.loadEventFired")
+ })
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 340,
@@ -282,14 +288,6 @@ async fn dom_resolve_geometry_and_mutation_target_loaded_background_owner_withou
#[tokio::test(flavor = "multi_thread")]
async fn dom_resolve_geometry_targets_inactive_loaded_owner_without_activation() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<!doctype html><html><body><article id='owned' style='position:absolute;left:7px;top:9px;width:13px;height:15px'>inactive</article></body></html>",
- )
- .await
- .expect("inactive page should load");
-
let mut active = BrowserContext::new("BID-active".to_owned());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active".to_owned());
@@ -297,10 +295,22 @@ async fn dom_resolve_geometry_targets_inactive_loaded_owner_without_activation()
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
+ inactive.set_target_url("about:blank".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.replace_loaded_page(Some(page));
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<!doctype html><html><body><article id='owned' style='position:absolute;left:7px;top:9px;width:13px;height:15px'>inactive</article></body></html>",
+ Some("SID-inactive"),
+ )
+ .await;
+ crate::testing::wait_until_renderer_document_load(
+ &mut ctx,
+ Some("SID-inactive"),
+ "TID-inactive",
+ crate::domains::page::LOADER_ID,
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 361,
@@ -312,6 +322,7 @@ async fn dom_resolve_geometry_targets_inactive_loaded_owner_without_activation()
let root_id = take_response_by_id(&mut ctx, 361)["result"]["root"]["nodeId"]
.as_u64()
.expect("document root node id");
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 362,
diff --git a/moli-protocol/src/domains/dom/tests/misc.rs b/moli-protocol/src/domains/dom/tests/misc.rs
index eea43f687..f3436c15c 100644
--- a/moli-protocol/src/domains/dom/tests/misc.rs
+++ b/moli-protocol/src/domains/dom/tests/misc.rs
@@ -58,6 +58,7 @@ async fn dom_agent_lifecycle_matches_chromium_errors_and_binding_reset() {
"<!doctype html><html><body><main id='target'></main></body></html>",
)
.await;
+ ctx.sent.clear();
ctx.process_async(json!({ "id": 11, "method": "DOM.disable" }))
.await;
@@ -126,6 +127,7 @@ async fn dom_enable_include_whitespace_controls_inspector_tree_projection() {
"<!doctype html><html><body>\n <div id='first'></div>\n <div id='second'></div>\n</body></html>",
)
.await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 2,
@@ -211,26 +213,22 @@ async fn dom_enable_include_whitespace_controls_inspector_tree_projection() {
#[tokio::test(flavor = "multi_thread")]
async fn dom_document_reads_target_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<!doctype html><html><body><section id='owned'>background</section></body></html>",
- )
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<!doctype html><html><body><section id='owned'>background</section></body></html>",
+ Some("SID-background"),
+ )
+ .await;
ctx.process_async(json!({
"id": 321,
@@ -294,14 +292,6 @@ async fn dom_document_reads_target_loaded_background_owner_without_promotion() {
#[tokio::test(flavor = "multi_thread")]
async fn dom_document_reads_target_inactive_loaded_owner_without_activation() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<!doctype html><html><body><section id='owned'>inactive</section></body></html>",
- )
- .await
- .expect("inactive page should load");
-
let mut active = BrowserContext::new("BID-active".to_owned());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active".to_owned());
@@ -309,10 +299,14 @@ async fn dom_document_reads_target_inactive_loaded_owner_without_activation() {
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
+ inactive.set_target_url("about:blank".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.replace_loaded_page(Some(page));
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<!doctype html><html><body><section id='owned'>inactive</section></body></html>",
+ Some("SID-inactive"),
+ )
+ .await;
ctx.process_async(json!({
"id": 331,
diff --git a/moli-protocol/src/domains/dom/tests/node_ops.rs b/moli-protocol/src/domains/dom/tests/node_ops.rs
index 4632c0f67..c1e08d4c0 100644
--- a/moli-protocol/src/domains/dom/tests/node_ops.rs
+++ b/moli-protocol/src/domains/dom/tests/node_ops.rs
@@ -2250,7 +2250,7 @@ async fn set_file_input_files_validates_node_before_reading_files() {
}
#[tokio::test(flavor = "multi_thread")]
-async fn file_chooser_opened_renderer_backend_node_id_is_scoped_to_document_replacement() {
+async fn file_chooser_backend_node_id_resolves_detached_source_after_document_open() {
let mut ctx = TestContext::new();
load_bc(&mut ctx, "BID-A");
navigate_to_data_html_async(
@@ -2288,6 +2288,21 @@ async fn file_chooser_opened_renderer_backend_node_id_is_scoped_to_document_repl
}
}))
.await;
+ let chooser_position = ctx
+ .sent
+ .iter()
+ .position(|message| message["method"] == json!("Page.fileChooserOpened"))
+ .unwrap_or_else(|| panic!("Page.fileChooserOpened should be emitted: {:?}", ctx.sent));
+ let response_position = ctx
+ .sent
+ .iter()
+ .position(|message| message["id"] == json!(3))
+ .expect("Runtime.evaluate response");
+ assert!(
+ chooser_position < response_position,
+ "Chromium emits fileChooserOpened synchronously before the invoking script response: {:?}",
+ ctx.sent
+ );
let evaluated = take_response_by_id(&mut ctx, 3);
assert_eq!(evaluated["result"]["result"]["value"], json!("fresh"));
@@ -2310,6 +2325,7 @@ async fn file_chooser_opened_renderer_backend_node_id_is_scoped_to_document_repl
moli_core::page::is_renderer_backend_node_id(backend_node_id),
"file chooser event should use renderer backend id namespace: {file_chooser:?}"
);
+
ctx.process_async(json!({
"id": 4,
"method": "DOM.resolveNode",
@@ -2321,9 +2337,13 @@ async fn file_chooser_opened_renderer_backend_node_id_is_scoped_to_document_repl
.await;
let resolved = take_response_by_id(&mut ctx, 4);
assert_eq!(
- resolved["error"]["message"],
- json!("Could not find node with given id"),
- "old file chooser backend id must not resolve against the replacement document: {resolved:?}"
+ resolved["result"]["object"]["subtype"],
+ json!("node"),
+ "Chromium keeps the event-exposed detached input resolvable after document.open: {resolved:?}"
+ );
+ assert!(
+ resolved["result"]["object"]["objectId"].as_str().is_some(),
+ "detached file input should resolve to a runtime object: {resolved:?}"
);
}
diff --git a/moli-protocol/src/domains/dom/tests/search.rs b/moli-protocol/src/domains/dom/tests/search.rs
index 12e3a04ec..a1479cce5 100644
--- a/moli-protocol/src/domains/dom/tests/search.rs
+++ b/moli-protocol/src/domains/dom/tests/search.rs
@@ -52,6 +52,7 @@ async fn search_flow_with_real_dom() {
"<!doctype html><html><body><p>one</p><p>two</p></body></html>",
)
.await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 2,
@@ -198,6 +199,7 @@ async fn perform_search_unions_plain_text_tag_attribute_and_xpath_matches() {
"<!doctype html><html><body><p id='first' data-label='Needle Value'>first paragraph</p><p id='second'>second paragraph</p></body></html>",
)
.await;
+ ctx.sent.clear();
publish_document_for_search(&mut ctx, 21, None).await;
let text_nodes = perform_search_and_get_all_results(&mut ctx, 30, "paragraph", 2).await;
@@ -471,26 +473,22 @@ async fn perform_search_selectors_cover_all_frame_documents_and_author_shadow_ro
#[tokio::test(flavor = "multi_thread")]
async fn dom_search_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<!doctype html><html><body><span>one</span><span>two</span></body></html>",
- )
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-A".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<!doctype html><html><body><span>one</span><span>two</span></body></html>",
+ Some("SID-background"),
+ )
+ .await;
ctx.process_async(json!({
"id": 301,
@@ -558,14 +556,6 @@ async fn dom_search_targets_loaded_background_owner_without_promotion() {
#[tokio::test(flavor = "multi_thread")]
async fn dom_search_targets_inactive_loaded_owner_without_activation() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<!doctype html><html><body><article>one</article><article>two</article></body></html>",
- )
- .await
- .expect("inactive page should load");
-
let mut active = BrowserContext::new("BID-active".to_owned());
active.set_active_target_id("TID-active".to_owned());
active.attach_active_session("SID-active".to_owned());
@@ -573,10 +563,14 @@ async fn dom_search_targets_inactive_loaded_owner_without_activation() {
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
+ inactive.set_target_url("about:blank".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.replace_loaded_page(Some(page));
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<!doctype html><html><body><article>one</article><article>two</article></body></html>",
+ Some("SID-inactive"),
+ )
+ .await;
ctx.process_async(json!({
"id": 311,
diff --git a/moli-protocol/src/domains/emulation/tests.rs b/moli-protocol/src/domains/emulation/tests.rs
index 7305e137d..f5361b4d8 100644
--- a/moli-protocol/src/domains/emulation/tests.rs
+++ b/moli-protocol/src/domains/emulation/tests.rs
@@ -1016,7 +1016,7 @@ async fn set_user_agent_override_applies_to_current_page_xhr_requests() {
"params": { "expression": "navigator.userAgent" }
}))
.await;
- let response = ctx.take_one();
+ let response = ctx.take_response_by_id(15);
assert_eq!(
response["result"]["result"]["value"],
json!("moli-emulation-live-ua")
@@ -1920,7 +1920,7 @@ async fn live_locale_override_updates_navigator_without_page_define_property() {
}
}))
.await;
- let response = ctx.take_one();
+ let response = ctx.take_response_by_id(152);
assert_eq!(response["result"]["result"]["value"], json!("tampered"));
ctx.process_async(json!({
@@ -1941,7 +1941,7 @@ async fn live_locale_override_updates_navigator_without_page_define_property() {
}
}))
.await;
- let response = ctx.take_one();
+ let response = ctx.take_response_by_id(154);
let payload = response["result"]["result"]["value"]
.as_str()
.expect("runtime evaluate should return a JSON string");
@@ -2034,26 +2034,23 @@ async fn locale_and_timezone_overrides_apply_to_locale_date_formatting() {
#[tokio::test(flavor = "multi_thread")]
async fn context_emulated_media_applies_to_loaded_background_page_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body>background</body>")
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::new(
+ let background = BackgroundTarget::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
TargetPageSlot::empty_for_test_fixture(),
);
- background.set_target_url(page.final_url().as_str().to_owned());
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body>background</body>",
+ Some("SID-background"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
@@ -2113,26 +2110,23 @@ async fn context_emulated_media_applies_to_loaded_background_page_without_promot
#[tokio::test(flavor = "multi_thread")]
async fn context_locale_override_applies_to_loaded_background_page_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body>background</body>")
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::new(
+ let background = BackgroundTarget::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
TargetIdentityState::about_blank(),
TargetPageSlot::empty_for_test_fixture(),
);
- background.set_target_url(page.final_url().as_str().to_owned());
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body>background</body>",
+ Some("SID-background"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
@@ -2193,25 +2187,23 @@ async fn context_locale_override_applies_to_loaded_background_page_without_promo
#[tokio::test(flavor = "multi_thread")]
async fn session_emulation_routes_to_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body>background</body>")
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::new(
+ let background = BackgroundTarget::new(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- TargetIdentityState::with_url(page.final_url().as_str().to_owned()),
+ TargetIdentityState::about_blank(),
TargetPageSlot::empty_for_test_fixture(),
);
- background.set_target_url(page.final_url().as_str().to_owned());
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active");
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body>background</body>",
+ Some("SID-background"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
@@ -2324,18 +2316,13 @@ async fn emulated_media_updates_existing_media_query_list_matches() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<body><script>globalThis.events = []; globalThis.darkMql = matchMedia('(prefers-color-scheme: dark)'); globalThis.lightMql = matchMedia('(prefers-color-scheme: light)'); darkMql.addEventListener('change', event => events.push(['dark', event.matches, event.media, event.target === darkMql])); lightMql.onchange = event => events.push(['light', event.matches, event.media, event.target === lightMql]);</script></body>",
- )
- .await
- .expect("page should load");
- let _ = bc
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body><script>globalThis.events = []; globalThis.darkMql = matchMedia('(prefers-color-scheme: dark)'); globalThis.lightMql = matchMedia('(prefers-color-scheme: light)'); darkMql.addEventListener('change', event => events.push(['dark', event.matches, event.media, event.target === darkMql])); lightMql.onchange = event => events.push(['light', event.matches, event.media, event.target === lightMql]);</script></body>",
+ Some("SID-1"),
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 184,
@@ -2402,16 +2389,10 @@ async fn generated_surface_refresh_does_not_freeze_match_media_override() {
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-1");
bc.attach_active_session("SID-1");
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body></body>")
- .await
- .expect("page should load");
- let _ = bc
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner("data:text/html,<body></body>", Some("SID-1"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 187,
@@ -2465,16 +2446,10 @@ async fn target_session_detach_clears_emulated_media_before_reattach() {
let mut ctx = TestContext::new();
let mut bc = BrowserContext::new("BID-1".into());
bc.set_active_target_id("TID-1");
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body></body>")
- .await
- .expect("page should load");
- let _ = bc
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner("data:text/html,<body></body>", None)
+ .await;
+ ctx.sent.clear();
ctx.conn.register_top_level_page_target("TID-1");
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/fetch/commands.rs b/moli-protocol/src/domains/fetch/commands.rs
index fdcfe6519..2731edae2 100644
--- a/moli-protocol/src/domains/fetch/commands.rs
+++ b/moli-protocol/src/domains/fetch/commands.rs
@@ -1,6 +1,7 @@
use crate::conn::{
- BackgroundNavigationBodyCompletionSink, CapturedBody, CdpConnection, Cmd, DEFAULT_LOADER_ID,
- PendingStreamingDocumentResponseNavigation, monotonic_timestamp_seconds,
+ BackgroundNavigationBodyCompletionSink, BackgroundNavigationCancellation, CapturedBody,
+ CdpConnection, Cmd, DEFAULT_LOADER_ID, PendingStreamingDocumentResponseNavigation,
+ monotonic_timestamp_seconds,
};
use crate::devtools_runtime::{
DevToolsAuthChallengeAction, DevToolsCommand, DevToolsContinueInterceptedRequestCommand,
@@ -274,7 +275,7 @@ fn start_devtools_continue_intercepted_request_command(
let configured_response_stage = conn
.target_fetch_subresource_interception_snapshot_for_session_owner(command_session_id)
.is_some_and(|snapshot| {
- snapshot.has_response_stage_candidate(pending.resource_type.as_cdp_type())
+ snapshot.has_response_stage_candidate(pending.resource_type.into())
});
let intercept_response = command.intercept_response || configured_response_stage;
if let Some(continuation) = pending.detached_parser_script_fetch_continuation() {
@@ -559,7 +560,7 @@ fn start_devtools_fail_intercepted_request_command(
&loader_id,
monotonic_timestamp_seconds(),
&error_text,
- pending.resource_type.as_cdp_type(),
+ pending.resource_type.into(),
);
plan.extend_background_events(events);
return FetchCommandTaskStep::Complete(plan);
@@ -1895,6 +1896,8 @@ fn continue_streaming_document_response_in_background(
.is_none()
.then(|| conn.none_session_owner_route_override())
.flatten();
+ let cancellation =
+ BackgroundNavigationCancellation::from_fetch_cancel_handle(response.cancellation_handle());
if response_code.is_none()
&& response_headers.is_empty()
&& let Some(prepared_document) = prepared_document
@@ -1902,6 +1905,7 @@ fn continue_streaming_document_response_in_background(
conn.record_background_navigation_started_scheduler_event(
&document_navigation_token,
&navigation,
+ cancellation,
);
tokio::task::spawn_local(async move {
let body_completion_sink = BackgroundNavigationBodyCompletionSink::new(
@@ -1933,6 +1937,7 @@ fn continue_streaming_document_response_in_background(
conn.record_background_navigation_started_scheduler_event(
&document_navigation_token,
&navigation,
+ cancellation,
);
tokio::task::spawn_local(async move {
let body_completion_sink = BackgroundNavigationBodyCompletionSink::new(
diff --git a/moli-protocol/src/domains/fetch/helpers.rs b/moli-protocol/src/domains/fetch/helpers.rs
index f61b5d863..b0df54dd3 100644
--- a/moli-protocol/src/domains/fetch/helpers.rs
+++ b/moli-protocol/src/domains/fetch/helpers.rs
@@ -6,7 +6,8 @@ use crate::conn::{
};
use crate::devtools_runtime::{
AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsNetworkInterceptId,
- DevToolsRequestId, DevToolsTargetId, NetworkAuthChallengeEvent, NetworkRequestEvent,
+ DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId, NetworkAuthChallengeEvent,
+ NetworkRequestEvent,
};
use crate::domains::network;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD};
@@ -212,7 +213,7 @@ fn navigation_auth_required_parts(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: request_cookie_report.cloned(),
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: Some(navigation.timestamp),
wall_time: Some(navigation.timestamp),
status: None,
@@ -276,12 +277,9 @@ fn pending_subresource_auth_required_parts(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: pending.request_cookie_report.clone(),
- resource_type: Some(
- pending
- .resource_type
- .as_cdp_fetch_interception_type()
- .to_owned(),
- ),
+ resource_type: Some(DevToolsNetworkResourceType::from_fetch_interception_type(
+ pending.resource_type,
+ )),
timestamp: None,
wall_time: None,
status: None,
@@ -354,7 +352,7 @@ fn navigation_response_stage_request_paused_parts(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: request_cookie_report.cloned(),
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: None,
wall_time: None,
status: Some(response_status),
@@ -416,12 +414,9 @@ fn pending_subresource_response_stage_request_paused_parts(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: pending.request_cookie_report.clone(),
- resource_type: Some(
- pending
- .resource_type
- .as_cdp_fetch_interception_type()
- .to_owned(),
- ),
+ resource_type: Some(DevToolsNetworkResourceType::from_fetch_interception_type(
+ pending.resource_type,
+ )),
timestamp: None,
wall_time: None,
status: Some(pending.response_status),
@@ -514,7 +509,7 @@ pub(crate) fn request_paused_background_event(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: pending.request_cookie_report.clone(),
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: Some(pending.navigation.timestamp),
wall_time: Some(pending.navigation.timestamp),
status: None,
diff --git a/moli-protocol/src/domains/fetch/navigation.rs b/moli-protocol/src/domains/fetch/navigation.rs
index 242a6c1a4..911494025 100644
--- a/moli-protocol/src/domains/fetch/navigation.rs
+++ b/moli-protocol/src/domains/fetch/navigation.rs
@@ -4,7 +4,7 @@ use crate::conn::{
PendingSubresourceFetchAuthStage, PendingSubresourceFetchAuthStageChain,
PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest, decode_data_url_response,
};
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use crate::domains::{command_output::CommandOutputBuffer, network, page};
use moli_cookie_jar::StoredCookieQueryReport;
use moli_core::page::{SubresourceAuthCredentials, SubresourceAuthScheme, SubresourceResourceType};
@@ -44,7 +44,7 @@ fn prepare_navigation_response_stage(
snapshot
.matching_response_stage_pause_sessions(
pending.navigation.navigate_session_id.as_deref(),
- "Document",
+ DevToolsNetworkResourceType::Document,
final_url,
)
.into_iter()
diff --git a/moli-protocol/src/domains/fetch/subresource.rs b/moli-protocol/src/domains/fetch/subresource.rs
index 400ded334..125937843 100644
--- a/moli-protocol/src/domains/fetch/subresource.rs
+++ b/moli-protocol/src/domains/fetch/subresource.rs
@@ -9,8 +9,8 @@ use crate::conn::{
PendingSubresourceFetchResponseRequest, build_event, monotonic_timestamp_seconds,
};
use crate::devtools_runtime::{
- AutomationEvent, DevToolsFrameId, DevToolsNetworkInterceptId, DevToolsRequestId,
- DevToolsTargetId, NetworkRequestEvent,
+ AutomationEvent, DevToolsFrameId, DevToolsNetworkInterceptId, DevToolsNetworkResourceType,
+ DevToolsRequestId, DevToolsTargetId, NetworkRequestEvent,
};
use crate::domains::network;
use moli_core::runtime::DetachedParserScriptFetchContinuation;
@@ -144,7 +144,7 @@ async fn prepare_subresource_fetch_pause_sources_async(
.cloned()
.unwrap_or_else(|| info.document_url.clone());
let frame_id = info.frame_id.as_deref().unwrap_or(&frame_id).to_owned();
- let resource_type = info.resource_type.as_cdp_type();
+ let resource_type = info.resource_type.into();
let request_stage_pause_sessions = fetch_snapshot.matching_request_stage_pause_sessions(
session_id,
resource_type,
@@ -435,10 +435,9 @@ fn subresource_request_paused_event(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: event_payload
- .get("resourceType")
- .and_then(Value::as_str)
- .map(str::to_owned),
+ resource_type: Some(DevToolsNetworkResourceType::from_fetch_interception_type(
+ pending.resource_type,
+ )),
timestamp: None,
wall_time: None,
status: None,
@@ -591,7 +590,7 @@ mod tests {
BackgroundProtocolEvent, BackgroundTarget, BrowserContext, CdpConnection,
PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,
};
- use crate::devtools_runtime::AutomationEvent;
+ use crate::devtools_runtime::{AutomationEvent, DevToolsNetworkResourceType};
use crate::domains::network::{
TargetSubresourceFetchPauseNetworkOutput, TargetSubresourceFetchPauseOutput,
};
@@ -739,13 +738,13 @@ mod tests {
sidecars[0].as_ref(),
Some(AutomationEvent::NetworkBeforeRequestSent(event))
if event.request_id.as_str() == "REQ-1"
- && event.resource_type.as_deref() == Some("Fetch")
+ && event.resource_type == Some(DevToolsNetworkResourceType::Fetch)
));
assert!(matches!(
sidecars[1].as_ref(),
Some(AutomationEvent::RequestPaused(event))
if event.request_id.as_str() == "FETCH-1"
- && event.resource_type.as_deref() == Some("XHR")
+ && event.resource_type == Some(DevToolsNetworkResourceType::Xhr)
&& event.url == "https://example.test/one"
));
diff --git a/moli-protocol/src/domains/fetch/tests/basics.rs b/moli-protocol/src/domains/fetch/tests/basics.rs
index d9fd2615e..ad131a2ad 100644
--- a/moli-protocol/src/domains/fetch/tests/basics.rs
+++ b/moli-protocol/src/domains/fetch/tests/basics.rs
@@ -3,7 +3,9 @@ use crate::conn::{
CdpCommandTaskStep, FetchInterceptionPattern, PendingSubresourceFetchAuthRequest,
PendingSubresourceFetchOwnerKind, PendingSubresourceFetchRequest,
};
-use crate::devtools_runtime::{AutomationEvent, DevToolsNetworkInterceptId};
+use crate::devtools_runtime::{
+ AutomationEvent, DevToolsNetworkInterceptId, DevToolsNetworkResourceType,
+};
use crate::domains::fetch::pending_subresource_auth_required_event;
use moli_core::page::SubresourceResourceType;
@@ -106,7 +108,10 @@ fn pending_subresource_auth_required_event_carries_typed_sidecar() {
sidecar.network_id.as_ref().map(|id| id.as_str()),
Some("NETWORK-7")
);
- assert_eq!(sidecar.resource_type.as_deref(), Some("XHR"));
+ assert_eq!(
+ sidecar.resource_type,
+ Some(DevToolsNetworkResourceType::Xhr)
+ );
assert_eq!(
sidecar.blocked_intercepts,
vec![DevToolsNetworkInterceptId::from("intercept-auth")]
@@ -393,24 +398,23 @@ async fn disable_drains_fetch_owned_pending_when_same_session_network_intercept_
#[tokio::test(flavor = "multi_thread")]
async fn enable_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<title>fetch background</title>")
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-fetch-bg".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<title>fetch background</title>",
+ Some("SID-background"),
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1201,
@@ -443,37 +447,38 @@ async fn enable_targets_loaded_background_owner_without_promotion() {
#[tokio::test(flavor = "multi_thread")]
async fn pending_fetch_enable_keeps_background_owner_route_across_completion() {
let mut ctx = TestContext::new();
- let active_page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<title>active fetch</title>")
- .await
- .expect("active page should load");
- let background_page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<title>background fetch</title>")
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-fetch-background".to_owned(),
None,
- background_page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(background_page));
let mut bc = BrowserContext::new("BID-fetch-owner-route".to_owned());
bc.set_active_target_id("TID-fetch-active".to_owned());
- bc.set_target_url(active_page.final_url().as_str().to_owned());
- bc.active_target
- .runtime_slot
- .set_loaded_page_for_test(active_page);
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<title>active fetch</title>",
+ None,
+ )
+ .await;
+
let background_route = ctx
.conn
.target_session_route_for_target_id("TID-fetch-background")
.expect("background target route");
+ let previous_route = ctx
+ .conn
+ .replace_none_session_owner_route_override(Some(background_route.clone()));
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<title>background fetch</title>",
+ None,
+ )
+ .await;
+ ctx.conn
+ .replace_none_session_owner_route_override(previous_route);
+ ctx.sent.clear();
let raw = serde_json::to_string(&json!({
"id": 1204,
"method": "Fetch.enable",
@@ -593,18 +598,11 @@ async fn enable_targets_inactive_owner_without_activation() {
#[tokio::test(flavor = "multi_thread")]
async fn disable_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<title>fetch disable background</title>")
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-fetch-disable-bg".to_owned());
bc.set_active_target_id("TID-active".to_owned());
@@ -622,6 +620,12 @@ async fn disable_targets_loaded_background_owner_without_promotion() {
);
});
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<title>fetch disable background</title>",
+ Some("SID-background"),
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1203,
diff --git a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
index 4ff4d5767..a8ee88f12 100644
--- a/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
+++ b/moli-protocol/src/domains/fetch/tests/runtime_auth_response.rs
@@ -1796,15 +1796,9 @@ async fn run_cdp_fetch_then_bidi_network_auth_required_terminal_credentials_comp
.await;
ctx.expect_result(35_980, json!({}), Some("SID-1"));
- let (
- result,
- add_intercept_scheduler_events,
- add_intercept_protocol_events,
- add_intercept_renderer_output_predecessor,
- ) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -1816,12 +1810,9 @@ async fn run_cdp_fetch_then_bidi_network_auth_required_terminal_credentials_comp
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: protected_url.clone(),
}],
- },
- ))
- .await
- .into_complete_parts();
- assert!(add_intercept_protocol_events.is_empty());
- assert!(add_intercept_renderer_output_predecessor.is_none());
+ }),
+ )
+ .await;
assert_eq!(
result.expect("BiDi add auth intercept should succeed"),
DevToolsCommandResult::AddNetworkIntercept(
@@ -1830,14 +1821,6 @@ async fn run_cdp_fetch_then_bidi_network_auth_required_terminal_credentials_comp
}
)
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
let protected_parsed_url = Url::parse(&protected_url).unwrap();
let auth_pause_sessions = ctx
.conn
diff --git a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
index 70a5552e4..cc4fdcc48 100644
--- a/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
+++ b/moli-protocol/src/domains/fetch/tests/runtime_fetch.rs
@@ -4,8 +4,8 @@ use crate::devtools_runtime::{
DevToolsCommandResult, DevToolsContinueInterceptedRequestCommand,
DevToolsContinueInterceptedResponseCommand, DevToolsEvaluateScriptCommand,
DevToolsNetworkInterceptId, DevToolsNetworkInterceptPattern, DevToolsNetworkInterceptPhase,
- DevToolsProtocol, DevToolsRequestId, DevToolsResultOwnership, DevToolsSessionId,
- DevToolsTargetId,
+ DevToolsNetworkResourceType, DevToolsProtocol, DevToolsRequestId, DevToolsResultOwnership,
+ DevToolsSessionId, DevToolsTargetId,
};
use crate::testing::{
drain_scheduler_events_like_scheduler,
@@ -1115,10 +1115,9 @@ async fn response_body_stream_taken_blocks_chained_bidi_response_stage_pause() {
.await;
ctx.expect_result(35_958, json!({}), Some("SID-1"));
- let (result, add_intercept_scheduler_events) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -1130,29 +1129,23 @@ async fn response_body_stream_taken_blocks_chained_bidi_response_stage_pause() {
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: hit_url.clone(),
}],
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
assert!(
result.is_ok(),
"BiDi response-stage add intercept should succeed: {result:?}"
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
-
let api_url = Url::parse(&hit_url).unwrap();
let response_pause_sessions = ctx
.conn
.target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))
.expect("active target fetch snapshot")
- .matching_response_stage_pause_sessions(Some("SID-1"), "Fetch", &api_url);
+ .matching_response_stage_pause_sessions(
+ Some("SID-1"),
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ );
assert_eq!(
response_pause_sessions
.iter()
@@ -6629,10 +6622,9 @@ async fn bidi_add_network_intercept_pauses_matching_fetch_subresources() {
with_loaded_http_document(&mut ctx, &page_url, "SID-1", "TID-1").await;
ctx.sent.clear();
- let (result, add_intercept_scheduler_events) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -6644,10 +6636,9 @@ async fn bidi_add_network_intercept_pauses_matching_fetch_subresources() {
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: hit_url.clone(),
}],
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
assert_eq!(
result.expect("BiDi add intercept should succeed"),
DevToolsCommandResult::AddNetworkIntercept(
@@ -6656,14 +6647,6 @@ async fn bidi_add_network_intercept_pauses_matching_fetch_subresources() {
}
)
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
ctx.sent.clear();
let (evaluate_result, scheduler_events, protocol_events, renderer_output_predecessor) = ctx
@@ -6787,10 +6770,9 @@ async fn cdp_fetch_then_bidi_network_intercept_request_stage_chain_completes() {
.await;
ctx.expect_result(41_010, json!({}), Some("SID-1"));
- let (result, add_intercept_scheduler_events) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -6802,22 +6784,13 @@ async fn cdp_fetch_then_bidi_network_intercept_request_stage_chain_completes() {
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: hit_url.clone(),
}],
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
assert!(
result.is_ok(),
"BiDi add intercept should succeed: {result:?}"
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
enable_runtime_async(&mut ctx, "SID-1", 41_011).await;
ctx.sent.clear();
@@ -6990,10 +6963,9 @@ async fn cdp_fetch_then_bidi_network_intercept_response_stage_chain_completes()
.await;
ctx.expect_result(41_110, json!({}), Some("SID-1"));
- let (result, add_intercept_scheduler_events) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -7005,28 +6977,23 @@ async fn cdp_fetch_then_bidi_network_intercept_response_stage_chain_completes()
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: hit_url.clone(),
}],
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
assert!(
result.is_ok(),
"BiDi response-stage add intercept should succeed: {result:?}"
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
let api_url = Url::parse(&hit_url).unwrap();
let response_pause_sessions = ctx
.conn
.target_fetch_subresource_interception_snapshot_for_session_owner(Some("SID-1"))
.expect("active target fetch snapshot")
- .matching_response_stage_pause_sessions(Some("SID-1"), "Fetch", &api_url);
+ .matching_response_stage_pause_sessions(
+ Some("SID-1"),
+ DevToolsNetworkResourceType::Fetch,
+ &api_url,
+ );
assert_eq!(
response_pause_sessions
.iter()
@@ -7253,10 +7220,9 @@ async fn bidi_response_stage_network_intercept_marks_fetch_continuation_request_
ctx.expect_result(41_200, json!({}), Some("SID-1"));
ctx.sent.clear();
- let (result, add_intercept_scheduler_events) = ctx
- .conn
- .execute_devtools_command(DevToolsCommand::AddNetworkIntercept(
- DevToolsAddNetworkInterceptCommand {
+ let result = ctx
+ .execute_devtools_command_through_renderer_fence_for_test(
+ DevToolsCommand::AddNetworkIntercept(DevToolsAddNetworkInterceptCommand {
context: DevToolsCommandContext {
protocol: DevToolsProtocol::WebDriverBidi,
session_id: Some(DevToolsSessionId::from("BIDI-SID")),
@@ -7268,10 +7234,9 @@ async fn bidi_response_stage_network_intercept_marks_fetch_continuation_request_
url_patterns: vec![DevToolsNetworkInterceptPattern {
url_pattern: hit_url.clone(),
}],
- },
- ))
- .await
- .into_parts();
+ }),
+ )
+ .await;
assert_eq!(
result.expect("BiDi add response-stage intercept should succeed"),
DevToolsCommandResult::AddNetworkIntercept(
@@ -7280,14 +7245,6 @@ async fn bidi_response_stage_network_intercept_marks_fetch_continuation_request_
}
)
);
- let mut add_intercept_output = Vec::new();
- drain_scheduler_events_like_scheduler(
- &mut ctx.conn,
- &mut add_intercept_output,
- add_intercept_scheduler_events,
- )
- .await;
- ctx.sent.extend(add_intercept_output);
ctx.sent.clear();
let (evaluate_result, scheduler_events, protocol_events, renderer_output_predecessor) = ctx
diff --git a/moli-protocol/src/domains/log.rs b/moli-protocol/src/domains/log.rs
index ce5c4e685..3c26b581c 100644
--- a/moli-protocol/src/domains/log.rs
+++ b/moli-protocol/src/domains/log.rs
@@ -360,7 +360,12 @@ mod tests {
"unexpected Log.entryAdded sidecar text: {log_event:?}"
);
assert_eq!(log_event.level, "error");
- assert_eq!(log_event.url.as_deref(), Some("data:text/html,log-test"));
+ assert_eq!(
+ log_event.url.as_deref(),
+ Some(
+ "data:text/html,<!doctype html><script>setTimeout(function(){ throw new Error('boot failure') }, 0)</script>"
+ )
+ );
let (response, response_sidecar) = events[1].clone().into_parts();
assert_eq!(response["id"], json!(1));
diff --git a/moli-protocol/src/domains/network.rs b/moli-protocol/src/domains/network.rs
index c41f854a2..a400ace2d 100644
--- a/moli-protocol/src/domains/network.rs
+++ b/moli-protocol/src/domains/network.rs
@@ -62,7 +62,8 @@ pub use agent::IoStreamState;
pub(crate) use agent::TargetIoStreamRead;
pub(crate) use agent::{
CapturedRequestBody, CapturedResponseBody, CollectedNetworkDataArtifact,
- NetworkBacklogPreferredRequestId, TargetNetworkAgentState, TargetNetworkArtifacts,
+ NetworkBacklogPreferredRequestId, RetiringTargetNetworkAgentState, TargetNetworkAgentState,
+ TargetNetworkArtifacts,
};
pub(crate) use backlog::{
NetworkBacklogProjectionContext, emit_pending_network_backlog_activity_background_events,
diff --git a/moli-protocol/src/domains/network/agent.rs b/moli-protocol/src/domains/network/agent.rs
index f7cbc00c3..1fabaf974 100644
--- a/moli-protocol/src/domains/network/agent.rs
+++ b/moli-protocol/src/domains/network/agent.rs
@@ -16,12 +16,19 @@ use super::{
const RESPONSE_BODY_BUFFER_MAX_TOTAL_BYTES: usize = 20_000_000;
const RESPONSE_BODY_BUFFER_MAX_ENTRY_BYTES: usize = 2_000_000;
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum RendererSubresourceTeardownDisposition {
+ RequiresDocumentTerminal,
+ DetachedKeepalive,
+}
+
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TargetNetworkAgentState {
primary_enabled: bool,
auxiliary_event_session_ids: Vec<String>,
output_queue: TargetNetworkOutputQueue,
- active_renderer_subresource_requests: HashSet<SubresourceNetworkRequestHandle>,
+ active_renderer_subresource_requests:
+ HashMap<SubresourceNetworkRequestHandle, RendererSubresourceTeardownDisposition>,
artifacts: TargetNetworkArtifacts,
}
@@ -35,23 +42,26 @@ pub(crate) struct CollectedNetworkDataArtifact {
}
struct NetworkBacklogRequestIdPlan<'a> {
- artifacts: &'a mut TargetNetworkArtifacts,
+ subresource_artifacts: &'a mut SubresourceNetworkArtifacts,
+ websocket_artifacts: &'a mut WebSocketNetworkArtifacts,
preferred_request_id: NetworkBacklogPreferredRequestIdBudget,
request_id_allocator: &'a mut ConnectionNetworkRequestIdAllocator,
}
impl<'a> NetworkBacklogRequestIdPlan<'a> {
fn new(
- artifacts: &'a mut TargetNetworkArtifacts,
+ subresource_artifacts: &'a mut SubresourceNetworkArtifacts,
+ websocket_artifacts: &'a mut WebSocketNetworkArtifacts,
preferred_request_id: Option<NetworkBacklogPreferredRequestId<'_>>,
request_id_allocator: &'a mut ConnectionNetworkRequestIdAllocator,
) -> Self {
let preferred_request_id = NetworkBacklogPreferredRequestIdBudget::new(
preferred_request_id,
- &artifacts.subresource_network_artifacts,
+ subresource_artifacts,
);
Self {
- artifacts,
+ subresource_artifacts,
+ websocket_artifacts,
preferred_request_id,
request_id_allocator,
}
@@ -61,16 +71,39 @@ impl<'a> NetworkBacklogRequestIdPlan<'a> {
&mut self,
output: &TargetSubresourcePlanOutput,
) -> String {
- self.artifacts.request_id_for_subresource_output(
- output,
- &mut self.preferred_request_id,
- self.request_id_allocator,
- )
+ if let Some(socket_id) = output.websocket_socket_id()
+ && let Some(request_id) = self.websocket_artifacts.request_id_for_socket(socket_id)
+ {
+ return request_id.to_owned();
+ }
+ if let Some(handle) = output.request_handle()
+ && let Some(request_id) = self.subresource_artifacts.request_id_for_handle(handle)
+ {
+ return request_id.to_owned();
+ }
+ let request_id = self
+ .preferred_request_id
+ .take_for_new_subresource(output.request_handle())
+ .unwrap_or_else(|| self.request_id_allocator.allocate_request_id());
+ if let Some(handle) = output.request_handle() {
+ self.subresource_artifacts
+ .set_request_id_for_handle_if_absent(handle, request_id.clone());
+ }
+ if let Some(socket_id) = output.websocket_socket_id() {
+ self.websocket_artifacts
+ .set_request_id_for_socket_if_absent(socket_id, request_id.clone());
+ }
+ request_id
}
fn request_id_for_websocket_socket(&mut self, socket_id: u64) -> String {
- self.artifacts
- .request_id_for_websocket_socket(socket_id, self.request_id_allocator)
+ if let Some(request_id) = self.websocket_artifacts.request_id_for_socket(socket_id) {
+ return request_id.to_owned();
+ }
+ let request_id = self.request_id_allocator.allocate_request_id();
+ self.websocket_artifacts
+ .set_request_id_for_socket_if_absent(socket_id, request_id.clone());
+ request_id
}
}
@@ -144,6 +177,29 @@ impl NetworkBacklogPreferredRequestIdBudget {
}
impl TargetNetworkAgentState {
+ /// Moves the Document-owned live queue and request correlations into a
+ /// short-lived predecessor state while retaining target/session policy and
+ /// target-scoped body/stream artifacts for the replacement Document.
+ ///
+ /// A renderer Page can publish its final cancellation batch after protocol
+ /// has installed its successor Page. Keeping the predecessor queue intact
+ /// lets those terminal facts reuse the request ids announced before the
+ /// commit without making the successor replay historical requests.
+ pub(crate) fn rotate_document_for_replacement(&mut self) -> RetiringTargetNetworkAgentState {
+ RetiringTargetNetworkAgentState {
+ output_queue: std::mem::take(&mut self.output_queue),
+ active_renderer_subresource_requests: std::mem::take(
+ &mut self.active_renderer_subresource_requests,
+ ),
+ subresource_network_artifacts: std::mem::take(
+ &mut self.artifacts.subresource_network_artifacts,
+ ),
+ websocket_network_artifacts: std::mem::take(
+ &mut self.artifacts.websocket_network_artifacts,
+ ),
+ }
+ }
+
pub(crate) fn primary_events_enabled(&self) -> bool {
self.primary_enabled
}
@@ -181,22 +237,10 @@ impl TargetNetworkAgentState {
item: &ScriptNetworkOutputItem,
document_loader_id: &str,
) {
- match item {
- ScriptNetworkOutputItem::SubresourceRequestStarted(request) => {
- self.active_renderer_subresource_requests
- .insert(request.handle());
- }
- ScriptNetworkOutputItem::SubresourceBodyFinished(body) => {
- self.active_renderer_subresource_requests
- .remove(&body.handle());
- }
- ScriptNetworkOutputItem::SubresourceNetworkRecord(_)
- | ScriptNetworkOutputItem::SubresourceResponseStarted(_)
- | ScriptNetworkOutputItem::SubresourceDataReceived(_)
- | ScriptNetworkOutputItem::SubresourceEventSourceMessageReceived(_)
- | ScriptNetworkOutputItem::WebSocketNetworkEvent(_)
- | ScriptNetworkOutputItem::WebSocketLifecycleEvent(_) => {}
- }
+ update_active_renderer_subresource_requests(
+ &mut self.active_renderer_subresource_requests,
+ item,
+ );
self.output_queue
.append_renderer_output_item_for_loader(item, document_loader_id);
}
@@ -246,7 +290,8 @@ impl TargetNetworkAgentState {
.collect(),
);
let mut request_ids = NetworkBacklogRequestIdPlan::new(
- &mut self.artifacts,
+ &mut self.artifacts.subresource_network_artifacts,
+ &mut self.artifacts.websocket_network_artifacts,
preferred_request_id,
request_id_allocator,
);
@@ -401,7 +446,8 @@ impl TargetNetworkAgentState {
let websocket_activity =
self.pending_websocket_activity(trigger_session_id, primary_session_id);
let mut request_ids = NetworkBacklogRequestIdPlan::new(
- &mut self.artifacts,
+ &mut self.artifacts.subresource_network_artifacts,
+ &mut self.artifacts.websocket_network_artifacts,
preferred_request_id,
request_id_allocator,
);
@@ -853,6 +899,126 @@ impl TargetNetworkAgentState {
}
}
+/// Network lifecycle state retained only until a replaced renderer Page has
+/// published and closed its final output stream.
+#[derive(Debug)]
+pub(crate) struct RetiringTargetNetworkAgentState {
+ output_queue: TargetNetworkOutputQueue,
+ active_renderer_subresource_requests:
+ HashMap<SubresourceNetworkRequestHandle, RendererSubresourceTeardownDisposition>,
+ subresource_network_artifacts: SubresourceNetworkArtifacts,
+ websocket_network_artifacts: WebSocketNetworkArtifacts,
+}
+
+impl RetiringTargetNetworkAgentState {
+ pub(crate) fn ingest_renderer_output_item_and_prepare_live_delivery(
+ &mut self,
+ item: &ScriptNetworkOutputItem,
+ document_loader_id: &str,
+ event_session_ids: Vec<Option<String>>,
+ preferred_request_id: Option<NetworkBacklogPreferredRequestId<'_>>,
+ request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,
+ ) -> TargetNetworkBacklogPreparedDelivery {
+ update_active_renderer_subresource_requests(
+ &mut self.active_renderer_subresource_requests,
+ item,
+ );
+
+ let subresource_start = self.output_queue.subresource_record_count();
+ let websocket_event_start = self.output_queue.websocket_event_count();
+ self.output_queue
+ .append_renderer_output_item_for_loader(item, document_loader_id);
+ let subresource_activity = PendingSubresourceNetworkActivity::from_sessions(
+ event_session_ids
+ .iter()
+ .cloned()
+ .map(|session_id| {
+ PendingSubresourceNetworkActivitySession::new(session_id, subresource_start)
+ })
+ .collect(),
+ );
+ let websocket_activity = PendingWebSocketNetworkActivity::from_sessions(
+ event_session_ids
+ .into_iter()
+ .map(|session_id| {
+ PendingWebSocketNetworkActivitySession::new(
+ session_id,
+ subresource_start,
+ websocket_event_start,
+ )
+ })
+ .collect(),
+ );
+ let mut request_ids = NetworkBacklogRequestIdPlan::new(
+ &mut self.subresource_network_artifacts,
+ &mut self.websocket_network_artifacts,
+ preferred_request_id,
+ request_id_allocator,
+ );
+ self.output_queue.backlog_prepared_delivery_for_activity(
+ subresource_activity,
+ websocket_activity,
+ &mut request_ids,
+ )
+ }
+
+ pub(crate) fn unterminated_document_bound_request_diagnostics(
+ &self,
+ ) -> Vec<(u64, Option<&str>)> {
+ let mut handles = self
+ .active_renderer_subresource_requests
+ .iter()
+ .filter_map(|(&handle, &disposition)| {
+ (disposition == RendererSubresourceTeardownDisposition::RequiresDocumentTerminal)
+ .then_some(handle)
+ })
+ .collect::<Vec<_>>();
+ handles.sort_unstable_by_key(|handle| handle.get());
+ handles
+ .into_iter()
+ .map(|handle| {
+ (
+ handle.get(),
+ self.subresource_network_artifacts
+ .request_id_for_handle(handle),
+ )
+ })
+ .collect()
+ }
+}
+
+fn update_active_renderer_subresource_requests(
+ active_requests: &mut HashMap<
+ SubresourceNetworkRequestHandle,
+ RendererSubresourceTeardownDisposition,
+ >,
+ item: &ScriptNetworkOutputItem,
+) {
+ match item {
+ ScriptNetworkOutputItem::SubresourceRequestStarted(request) => {
+ let disposition = if request.keepalive() {
+ RendererSubresourceTeardownDisposition::DetachedKeepalive
+ } else {
+ RendererSubresourceTeardownDisposition::RequiresDocumentTerminal
+ };
+ active_requests.insert(request.handle(), disposition);
+ }
+ ScriptNetworkOutputItem::SubresourceBodyFinished(body) => {
+ active_requests.remove(&body.handle());
+ }
+ ScriptNetworkOutputItem::SubresourceNetworkRecord(record) => {
+ if let Some(handle) = record.request_handle() {
+ active_requests.remove(&handle);
+ }
+ }
+ ScriptNetworkOutputItem::SubresourceResponseStarted(_)
+ | ScriptNetworkOutputItem::SubresourceDataReceived(_)
+ | ScriptNetworkOutputItem::SubresourceEventSourceMessageReceived(_)
+ | ScriptNetworkOutputItem::WebSocketNetworkEvent(_)
+ | ScriptNetworkOutputItem::WebSocketLifecycleEvent(_) => {}
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct CapturedResponseBody {
state: CapturedResponseBodyState,
@@ -1344,35 +1510,7 @@ impl TargetNetworkArtifacts {
.emitted_event_count_for_session(session_id)
}
- fn request_id_for_subresource_output(
- &mut self,
- output: &TargetSubresourcePlanOutput,
- preferred_request_id: &mut NetworkBacklogPreferredRequestIdBudget,
- request_id_allocator: &mut ConnectionNetworkRequestIdAllocator,
- ) -> String {
- if let Some(socket_id) = output.websocket_socket_id()
- && let Some(request_id) = self.websocket_request_id_for_socket(socket_id)
- {
- return request_id.to_owned();
- }
- if let Some(handle) = output.request_handle()
- && let Some(request_id) = self
- .subresource_network_artifacts
- .request_id_for_handle(handle)
- {
- return request_id.to_owned();
- }
- let request_id = preferred_request_id
- .take_for_new_subresource(output.request_handle())
- .unwrap_or_else(|| request_id_allocator.allocate_request_id());
- if let Some(handle) = output.request_handle() {
- self.subresource_network_artifacts
- .set_request_id_for_handle_if_absent(handle, request_id.clone());
- }
- self.record_websocket_request_id_for_subresource_output_if_absent(output, &request_id);
- request_id
- }
-
+ #[cfg(test)]
fn request_id_for_websocket_socket(
&mut self,
socket_id: u64,
@@ -1386,11 +1524,13 @@ impl TargetNetworkArtifacts {
request_id
}
+ #[cfg(test)]
fn websocket_request_id_for_socket(&self, socket_id: u64) -> Option<&str> {
self.websocket_network_artifacts
.request_id_for_socket(socket_id)
}
+ #[cfg(test)]
fn record_websocket_request_id_for_socket_if_absent(
&mut self,
socket_id: u64,
@@ -1400,17 +1540,6 @@ impl TargetNetworkArtifacts {
.set_request_id_for_socket_if_absent(socket_id, request_id);
}
- fn record_websocket_request_id_for_subresource_output_if_absent(
- &mut self,
- output: &TargetSubresourcePlanOutput,
- request_id: &str,
- ) {
- let Some(socket_id) = output.websocket_socket_id() else {
- return;
- };
- self.record_websocket_request_id_for_socket_if_absent(socket_id, request_id.to_owned());
- }
-
pub(crate) fn clear_session_scoped_observation_artifacts(&mut self) {
self.body_artifacts.clear_session_scoped();
self.subresource_network_artifacts.clear_request_ids();
@@ -1761,8 +1890,8 @@ impl SubresourceNetworkArtifacts {
mod tests {
use moli_core::page::{
ScriptNetworkOutputItem, SubresourceNetworkRecord, SubresourceNetworkRequestHandle,
- SubresourceResourceType, WebSocketFrameDirection, WebSocketFrameOpcode,
- WebSocketNetworkEvent,
+ SubresourceRequestInitiatorType, SubresourceRequestStarted, SubresourceResourceType,
+ WebSocketFrameDirection, WebSocketFrameOpcode, WebSocketNetworkEvent,
};
use url::Url;
@@ -1953,6 +2082,94 @@ mod tests {
}
}
+ #[test]
+ fn handled_terminal_network_record_retires_staged_request_from_idle_accounting() {
+ let mut agent = TargetNetworkAgentState::default();
+ let handle = SubresourceNetworkRequestHandle::new(17);
+ let document_url = Url::parse("https://example.com/").expect("document URL should parse");
+ let request_url =
+ Url::parse("https://example.com/late-xhr").expect("request URL should parse");
+ let started = ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(
+ SubresourceRequestStarted::new(
+ handle,
+ None,
+ document_url,
+ request_url,
+ "GET".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Xhr,
+ SubresourceRequestInitiatorType::Script,
+ None,
+ ),
+ ));
+ agent.ingest_renderer_output_item(&started, "LOADER-1");
+ assert!(!agent.renderer_subresources_are_idle());
+
+ let terminal = ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(
+ subresource_record("https://example.com/late-xhr").with_request_handle(handle),
+ ));
+ agent.ingest_renderer_output_item(&terminal, "LOADER-1");
+
+ assert!(
+ agent.renderer_subresources_are_idle(),
+ "a handled all-in-one record is terminal for the staged request with the same handle"
+ );
+ }
+
+ #[test]
+ fn retiring_keepalive_does_not_require_a_document_bound_terminal() {
+ fn started(
+ handle: SubresourceNetworkRequestHandle,
+ keepalive: bool,
+ ) -> ScriptNetworkOutputItem {
+ ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(
+ SubresourceRequestStarted::new(
+ handle,
+ None,
+ Url::parse("https://example.com/").expect("document URL should parse"),
+ Url::parse("https://example.com/collect").expect("request URL should parse"),
+ "POST".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Fetch,
+ SubresourceRequestInitiatorType::Script,
+ None,
+ )
+ .with_keepalive(keepalive),
+ ))
+ }
+
+ let mut keepalive_agent = TargetNetworkAgentState::default();
+ keepalive_agent.ingest_renderer_output_item(
+ &started(SubresourceNetworkRequestHandle::new(18), true),
+ "LOADER-1",
+ );
+ assert!(
+ !keepalive_agent.renderer_subresources_are_idle(),
+ "a keepalive remains current-document activity until replacement"
+ );
+ let retiring_keepalive = keepalive_agent.rotate_document_for_replacement();
+ assert!(
+ retiring_keepalive
+ .unterminated_document_bound_request_diagnostics()
+ .is_empty(),
+ "a detached keepalive may outlive its Document without a CDP terminal"
+ );
+
+ let mut ordinary_agent = TargetNetworkAgentState::default();
+ ordinary_agent.ingest_renderer_output_item(
+ &started(SubresourceNetworkRequestHandle::new(19), false),
+ "LOADER-2",
+ );
+ let retiring_ordinary = ordinary_agent.rotate_document_for_replacement();
+ assert_eq!(
+ retiring_ordinary.unterminated_document_bound_request_diagnostics(),
+ vec![(19, None)],
+ "an ordinary request still requires a terminal before its renderer stream closes"
+ );
+ }
+
fn pending_combined_snapshot(
agent: &mut TargetNetworkAgentState,
preferred_request_id: Option<&str>,
@@ -2638,7 +2855,8 @@ mod tests {
.expect("test websocket activity should be visible");
let mut request_id_allocator = ConnectionNetworkRequestIdAllocator::default();
let mut request_ids = NetworkBacklogRequestIdPlan::new(
- &mut agent.artifacts,
+ &mut agent.artifacts.subresource_network_artifacts,
+ &mut agent.artifacts.websocket_network_artifacts,
Some(contextual_preferred_request_id("REQ-main")),
&mut request_id_allocator,
);
diff --git a/moli-protocol/src/domains/network/backlog.rs b/moli-protocol/src/domains/network/backlog.rs
index 3423b8605..0fa34640b 100644
--- a/moli-protocol/src/domains/network/backlog.rs
+++ b/moli-protocol/src/domains/network/backlog.rs
@@ -3,7 +3,7 @@ use moli_core::page::{SubresourceBodyFinishedResult, SubresourceResponseBody};
use crate::conn::{
BackgroundProtocolEvent, CdpConnection, FetchRequestStage, monotonic_timestamp_seconds,
};
-use crate::devtools_runtime::DevToolsNetworkInterceptId;
+use crate::devtools_runtime::{DevToolsNetworkInterceptId, DevToolsNetworkResourceType};
use crate::domains::network::{NetworkBacklogPreferredRequestId, NetworkPreparedOutputs};
use super::events::{
@@ -212,7 +212,7 @@ fn emit_complete_subresource_network_delivery_record(
let loader_id = output.loader_id();
let record_document_url = output.document_url();
let timestamp = base_timestamp + ((output.index() + 1) as f64 * 0.000_001);
- let resource_type = output.resource_type().as_cdp_type();
+ let resource_type = output.resource_type().into();
let Ok(runtime_slot) = conn.runtime_session_owner_slot_mut(session_id) else {
return false;
};
@@ -364,7 +364,7 @@ fn emit_complete_subresource_network_delivery_record(
loader_id,
timestamp,
*response_body_len,
- None,
+ resource_type,
);
}
}
@@ -413,7 +413,7 @@ fn emit_staged_subresource_request_started(
let record_frame_id = output.frame_id().unwrap_or(frame_id);
let loader_id = output.loader_id();
let timestamp = base_timestamp + ((output.index() + 1) as f64 * 0.000_001);
- let resource_type = output.resource_type().as_cdp_type();
+ let resource_type = output.resource_type().into();
let request_was_announced_by_fetch_pause = conn
.runtime_session_owner_slot_mut(session_id)
.is_ok_and(|runtime_slot| runtime_slot.take_fetch_pause_announced_request_id(request_id));
@@ -495,7 +495,7 @@ fn emit_staged_subresource_response_started(
let record_frame_id = request.frame_id().unwrap_or(frame_id);
let loader_id = request.loader_id();
let timestamp = base_timestamp + ((output.index() + 1) as f64 * 0.000_001);
- let resource_type = request.resource_type().as_cdp_type();
+ let resource_type = request.resource_type().into();
for redirect in output.redirect_chain() {
for event_session_id in event_session_ids {
emit_request_will_be_sent(
@@ -577,7 +577,7 @@ fn matching_subresource_network_intercepts(
conn: &CdpConnection,
session_id: Option<&str>,
request_stage: FetchRequestStage,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
url: &url::Url,
) -> Vec<DevToolsNetworkInterceptId> {
conn.target_fetch_subresource_interception_snapshot_for_session_owner(session_id)
@@ -604,7 +604,7 @@ fn emit_staged_subresource_body_finished(
let record_frame_id = request.frame_id().unwrap_or(frame_id);
let loader_id = request.loader_id();
let timestamp = base_timestamp + ((output.index() + 1) as f64 * 0.000_001);
- let resource_type = request.resource_type().as_cdp_type();
+ let resource_type = request.resource_type().into();
match output.result() {
SubresourceBodyFinishedResult::Ready(response_body) => {
let response_body_len = response_body.len();
@@ -625,7 +625,7 @@ fn emit_staged_subresource_body_finished(
loader_id,
timestamp,
response_body_len,
- None,
+ resource_type,
);
} else {
emit_body_finished(
@@ -636,7 +636,7 @@ fn emit_staged_subresource_body_finished(
loader_id,
timestamp,
response_body_len,
- None,
+ resource_type,
);
}
}
@@ -1038,9 +1038,89 @@ fn emit_websocket_network_delivery_record(
#[cfg(test)]
mod tests {
- use crate::domains::network::NetworkPreparedOutputs;
+ use moli_core::page::{
+ ScriptNetworkOutputItem, SubresourceBodyFinished, SubresourceNetworkRecord,
+ SubresourceNetworkRequestHandle, SubresourceRequestInitiatorType,
+ SubresourceRequestStarted, SubresourceResourceType, SubresourceResponseBody,
+ SubresourceResponseStarted,
+ };
+ use url::Url;
+
+ use crate::{
+ conn::CdpConnection,
+ devtools_runtime::{AutomationEvent, DevToolsNetworkResourceType},
+ domains::network::{
+ NetworkPreparedOutputs, PendingSubresourceNetworkActivity,
+ PendingSubresourceNetworkActivitySession, TargetNetworkBacklogRequestIdResolver,
+ TargetNetworkOutputQueue, TargetSubresourcePlanOutput,
+ },
+ };
+
+ use super::{
+ NetworkBacklogPreferredRequestId, NetworkBacklogProjectionContext,
+ emit_network_delivery_snapshot,
+ };
+
+ struct FixedRequestId;
+
+ impl TargetNetworkBacklogRequestIdResolver for FixedRequestId {
+ fn request_id_for_subresource_output(
+ &mut self,
+ _output: &TargetSubresourcePlanOutput,
+ ) -> String {
+ "REQ-XHR".to_owned()
+ }
- use super::{NetworkBacklogPreferredRequestId, NetworkBacklogProjectionContext};
+ fn request_id_for_websocket_socket(&mut self, _socket_id: u64) -> String {
+ "REQ-WS".to_owned()
+ }
+ }
+
+ fn emitted_terminal_for(items: Vec<ScriptNetworkOutputItem>) -> crate::BackgroundProtocolEvent {
+ let mut queue = TargetNetworkOutputQueue::default();
+ for item in items {
+ queue.append_renderer_output_item_for_loader(&item, "LOADER-1");
+ }
+ let activity = PendingSubresourceNetworkActivity::from_sessions(vec![
+ PendingSubresourceNetworkActivitySession::new(None, 0),
+ ]);
+ let mut request_ids = FixedRequestId;
+ let mut prepared =
+ queue.backlog_prepared_delivery_for_activity(activity, None, &mut request_ids);
+ let snapshot = queue
+ .pending_network_backlog_delivery_snapshot_from_backlog(&mut prepared)
+ .expect("XHR output should produce a delivery snapshot");
+ let mut events = Vec::new();
+ let mut conn = CdpConnection::new();
+ conn.install_default_browser_target();
+ emit_network_delivery_snapshot(&mut conn, &mut events, None, "FRAME-1", 1.0, snapshot);
+ events
+ .into_iter()
+ .find(|event| event.protocol_method() == Some("Network.loadingFinished"))
+ .expect("successful XHR should emit loadingFinished")
+ }
+
+ fn assert_xhr_terminal_retains_internal_resource_type(items: Vec<ScriptNetworkOutputItem>) {
+ let terminal = emitted_terminal_for(items);
+ assert_eq!(
+ terminal
+ .trace_network_summary()
+ .and_then(|summary| summary.1),
+ Some("XHR")
+ );
+ assert!(
+ terminal.should_wait_for_background_navigation_completion(),
+ "a successful XHR terminal must stay behind the same navigation gate as its start and response"
+ );
+ let (message, automation_event) = terminal.into_parts();
+ assert_eq!(message["method"], "Network.loadingFinished");
+ assert!(message["params"].get("type").is_none());
+ assert!(matches!(
+ automation_event,
+ Some(AutomationEvent::NetworkResponseCompleted(event))
+ if event.resource_type == Some(DevToolsNetworkResourceType::Xhr)
+ ));
+ }
#[test]
fn backlog_projection_context_wraps_contextual_subresource_preferred_request_id() {
@@ -1072,4 +1152,60 @@ mod tests {
"Network backlog context should carry the prepared output slot instead of exposing it as a separate emitter parameter"
);
}
+
+ #[test]
+ fn successful_complete_and_staged_xhr_terminals_keep_their_internal_resource_type() {
+ let document_url = Url::parse("https://example.test/").unwrap();
+ let request_url = Url::parse("https://example.test/api").unwrap();
+ let complete = SubresourceNetworkRecord::success_with_body(
+ Some("FRAME-1".to_owned()),
+ document_url.clone(),
+ request_url.clone(),
+ "GET".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Xhr,
+ None,
+ Vec::new(),
+ request_url.clone(),
+ 200,
+ Vec::new(),
+ SubresourceResponseBody::from_text("complete".to_owned()),
+ Vec::new(),
+ );
+ assert_xhr_terminal_retains_internal_resource_type(vec![
+ ScriptNetworkOutputItem::SubresourceNetworkRecord(Box::new(complete)),
+ ]);
+
+ let handle = SubresourceNetworkRequestHandle::new(1);
+ let request = SubresourceRequestStarted::new(
+ handle,
+ Some("FRAME-1".to_owned()),
+ document_url,
+ request_url.clone(),
+ "GET".to_owned(),
+ Vec::new(),
+ None,
+ SubresourceResourceType::Xhr,
+ SubresourceRequestInitiatorType::Script,
+ None,
+ );
+ let response = SubresourceResponseStarted::new(
+ handle,
+ Vec::new(),
+ request_url,
+ 200,
+ Vec::new(),
+ Vec::new(),
+ );
+ let body = SubresourceBodyFinished::ready(
+ handle,
+ SubresourceResponseBody::from_text("staged".to_owned()),
+ );
+ assert_xhr_terminal_retains_internal_resource_type(vec![
+ ScriptNetworkOutputItem::SubresourceRequestStarted(Box::new(request)),
+ ScriptNetworkOutputItem::SubresourceResponseStarted(Box::new(response)),
+ ScriptNetworkOutputItem::SubresourceBodyFinished(Box::new(body)),
+ ]);
+ }
}
diff --git a/moli-protocol/src/domains/network/events.rs b/moli-protocol/src/domains/network/events.rs
index 5616de321..9ab74f308 100644
--- a/moli-protocol/src/domains/network/events.rs
+++ b/moli-protocol/src/domains/network/events.rs
@@ -1,7 +1,7 @@
use crate::devtools_runtime::{
AutomationEvent, DevToolsFetchRequestId, DevToolsFrameId, DevToolsLoaderId,
- DevToolsNetworkInterceptId, DevToolsRequestId, DevToolsTargetId, NetworkRedirectResponseEvent,
- NetworkRequestEvent,
+ DevToolsNetworkInterceptId, DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId,
+ NetworkRedirectResponseEvent, NetworkRequestEvent,
};
use moli_cookie_jar::StoredCookieSetReport;
use moli_core::page::{
@@ -267,7 +267,7 @@ pub(crate) fn emit_request_will_be_sent(
method: &str,
request_body: Option<&str>,
request_headers: &[(String, String)],
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
request_initiator_type: SubresourceRequestInitiatorType,
redirect_response: Option<(
&Url,
@@ -322,7 +322,7 @@ pub(crate) fn emit_request_will_be_sent(
),
redirect_has_extra_info,
request_cookie_report: cookie_access_report.cloned(),
- resource_type: Some(resource_type.to_owned()),
+ resource_type: Some(resource_type),
timestamp: Some(timestamp),
wall_time: Some(timestamp),
status: None,
@@ -359,7 +359,7 @@ pub(crate) fn fetch_subresource_initial_request_network_events(
session_id: Option<&str>,
output: &TargetSubresourceFetchPauseNetworkOutput,
) -> Vec<BackgroundProtocolEvent> {
- let resource_type = output.resource_type().as_cdp_type();
+ let resource_type = output.resource_type().into();
let event = NetworkRequestEvent {
target_id: DevToolsTargetId::from(output.frame_id()),
frame_id: Some(DevToolsFrameId::from(output.frame_id())),
@@ -382,7 +382,7 @@ pub(crate) fn fetch_subresource_initial_request_network_events(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: output.request_cookie_report().cloned(),
- resource_type: Some(resource_type.to_owned()),
+ resource_type: Some(resource_type),
timestamp: Some(output.timestamp()),
wall_time: Some(output.timestamp()),
status: None,
@@ -467,7 +467,7 @@ pub(crate) fn emit_response_received(
from_cache: bool,
negotiated_http_version: Option<moli_fetch::NegotiatedHttpVersion>,
network_extra_info_available: bool,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
blocked_intercepts: &[DevToolsNetworkInterceptId],
fetch_request_id: Option<&str>,
) {
@@ -510,7 +510,7 @@ pub(crate) fn emit_response_received_without_extra_info_event(
from_cache: bool,
negotiated_http_version: Option<moli_fetch::NegotiatedHttpVersion>,
network_extra_info_available: bool,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
) {
emit_response_received_with_extra_info_delivery(
out,
@@ -553,7 +553,7 @@ fn emit_response_received_with_extra_info_delivery(
negotiated_http_version: Option<moli_fetch::NegotiatedHttpVersion>,
network_extra_info_available: bool,
emit_extra_info_event: bool,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
blocked_intercepts: &[DevToolsNetworkInterceptId],
fetch_request_id: Option<&str>,
) {
@@ -578,7 +578,7 @@ fn emit_response_received_with_extra_info_delivery(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some(resource_type.to_owned()),
+ resource_type: Some(resource_type),
timestamp: Some(timestamp),
wall_time: None,
status: Some(status),
@@ -620,7 +620,7 @@ pub(crate) fn emit_body_finished(
loader_id: &str,
timestamp: f64,
encoded_data_length: usize,
- resource_type: Option<&str>,
+ resource_type: DevToolsNetworkResourceType,
) {
emit_data_received(
out,
@@ -650,7 +650,7 @@ pub(crate) fn emit_loading_finished(
loader_id: &str,
timestamp: f64,
encoded_data_length: usize,
- resource_type: Option<&str>,
+ resource_type: DevToolsNetworkResourceType,
) {
emit_cdp_network_automation_event(
out,
@@ -669,7 +669,7 @@ pub(crate) fn emit_loading_finished(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: resource_type.map(str::to_owned),
+ resource_type: Some(resource_type),
timestamp: Some(timestamp),
wall_time: None,
status: None,
@@ -757,7 +757,7 @@ pub(crate) fn emit_loading_failed(
loader_id: &str,
timestamp: f64,
error_text: &str,
- resource_type: &str,
+ resource_type: DevToolsNetworkResourceType,
) {
emit_cdp_network_automation_event(
out,
@@ -776,7 +776,7 @@ pub(crate) fn emit_loading_failed(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some(resource_type.to_owned()),
+ resource_type: Some(resource_type),
timestamp: Some(timestamp),
wall_time: None,
status: None,
@@ -828,7 +828,10 @@ pub(crate) fn emit_cdp_network_automation_event(
"requestId": network_event.request_id.as_str(),
"loaderId": network_event.loader_id.as_ref().map(|id| id.as_str()).unwrap_or(""),
"timestamp": network_event.timestamp.unwrap_or_default(),
- "type": network_event.resource_type.as_deref().unwrap_or_default(),
+ "type": network_event
+ .resource_type
+ .map(DevToolsNetworkResourceType::as_cdp_type)
+ .unwrap_or_default(),
"frameId": network_event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or(""),
"response": {
"url": network_event.url.as_str(),
@@ -877,7 +880,10 @@ pub(crate) fn emit_cdp_network_automation_event(
let params = json!({
"requestId": network_event.request_id.as_str(),
"timestamp": network_event.timestamp.unwrap_or_default(),
- "type": network_event.resource_type.as_deref().unwrap_or_default(),
+ "type": network_event
+ .resource_type
+ .map(DevToolsNetworkResourceType::as_cdp_type)
+ .unwrap_or_default(),
"errorText": network_event.error_text.as_deref().unwrap_or_default(),
"canceled": network_event.loading_failed_canceled,
});
@@ -941,7 +947,10 @@ fn emit_network_before_request_sent(
.unwrap_or("other")
},
"redirectHasExtraInfo": network_event.redirect_has_extra_info,
- "type": network_event.resource_type.as_deref().unwrap_or_default(),
+ "type": network_event
+ .resource_type
+ .map(DevToolsNetworkResourceType::as_cdp_type)
+ .unwrap_or_default(),
"frameId": network_event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or(""),
"hasUserGesture": false,
});
@@ -973,7 +982,10 @@ pub fn fetch_auth_required_params(network_event: &NetworkRequestEvent) -> Value
"requestId": network_event.request_id.as_str(),
"frameId": network_event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or(""),
"request": fetch_request_payload(network_event),
- "resourceType": network_event.resource_type.as_deref().unwrap_or_default(),
+ "resourceType": network_event
+ .resource_type
+ .map(DevToolsNetworkResourceType::as_cdp_type)
+ .unwrap_or_default(),
"authChallenge": fetch_auth_challenge_payload(network_event),
})
}
@@ -983,7 +995,10 @@ pub fn fetch_request_paused_params(network_event: &NetworkRequestEvent) -> Value
"requestId": network_event.request_id.as_str(),
"frameId": network_event.frame_id.as_ref().map(|id| id.as_str()).unwrap_or(""),
"request": fetch_request_payload(network_event),
- "resourceType": network_event.resource_type.as_deref().unwrap_or_default(),
+ "resourceType": network_event
+ .resource_type
+ .map(DevToolsNetworkResourceType::as_cdp_type)
+ .unwrap_or_default(),
});
if let Some(network_id) = network_event.network_id.as_ref() {
params["networkId"] = json!(network_id.as_str());
@@ -1280,7 +1295,7 @@ mod tests {
use crate::devtools_runtime::{
AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsNetworkInterceptId,
- DevToolsRequestId, DevToolsTargetId, NetworkRequestEvent,
+ DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId, NetworkRequestEvent,
};
use crate::domains::network::TargetSubresourceFetchPauseNetworkOutput;
@@ -1382,7 +1397,7 @@ mod tests {
if event.request_id.as_str() == "REQ-42"
&& event.method.as_deref() == Some("POST")
&& event.request_body.as_deref() == Some("body")
- && event.resource_type.as_deref() == Some("Fetch")
+ && event.resource_type == Some(DevToolsNetworkResourceType::Fetch)
&& event.fetch_request_id.is_none()
));
}
@@ -1410,7 +1425,7 @@ mod tests {
false,
Some(moli_fetch::NegotiatedHttpVersion::Http2),
false,
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
&[],
None,
);
@@ -1463,7 +1478,7 @@ mod tests {
true,
None,
false,
- "Script",
+ DevToolsNetworkResourceType::Script,
&[],
None,
);
@@ -1509,7 +1524,7 @@ mod tests {
"GET",
None,
&[],
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
SubresourceRequestInitiatorType::Script,
Some((
&redirect_url,
@@ -1572,7 +1587,7 @@ mod tests {
false,
None,
false,
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
&[],
None,
);
@@ -1604,7 +1619,7 @@ mod tests {
false,
None,
false,
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
&[DevToolsNetworkInterceptId::from("intercept-response")],
Some("FETCH-42"),
);
@@ -1653,7 +1668,7 @@ mod tests {
"LOADER-1",
44.0,
256,
- None,
+ DevToolsNetworkResourceType::Xhr,
);
assert!(events[0].clone().into_parts().1.is_none());
assert!(matches!(
@@ -1661,6 +1676,7 @@ mod tests {
Some(AutomationEvent::NetworkResponseCompleted(network_event))
if network_event.request_id == DevToolsRequestId::from("REQ-42")
&& network_event.encoded_data_length == Some(256)
+ && network_event.resource_type == Some(DevToolsNetworkResourceType::Xhr)
));
let out = protocol_messages_from_background_events(events);
@@ -1700,7 +1716,7 @@ mod tests {
"LOADER-1",
44.0,
0,
- None,
+ DevToolsNetworkResourceType::Xhr,
);
let out = protocol_messages_from_background_events(events);
@@ -1721,7 +1737,7 @@ mod tests {
"LOADER-1",
45.0,
"net::ERR_FAILED",
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
);
assert!(matches!(
events[0].clone().into_parts().1,
@@ -1758,7 +1774,7 @@ mod tests {
"LOADER-1",
45.0,
NET_ERR_ABORTED_ERROR_TEXT,
- "Fetch",
+ DevToolsNetworkResourceType::Fetch,
);
let out = protocol_messages_from_background_events(events);
@@ -1789,7 +1805,7 @@ mod tests {
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Fetch".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Fetch),
timestamp: Some(45.0),
wall_time: None,
status: None,
diff --git a/moli-protocol/src/domains/network/main_document_progress/emit.rs b/moli-protocol/src/domains/network/main_document_progress/emit.rs
index 65bcd6916..43d8bac88 100644
--- a/moli-protocol/src/domains/network/main_document_progress/emit.rs
+++ b/moli-protocol/src/domains/network/main_document_progress/emit.rs
@@ -1,6 +1,6 @@
use crate::devtools_runtime::{
- AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsRequestId, DevToolsTargetId,
- NetworkRedirectResponseEvent, NetworkRequestEvent,
+ AutomationEvent, DevToolsFrameId, DevToolsLoaderId, DevToolsNetworkResourceType,
+ DevToolsRequestId, DevToolsTargetId, NetworkRedirectResponseEvent, NetworkRequestEvent,
};
use moli_cookie_jar::{StoredCookieQueryReport, StoredCookieSetReport};
use moli_core::page::{
@@ -207,7 +207,7 @@ pub(super) fn emit_main_document_request_will_be_sent(
),
redirect_has_extra_info,
request_cookie_report: cookie_access_report.cloned(),
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: Some(timestamp),
wall_time: Some(timestamp),
status: None,
@@ -319,7 +319,7 @@ pub(super) fn emit_main_document_response_received(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: Some(timestamp),
wall_time: None,
status: Some(status),
@@ -360,7 +360,7 @@ pub(super) fn emit_body_finished(
loader_id,
timestamp,
encoded_data_length,
- Some("Document"),
+ DevToolsNetworkResourceType::Document,
);
}
@@ -390,7 +390,7 @@ pub(super) fn emit_loading_failed(
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some("Document".to_owned()),
+ resource_type: Some(DevToolsNetworkResourceType::Document),
timestamp: Some(timestamp),
wall_time: None,
status: None,
diff --git a/moli-protocol/src/domains/network/main_document_progress/tests.rs b/moli-protocol/src/domains/network/main_document_progress/tests.rs
index 6974be8fc..961415fb4 100644
--- a/moli-protocol/src/domains/network/main_document_progress/tests.rs
+++ b/moli-protocol/src/domains/network/main_document_progress/tests.rs
@@ -1,4 +1,4 @@
-use crate::devtools_runtime::AutomationEvent;
+use crate::devtools_runtime::{AutomationEvent, DevToolsNetworkResourceType};
use moli_cookie_jar::{
StoredCookieQueryReport, StoredCookieSetRejectionReason, StoredCookieSetStatus,
};
@@ -1398,7 +1398,7 @@ fn failed_navigation_progress_drain_prequeues_loading_failed() {
failed_sidecar,
Some(AutomationEvent::NetworkFetchError(event))
if event.request_id.as_str() == "REQ-1"
- && event.resource_type.as_deref() == Some("Document")
+ && event.resource_type == Some(DevToolsNetworkResourceType::Document)
&& event.error_text.as_deref() == Some("net::ERR_FAILED")
));
assert_eq!(failed["method"], json!("Network.loadingFailed"));
diff --git a/moli-protocol/src/domains/page.rs b/moli-protocol/src/domains/page.rs
index 509e147a3..529561e82 100644
--- a/moli-protocol/src/domains/page.rs
+++ b/moli-protocol/src/domains/page.rs
@@ -15,7 +15,6 @@ use chromiumoxide_cdp::cdp::browser_protocol::page::{
PrintToPdfTransferMode, SetBypassCspParams, SetDocumentContentParams,
SetInterceptFileChooserDialogParams, SetLifecycleEventsEnabledParams as LifecycleParams,
};
-use moli_core::RendererRuntimeCommandCausalIdentity;
use moli_core::page::{
ChildFrameDocumentNetworkActivitySnapshot, ChildFrameDocumentOpenedSnapshot,
ChildFrameNavigationSnapshot, ChildFrameTreeEventSnapshot, ChildFrameTreeSnapshot,
@@ -29,6 +28,7 @@ use moli_core::page::{
RendererScreenshotClip, RendererScreenshotFormat, RendererScreenshotPurpose,
RendererScreenshotRegion, RendererSetDocumentContentResult,
};
+use moli_core::{RendererDocumentTitleChanged, RendererRuntimeCommandCausalIdentity};
use serde::Deserialize;
use serde_json::{Value, json};
use std::time::{SystemTime, UNIX_EPOCH};
@@ -470,6 +470,7 @@ enum PageOutputProjectionStep {
JavascriptDialog,
WindowOpen,
Popup,
+ DocumentTitleChanged,
DocumentLifecycle,
ChildFrameActivity,
SameDocumentNavigation,
@@ -482,6 +483,7 @@ pub(crate) struct PagePreparedOutputs {
javascript_dialogs: Vec<javascript_dialog::PreparedJavaScriptDialog>,
window_open_events: Vec<popup::PagePreparedWindowOpenEvent>,
popup_activations: Vec<popup::PagePreparedPopupActivation>,
+ document_title_changes: Vec<RendererDocumentTitleChanged>,
document_lifecycle_events: Vec<RendererDocumentLifecycleEvent>,
child_frame_activities: Vec<PagePreparedChildFrameActivity>,
same_document_navigations: Vec<PagePreparedSameDocumentNavigation>,
@@ -770,10 +772,21 @@ impl PagePreparedOutputs {
}
}
+ pub(crate) fn from_renderer_document_title_change(
+ change: RendererDocumentTitleChanged,
+ ) -> Self {
+ Self {
+ document_title_changes: vec![change],
+ ..Default::default()
+ }
+ }
+
pub(crate) fn extend(&mut self, other: Self) {
self.javascript_dialogs.extend(other.javascript_dialogs);
self.window_open_events.extend(other.window_open_events);
self.popup_activations.extend(other.popup_activations);
+ self.document_title_changes
+ .extend(other.document_title_changes);
self.document_lifecycle_events
.extend(other.document_lifecycle_events);
for activity in other.child_frame_activities {
@@ -829,6 +842,16 @@ impl PagePreparedOutputs {
}
}
+ pub(in crate::domains) fn append_to_document_title_output_sink(
+ self,
+ sink: &mut (impl ProtocolOutputSink + ?Sized),
+ ) {
+ if !self.document_title_changes.is_empty() {
+ sink.push_produced_slot(SLOT_DOCUMENT_TITLE_CHANGED);
+ sink.push_prepared_payload(PagePreparedOutputSlot::from_outputs(self).into());
+ }
+ }
+
pub(in crate::domains) fn append_to_child_frame_output_sink(
self,
sink: &mut (impl ProtocolOutputSink + ?Sized),
@@ -892,6 +915,7 @@ impl PagePreparedOutputs {
.collect(),
window_open_events: Vec::new(),
popup_activations: Vec::new(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: Vec::new(),
same_document_navigations: Vec::new(),
@@ -917,6 +941,7 @@ impl PagePreparedOutputs {
)
})
.collect(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: Vec::new(),
same_document_navigations: Vec::new(),
@@ -963,6 +988,7 @@ impl PagePreparedOutputs {
javascript_dialogs: Vec::new(),
window_open_events: Vec::new(),
popup_activations: Vec::new(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: vec![activity],
same_document_navigations: Vec::new(),
@@ -980,6 +1006,7 @@ impl PagePreparedOutputs {
javascript_dialogs: Vec::new(),
window_open_events: Vec::new(),
popup_activations: Vec::new(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: Vec::new(),
same_document_navigations: navigations
@@ -1002,6 +1029,7 @@ impl PagePreparedOutputs {
javascript_dialogs: Vec::new(),
window_open_events: Vec::new(),
popup_activations: Vec::new(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: Vec::new(),
same_document_navigations: Vec::new(),
@@ -1049,6 +1077,11 @@ impl PagePreparedOutputSlot {
.then(|| std::mem::take(&mut self.outputs.document_lifecycle_events))
}
+ fn take_document_title_changes(&mut self) -> Option<Vec<RendererDocumentTitleChanged>> {
+ (!self.outputs.document_title_changes.is_empty())
+ .then(|| std::mem::take(&mut self.outputs.document_title_changes))
+ }
+
pub(crate) fn take_child_frame_activity(
&mut self,
) -> Option<Vec<PagePreparedChildFrameActivity>> {
@@ -1117,6 +1150,8 @@ pub(in crate::domains) const SLOT_WINDOW_OPEN: ProtocolOutputSlot = ProtocolOutp
pub(in crate::domains) const SLOT_POPUP: ProtocolOutputSlot = ProtocolOutputSlot::Popup;
pub(in crate::domains) const SLOT_DOCUMENT_LIFECYCLE: ProtocolOutputSlot =
ProtocolOutputSlot::DocumentLifecycle;
+pub(in crate::domains) const SLOT_DOCUMENT_TITLE_CHANGED: ProtocolOutputSlot =
+ ProtocolOutputSlot::DocumentTitleChanged;
pub(in crate::domains) const SLOT_CHILD_FRAME_ACTIVITY: ProtocolOutputSlot =
ProtocolOutputSlot::ChildFrameActivity;
@@ -1174,6 +1209,30 @@ impl PageOutputProjectionStep {
}
}
}
+ PageOutputProjectionStep::DocumentTitleChanged => {
+ if let Some(changes) = prepared_outputs
+ .and_then(ProtocolOutputPayloads::page_mut)
+ .and_then(PagePreparedOutputSlot::take_document_title_changes)
+ {
+ let mut events = Vec::new();
+ for change in changes {
+ if conn
+ .apply_renderer_document_title_for_session_owner(
+ context.session_id,
+ &change,
+ )
+ .unwrap_or(false)
+ {
+ crate::domains::target::emit_target_info_changed_for_session_owner_background_event(
+ conn,
+ &mut events,
+ context.session_id,
+ );
+ }
+ }
+ context.command.protocol_events_mut().extend(events);
+ }
+ }
PageOutputProjectionStep::FileChooser => {
let mut events = Vec::new();
input::emit_file_chooser_activity_background_events_async(
@@ -1277,6 +1336,7 @@ pub(in crate::domains) async fn project_page_output_async(
ProtocolOutputSlot::JavascriptDialog => PageOutputProjectionStep::JavascriptDialog,
ProtocolOutputSlot::WindowOpen => PageOutputProjectionStep::WindowOpen,
ProtocolOutputSlot::Popup => PageOutputProjectionStep::Popup,
+ ProtocolOutputSlot::DocumentTitleChanged => PageOutputProjectionStep::DocumentTitleChanged,
ProtocolOutputSlot::DocumentLifecycle => PageOutputProjectionStep::DocumentLifecycle,
ProtocolOutputSlot::ChildFrameActivity => PageOutputProjectionStep::ChildFrameActivity,
ProtocolOutputSlot::SameDocumentNavigation => {
@@ -2371,6 +2431,7 @@ pub(in crate::domains) async fn emit_same_document_navigation_activity_backgroun
#[cfg(test)]
mod producer_tests {
+ use moli_core::RendererDocumentTitleChanged;
use moli_core::page::{
ChildFrameDocumentNetworkActivitySnapshot, ChildFrameDocumentNetworkSnapshot,
ChildFrameNavigationSnapshot, RENDERER_BACKEND_NODE_ID_START,
@@ -2582,6 +2643,70 @@ mod producer_tests {
.collect()
}
+ #[test]
+ fn stale_document_title_cannot_overwrite_replacement_target_metadata() {
+ let mut conn = CdpConnection::default();
+ let mut bc = BrowserContext::new("BID-title-source".into());
+ bc.set_active_target_id("TID-title-source");
+ bc.attach_active_session("SID-title-source");
+ conn.browser_context = Some(bc);
+
+ let predecessor = renderer_document_identity_for_test(1, 1);
+ bind_renderer_document_for_test(
+ &mut conn,
+ "SID-title-source",
+ "TID-title-source",
+ predecessor,
+ );
+ assert_eq!(
+ conn.apply_renderer_document_title_for_session_owner(
+ Some("SID-title-source"),
+ &RendererDocumentTitleChanged {
+ source_document: predecessor,
+ title: "predecessor".to_owned(),
+ },
+ ),
+ Some(true)
+ );
+
+ let replacement = renderer_document_identity_for_test(2, 2);
+ bind_renderer_document_for_test(
+ &mut conn,
+ "SID-title-source",
+ "TID-title-source",
+ replacement,
+ );
+ assert_eq!(
+ conn.apply_renderer_document_title_for_session_owner(
+ Some("SID-title-source"),
+ &RendererDocumentTitleChanged {
+ source_document: replacement,
+ title: "replacement".to_owned(),
+ },
+ ),
+ Some(true)
+ );
+
+ assert_eq!(
+ conn.apply_renderer_document_title_for_session_owner(
+ Some("SID-title-source"),
+ &RendererDocumentTitleChanged {
+ source_document: predecessor,
+ title: "late predecessor".to_owned(),
+ },
+ ),
+ None,
+ "an old renderer Document must lose authority at replacement commit"
+ );
+ assert_eq!(
+ conn.browser_context
+ .as_ref()
+ .and_then(|context| context.target_info("TID-title-source"))
+ .and_then(|target| target["title"].as_str().map(str::to_owned)),
+ Some("replacement".to_owned())
+ );
+ }
+
#[tokio::test(flavor = "multi_thread")]
async fn javascript_dialog_drain_consumes_prepared_dialogs_without_page_readback() {
let mut conn = CdpConnection::default();
@@ -4243,6 +4368,7 @@ mod producer_tests {
javascript_dialogs: Vec::new(),
window_open_events: Vec::new(),
popup_activations: Vec::new(),
+ document_title_changes: Vec::new(),
document_lifecycle_events: Vec::new(),
child_frame_activities: vec![super::PagePreparedChildFrameActivity::from_document(
root_document_attachment_for_test(&conn, "SID-1", source_document),
diff --git a/moli-protocol/src/domains/page/lifecycle.rs b/moli-protocol/src/domains/page/lifecycle.rs
index bbb7617b8..ee86834cb 100644
--- a/moli-protocol/src/domains/page/lifecycle.rs
+++ b/moli-protocol/src/domains/page/lifecycle.rs
@@ -177,7 +177,7 @@ fn emit_renderer_navigation_domcontentloaded_background_events(
}
pub(crate) fn emit_bound_renderer_document_lifecycle_background_events(
- conn: &CdpConnection,
+ conn: &mut CdpConnection,
out: &mut Vec<BackgroundProtocolEvent>,
owner_session_id: Option<&str>,
binding: &CommittedRendererDocumentBinding,
diff --git a/moli-protocol/src/domains/page/navigation.rs b/moli-protocol/src/domains/page/navigation.rs
index 4bff10a64..a16841ef1 100644
--- a/moli-protocol/src/domains/page/navigation.rs
+++ b/moli-protocol/src/domains/page/navigation.rs
@@ -3031,6 +3031,7 @@ fn start_navigate_to_url_command_with_background_policy_and_request(
body_progress_source,
early_result,
);
+ let cancellation = job.cancellation();
let none_session_owner_route = completion_state
.navigate_session_id
.is_none()
@@ -3039,6 +3040,7 @@ fn start_navigate_to_url_command_with_background_policy_and_request(
conn.record_background_navigation_started_scheduler_event(
&document_navigation_token,
&completion_state,
+ cancellation,
);
tokio::task::spawn_local(async move {
let body_completion_sink = crate::conn::BackgroundNavigationBodyCompletionSink::new(
diff --git a/moli-protocol/src/domains/page/navigation_commit.rs b/moli-protocol/src/domains/page/navigation_commit.rs
index 2a71f254b..8c8f56269 100644
--- a/moli-protocol/src/domains/page/navigation_commit.rs
+++ b/moli-protocol/src/domains/page/navigation_commit.rs
@@ -488,6 +488,11 @@ async fn restore_and_commit_loaded_navigation_page_async(
.await;
out.extend_background_events_after_messages(worker_retirement_events);
}
+ if let Some(continuation) = page_commit.committed_document_post_response_continuation {
+ command_context
+ .response_flush()
+ .defer_until_response_flush(move || continuation.release());
+ }
let _ = conn.commit_loaded_navigation_target_identity_for_session_owner(
state.navigate_session_id.as_deref(),
main_document_commit,
diff --git a/moli-protocol/src/domains/page/tests/capture.rs b/moli-protocol/src/domains/page/tests/capture.rs
index ccb5a5e27..f190a954a 100644
--- a/moli-protocol/src/domains/page/tests/capture.rs
+++ b/moli-protocol/src/domains/page/tests/capture.rs
@@ -135,10 +135,10 @@ async fn capture_screenshot_uses_pending_renderer_page_command_residence() {
else {
panic!("captureScreenshot should complete after one renderer page command");
};
- assert!(
- command_context.take_renderer_output_predecessor().is_none(),
- "a screenshot turn that publishes no renderer event needs no concrete output fence"
- );
+ if let Some(predecessor) = command_context.take_renderer_output_predecessor() {
+ ctx.route_direct_command_renderer_predecessor_for_test(predecessor)
+ .await;
+ }
let mut out = Vec::new();
plan.emit_into(&mut out, cmd.id, cmd.session_id);
@@ -487,38 +487,45 @@ async fn capture_screenshot_uses_emulated_device_metrics() {
#[tokio::test(flavor = "multi_thread")]
async fn capture_screenshot_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<title>Background Screenshot</title><main>background</main>",
- )
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-screenshot-background".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
- bc.replace_parked_page_session_state(
- "TID-background".to_owned(),
- crate::conn::ParkedPageSessionState {
- emulated_device_metrics: Some(EmulatedDeviceMetrics {
- width: 320,
- height: 240,
- device_scale_factor: 2.0,
- screen_width: 320,
- screen_height: 240,
- }),
- ..Default::default()
- },
- );
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<title>Background Screenshot</title><main>background</main>",
+ Some("SID-background"),
+ )
+ .await;
+ ctx.wait_for_scheduler_message("background screenshot fixture load", |message| {
+ message["method"] == json!("Page.loadEventFired")
+ && message["sessionId"] == json!("SID-background")
+ })
+ .await;
+ ctx.sent.clear();
+ ctx.conn
+ .browser_context
+ .as_mut()
+ .expect("browser context")
+ .replace_parked_page_session_state(
+ "TID-background".to_owned(),
+ crate::conn::ParkedPageSessionState {
+ emulated_device_metrics: Some(EmulatedDeviceMetrics {
+ width: 320,
+ height: 240,
+ device_scale_factor: 2.0,
+ screen_width: 320,
+ screen_height: 240,
+ }),
+ ..Default::default()
+ },
+ );
ctx.process_async(json!({
"id": 114,
@@ -761,18 +768,14 @@ async fn install_active_screenshot_page(
url: &str,
) {
load_bc_with_session(ctx, browser_context_id, target_id, session_id, url);
- let page = ctx
- .conn
- .load_page_via_runtime_async(url)
- .await
- .expect("screenshot page should load");
- ctx.conn
- .browser_context
- .as_mut()
- .expect("browser context")
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
+ ctx.install_navigation_fixture_for_session_owner(url, Some(session_id))
+ .await;
+ ctx.wait_for_scheduler_message("screenshot fixture load", |message| {
+ message["method"] == json!("Page.loadEventFired")
+ && message["sessionId"] == json!(session_id)
+ })
+ .await;
+ ctx.sent.clear();
}
async fn set_screenshot_viewport(
@@ -949,17 +952,11 @@ async fn get_layout_metrics_queries_live_renderer_for_loaded_pages() {
async fn get_layout_metrics_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<html style='width:2300px;height:1700px'><body style='margin:0;width:2300px;height:1700px'><div style='width:2300px;height:1700px'></div></body></html>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(page_url)
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
@@ -967,6 +964,9 @@ async fn get_layout_metrics_targets_loaded_background_owner_without_promotion()
bc.set_target_url("data:text/html,<body>active</body>".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-background"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 121,
@@ -1011,20 +1011,14 @@ async fn get_layout_metrics_targets_loaded_background_owner_without_promotion()
async fn get_layout_metrics_targets_inactive_loaded_owner_without_activation() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<html style='width:2100px;height:1600px'><body style='margin:0;width:2100px;height:1600px'><div style='width:2100px;height:1600px'></div></body></html>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(page_url)
- .await
- .expect("inactive page should load");
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
- inactive
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
+ inactive.set_target_url("about:blank".to_owned());
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-inactive"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 121,
diff --git a/moli-protocol/src/domains/page/tests/frame_tree.rs b/moli-protocol/src/domains/page/tests/frame_tree.rs
index 4a8744615..38873f95e 100644
--- a/moli-protocol/src/domains/page/tests/frame_tree.rs
+++ b/moli-protocol/src/domains/page/tests/frame_tree.rs
@@ -553,17 +553,11 @@ async fn pending_get_frame_tree_after_page_unload_returns_empty_target_tree() {
async fn get_frame_tree_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<iframe name='background-child'></iframe>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(page_url)
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
@@ -571,6 +565,9 @@ async fn get_frame_tree_targets_loaded_background_owner_without_promotion() {
bc.set_target_url("data:text/html,<body>active</body>".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-background"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1202,
@@ -604,20 +601,14 @@ async fn get_frame_tree_targets_loaded_background_owner_without_promotion() {
async fn get_frame_tree_targets_inactive_loaded_owner_without_activation() {
let mut ctx = TestContext::new();
let page_url = "data:text/html,<iframe name='inactive-child'></iframe>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(page_url)
- .await
- .expect("inactive page should load");
let mut inactive = BrowserContext::new("BID-inactive".to_owned());
inactive.set_active_target_id("TID-inactive".to_owned());
inactive.attach_active_session("SID-inactive".to_owned());
- inactive.set_target_url(page.final_url().as_str().to_owned());
- inactive
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
+ inactive.set_target_url("about:blank".to_owned());
ctx.conn.inactive_browser_contexts.push(inactive);
+ ctx.install_navigation_fixture_for_session_owner(page_url, Some("SID-inactive"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1203,
diff --git a/moli-protocol/src/domains/page/tests/lifecycle.rs b/moli-protocol/src/domains/page/tests/lifecycle.rs
index feee44d1a..0589773b5 100644
--- a/moli-protocol/src/domains/page/tests/lifecycle.rs
+++ b/moli-protocol/src/domains/page/tests/lifecycle.rs
@@ -2097,17 +2097,12 @@ async fn add_script_run_immediately_creates_top_level_world_even_when_child_worl
async fn add_script_run_immediately_installs_matching_bindings_into_new_top_level_world() {
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
- let page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<body>parent-frame<iframe srcdoc=\"<body>child-frame</body>\"></iframe></body>",
- ).await
- .expect("page should load");
- let bc = ctx.conn.browser_context.as_mut().expect("browser context");
- let _ = bc
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(page));
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body>parent-frame<iframe srcdoc=\"<body>child-frame</body>\"></iframe></body>",
+ Some("SID-1"),
+ )
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 4160,
"method": "Runtime.enable",
@@ -2207,29 +2202,32 @@ async fn add_script_run_immediately_installs_matching_bindings_into_new_top_leve
#[tokio::test(flavor = "multi_thread")]
async fn document_start_script_run_immediately_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
- let page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<body>background</body>")
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
- bc.mutate_parked_page_session_state("TID-background", |state| {
- state
- .devtools_session_state
- .runtime_session_state
- .runtime_frontend_enabled = true;
- });
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<body>background</body>",
+ Some("SID-background"),
+ )
+ .await;
+ ctx.conn
+ .browser_context
+ .as_mut()
+ .expect("browser context")
+ .mutate_parked_page_session_state("TID-background", |state| {
+ state
+ .devtools_session_state
+ .runtime_session_state
+ .runtime_frontend_enabled = true;
+ });
ctx.sent.clear();
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/page/tests/navigation.rs b/moli-protocol/src/domains/page/tests/navigation.rs
index 4bfc77f15..462c1efff 100644
--- a/moli-protocol/src/domains/page/tests/navigation.rs
+++ b/moli-protocol/src/domains/page/tests/navigation.rs
@@ -372,6 +372,13 @@ async fn navigation_history_supports_playwright_back_forward_commands() {
}))
.await;
take_response_by_id(&mut ctx, 1);
+ wait_until_message(
+ &mut ctx,
+ Some("SID-1"),
+ "first history document DOMContentLoaded",
+ |message| message["method"] == json!("Page.domContentEventFired"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
@@ -382,6 +389,13 @@ async fn navigation_history_supports_playwright_back_forward_commands() {
}))
.await;
take_response_by_id(&mut ctx, 2);
+ wait_until_message(
+ &mut ctx,
+ Some("SID-1"),
+ "second history document DOMContentLoaded",
+ |message| message["method"] == json!("Page.domContentEventFired"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
@@ -1278,17 +1292,11 @@ async fn navigation_history_is_preserved_per_parked_target() {
async fn get_navigation_history_targets_loaded_background_owner_without_promotion() {
let mut ctx = TestContext::new();
let background_url = "data:text/html,<title>Background History</title><main>background</main>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(background_url)
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-1".to_owned());
bc.set_active_target_id("TID-active".to_owned());
@@ -1296,6 +1304,9 @@ async fn get_navigation_history_targets_loaded_background_owner_without_promotio
bc.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(background_url, Some("SID-background"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 15,
@@ -1326,17 +1337,11 @@ async fn reset_navigation_history_targets_loaded_background_owner_without_promot
let mut ctx = TestContext::new();
let background_url =
"data:text/html,<title>Background Reset History</title><main>background</main>";
- let page = ctx
- .conn
- .load_page_via_runtime_async(background_url)
- .await
- .expect("background page should load");
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background-reset".to_owned(),
Some("SID-background-reset".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut browser_context = BrowserContext::new("BID-reset-background".to_owned());
browser_context.set_active_target_id("TID-active".to_owned());
@@ -1345,6 +1350,9 @@ async fn reset_navigation_history_targets_loaded_background_owner_without_promot
.set_target_url("data:text/html,<title>Active</title><main>active</main>".to_owned());
browser_context.background_targets.push(background);
ctx.conn.browser_context = Some(browser_context);
+ ctx.install_navigation_fixture_for_session_owner(background_url, Some("SID-background-reset"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 1215,
@@ -2752,8 +2760,22 @@ async fn navigate_after_target_discovery_emits_target_info_changed() {
}))
.await;
+ wait_until_message(
+ &mut ctx,
+ None,
+ "parsed document title targetInfoChanged",
+ |message| {
+ message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"]
+ == json!("TID-target-info-navigation")
+ && message["params"]["targetInfo"]["title"] == json!("Target Info Title")
+ },
+ )
+ .await;
let changed = ctx.take_first_matching("Target.targetInfoChanged", |message| {
message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!("TID-target-info-navigation")
+ && message["params"]["targetInfo"]["title"] == json!("Target Info Title")
});
assert_eq!(
changed["params"]["targetInfo"]["targetId"],
@@ -2838,6 +2860,16 @@ async fn runtime_removing_child_iframe_emits_frame_detached_and_forgets_owner_st
}))
.await;
let _ = take_response_by_id(&mut ctx, 5242);
+ wait_until_message(
+ &mut ctx,
+ "SID-1",
+ "removable child frame attachment after Page.navigate response",
+ |message| {
+ message["method"] == json!("Page.frameAttached")
+ && message["params"]["parentFrameId"] == json!("TID-1")
+ },
+ )
+ .await;
let child_frame_id = ctx
.sent
.iter()
@@ -6577,7 +6609,7 @@ async fn parser_script_location_navigation_suppresses_aborted_document_dcl() {
}
#[tokio::test(flavor = "multi_thread")]
-async fn parser_script_location_navigation_suppression_is_independent_of_target_response() {
+async fn parser_script_location_navigation_continues_after_target_response() {
async fn challenge() -> impl axum::response::IntoResponse {
(
[(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],
@@ -6617,13 +6649,19 @@ async fn parser_script_location_navigation_suppression_is_independent_of_target_
let mut ctx = TestContext::new();
load_bc_with_session(&mut ctx, "BID-1", "TID-1", "SID-1", "about:blank");
- let navigation = ctx.process_async(json!({
+ ctx.process_async(json!({
"id": 252,
"method": "Page.navigate",
"sessionId": "SID-1",
"params": { "url": format!("http://{addr}/challenge") }
- }));
- let release_response = async {
+ }))
+ .await;
+ let _ = take_response_by_id(&mut ctx, 252);
+
+ // Chromium returns Page.navigate once the new document commits. Parser
+ // continuation (and therefore this script navigation) is admitted only
+ // after that response boundary has been flushed.
+ let release_response = tokio::spawn(async move {
tokio::time::timeout(
std::time::Duration::from_secs(5),
final_requested.notified(),
@@ -6631,9 +6669,7 @@ async fn parser_script_location_navigation_suppression_is_independent_of_target_
.await
.expect("successor navigation should request the gated final response");
final_release.notify_one();
- };
- let ((), ()) = tokio::join!(navigation, release_response);
- let _ = take_response_by_id(&mut ctx, 252);
+ });
wait_until_messages(
&mut ctx,
Some("SID-1"),
@@ -6650,6 +6686,9 @@ async fn parser_script_location_navigation_suppression_is_independent_of_target_
},
)
.await;
+ release_response
+ .await
+ .expect("gated final-response release task");
let events = ctx.take_all();
assert_eq!(
diff --git a/moli-protocol/src/domains/runtime/tests/console.rs b/moli-protocol/src/domains/runtime/tests/console.rs
index ae4aa0e3e..66adf35f3 100644
--- a/moli-protocol/src/domains/runtime/tests/console.rs
+++ b/moli-protocol/src/domains/runtime/tests/console.rs
@@ -53,37 +53,27 @@ async fn runtime_discard_console_entries_suppresses_buffered_runtime_events() {
#[tokio::test(flavor = "multi_thread")]
async fn runtime_discard_console_entries_is_page_target_local() {
let mut ctx = TestContext::new();
- let active_page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<script>console.log('active-discard-peer')</script>",
- )
- .await
- .expect("active page should load");
- let background_page = ctx
- .conn
- .load_page_via_runtime_async(
- "data:text/html,<script>console.log('background-discard-owner')</script>",
- )
- .await
- .expect("background page should load");
- let background_url = background_page.final_url().as_str().to_owned();
- let mut background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- background_url,
+ "about:blank".to_owned(),
);
- background_target.replace_loaded_page(Some(background_page));
let mut browser_context = BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active");
browser_context.attach_active_session("SID-active");
- browser_context
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(active_page));
browser_context.background_targets.push(background_target);
ctx.conn.browser_context = Some(browser_context);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<script>console.log('active-discard-peer')</script>",
+ Some("SID-active"),
+ )
+ .await;
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<script>console.log('background-discard-owner')</script>",
+ Some("SID-background"),
+ )
+ .await;
ctx.sent.clear();
ctx.process_async(json!({
diff --git a/moli-protocol/src/domains/runtime/tests/evaluate.rs b/moli-protocol/src/domains/runtime/tests/evaluate.rs
index ffbecf807..2ef76ab02 100644
--- a/moli-protocol/src/domains/runtime/tests/evaluate.rs
+++ b/moli-protocol/src/domains/runtime/tests/evaluate.rs
@@ -1897,23 +1897,11 @@ async fn dom_get_document_rejects_while_main_document_navigation_is_pending() {
#[tokio::test]
async fn document_navigation_gate_is_scoped_to_background_target_owner() {
let mut ctx = TestContext::new();
- let active_page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<html><title>active</title></html>")
- .await
- .expect("active page should load");
- let background_page = ctx
- .conn
- .load_page_via_runtime_async("data:text/html,<html><title>background</title></html>")
- .await
- .expect("background page should load");
- let background_url = background_page.final_url().as_str().to_owned();
- let mut background_target = crate::conn::BackgroundTarget::with_url(
+ let background_target = crate::conn::BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- background_url,
+ "about:blank".to_owned(),
);
- background_target.replace_loaded_page(Some(background_page));
let mut browser_context = BrowserContext::new("BID-1".to_owned());
browser_context.set_active_target_id("TID-active");
@@ -1922,11 +1910,19 @@ async fn document_navigation_gate_is_scoped_to_background_target_owner() {
.devtools_session_state
.runtime_session_state
.runtime_frontend_enabled = true;
- browser_context
- .active_target
- .runtime_slot
- .replace_loaded_page(Some(active_page));
browser_context.background_targets.push(background_target);
+ ctx.conn.browser_context = Some(browser_context);
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><title>active</title></html>",
+ Some("SID-active"),
+ )
+ .await;
+ ctx.install_navigation_fixture_for_session_owner(
+ "data:text/html,<html><title>background</title></html>",
+ Some("SID-background"),
+ )
+ .await;
+ let browser_context = ctx.conn.browser_context.as_mut().expect("browser context");
browser_context.mutate_parked_page_session_state("TID-background", |state| {
state
.devtools_session_state
@@ -1940,7 +1936,6 @@ async fn document_navigation_gate_is_scoped_to_background_target_owner() {
"PENDING-BACKGROUND-LOADER".to_owned(),
)
.expect("background document navigation should start");
- ctx.conn.browser_context = Some(browser_context);
assert!(
ctx.conn
.has_pending_document_navigation_for_session_owner(Some("SID-background")),
@@ -3342,7 +3337,8 @@ async fn runtime_evaluate_document_replacement_clears_timer_mutated_inline_style
resolve("mutated");
}, 0));
})()"#,
- "awaitPromise": true
+ "awaitPromise": true,
+ "returnByValue": true
}
}))
.await;
@@ -3421,7 +3417,8 @@ async fn isolated_call_function_document_replacement_clears_default_world_style_
resolve("mutated");
}, 0));
})()"#,
- "awaitPromise": true
+ "awaitPromise": true,
+ "returnByValue": true
}
}))
.await;
@@ -3526,7 +3523,7 @@ async fn playwright_utility_document_replacement_clears_default_world_style_stat
{ "objectId": isolated_utility },
{ "value": r#"(() => {
document.open();
- document.write("<!doctype html><html><body><div id='before' style='display:none'>before</div><script>setTimeout(() => { document.getElementById('before').style.display = 'block'; }, 0);</script></body></html>");
+ document.write("<!doctype html><html><body><div id='before' style='display:none'>before</div><script>globalThis.__lm_timer_style_mutation = new Promise(resolve => { setTimeout(() => { document.getElementById('before').style.display = 'block'; resolve('mutated'); }, 0); });</script></body></html>");
document.close();
})()"# }
],
@@ -3537,34 +3534,26 @@ async fn playwright_utility_document_replacement_clears_default_world_style_stat
.await;
let _ = take_response_by_id(&mut ctx, 3_144);
- for attempt in 0..16 {
- ctx.process_async(json!({
- "id": 3_145,
- "method": "Runtime.callFunctionOn",
- "params": {
- "objectId": default_utility,
- "functionDeclaration": "(utility, expression) => utility.evaluate(expression)",
- "arguments": [
- { "objectId": default_utility },
- { "value": r#"(() => {
+ ctx.process_async(json!({
+ "id": 3_145,
+ "method": "Runtime.callFunctionOn",
+ "params": {
+ "objectId": default_utility,
+ "functionDeclaration": "(utility, expression) => utility.evaluate(expression)",
+ "arguments": [
+ { "objectId": default_utility },
+ { "value": r#"globalThis.__lm_timer_style_mutation.then(() => {
const before = document.getElementById('before');
return `${before.style.display}:${getComputedStyle(before).display}:${before.getClientRects().length}`;
-})()"# }
- ],
- "returnByValue": true,
- "awaitPromise": true
- }
- }))
- .await;
- let warmed = take_response_by_id(&mut ctx, 3_145);
- if warmed["result"]["result"]["value"] == json!("block:block:1") {
- break;
- }
- if attempt + 1 == 16 {
- panic!("timer style mutation did not become visible: {warmed:?}");
+})"# }
+ ],
+ "returnByValue": true,
+ "awaitPromise": true
}
- tokio::time::sleep(std::time::Duration::from_millis(10)).await;
- }
+ }))
+ .await;
+ let warmed = take_response_by_id(&mut ctx, 3_145);
+ assert_eq!(warmed["result"]["result"]["value"], json!("block:block:1"));
ctx.process_async(json!({
"id": 3_146,
diff --git a/moli-protocol/src/domains/storage/tests.rs b/moli-protocol/src/domains/storage/tests.rs
index 20254e2f1..369a9f441 100644
--- a/moli-protocol/src/domains/storage/tests.rs
+++ b/moli-protocol/src/domains/storage/tests.rs
@@ -774,24 +774,20 @@ async fn storage_key_targets_loaded_background_owner_without_promotion() {
.expect("page url should parse")
.origin()
.ascii_serialization();
- let page = ctx
- .conn
- .load_page_via_runtime_async(&page_url)
- .await
- .expect("background page should load");
-
- let mut background = BackgroundTarget::with_url(
+ let background = BackgroundTarget::with_url(
"TID-background".to_owned(),
Some("SID-background".to_owned()),
- page.final_url().as_str().to_owned(),
+ "about:blank".to_owned(),
);
- background.replace_loaded_page(Some(page));
let mut bc = BrowserContext::new("BID-SK-BG".to_owned());
bc.set_active_target_id("TID-active".to_owned());
bc.attach_active_session("SID-active".to_owned());
bc.background_targets.push(background);
ctx.conn.browser_context = Some(bc);
+ ctx.install_navigation_fixture_for_session_owner(&page_url, Some("SID-background"))
+ .await;
+ ctx.sent.clear();
ctx.process_async(json!({
"id": 101,
diff --git a/moli-protocol/src/domains/target/tests/tests_background_staging.rs b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
index 26afea7ec..38fbbc345 100644
--- a/moli-protocol/src/domains/target/tests/tests_background_staging.rs
+++ b/moli-protocol/src/domains/target/tests/tests_background_staging.rs
@@ -5090,10 +5090,13 @@ async fn same_context_named_popup_reuse_navigates_loaded_background_owner_withou
|conn| {
conn.browser_context_by_id("BID-9-NAMED-POPUP")
.and_then(|browser_context| browser_context.background_target(&owner.target_id))
- .and_then(|target| target.loaded_page())
- .is_some_and(|page| {
- page.final_url().as_str()
+ .is_some_and(|target| {
+ target.target_url()
== "data:text/html,<title>named</title><main>named target</main>"
+ && target.loaded_page().is_some_and(|page| {
+ page.final_url().as_str()
+ == "data:text/html,<title>named</title><main>named target</main>"
+ })
})
},
)
@@ -5107,7 +5110,12 @@ async fn same_context_named_popup_reuse_navigates_loaded_background_owner_withou
);
let changed = emitted
.iter()
- .find(|message| message["method"] == json!("Target.targetInfoChanged"))
+ .find(|message| {
+ message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!(owner.target_id)
+ && message["params"]["targetInfo"]["url"]
+ == json!("data:text/html,<title>named</title><main>named target</main>")
+ })
.unwrap_or_else(|| {
panic!("loaded named target reuse should report targetInfoChanged: {emitted:?}")
});
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs
index b7b85f0c0..2ef212a5a 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_page.rs
@@ -260,6 +260,16 @@ async fn rust_cdp_p0_page_get_frame_tree_includes_child_iframe() {
page.navigate(&mut ctx, 140_006, fixture.url("/iframe"))
.await;
+ crate::testing::wait_until_message(
+ &mut ctx,
+ Some(page.session_id.as_str()),
+ "child frame attachment after Page.navigate response",
+ |message| {
+ message["method"] == json!("Page.frameAttached")
+ && message["params"]["parentFrameId"] == json!(page.target_id)
+ },
+ )
+ .await;
let child_frame_id = ctx
.sent
.iter()
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_runtime.rs b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_runtime.rs
index dc4579c96..79f928271 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_runtime.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_chromium_imports/p0_runtime.rs
@@ -139,6 +139,16 @@ async fn rust_cdp_p0_runtime_child_frame_default_context_created() {
page.navigate(&mut ctx, 147_005, fixture.url("/iframe"))
.await;
+ crate::testing::wait_until_message(
+ &mut ctx,
+ Some(page.session_id.as_str()),
+ "child frame attachment after Page.navigate response",
+ |message| {
+ message["method"] == json!("Page.frameAttached")
+ && message["params"]["parentFrameId"] == json!(page.target_id)
+ },
+ )
+ .await;
let child_frame_id = ctx
.sent
.iter()
diff --git a/moli-protocol/src/domains/target/tests/tests_cdp_smoke_chromium.rs b/moli-protocol/src/domains/target/tests/tests_cdp_smoke_chromium.rs
index 6f54f5a97..2626951d1 100644
--- a/moli-protocol/src/domains/target/tests/tests_cdp_smoke_chromium.rs
+++ b/moli-protocol/src/domains/target/tests/tests_cdp_smoke_chromium.rs
@@ -1264,12 +1264,13 @@ async fn rust_cdp_chromium_dom_get_node_for_location_contract() {
.await;
let loader_id = navigation["result"]["loaderId"]
.as_str()
- .expect("navigation loader id");
+ .expect("hit-test navigation loader id")
+ .to_owned();
crate::testing::wait_until_renderer_document_load(
&mut ctx,
- Some(&attached.session_id),
+ Some(attached.session_id.as_str()),
&attached.target_id,
- loader_id,
+ &loader_id,
)
.await;
diff --git a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
index eefe14fac..9273617ab 100644
--- a/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
+++ b/moli-protocol/src/domains/target/tests/tests_playwright_cdp.rs
@@ -553,6 +553,17 @@ async fn playwright_over_cdp_child_frame_playwright_style_utility_script_uses_ch
let navigation = take_response_by_id(&mut ctx, 5205);
assert_eq!(navigation["sessionId"], json!(session_id));
+ crate::testing::wait_until_message(
+ &mut ctx,
+ Some(session_id.as_str()),
+ "Playwright child frame attachment after Page.navigate response",
+ |message| {
+ message["sessionId"] == json!(session_id)
+ && message["method"] == json!("Page.frameAttached")
+ && message["params"]["parentFrameId"] == json!(attached.target_id)
+ },
+ )
+ .await;
let child_frame_id = ctx
.sent
.iter()
@@ -1254,8 +1265,7 @@ async fn playwright_connect_over_cdp_second_page_window_query_keeps_background_t
}
#[tokio::test(flavor = "multi_thread")]
-async fn playwright_over_cdp_child_frame_is_visible_in_frame_tree_immediately_after_navigation_response()
- {
+async fn playwright_over_cdp_child_frame_is_visible_in_frame_tree_after_frame_attachment() {
async fn parent() -> impl IntoResponse {
(
[(CONTENT_TYPE.as_str(), "text/html")],
@@ -1300,6 +1310,17 @@ async fn playwright_over_cdp_child_frame_is_visible_in_frame_tree_immediately_af
let navigation = take_response_by_id(&mut ctx, 5323);
assert_eq!(navigation["sessionId"], json!(attached.session_id));
+ crate::testing::wait_until_message(
+ &mut ctx,
+ Some(session_id.as_str()),
+ "Playwright child frame attachment after Page.navigate response",
+ |message| {
+ message["sessionId"] == json!(session_id)
+ && message["method"] == json!("Page.frameAttached")
+ && message["params"]["parentFrameId"] == json!(target_id)
+ },
+ )
+ .await;
let child_frame_id = ctx
.sent
.iter()
@@ -6088,6 +6109,10 @@ async fn playwright_over_cdp_script_execution_disabled_blocks_page_scripts_but_n
.await;
let response = take_response_by_id(&mut ctx, 246);
assert_eq!(response["sessionId"], json!(session_id));
+ let loader_id = response["result"]["loaderId"]
+ .as_str()
+ .expect("script-disabled navigation loader id")
+ .to_owned();
assert!(
ctx.sent
.iter()
@@ -6096,6 +6121,21 @@ async fn playwright_over_cdp_script_execution_disabled_blocks_page_scripts_but_n
ctx.sent
);
ctx.take_all();
+ crate::testing::wait_until_renderer_document_load(
+ &mut ctx,
+ Some(session_id.as_str()),
+ &attached.target_id,
+ &loader_id,
+ )
+ .await;
+ ctx.conn
+ .browser_context
+ .as_mut()
+ .and_then(|browser_context| browser_context.active_target.runtime_slot.loaded_page_mut())
+ .expect("script-disabled loaded page")
+ .refresh_script_execution_report_async()
+ .await
+ .expect("script-disabled report refresh");
let active = ctx
.conn
diff --git a/moli-protocol/src/domains/target/tests/tests_target_creation.rs b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
index 594496e27..feed99e91 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_creation.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_creation.rs
@@ -703,12 +703,18 @@ async fn browser_target_session_discovery_receives_target_info_changed_after_nav
}))
.await;
- let changed =
- ctx.take_first_matching("session targetInfoChanged after navigation", |message| {
- message["sessionId"] == json!(browser_session_id)
- && message["method"] == json!("Target.targetInfoChanged")
- && message["params"]["targetInfo"]["targetId"] == json!(target_id)
- });
+ let changed = ctx
+ .wait_for_scheduler_message(
+ "title-aware targetInfoChanged after navigation",
+ |message| {
+ message["sessionId"] == json!(browser_session_id)
+ && message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ && message["params"]["targetInfo"]["title"]
+ == json!("Session Discovery Navigation")
+ },
+ )
+ .await;
assert_eq!(changed["params"]["targetInfo"]["url"], json!(url));
assert_eq!(
changed["params"]["targetInfo"]["title"],
@@ -2100,10 +2106,23 @@ async fn auto_attach_only_owner_receives_target_info_changed_without_target_crea
}))
.await;
+ crate::testing::wait_until_message(
+ &mut ctx,
+ None,
+ "auto-attach-only parsed title targetInfoChanged",
+ |message| {
+ message.get("sessionId").is_none()
+ && message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ && message["params"]["targetInfo"]["title"] == json!("Auto Attach InfoChanged")
+ },
+ )
+ .await;
let changed = ctx.take_first_matching("auto-attach-only targetInfoChanged", |message| {
message.get("sessionId").is_none()
&& message["method"] == json!("Target.targetInfoChanged")
&& message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ && message["params"]["targetInfo"]["title"] == json!("Auto Attach InfoChanged")
});
assert_eq!(changed["params"]["targetInfo"]["url"], json!(url));
assert_eq!(
@@ -2982,6 +3001,13 @@ async fn create_target_without_debugger_wait_starts_requested_url_navigation() {
)
);
+ ctx.wait_for_scheduler_message("created target title metadata", |message| {
+ message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!(target_id)
+ && message["params"]["targetInfo"]["title"] == json!("created-target-ready")
+ })
+ .await;
+
ctx.process_async(json!({
"id": 9011,
"sessionId": session_id,
diff --git a/moli-protocol/src/domains/target/tests/tests_target_management.rs b/moli-protocol/src/domains/target/tests/tests_target_management.rs
index 434d7d8b3..97bb2952c 100644
--- a/moli-protocol/src/domains/target/tests/tests_target_management.rs
+++ b/moli-protocol/src/domains/target/tests/tests_target_management.rs
@@ -271,9 +271,21 @@ async fn puppeteer_target_events_create_navigate_close_page_sequence() {
"params": { "url": navigated_url }
}))
.await;
+ crate::testing::wait_until_message(
+ &mut ctx,
+ None,
+ "Puppeteer parsed title targetInfoChanged",
+ |message| {
+ message["method"] == json!("Target.targetInfoChanged")
+ && message["params"]["targetInfo"]["targetId"] == json!(page_target_id)
+ && message["params"]["targetInfo"]["title"] == json!("Puppeteer Target Events")
+ },
+ )
+ .await;
let changed = ctx.take_first_matching("Puppeteer page targetInfoChanged", |message| {
message["method"] == json!("Target.targetInfoChanged")
&& message["params"]["targetInfo"]["targetId"] == json!(page_target_id)
+ && message["params"]["targetInfo"]["title"] == json!("Puppeteer Target Events")
});
assert_eq!(changed["params"]["targetInfo"]["type"], json!("page"));
assert_eq!(
diff --git a/moli-protocol/src/domains/target/worker_target.rs b/moli-protocol/src/domains/target/worker_target.rs
index 898f16b2a..fb21ab60b 100644
--- a/moli-protocol/src/domains/target/worker_target.rs
+++ b/moli-protocol/src/domains/target/worker_target.rs
@@ -24,9 +24,11 @@ use moli_shared_worker::SharedWorkerInstanceId;
use serde_json::json;
use url::Url;
+use crate::devtools_runtime::{
+ DevToolsNetworkResourceType, DevToolsTargetKind, RuntimeExecutionContextsClearedEvent,
+};
#[cfg(test)]
use crate::devtools_runtime::{DevToolsTargetInfo, RuntimeExecutionContextEvent};
-use crate::devtools_runtime::{DevToolsTargetKind, RuntimeExecutionContextsClearedEvent};
use crate::{
conn::{
BackgroundProtocolEvent, CdpConnection, PreparedTargetAttach, PreparedTargetHostDelta,
@@ -759,7 +761,7 @@ fn register_dedicated_worker_target(
"GET",
None,
&[],
- "Script",
+ DevToolsNetworkResourceType::Script,
SubresourceRequestInitiatorType::Other,
None,
false,
@@ -1044,7 +1046,7 @@ fn dedicated_worker_main_script_worker_events(
response.from_cache,
response.negotiated_http_version,
has_extra_info,
- "Script",
+ DevToolsNetworkResourceType::Script,
);
}
match &script.outcome {
@@ -1057,7 +1059,7 @@ fn dedicated_worker_main_script_worker_events(
target_id,
timestamp,
response.body_bytes().len(),
- Some("Script"),
+ DevToolsNetworkResourceType::Script,
);
}
crate::conn::DedicatedWorkerMainScriptOutcome::Failed { error_message, .. } => {
@@ -1069,7 +1071,7 @@ fn dedicated_worker_main_script_worker_events(
target_id,
timestamp,
dedicated_worker_loading_error_text(error_message),
- "Script",
+ DevToolsNetworkResourceType::Script,
);
}
}
@@ -3386,7 +3388,7 @@ fn emit_service_worker_fetch_diagnostic_events(
&loader_id,
timestamp + 0.000_001,
*body_len,
- None,
+ resource_type,
);
for event in &mut out[body_finished_event_start..] {
tag_service_worker_fetch_diagnostic_event(Some(event), diagnostic);
@@ -3484,19 +3486,21 @@ fn service_worker_fetch_diagnostic_result_name(
}
}
-fn service_worker_fetch_diagnostic_resource_type(destination: &str) -> &'static str {
+fn service_worker_fetch_diagnostic_resource_type(destination: &str) -> DevToolsNetworkResourceType {
match destination {
- "document" | "iframe" | "frame" => "Document",
- "style" => "Stylesheet",
- "image" => "Image",
- "font" => "Font",
- "audio" | "video" => "Media",
- "script" | "worker" | "sharedworker" | "serviceworker" => "Script",
- "track" => "TextTrack",
- "manifest" => "Manifest",
- "report" => "CSPViolationReport",
- "" => "Fetch",
- _ => "Other",
+ "document" | "iframe" | "frame" => DevToolsNetworkResourceType::Document,
+ "style" => DevToolsNetworkResourceType::Stylesheet,
+ "image" => DevToolsNetworkResourceType::Image,
+ "font" => DevToolsNetworkResourceType::Font,
+ "audio" | "video" => DevToolsNetworkResourceType::Media,
+ "script" | "worker" | "sharedworker" | "serviceworker" => {
+ DevToolsNetworkResourceType::Script
+ }
+ "track" => DevToolsNetworkResourceType::TextTrack,
+ "manifest" => DevToolsNetworkResourceType::Manifest,
+ "report" => DevToolsNetworkResourceType::CspViolationReport,
+ "" => DevToolsNetworkResourceType::Fetch,
+ _ => DevToolsNetworkResourceType::Other,
}
}
@@ -6373,7 +6377,8 @@ mod tests {
Some(crate::devtools_runtime::AutomationEvent::NetworkBeforeRequestSent(event))
if event.request_id.as_str() == "TID-service-worker.sw-fetch.101.4"
&& event.method.as_deref() == Some("POST")
- && event.resource_type.as_deref() == Some("Fetch")
+ && event.resource_type
+ == Some(crate::devtools_runtime::DevToolsNetworkResourceType::Fetch)
));
assert!(matches!(
sidecars[1].as_ref(),
@@ -6385,18 +6390,22 @@ mod tests {
sidecars[3].as_ref(),
Some(crate::devtools_runtime::AutomationEvent::NetworkResponseCompleted(event))
if event.encoded_data_length == Some(2)
+ && event.resource_type
+ == Some(crate::devtools_runtime::DevToolsNetworkResourceType::Fetch)
));
assert!(matches!(
sidecars[5].as_ref(),
Some(crate::devtools_runtime::AutomationEvent::NetworkFetchError(event))
if event.error_text.as_deref() == Some("ServiceWorkerFallback")
- && event.resource_type.as_deref() == Some("Script")
+ && event.resource_type
+ == Some(crate::devtools_runtime::DevToolsNetworkResourceType::Script)
));
assert!(matches!(
sidecars[7].as_ref(),
Some(crate::devtools_runtime::AutomationEvent::NetworkFetchError(event))
if event.error_text.as_deref() == Some("network down")
- && event.resource_type.as_deref() == Some("Image")
+ && event.resource_type
+ == Some(crate::devtools_runtime::DevToolsNetworkResourceType::Image)
));
}
diff --git a/moli-protocol/src/lib.rs b/moli-protocol/src/lib.rs
index 2b92c36f2..cb1b4e9e6 100644
--- a/moli-protocol/src/lib.rs
+++ b/moli-protocol/src/lib.rs
@@ -18,13 +18,14 @@ pub mod version;
pub use devtools_runtime::*;
pub use conn::{
- BackgroundCommandResponsePayload, BackgroundNavigationGateKey, BackgroundProtocolEvent,
- CdpCommandTaskStep, CdpConnection, CdpInitialStoragePartition, CdpRendererCommandAccess,
- CdpRendererCommandReplacement, CdpRendererCommandReplayDispatch, CdpSchedulerEvent,
- CdpTargetHostLifecycleDelta, CdpTargetHostLifecycleObserver, CdpTurnOutcome,
- CommandDispatchContext, CommandResponseFlushContext, CommandResponseFlushPermit,
- CompletedCdpCommandDispatch, CompletedDeferredMainDocumentLoadCompletion,
- CompletedRuntimeProtocolMessageDispatch, DeferredMainDocumentLoadCompletionOutputAction,
+ BackgroundCommandResponsePayload, BackgroundNavigationCancellation,
+ BackgroundNavigationGateKey, BackgroundProtocolEvent, CdpCommandTaskStep, CdpConnection,
+ CdpInitialStoragePartition, CdpRendererCommandAccess, CdpRendererCommandReplacement,
+ CdpRendererCommandReplayDispatch, CdpSchedulerEvent, CdpTargetHostLifecycleDelta,
+ CdpTargetHostLifecycleObserver, CdpTurnOutcome, CommandDispatchContext,
+ CommandResponseFlushContext, CommandResponseFlushPermit, CompletedCdpCommandDispatch,
+ CompletedDeferredMainDocumentLoadCompletion, CompletedRuntimeProtocolMessageDispatch,
+ DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadObservationId,
DeferredMainDocumentLoadPredecessorCandidate, DevToolsCommandDispatchOutcome,
DevToolsDocumentLifecycleWaitKey, DevToolsDocumentLifecycleWaitState,
diff --git a/moli-protocol/src/testing.rs b/moli-protocol/src/testing.rs
index 742b38628..4f14ff311 100644
--- a/moli-protocol/src/testing.rs
+++ b/moli-protocol/src/testing.rs
@@ -10,10 +10,12 @@ use std::time::Duration;
use super::conn::{
BackgroundProtocolEvent, CdpCommandTaskStep, CdpConnection, CdpInitialStoragePartition,
CdpSchedulerEvent, CdpTurnOutcome, CommandDispatchContext, CommandResponseFlushPermit,
- ParsedCdpCommand, PendingCdpCommandDispatch, RuntimeInspectorResponseReady,
+ LoadedNavigationRendererAttachmentCommit, ParsedCdpCommand, PendingCdpCommandDispatch,
+ RuntimeInspectorResponseReady,
};
+use crate::devtools_runtime::{DevToolsCommand, DevToolsCommandResult, DevToolsError};
use crate::domains::activity::{
- ProtocolSchedulerWork, RuntimeCommandOutputBarrierCompletion,
+ ProtocolSchedulerWork, ProtocolSchedulerWorkKind, RuntimeCommandOutputBarrierCompletion,
RuntimeCommandOutputBarrierPermit, RuntimeCommandOutputBarriers,
};
use moli_core::{
@@ -310,30 +312,36 @@ impl TestContext {
.expect("navigation fixture requires an installed browser context");
let target_id = target_id.expect("navigation fixture requires an exact target");
let renderer_output_predecessor = navigation.renderer_output_predecessor;
- let renderer_page = crate::conn::RendererPageResidenceIdentity::from_page(&navigation.page);
let navigation_engine = navigation.navigation_engine.take();
let page_creation_artifacts = navigation.page_creation_artifacts;
- self.conn
- .runtime_session_owner_slot_mut(session_id)
+ let final_url = navigation.final_url;
+ let main_document_commit = navigation
+ .main_document_commit
+ .expect("navigation fixture must retain its frozen Document commit identity");
+ let page_commit = self
+ .conn
+ .commit_loaded_navigation_page_for_session_owner_async(
+ session_id,
+ navigation.page,
+ LoadedNavigationRendererAttachmentCommit::Prepare(None),
+ &final_url,
+ )
+ .await
.expect("navigation fixture target must remain installed")
- .set_loaded_page_for_test(navigation.page);
- assert_eq!(
- self.conn
- .renderer_page_residence_identity_for_session_owner(session_id),
- Some(renderer_page),
- "navigation fixture must install the exact renderer Page before binding its output stream"
+ .expect("navigation fixture Page commit must succeed");
+ assert!(
+ page_commit
+ .committed_document_post_response_continuation
+ .is_none(),
+ "lifecycle-target fixture must not retain a DocumentCommit response gate"
);
- // The production navigation transaction binds a reserved renderer
- // Page before its first publication can reach protocol ingress. This
- // synchronous fixture has no concurrent ingress, so install the Page
- // first and then bind the exact residence instead of manufacturing a
- // test-only "unowned but about to be installed" compatibility state.
- let page_owner = self
+ let _ = self
.conn
- .target_page_residence_identity_for_session(session_id)
- .expect("navigation fixture must retain its exact target Page owner");
- self.conn
- .bind_renderer_page_output_owner(renderer_page, page_owner);
+ .commit_loaded_navigation_target_identity_for_session_owner(
+ session_id,
+ &main_document_commit,
+ &final_url,
+ );
let (binding, _) = self
.conn
.bind_renderer_document_lifecycle_for_session_owner(
@@ -876,6 +884,26 @@ impl TestContext {
Box::pin(self.route_renderer_output_predecessor_before_command_response(predecessor)).await;
}
+ /// Completes one protocol-neutral command across the same concrete
+ /// renderer-output boundary as the production actor.
+ pub(crate) async fn execute_devtools_command_through_renderer_fence_for_test(
+ &mut self,
+ command: DevToolsCommand,
+ ) -> Result<DevToolsCommandResult, DevToolsError> {
+ let (result, scheduler_events, protocol_events, renderer_output_predecessor) = self
+ .conn
+ .execute_devtools_command(command)
+ .await
+ .into_complete_parts();
+ if let Some(predecessor) = renderer_output_predecessor {
+ self.route_direct_command_renderer_predecessor_for_test(predecessor)
+ .await;
+ }
+ self.route_direct_command_output_for_test(protocol_events, scheduler_events)
+ .await;
+ result
+ }
+
/// Routes an explicitly completed command turn through the same ordered
/// renderer boundary used by the production actor.
///
@@ -1418,18 +1446,37 @@ impl TestContext {
&mut self,
work: &mut VecDeque<TestSchedulerWork>,
) {
- while let Some(ready) = self
- .pending_protocol_scheduler_work
- .front()
- .map(ProtocolSchedulerWork::is_ready)
- {
- if !ready {
- return;
- }
+ loop {
+ let selected_index = match self.pending_protocol_scheduler_work.front() {
+ Some(front) if front.is_ready() => 0,
+ Some(front)
+ if front.kind() == ProtocolSchedulerWorkKind::MainDocumentLoadOwnerAction =>
+ {
+ let Some(index) =
+ self.pending_protocol_scheduler_work
+ .iter()
+ .position(|candidate| {
+ candidate.is_ready()
+ && candidate.is_top_level_location_navigation_owner_action()
+ })
+ else {
+ return;
+ };
+ // Production checks the pending load observer out of the
+ // FIFO while it waits for the renderer. An unconstrained
+ // location owner action may then run and replace that
+ // exact source Document, which completes the observer as
+ // Superseded. Keeping the pending observer at the front in
+ // this protocol-only harness would deadlock the action
+ // needed to make it terminal.
+ index
+ }
+ Some(_) | None => return,
+ };
if !self.background_navigation_scheduler_enabled
&& self
.pending_protocol_scheduler_work
- .front()
+ .get(selected_index)
.is_some_and(ProtocolSchedulerWork::requires_background_navigation_scheduler)
{
// The default protocol fixture has no owner task lane. Keep
@@ -1442,7 +1489,7 @@ impl TestContext {
}
let protocol_work = self
.pending_protocol_scheduler_work
- .pop_front()
+ .remove(selected_index)
.expect("ready protocol work must remain resident");
let (events, scheduler_events, renderer_output_predecessor) = self
.conn
@@ -1828,7 +1875,7 @@ fn enqueue_scheduler_events_like_scheduler(
CdpSchedulerEvent::ProtocolWorkPublished { work } => {
queue.push_back(TestDeferredSchedulerWork(work));
}
- CdpSchedulerEvent::BackgroundNavigationStarted { key: _ } => {}
+ CdpSchedulerEvent::BackgroundNavigationStarted { .. } => {}
CdpSchedulerEvent::PageScreencastStarted { .. } => {}
}
}
diff --git a/moli-renderer-v8/src/document_runtime.rs b/moli-renderer-v8/src/document_runtime.rs
index 2e570b276..29de61c1b 100644
--- a/moli-renderer-v8/src/document_runtime.rs
+++ b/moli-renderer-v8/src/document_runtime.rs
@@ -58,7 +58,11 @@ use crate::{
},
},
frame_owner_model::FrameDocumentTaskOwner,
- live_document_parser::{DocumentParserLifetime, DocumentParserSession},
+ live_document_parser::{
+ DocumentParserLifetime, DocumentParserRunState, DocumentParserSession,
+ DocumentParserSessionControlHandle, ParserResumeApplication, ParserResumePermit,
+ ParserSuspensionCause,
+ },
module_runtime::ModuleMapKey,
network::ResourceRequestClient,
parser::{HtmlParser, ParserInputContext, ParserInputSession},
@@ -163,19 +167,10 @@ pub(crate) enum PostParseOwnerDriverStep {
#[derive(Debug)]
struct ParserConnectedScriptContext {
- visibility_boundary: Option<ParserVisibilityBoundary>,
insertion_controller: ParserInsertionController,
_input_context: ParserInputContext,
}
-#[derive(Debug)]
-struct ParserVisibilityBoundary {
- document: DomHandle,
- current_script: DomHandle,
- current_script_ancestor_chain: Vec<DomHandle>,
- query_version: u64,
-}
-
#[derive(Debug)]
struct CurrentScriptContext {
handle: Option<DomHandle>,
@@ -193,25 +188,40 @@ pub(crate) struct CurrentScriptContextSpec {
pub(crate) struct ParserInsertionController {
input_session: ParserInputSession,
parser_stream: ParserStreamHandle,
+ parser_control: DocumentParserSessionControlHandle,
}
impl std::fmt::Debug for ParserInsertionController {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ParserInsertionController")
.field("input_session", &self.input_session)
+ .field("session_id", &self.parser_control.session_id())
+ .field("run_state", &self.parser_control.run_state())
.finish()
}
}
impl ParserInsertionController {
+ #[cfg(test)]
pub(crate) fn for_stream(stream: ParserStreamHandle) -> Self {
let input_session = stream.borrow().script_input_session();
Self {
input_session,
parser_stream: stream,
+ parser_control: DocumentParserSessionControlHandle::new(),
}
}
+ pub(crate) fn for_session(parser: &DocumentParserSession) -> Option<Self> {
+ let parser_stream = parser.html_stream_handle()?;
+ let input_session = parser_stream.borrow().script_input_session();
+ Some(Self {
+ input_session,
+ parser_stream,
+ parser_control: parser.control_handle(),
+ })
+ }
+
pub(crate) fn input_session(&self) -> ParserInputSession {
self.input_session.clone()
}
@@ -219,6 +229,22 @@ impl ParserInsertionController {
pub(crate) fn parser_stream(&self) -> ParserStreamHandle {
self.parser_stream.clone()
}
+
+ pub(crate) fn run_state(&self) -> DocumentParserRunState {
+ self.parser_control.run_state()
+ }
+
+ pub(crate) fn suspend(&self, cause: ParserSuspensionCause) -> ParserResumePermit {
+ self.parser_control.suspend(cause)
+ }
+
+ pub(crate) fn resume(&self, permit: ParserResumePermit) -> ParserResumeApplication {
+ self.parser_control.resume(permit)
+ }
+
+ pub(crate) fn begin_pump(&self) -> crate::live_document_parser::DocumentParserPumpGuard {
+ self.parser_control.begin_pump()
+ }
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
@@ -394,7 +420,8 @@ struct DocumentWriteExternalScriptStart {
struct SuspendedDocumentWriteInsertion {
document_handle: DomHandle,
parser_insertion_controller: ParserInsertionController,
- pending_html_tail: String,
+ resume_permit: ParserResumePermit,
+ resume_permit_consumed: bool,
}
#[derive(Debug)]
@@ -691,6 +718,10 @@ pub(super) struct DocumentRuntime {
next_document_write_external_script_load_id: u64,
document_write_script_preload_scanner:
Option<Box<crate::runtime::IncrementalBufferedScriptPreloadScanner>>,
+ /// In-flight classic script loads started by the main-document scanner.
+ /// The Document shares this resource residence with parser re-entry while
+ /// scanner/tokenizer state remains owned by phase one.
+ main_document_script_preloads: crate::runtime::DocumentScriptPreloadStore,
document_write_script_preloads:
HashMap<crate::runtime::BufferedScriptPreloadKey, DocumentWriteScriptPreload>,
pending_document_write_external_script_load: Option<PendingDocumentWriteExternalScriptLoad>,
@@ -1226,10 +1257,9 @@ mod tests {
crate::dom::native::NativeDom,
Vec<crate::DocumentOwnedBlockingStylesheetDiscoveryInput>,
) {
- let (document, handoffs) =
- HtmlParser.parse_dom_host_with_document_handoffs(final_url, html.into());
- let (_, inputs) = handoffs.into_parts();
- (document.into_dom(), inputs)
+ let (document, _, inputs) =
+ crate::parse_html_test_fixture_with_parser_outputs(final_url, html.into());
+ (document, inputs)
}
fn preload_load_parameters(url: Url) -> ConnectedLoadParameters {
diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rs
index e81ef1ebd..cef24a6a6 100644
--- a/moli-renderer-v8/src/document_runtime/document_write.rs
+++ b/moli-renderer-v8/src/document_runtime/document_write.rs
@@ -19,13 +19,19 @@ use moli_parser::{
ParserElementCreationConsumer, ParserElementCreationRequest, ParserMutationEffectConsumer,
ParserPumpOutcome,
};
-use std::{collections::HashSet, rc::Rc};
+use std::collections::HashSet;
use tracing::debug;
struct DocumentWriteParserPumpStep {
outcome: ParserPumpOutcome,
}
+enum DocumentWriteParserPumpInput<'a> {
+ Inserted(&'a str),
+ Ordinary(&'a str),
+ QueuedOrBuffered,
+}
+
#[derive(Clone, Copy, Eq, PartialEq)]
enum HtmlFragmentParserContextMode {
Standard,
@@ -203,6 +209,10 @@ impl ParserDomMutationConsumer for DocumentWriteParserMutationOwner<'_, '_, '_>
.create_processing_instruction_in_live_dom_host(target, data)
}
+ fn create_cdata_section(&mut self, data: String) -> DomHandle {
+ self.runtime.create_cdata_section_in_live_dom_host(data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -310,15 +320,20 @@ impl ParserElementCreationConsumer for DocumentWriteParserMutationOwner<'_, '_,
// "HTML string -> parser output -> document.write/fragment effects" rather than mixing two different
// mutation models in one refactor slice.
impl DocumentRuntime {
- pub(crate) fn start_root_document_parser_stream(&mut self) {
+ pub(crate) fn start_root_document_parser_stream(
+ &mut self,
+ owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ ) {
debug_assert!(
self.root_document_parser.is_none(),
"opening a root document must discard the previous parser stream first"
);
- self.root_document_parser = Some(DocumentParserSession::start_open_live_document(
+ let mut parser = DocumentParserSession::start_open_live_document(
self.document_url().clone(),
self.document_handle(),
- ));
+ );
+ parser.bind_owner(owner, self.runtime_reset_generation());
+ self.root_document_parser = Some(parser);
}
pub(crate) fn close_root_document_parser_stream(
@@ -363,6 +378,14 @@ impl DocumentRuntime {
.as_ref()
.is_none_or(|parser| parser.lifetime() != DocumentParserLifetime::Closing)
|| self.has_pending_document_write_parser_blocking_work()
+ || self
+ .root_document_parser
+ .as_ref()
+ .is_some_and(|parser| parser.run_state() != DocumentParserRunState::Ready)
+ || self
+ .root_document_parser
+ .as_ref()
+ .is_some_and(|parser| !parser.input_is_empty())
{
return false;
}
@@ -378,7 +401,7 @@ impl DocumentRuntime {
{
return false;
}
- let Some(parser) = self.root_document_parser.take() else {
+ let Some(mut parser) = self.root_document_parser.take() else {
return false;
};
let finish_signals = self.with_dom_host_parse_step(|runtime| {
@@ -1291,12 +1314,16 @@ impl DocumentRuntime {
let Some(pending) = self.pending_document_write_external_script_load.as_mut() else {
return false;
};
+ pending
+ .insertion
+ .parser_insertion_controller
+ .input_session()
+ .enqueue_script_input_html(html.to_owned());
pending
.insertion
.parser_insertion_controller
.input_session()
.enqueue_script_input_preload_html(html.to_owned());
- pending.insertion.pending_html_tail.push_str(html);
true
}
@@ -1307,12 +1334,16 @@ impl DocumentRuntime {
else {
return false;
};
+ pending
+ .insertion
+ .parser_insertion_controller
+ .input_session()
+ .enqueue_script_input_html(html.to_owned());
pending
.insertion
.parser_insertion_controller
.input_session()
.enqueue_script_input_preload_html(html.to_owned());
- pending.insertion.pending_html_tail.push_str(html);
true
}
@@ -1320,12 +1351,16 @@ impl DocumentRuntime {
let Some(pending) = self.pending_document_write_stylesheet_parser_pause.as_mut() else {
return false;
};
+ pending
+ .insertion
+ .parser_insertion_controller
+ .input_session()
+ .enqueue_script_input_html(html.to_owned());
pending
.insertion
.parser_insertion_controller
.input_session()
.enqueue_script_input_preload_html(html.to_owned());
- pending.insertion.pending_html_tail.push_str(html);
true
}
@@ -1515,76 +1550,112 @@ impl DocumentRuntime {
if self.park_suspended_insertion_behind_reentrant_parser_work(&mut insertion) {
return true;
}
+ if !Self::resume_document_write_insertion_permit(&mut insertion) {
+ tracing::debug!(
+ document_handle = ?insertion.document_handle,
+ permit = ?insertion.resume_permit,
+ run_state = ?insertion.parser_insertion_controller.run_state(),
+ "dropping stale document.write parser continuation"
+ );
+ return false;
+ }
let mut changed = false;
- let mut script_input_tail = String::new();
let parser_input_session = insertion.parser_insertion_controller.input_session();
while let Some(script_input_html) = parser_input_session.take_next_script_input_html() {
- script_input_tail.push_str(&script_input_html);
+ if self.write_html_via_parser_stream(
+ scope,
+ host_ptr,
+ insertion.document_handle,
+ &script_input_html,
+ false,
+ &insertion.parser_insertion_controller,
+ ) {
+ changed = true;
+ }
+ if self.has_pending_document_write_parser_blocking_work() {
+ return true;
+ }
}
- script_input_tail.push_str(&std::mem::take(&mut insertion.pending_html_tail));
- let buffered_parser_tail = insertion
- .parser_insertion_controller
- .parser_stream()
- .borrow_mut()
- .take_buffered_input();
- script_input_tail.push_str(&buffered_parser_tail);
- if !script_input_tail.is_empty() {
- let pending_html_tail = script_input_tail;
+
+ // The blocker yielded from an insertion frame that is still resident
+ // in HtmlParserSession. Draining one frame restores its parent and
+ // reports an input boundary before that parent is pumped. Keep driving
+ // the parser-owned segment stack until the complete input is drained
+ // or another parser-blocking boundary takes ownership.
+ loop {
if self.write_html_via_parser_stream(
scope,
host_ptr,
insertion.document_handle,
- &pending_html_tail,
+ "",
+ true,
&insertion.parser_insertion_controller,
) {
changed = true;
}
+ if self.has_pending_document_write_parser_blocking_work() {
+ return true;
+ }
+ if !insertion
+ .parser_insertion_controller
+ .parser_stream()
+ .borrow()
+ .has_pending_input()
+ {
+ break;
+ }
}
changed
}
+ fn resume_document_write_insertion_permit(
+ insertion: &mut SuspendedDocumentWriteInsertion,
+ ) -> bool {
+ if insertion.resume_permit_consumed {
+ return insertion.parser_insertion_controller.run_state()
+ == DocumentParserRunState::Ready;
+ }
+ let resumed = match insertion.parser_insertion_controller.run_state() {
+ DocumentParserRunState::Ready => false,
+ DocumentParserRunState::Suspended { .. } => {
+ insertion
+ .parser_insertion_controller
+ .resume(insertion.resume_permit)
+ == ParserResumeApplication::Resumed
+ }
+ DocumentParserRunState::Pumping { .. }
+ | DocumentParserRunState::Finishing
+ | DocumentParserRunState::Finished
+ | DocumentParserRunState::Stopped(_) => false,
+ };
+ if resumed {
+ insertion.resume_permit_consumed = true;
+ }
+ resumed
+ }
+
+ fn resuspend_document_write_insertion(
+ insertion: &mut SuspendedDocumentWriteInsertion,
+ cause: ParserSuspensionCause,
+ ) {
+ insertion.resume_permit = insertion.parser_insertion_controller.suspend(cause);
+ insertion.resume_permit_consumed = false;
+ }
+
/// A resumed parser script may synchronously create a newer blocking
/// owner through document.write(). The older suspension's parser tail then
/// belongs behind that new owner; consuming it immediately would parse
/// past a stylesheet or script boundary that Blink keeps closed.
fn park_suspended_insertion_behind_reentrant_parser_work(
&mut self,
- insertion: &mut SuspendedDocumentWriteInsertion,
+ _insertion: &mut SuspendedDocumentWriteInsertion,
) -> bool {
- if !self.has_pending_document_write_parser_blocking_work() {
- return false;
- }
-
- let parser_stream = insertion.parser_insertion_controller.parser_stream();
- let mut deferred_tail = parser_stream.borrow_mut().take_buffered_input();
- deferred_tail.push_str(&std::mem::take(&mut insertion.pending_html_tail));
-
- let pending_insertion = if let Some(pending) =
- self.pending_document_write_stylesheet_parser_pause.as_mut()
- {
- &mut pending.insertion
- } else if let Some(pending) = self
- .pending_document_write_stylesheet_blocked_script
- .as_mut()
- {
- &mut pending.insertion
- } else if let Some(pending) = self.pending_document_write_external_script_load.as_mut() {
- &mut pending.insertion
- } else {
- unreachable!("pending document.write parser work must retain its insertion owner")
- };
-
- debug_assert_eq!(pending_insertion.document_handle, insertion.document_handle);
- debug_assert!(Rc::ptr_eq(
- &pending_insertion
- .parser_insertion_controller
- .parser_stream(),
- &parser_stream,
- ));
- pending_insertion.pending_html_tail.push_str(&deferred_tail);
- true
+ // Every insertion frame and parent tail already resides in the shared
+ // HtmlParserSession stack. A newer blocking owner therefore parks the
+ // older continuation by ownership alone; there is no tail to move.
+ self.has_pending_document_write_parser_blocking_work()
}
fn complete_document_write_script_preload(
@@ -1666,10 +1737,19 @@ impl DocumentRuntime {
let completion_target = completion.target();
let PendingDocumentWriteExternalScriptLoad {
start,
- insertion,
+ mut insertion,
mut resume_after_completion,
..
} = pending;
+ if !Self::resume_document_write_insertion_permit(&mut insertion) {
+ tracing::debug!(
+ target = ?completion_target,
+ permit = ?insertion.resume_permit,
+ run_state = ?insertion.parser_insertion_controller.run_state(),
+ "rejecting document.write external-script terminal for a stale parser suspension"
+ );
+ return super::DocumentWriteExternalScriptLoadApplication::RejectedStaleTarget;
+ }
match completion.into_result() {
Ok(source) => {
let csp_request =
@@ -1774,16 +1854,27 @@ impl DocumentRuntime {
scope: &mut v8::PinScope<'_, '_>,
host_ptr: *mut JsContextHost,
stream: &mut DocumentStream,
- chunk: &str,
+ input: DocumentWriteParserPumpInput<'_>,
) -> DocumentWriteParserPumpStep {
- let outcome = self.with_dom_host_parse_step(|runtime| {
- let mut mutation_owner = DocumentWriteParserMutationOwner {
- runtime,
- scope,
- host_ptr,
- };
- stream.pump_parser_inserted_step_with_runtime_dom_consumer(chunk, &mut mutation_owner)
- });
+ let outcome =
+ self.with_dom_host_parse_step(|runtime| {
+ let mut mutation_owner = DocumentWriteParserMutationOwner {
+ runtime,
+ scope,
+ host_ptr,
+ };
+ match input {
+ DocumentWriteParserPumpInput::Inserted(chunk) => stream
+ .pump_parser_inserted_step_with_runtime_dom_consumer(
+ chunk,
+ &mut mutation_owner,
+ ),
+ DocumentWriteParserPumpInput::Ordinary(chunk) => stream
+ .pump_parser_step_with_runtime_dom_consumer(chunk, &mut mutation_owner),
+ DocumentWriteParserPumpInput::QueuedOrBuffered => stream
+ .pump_next_parser_step_with_runtime_dom_consumer(0, &mut mutation_owner),
+ }
+ });
let null_custom_element_registry_elements =
stream.take_parser_stream_null_custom_element_registry_elements();
custom_elements::apply_parser_created_null_registry_associations(
@@ -1798,19 +1889,13 @@ impl DocumentRuntime {
&mut self,
document_handle: DomHandle,
parser_insertion_controller: &ParserInsertionController,
- network_tail: &mut String,
+ cause: ParserSuspensionCause,
) -> SuspendedDocumentWriteInsertion {
- let stream = parser_insertion_controller.parser_stream();
- let pending_html_tail = stream.borrow_mut().take_buffered_input();
- if !network_tail.is_empty() {
- stream
- .borrow_mut()
- .prepend_buffered_input(std::mem::take(network_tail));
- }
SuspendedDocumentWriteInsertion {
document_handle,
parser_insertion_controller: parser_insertion_controller.clone(),
- pending_html_tail,
+ resume_permit: parser_insertion_controller.suspend(cause),
+ resume_permit_consumed: false,
}
}
@@ -1823,7 +1908,6 @@ impl DocumentRuntime {
start_column: u64,
script: PreparedScript,
blocking_signatures_before: HashSet<DocumentBlockingStylesheetSignature>,
- network_tail: &mut String,
) -> bool {
debug_assert!(
self.pending_document_write_stylesheet_blocked_script
@@ -1835,7 +1919,7 @@ impl DocumentRuntime {
let insertion = self.take_suspended_document_write_insertion(
document_handle,
parser_insertion_controller,
- network_tail,
+ ParserSuspensionCause::ParserClassicStylesheets { script: node },
);
self.pending_document_write_stylesheet_blocked_script =
Some(PendingDocumentWriteStylesheetBlockedScript {
@@ -1854,8 +1938,8 @@ impl DocumentRuntime {
host_ptr: *mut JsContextHost,
document_handle: DomHandle,
parser_insertion_controller: &ParserInsertionController,
+ stylesheet_owner: DomHandle,
blocking_signatures: HashSet<DocumentBlockingStylesheetSignature>,
- network_tail: &mut String,
) -> bool {
debug_assert!(
self.pending_document_write_stylesheet_parser_pause
@@ -1865,15 +1949,14 @@ impl DocumentRuntime {
let insertion = self.take_suspended_document_write_insertion(
document_handle,
parser_insertion_controller,
- network_tail,
- );
- let mut preload_html = insertion.pending_html_tail.clone();
- preload_html.push_str(
- &parser_insertion_controller
- .parser_stream()
- .borrow_mut()
- .peek_buffered_input(),
+ ParserSuspensionCause::ParserCreatedStylesheet {
+ owner: stylesheet_owner,
+ },
);
+ let preload_html = parser_insertion_controller
+ .parser_stream()
+ .borrow()
+ .snapshot_pending_input();
self.scan_document_write_script_preloads(host_ptr, &preload_html, true);
self.pending_document_write_stylesheet_parser_pause =
Some(PendingDocumentWriteStylesheetParserPause {
@@ -1894,7 +1977,6 @@ impl DocumentRuntime {
start_column: u64,
script: PreparedScript,
blocking_signatures_before: HashSet<DocumentBlockingStylesheetSignature>,
- network_tail: &mut String,
) -> bool {
self.note_parser_script_start_position(node, start_line, start_column);
let _ = self.dom_host_mut().set_script_already_started(node, false);
@@ -1912,7 +1994,7 @@ impl DocumentRuntime {
let insertion = self.take_suspended_document_write_insertion(
document_handle,
parser_insertion_controller,
- network_tail,
+ ParserSuspensionCause::DocumentWriteExternalScript { script: node },
);
self.start_document_write_external_script_load(
scope,
@@ -1973,8 +2055,11 @@ impl DocumentRuntime {
start_column,
script,
blocking_signatures_before: _,
- insertion,
+ mut insertion,
} = pending;
+ if !Self::resume_document_write_insertion_permit(&mut insertion) {
+ return false;
+ }
self.note_parser_script_start_position(node, start_line, start_column);
let _ = self.dom_host_mut().set_script_already_started(node, false);
match self.run_prepared_document_write_connected_script(
@@ -1997,6 +2082,10 @@ impl DocumentRuntime {
true
}
DocumentWriteScriptRunOutcome::Suspend(start) => {
+ Self::resuspend_document_write_insertion(
+ &mut insertion,
+ ParserSuspensionCause::DocumentWriteExternalScript { script: node },
+ );
self.start_document_write_external_script_load(
scope,
host_ptr,
@@ -2019,7 +2108,6 @@ impl DocumentRuntime {
start_line: u64,
start_column: u64,
script: PreparedScript,
- network_tail: &mut String,
) -> bool {
self.note_parser_script_start_position(node, start_line, start_column);
let _ = self.dom_host_mut().set_script_already_started(node, false);
@@ -2030,11 +2118,9 @@ impl DocumentRuntime {
script,
Some(parser_insertion_controller.clone()),
) {
- DocumentWriteScriptRunOutcome::Complete => self
- .park_outer_parser_tail_behind_reentrant_document_write_work(
- parser_insertion_controller,
- network_tail,
- ),
+ DocumentWriteScriptRunOutcome::Complete => {
+ self.has_pending_document_write_parser_blocking_work()
+ }
DocumentWriteScriptRunOutcome::Suspend(start) => self
.suspend_document_write_parser_handoff(
scope,
@@ -2042,38 +2128,9 @@ impl DocumentRuntime {
document_handle,
parser_insertion_controller,
start,
- network_tail,
),
}
}
-
- /// Stop the parser that invoked a script when a nested `document.write()`
- /// created a new parser-blocking owner.
- ///
- /// The nested write has already parked the remainder of the invoking
- /// parser's current input in the shared stream. `network_tail` was removed
- /// before that input was pumped, so it belongs strictly after the buffered
- /// remainder and must be restored in that order. The completion owner of
- /// the nested work will resume this same parser stream.
- fn park_outer_parser_tail_behind_reentrant_document_write_work(
- &mut self,
- parser_insertion_controller: &ParserInsertionController,
- network_tail: &mut String,
- ) -> bool {
- if !self.has_pending_document_write_parser_blocking_work() {
- return false;
- }
- if network_tail.is_empty() {
- return true;
- }
-
- let stream = parser_insertion_controller.parser_stream();
- let mut stream = stream.borrow_mut();
- let mut buffered_parser_tail = stream.take_buffered_input();
- buffered_parser_tail.push_str(&std::mem::take(network_tail));
- stream.prepend_buffered_input(buffered_parser_tail);
- true
- }
fn queue_document_write_parser_owned_post_parse_script(
&mut self,
host_ptr: *mut JsContextHost,
@@ -2119,11 +2176,14 @@ impl DocumentRuntime {
);
return;
};
+ let shared_preload = self
+ .main_document_script_preloads
+ .shared_preload_for_script(&script);
let document_character_set = self.document_character_set().to_owned();
let Some(start) = self.accept_main_parser_deferred_script(
task_owner,
script,
- None,
+ shared_preload,
Some(&document_character_set),
blocking_signatures_before,
load_delay_token,
@@ -2251,12 +2311,12 @@ impl DocumentRuntime {
document_handle: DomHandle,
parser_insertion_controller: &ParserInsertionController,
start: Box<DocumentWriteExternalScriptStart>,
- network_tail: &mut String,
) -> bool {
+ let script = start.node;
let insertion = self.take_suspended_document_write_insertion(
document_handle,
parser_insertion_controller,
- network_tail,
+ ParserSuspensionCause::DocumentWriteExternalScript { script },
);
self.start_document_write_external_script_load(
scope,
@@ -2274,7 +2334,6 @@ impl DocumentRuntime {
document_handle: DomHandle,
parser_insertion_controller: &ParserInsertionController,
handoff: ParserScriptHandoff,
- network_tail: &mut String,
) -> bool {
match handoff {
ParserScriptHandoff::BlockingClassic {
@@ -2298,7 +2357,6 @@ impl DocumentRuntime {
start_column,
script,
blocking_signatures_before,
- network_tail,
)
} else {
self.suspend_document_write_stylesheet_blocked_script(
@@ -2309,7 +2367,6 @@ impl DocumentRuntime {
start_column,
script,
blocking_signatures_before,
- network_tail,
)
}
} else {
@@ -2322,7 +2379,6 @@ impl DocumentRuntime {
start_line,
start_column,
script,
- network_tail,
)
}
}
@@ -2410,6 +2466,7 @@ impl DocumentRuntime {
host_ptr: *mut JsContextHost,
document_handle: DomHandle,
html: &str,
+ resume_existing_insertion: bool,
parser_insertion_controller: &ParserInsertionController,
) -> bool {
let stream = parser_insertion_controller.parser_stream();
@@ -2418,13 +2475,34 @@ impl DocumentRuntime {
let mut chunk = parser_input_session.take_current_script_input_html();
chunk.push_str(html);
- if chunk.is_empty() {
+ if chunk.is_empty() && !resume_existing_insertion {
return true;
}
let _parser_insertion_session = self.enter_parser_insertion_session();
- let mut network_tail = stream.borrow_mut().take_buffered_input();
+ let mut begin_insertion = !chunk.is_empty();
loop {
+ let parser_step = {
+ let _pump_guard = parser_insertion_controller.begin_pump();
+ let input = if begin_insertion {
+ DocumentWriteParserPumpInput::Inserted(chunk.as_str())
+ } else if resume_existing_insertion && chunk.is_empty() {
+ // Resuming a parser-inserted frame can expose either the
+ // tokenizer's buffered parent frame or a later root input
+ // segment. The parser owns that ordering; selecting its
+ // next queued input is required to make progress once the
+ // tokenizer buffer itself is empty.
+ DocumentWriteParserPumpInput::QueuedOrBuffered
+ } else {
+ DocumentWriteParserPumpInput::Ordinary(chunk.as_str())
+ };
+ self.pump_document_write_parser_step(
+ scope,
+ host_ptr,
+ &mut stream.borrow_mut(),
+ input,
+ )
+ };
let DocumentWriteParserPumpStep {
outcome:
ParserPumpOutcome {
@@ -2433,12 +2511,7 @@ impl DocumentRuntime {
discovered_modulepreload_link_candidates,
discovered_blocking_stylesheet_inputs,
},
- } = self.pump_document_write_parser_step(
- scope,
- host_ptr,
- &mut stream.borrow_mut(),
- chunk.as_str(),
- );
+ } = parser_step;
let discovered_parser_meta_csp_candidates = stream
.borrow_mut()
.drain_discovered_parser_meta_csp_candidates();
@@ -2454,6 +2527,7 @@ impl DocumentRuntime {
);
self.run_pending_parser_post_step_runtime_work(scope, host_ptr);
chunk.clear();
+ begin_insertion = false;
self.note_discovered_document_owned_blocking_stylesheet_inputs(
discovered_blocking_stylesheet_inputs.iter(),
@@ -2461,7 +2535,6 @@ impl DocumentRuntime {
match result {
ParserPumpStep::InputDrained => {
- stream.borrow_mut().prepend_buffered_input(network_tail);
return true;
}
ParserPumpStep::Yield(ParserYield::CustomElementConstruction(_handoff)) => {
@@ -2470,7 +2543,7 @@ impl DocumentRuntime {
// behavior until that owner can safely run constructors from a shallow V8
// entry.
}
- ParserPumpStep::Yield(ParserYield::BlockingStylesheet(_pause)) => {
+ ParserPumpStep::Yield(ParserYield::BlockingStylesheet(pause)) => {
if self.current_document_resource_loader().is_none() {
continue;
}
@@ -2483,8 +2556,8 @@ impl DocumentRuntime {
host_ptr,
document_handle,
parser_insertion_controller,
+ pause.node_id,
blocking_signatures,
- &mut network_tail,
)
{
return true;
@@ -2497,7 +2570,6 @@ impl DocumentRuntime {
document_handle,
parser_insertion_controller,
*handoff,
- &mut network_tail,
) {
return true;
}
@@ -2599,7 +2671,7 @@ impl DocumentRuntime {
let parser_insertion_controller = self
.root_document_parser
.as_ref()
- .map(|parser| ParserInsertionController::for_stream(parser.stream_handle()))
+ .and_then(ParserInsertionController::for_session)
.or_else(|| self.current_parser_insertion_controller())
.expect("document.write() must have a live root stream or parser insertion controller");
self.write_html_via_parser_stream(
@@ -2607,6 +2679,7 @@ impl DocumentRuntime {
host_ptr,
document_handle,
html,
+ false,
&parser_insertion_controller,
)
}
@@ -2693,7 +2766,13 @@ mod tests {
let document = HtmlParser.parse(document_url, "<!doctype html>".to_owned());
let mut runtime = DocumentRuntime::new(&document);
- runtime.start_root_document_parser_stream();
+ runtime.start_root_document_parser_stream(
+ crate::frame_owner_model::FrameDocumentTaskOwner::new(
+ crate::frame_owner_model::FrameSchedulerLaneId(1),
+ crate::frame_owner_model::LocalWindowId(1),
+ crate::frame_owner_model::DocumentId(1),
+ ),
+ );
let parser = runtime
.root_document_parser
diff --git a/moli-renderer-v8/src/document_runtime/dom_facade.rs b/moli-renderer-v8/src/document_runtime/dom_facade.rs
index 6ba6b4f72..1c71eb578 100644
--- a/moli-renderer-v8/src/document_runtime/dom_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/dom_facade.rs
@@ -381,6 +381,11 @@ impl DocumentRuntime {
.create_processing_instruction(&target, &data)
}
+ pub(crate) fn create_cdata_section_in_live_dom_host(&mut self, data: String) -> DomHandle {
+ self.dom_host_mut_for_active_parser_step()
+ .create_cdata_section(&data)
+ }
+
pub(crate) fn create_document_type_in_live_dom_host(
&mut self,
name: String,
diff --git a/moli-renderer-v8/src/document_runtime/lifecycle.rs b/moli-renderer-v8/src/document_runtime/lifecycle.rs
index 351da33e6..44518d00f 100644
--- a/moli-renderer-v8/src/document_runtime/lifecycle.rs
+++ b/moli-renderer-v8/src/document_runtime/lifecycle.rs
@@ -37,6 +37,13 @@ fn image_is_small_for_priority_boost(element: &crate::dom::native::Element) -> b
// the host document state accessors, current-script/parser visibility
// bookkeeping, and pending resource-load delivery that feed DCL/load decisions.
impl DocumentRuntime {
+ pub(crate) fn bind_main_document_script_preload_store(
+ &mut self,
+ store: crate::runtime::DocumentScriptPreloadStore,
+ ) {
+ self.main_document_script_preloads = store;
+ }
+
pub(crate) fn bind_main_document_runtime_producer(
&mut self,
owner: crate::frame_owner_model::FrameDocumentTaskOwner,
@@ -225,6 +232,7 @@ impl DocumentRuntime {
self.pending_inspector_issues.clear();
self.quirks_mode_issue_reported = false;
self.document_write_script_preload_scanner = None;
+ self.main_document_script_preloads = Default::default();
self.document_write_script_preloads.clear();
self.pending_document_write_external_script_load = None;
self.pending_document_write_stylesheet_blocked_script = None;
@@ -412,8 +420,6 @@ impl DocumentRuntime {
let parser_connected = parser_insertion_controller.map(|insertion_controller| {
let input_context = insertion_controller.input_session().enter_pending_context();
ParserConnectedScriptContext {
- visibility_boundary: handle
- .map(|current_script| self.begin_parser_visibility_boundary(current_script)),
insertion_controller,
_input_context: input_context,
}
@@ -429,17 +435,7 @@ impl DocumentRuntime {
}
pub(crate) fn clear_current_script_handle(&mut self) {
- let Some(context) = self.script_context_stack.pop() else {
- return;
- };
- if context
- .parser_connected
- .as_ref()
- .is_some_and(|parser| parser.visibility_boundary.is_some())
- {
- self.dom_host.end_tree_insertion_tracking();
- }
- drop(context);
+ self.script_context_stack.pop();
}
pub(crate) fn has_active_parser_write_insertion_point(&self) -> bool {
@@ -463,13 +459,6 @@ impl DocumentRuntime {
self.take_post_parse_schedule_invalidated()
}
- pub(crate) fn filter_parser_visible_handles(&self, handles: Vec<DomHandle>) -> Vec<DomHandle> {
- handles
- .into_iter()
- .filter(|handle| self.is_parser_visible_handle(*handle))
- .collect()
- }
-
pub(crate) fn queue_current_main_document_image_load_events(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
@@ -532,73 +521,6 @@ impl DocumentRuntime {
}
}
}
-
- fn is_parser_visible_handle(&self, handle: DomHandle) -> bool {
- self.current_script_context()
- .and_then(|context| context.parser_connected.as_ref())
- .is_none_or(|state| {
- state.visibility_boundary.as_ref().is_none_or(|boundary| {
- self.is_handle_visible_at_parser_boundary(handle, boundary)
- })
- })
- }
-
- fn begin_parser_visibility_boundary(
- &self,
- current_script: DomHandle,
- ) -> ParserVisibilityBoundary {
- self.dom_host.begin_tree_insertion_tracking();
- ParserVisibilityBoundary {
- document: self.dom_host.document_handle(),
- current_script,
- current_script_ancestor_chain: self.ancestor_chain(current_script),
- query_version: self.dom_host.query_version(),
- }
- }
-
- fn is_handle_visible_at_parser_boundary(
- &self,
- handle: DomHandle,
- boundary: &ParserVisibilityBoundary,
- ) -> bool {
- if self.handle_is_statically_visible_at_parser_boundary(handle, boundary) {
- return true;
- }
-
- // The parser stream has already materialized nodes beyond the current
- // blocking script. A script can also insert real DOM nodes after its
- // own position, though, and those must be observable immediately. Find
- // the outermost subtree inserted since this parser boundary and judge
- // it by the visibility of its insertion parent. This preserves the
- // parser frontier without snapshotting or rescanning the whole DOM.
- let chain = self.ancestor_chain(handle);
- let Some(inserted_root_index) = chain.iter().position(|candidate| {
- self.dom_host
- .tree_insertion_version(*candidate)
- .is_some_and(|version| version > boundary.query_version)
- }) else {
- return false;
- };
- inserted_root_index
- .checked_sub(1)
- .and_then(|parent_index| chain.get(parent_index))
- .is_some_and(|parent| {
- self.handle_is_statically_visible_at_parser_boundary(*parent, boundary)
- })
- }
-
- fn handle_is_statically_visible_at_parser_boundary(
- &self,
- handle: DomHandle,
- boundary: &ParserVisibilityBoundary,
- ) -> bool {
- handle == boundary.current_script
- || self.dom_host.root_node_handle(handle) != Some(boundary.document)
- || self.precedes_in_document_order_against_ancestor_chain(
- handle,
- &boundary.current_script_ancestor_chain,
- )
- }
}
#[cfg(test)]
@@ -796,90 +718,6 @@ mod tests {
)
}
- #[test]
- fn parser_visibility_boundary_preserves_document_order_without_materializing_future_nodes() {
- let document = HtmlParser.parse(
- Url::parse("https://example.com/").unwrap(),
- concat!(
- "<!doctype html><html><head></head><body>",
- "<section id='before'><span id='before-child'></span></section>",
- "<script id='current'>window.ready = true;</script>",
- "<article id='after'><span id='after-child'></span></article>",
- "</body></html>"
- )
- .to_owned(),
- );
- let mut runtime = DocumentRuntime::new(&document);
- let current = runtime
- .dom_host()
- .element_handle_by_id("current")
- .expect("current script");
- let before = runtime
- .dom_host()
- .element_handle_by_id("before")
- .expect("preceding element");
- let before_child = runtime
- .dom_host()
- .element_handle_by_id("before-child")
- .expect("preceding descendant");
- let after = runtime
- .dom_host()
- .element_handle_by_id("after")
- .expect("following element");
- let after_child = runtime
- .dom_host()
- .element_handle_by_id("after-child")
- .expect("following descendant");
- let script_text = runtime
- .dom_host()
- .first_child(current)
- .expect("script text child");
- let detached = runtime.dom_host_mut().create_element("aside");
- let boundary = runtime.begin_parser_visibility_boundary(current);
-
- assert_eq!(boundary.current_script, current);
- assert_eq!(
- boundary.current_script_ancestor_chain.last(),
- Some(&current)
- );
- assert!(boundary.current_script_ancestor_chain.len() < 8);
- for visible in [boundary.document, before, before_child, current, detached] {
- assert!(
- runtime.is_handle_visible_at_parser_boundary(visible, &boundary),
- "expected {visible:?} to be parser-visible"
- );
- }
- for hidden in [script_text, after, after_child] {
- assert!(
- !runtime.is_handle_visible_at_parser_boundary(hidden, &boundary),
- "expected {hidden:?} to remain behind the parser boundary"
- );
- }
-
- let body = runtime.dom_host().document_body_handle().expect("body");
- assert!(runtime.dom_host_mut().append_child(body, detached));
- let dynamic = runtime.dom_host_mut().create_element("strong");
- assert!(runtime.dom_host_mut().append_child(body, dynamic));
- let dynamic_under_hidden = runtime.dom_host_mut().create_element("em");
- assert!(
- runtime
- .dom_host_mut()
- .append_child(after, dynamic_under_hidden)
- );
-
- for visible in [detached, dynamic] {
- assert!(
- runtime.is_handle_visible_at_parser_boundary(visible, &boundary),
- "expected dynamically inserted {visible:?} to be parser-visible"
- );
- }
- assert!(
- !runtime.is_handle_visible_at_parser_boundary(dynamic_under_hidden, &boundary),
- "a dynamic child must not expose its parser-hidden insertion parent"
- );
- runtime.dom_host().end_tree_insertion_tracking();
- }
-
#[test]
fn runtime_binding_queue_is_drained_once() {
let document = HtmlParser.parse(
diff --git a/moli-renderer-v8/src/document_runtime/main_parser_continuation.rs b/moli-renderer-v8/src/document_runtime/main_parser_continuation.rs
index d8b1e625a..c48e03432 100644
--- a/moli-renderer-v8/src/document_runtime/main_parser_continuation.rs
+++ b/moli-renderer-v8/src/document_runtime/main_parser_continuation.rs
@@ -126,6 +126,10 @@ impl DocumentRuntime {
std::mem::take(&mut self.main_parser_continuation.admitted)
}
+ pub(crate) fn has_main_parser_continuation_admission(&self) -> bool {
+ self.main_parser_continuation.admitted
+ }
+
pub(super) fn reset_main_parser_continuation_for_document_replacement(&mut self) {
self.main_parser_continuation
.reset_for_document_replacement();
diff --git a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/tree_order.rs b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/tree_order.rs
index b6ddf25cb..ade5a782e 100644
--- a/moli-renderer-v8/src/document_runtime/mutation_commands/tree/tree_order.rs
+++ b/moli-renderer-v8/src/document_runtime/mutation_commands/tree/tree_order.rs
@@ -33,6 +33,7 @@ impl DocumentRuntime {
self.precedes_in_document_order_against_ancestor_chain(left, &right_chain)
}
+ #[cfg(test)]
pub(in crate::document_runtime) fn precedes_in_document_order_against_ancestor_chain(
&self,
left: DomHandle,
@@ -71,6 +72,7 @@ impl DocumentRuntime {
false
}
+ #[cfg(test)]
pub(in crate::document_runtime) fn ancestor_chain(&self, node: DomHandle) -> Vec<DomHandle> {
let mut chain = Vec::new();
let mut current = Some(node);
diff --git a/moli-renderer-v8/src/document_runtime/query_facade.rs b/moli-renderer-v8/src/document_runtime/query_facade.rs
index 3842378a2..1cc46afc0 100644
--- a/moli-renderer-v8/src/document_runtime/query_facade.rs
+++ b/moli-renderer-v8/src/document_runtime/query_facade.rs
@@ -10,7 +10,6 @@ static HOT_SELECTOR_API_TRACE_COUNT: AtomicU32 = AtomicU32::new(0);
//
// It is intentionally separate from the low-level DOM facade and the mutation commands because it
// is the one place where `DocumentRuntime` combines:
-// - parser-visibility filtering
// - selector-engine entrypoints
// - selector-specific debug counters / hot-call tracing
//
@@ -32,10 +31,7 @@ impl DocumentRuntime {
root,
selector,
)?;
- Ok(self
- .filter_parser_visible_handles(handles)
- .into_iter()
- .next())
+ Ok(handles.into_iter().next())
} else {
self.selector_engine
.query_selector_in_host(&self.dom_host, root, selector)
@@ -61,11 +57,7 @@ impl DocumentRuntime {
root,
selector,
)?;
- if self.dom_host.node(root).is_some_and(Node::is_document) {
- Ok(self.filter_parser_visible_handles(handles))
- } else {
- Ok(handles)
- }
+ Ok(handles)
}
None => self
.selector_engine
diff --git a/moli-renderer-v8/src/document_runtime/runtime_core.rs b/moli-renderer-v8/src/document_runtime/runtime_core.rs
index 021b5819d..747bca3ca 100644
--- a/moli-renderer-v8/src/document_runtime/runtime_core.rs
+++ b/moli-renderer-v8/src/document_runtime/runtime_core.rs
@@ -86,6 +86,7 @@ impl DocumentRuntime {
document_open_generation: None,
next_document_write_external_script_load_id: 0,
document_write_script_preload_scanner: None,
+ main_document_script_preloads: Default::default(),
document_write_script_preloads: HashMap::new(),
pending_document_write_external_script_load: None,
pending_document_write_stylesheet_blocked_script: None,
@@ -205,6 +206,7 @@ impl DocumentRuntime {
document_open_generation: _,
next_document_write_external_script_load_id: _,
document_write_script_preload_scanner: _,
+ main_document_script_preloads: _,
document_write_script_preloads: _,
pending_document_write_external_script_load: _,
pending_document_write_stylesheet_blocked_script: _,
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling.rs b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
index a1325d563..e84079464 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling.rs
@@ -108,12 +108,11 @@ mod tests {
NativeDom,
Vec<crate::DocumentOwnedBlockingStylesheetDiscoveryInput>,
) {
- let (document, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
+ let (document, _, inputs) = crate::parse_html_test_fixture_with_parser_outputs(
Url::parse("https://example.com/").unwrap(),
html.to_owned(),
);
- let (_, inputs) = handoffs.into_parts();
- (document.into_dom(), inputs)
+ (document, inputs)
}
fn prepared_script(position: usize, node_index: usize, mode: ScriptMode) -> PreparedScript {
diff --git a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
index f7912a1a3..0522e3281 100644
--- a/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
+++ b/moli-renderer-v8/src/document_runtime/script_scheduling/document_write_scripts.rs
@@ -7,6 +7,10 @@ use crate::planning::{PreparedScriptRuntimeGeneration, ScriptSource};
use crate::script_vm::perform_microtask_checkpoint_and_report_pending_promise_rejections;
use crate::types::ScriptKind;
use crate::util::create_script_origin;
+use crate::v8_execution_watchdog::{
+ SCRIPT_TURN_WATCHDOG_TIMEOUT, V8ExecutionWatchdog, V8ExecutionWatchdogKind,
+ V8ExecutionWatchdogOutcome,
+};
use crate::{context_bootstrap, native_bridge};
use tracing::debug;
@@ -147,6 +151,11 @@ impl DocumentRuntime {
"parser-created top-level script execution requires the page main-world context",
);
let scope = &mut v8::ContextScope::new(scope, default_context);
+ let watchdog = V8ExecutionWatchdog::arm(
+ V8ExecutionWatchdogKind::ScriptTurn,
+ scope.thread_safe_handle(),
+ SCRIPT_TURN_WATCHDOG_TIMEOUT,
+ );
let run_result = {
let _parser_script_nesting = self.enter_parser_script_nesting();
(|| {
@@ -156,8 +165,16 @@ impl DocumentRuntime {
script.run(scope)
})()
};
+ let script_timed_out = watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut;
self.clear_current_script_handle();
if run_result.is_none() {
+ if script_timed_out {
+ tracing::warn!(
+ host_script_handle,
+ timeout = ?SCRIPT_TURN_WATCHDOG_TIMEOUT,
+ "document.write script execution exceeded its deadline and was terminated"
+ );
+ }
return;
}
match current_script_event_behavior {
@@ -174,7 +191,19 @@ impl DocumentRuntime {
}
}
}
+ let watchdog = V8ExecutionWatchdog::arm(
+ V8ExecutionWatchdogKind::ScriptTurn,
+ scope.thread_safe_handle(),
+ SCRIPT_TURN_WATCHDOG_TIMEOUT,
+ );
perform_document_write_microtask_checkpoints(scope);
+ if watchdog.disarm() == V8ExecutionWatchdogOutcome::TimedOut {
+ tracing::warn!(
+ host_script_handle,
+ timeout = ?SCRIPT_TURN_WATCHDOG_TIMEOUT,
+ "document.write script microtask checkpoint exceeded its deadline and was terminated"
+ );
+ }
}
fn execute_document_write_prepared_script(
diff --git a/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs b/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
index b450893cc..f243e3a8a 100644
--- a/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
+++ b/moli-renderer-v8/src/document_script_scheduler/page_task_adapter.rs
@@ -271,7 +271,7 @@ mod tests {
async fn parser_defer_finalization_preserves_handoff_stylesheet_snapshot() {
let document_url =
Url::parse("https://post-parse.test/page.html").expect("test document URL");
- let (mut document, handoffs) = HtmlParser.parse_dom_host_with_script_handoffs(
+ let (mut document, handoffs, _) = crate::parse_html_test_fixture_with_parser_outputs(
document_url,
concat!(
"<!doctype html><link rel='stylesheet' href='/before.css'>",
@@ -290,7 +290,7 @@ mod tests {
assert_eq!(blocking_signatures_before.len(), 1);
let link = document
- .elements_by_tag_name(document.document_handle(), "link", false)
+ .elements_by_tag_name(document.document_node_id(), "link", false)
.into_iter()
.next()
.expect("stylesheet link");
diff --git a/moli-renderer-v8/src/frame_owner_model/classic_script_tasks.rs b/moli-renderer-v8/src/frame_owner_model/classic_script_tasks.rs
index b05406a8e..8cf7db9f6 100644
--- a/moli-renderer-v8/src/frame_owner_model/classic_script_tasks.rs
+++ b/moli-renderer-v8/src/frame_owner_model/classic_script_tasks.rs
@@ -124,6 +124,7 @@ pub(crate) enum FrameDocumentClassicPrepareDropReason {
StaleDocumentOwner,
BeginExecutionUnavailable,
ExecutionActionUnavailable,
+ StaleParserSuspension,
}
#[derive(Debug, Clone)]
@@ -453,6 +454,7 @@ pub(crate) struct FrameDocumentClassicParserResumeApplication {
pub(crate) enum FrameDocumentClassicParserResumeSkipReason {
StaleDocumentOwner,
StaleRealm,
+ StaleParserSuspension,
MissingCurrentChildSnapshot,
MissingLiveParser,
}
diff --git a/moli-renderer-v8/src/lib.rs b/moli-renderer-v8/src/lib.rs
index 63e380472..59f4db242 100644
--- a/moli-renderer-v8/src/lib.rs
+++ b/moli-renderer-v8/src/lib.rs
@@ -130,6 +130,33 @@ pub(crate) const fn real_layout_test_policy() -> moli_page_types::LayoutPolicy {
moli_page_types::LayoutPolicy::OnDemand
}
+/// Builds an owned HTML fixture through the same incremental parser frontier
+/// used by executable Documents while retaining parser-time discovery output
+/// needed by unit tests. This is deliberately test-only: production code must
+/// keep the live parser session and deliver each handoff at its source boundary.
+#[cfg(test)]
+pub(crate) fn parse_html_test_fixture_with_parser_outputs(
+ final_url: url::Url,
+ html: String,
+) -> (
+ dom::native::NativeDom,
+ Vec<parser::ParserScriptHandoff>,
+ Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
+) {
+ let mut stream = parser::HtmlParser.start_document(final_url);
+ stream.append_to_end(html);
+ let mut scripts = Vec::new();
+ let mut blocking_stylesheets = Vec::new();
+ while stream.has_pending_input() {
+ let outcome = stream.pump_next_parser_step(0);
+ blocking_stylesheets.extend(outcome.discovered_blocking_stylesheet_inputs);
+ if let parser::ParserPumpStep::Yield(parser::ParserYield::Script(script)) = outcome.result {
+ scripts.push(*script);
+ }
+ }
+ (stream.finish(), scripts, blocking_stylesheets)
+}
+
#[allow(unused_imports)]
pub(crate) use crate::script_planning::{
ParserPlanningReadView, ParserScriptRead, PrepareScriptOutcome, PreparedScript,
@@ -209,13 +236,13 @@ pub use runtime::{
RendererDocumentQuerySelectorWithChildNodeSnapshotEvents,
RendererDocumentSourcedSameDocumentNavigation,
RendererDocumentSourcedTopLevelLocationNavigation, RendererDocumentTerminationReason,
- RendererDocumentToken, RendererDomAttributeMutation, RendererDomAttributeMutationOutcome,
- RendererDomBidiNodeBindingResolution, RendererDomBidiNodeSharedIdResolution,
- RendererDomDebuggerDomBreakpointResolution, RendererDomDebuggerEventListener,
- RendererDomDebuggerEventListenerBreakpoint, RendererDomDebuggerEventListenersResolution,
- RendererDomDebuggerXhrBreakpoint, RendererDomEdit, RendererDomEditOutcome,
- RendererDomFocusOutcome, RendererDomFrontendNodeBindingResolution, RendererDomMutationEvent,
- RendererDomMutationEventBatch, RendererDomNodeCreationStackFrame,
+ RendererDocumentTitleChanged, RendererDocumentToken, RendererDomAttributeMutation,
+ RendererDomAttributeMutationOutcome, RendererDomBidiNodeBindingResolution,
+ RendererDomBidiNodeSharedIdResolution, RendererDomDebuggerDomBreakpointResolution,
+ RendererDomDebuggerEventListener, RendererDomDebuggerEventListenerBreakpoint,
+ RendererDomDebuggerEventListenersResolution, RendererDomDebuggerXhrBreakpoint, RendererDomEdit,
+ RendererDomEditOutcome, RendererDomFocusOutcome, RendererDomFrontendNodeBindingResolution,
+ RendererDomMutationEvent, RendererDomMutationEventBatch, RendererDomNodeCreationStackFrame,
RendererDomNodeCreationStackTrace, RendererDomNodeStackTraceResolution,
RendererDomSearchRegistration, RendererDomSearchResultNode, RendererDomSearchResultsResolution,
RendererDomSnapshotCaptureOptions, RendererDomSnapshotCapturePayload, RendererDragData,
diff --git a/moli-renderer-v8/src/live_document_parser.rs b/moli-renderer-v8/src/live_document_parser.rs
index 2c4762e39..b4594910d 100644
--- a/moli-renderer-v8/src/live_document_parser.rs
+++ b/moli-renderer-v8/src/live_document_parser.rs
@@ -1,17 +1,23 @@
use crate::{
DocumentOwnedBlockingStylesheetDiscoveryInput,
- dom::native::NativeNodeId,
+ dom::native::{DomHost, NativeNodeId},
+ frame_owner_model::FrameDocumentTaskOwner,
parser::{
DocumentStream, HtmlParser, ParserBlockingStylesheetPause,
ParserCustomElementConstructionHandoff, ParserDomMutationConsumer, ParserDomReadConsumer,
ParserElementCreationConsumer, ParserMutationEffectConsumer, ParserPumpOutcome,
- ParserPumpStep, ParserScriptHandoff, ParserYield, PreparedScript,
+ ParserPumpStep, ParserScriptHandoff, ParserYield, PreparedScript, XmlDocumentStream,
},
};
-use std::{cell::RefCell, collections::VecDeque, rc::Rc};
+use std::{
+ cell::RefCell,
+ rc::Rc,
+ sync::atomic::{AtomicU64, Ordering},
+};
use url::Url;
pub(crate) type DocumentParserStreamHandle = Rc<RefCell<DocumentStream>>;
+type XmlDocumentParserStreamHandle = Rc<RefCell<XmlDocumentStream>>;
fn new_document_parser_stream_handle(stream: DocumentStream) -> DocumentParserStreamHandle {
Rc::new(RefCell::new(stream))
@@ -25,6 +31,7 @@ pub(crate) trait LiveDocumentParserOwner:
{
}
+#[cfg(test)]
fn pump_live_document_parser_step(
stream: &mut DocumentStream,
chunk: &str,
@@ -33,6 +40,14 @@ fn pump_live_document_parser_step(
stream.pump_parser_step_with_runtime_dom_consumer(chunk, owner)
}
+fn pump_next_live_document_parser_step(
+ stream: &mut DocumentStream,
+ max_bytes: usize,
+ owner: &mut impl LiveDocumentParserOwner,
+) -> ParserPumpOutcome {
+ stream.pump_next_parser_step_with_runtime_dom_consumer(max_bytes, owner)
+}
+
pub(crate) enum LiveDocumentParserStepOutcome {
/// The current parser input was consumed without producing a synchronous
/// parser lifecycle handoff.
@@ -80,6 +95,7 @@ impl LiveDocumentParserDiscoverySignals {
}
impl LiveDocumentParserStepAdvance {
+ #[cfg(test)]
fn split(
self,
) -> (
@@ -90,6 +106,7 @@ impl LiveDocumentParserStepAdvance {
}
}
+#[cfg(test)]
fn advance_live_document_parser_step<Driver>(
stream: &mut DocumentStream,
parser_step: &str,
@@ -98,14 +115,34 @@ fn advance_live_document_parser_step<Driver>(
where
Driver: LiveDocumentParserOwner,
{
+ let outcome = pump_live_document_parser_step(stream, parser_step, driver);
+ let parser_meta_csp_candidates = stream.drain_discovered_parser_meta_csp_candidates();
+ live_document_parser_advance_from_outcome(outcome, parser_meta_csp_candidates)
+}
+
+fn advance_next_live_document_parser_step<Driver>(
+ stream: &mut DocumentStream,
+ max_bytes: usize,
+ driver: &mut Driver,
+) -> LiveDocumentParserStepAdvance
+where
+ Driver: LiveDocumentParserOwner,
+{
+ let outcome = pump_next_live_document_parser_step(stream, max_bytes, driver);
+ let parser_meta_csp_candidates = stream.drain_discovered_parser_meta_csp_candidates();
+ live_document_parser_advance_from_outcome(outcome, parser_meta_csp_candidates)
+}
+
+fn live_document_parser_advance_from_outcome(
+ outcome: ParserPumpOutcome,
+ discovered_parser_meta_csp_candidates: Vec<NativeNodeId>,
+) -> LiveDocumentParserStepAdvance {
let ParserPumpOutcome {
result,
discovered_async_prefetch_scripts,
discovered_modulepreload_link_candidates,
discovered_blocking_stylesheet_inputs,
- } = pump_live_document_parser_step(stream, parser_step, driver);
- let discovered_parser_meta_csp_candidates =
- stream.drain_discovered_parser_meta_csp_candidates();
+ } = outcome;
let discovery_signals = LiveDocumentParserDiscoverySignals {
async_prefetch_scripts: discovered_async_prefetch_scripts,
modulepreload_link_candidates: discovered_modulepreload_link_candidates,
@@ -140,126 +177,317 @@ pub(crate) enum DocumentParserLifetime {
Closing,
}
-/// The canonical runtime owner of one live document parser.
-///
-/// Root and child documents store this same type. A `ParserInsertionController`
-/// is only a temporary reentrant capability derived from its stream handle; it
-/// does not own parser lifetime or suspension state.
-pub(crate) struct DocumentParserSession {
- stream: DocumentParserStreamHandle,
- input: ParserInputBuffer,
- discovery_signals: LiveDocumentParserDiscoverySignals,
- lifetime: DocumentParserLifetime,
- waiting_for_blocking_stylesheet: bool,
- waiting_for_parser_script: bool,
+static NEXT_DOCUMENT_PARSER_SESSION_ID: AtomicU64 = AtomicU64::new(1);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct ParserSessionId(u64);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub(crate) struct ParserSuspensionId(u64);
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct DocumentParserOwnerIdentity {
+ document_owner: FrameDocumentTaskOwner,
+ runtime_generation: u64,
}
-impl std::fmt::Debug for DocumentParserSession {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- formatter
- .debug_struct("DocumentParserSession")
- .field("lifetime", &self.lifetime)
- .field(
- "waiting_for_blocking_stylesheet",
- &self.waiting_for_blocking_stylesheet,
- )
- .field("waiting_for_parser_script", &self.waiting_for_parser_script)
- .finish_non_exhaustive()
+impl DocumentParserOwnerIdentity {
+ fn new(document_owner: FrameDocumentTaskOwner, runtime_generation: u64) -> Self {
+ Self {
+ document_owner,
+ runtime_generation,
+ }
}
}
-pub(crate) struct ParserInputBuffer {
- queued_chunks: VecDeque<String>,
- current_chunk: Option<String>,
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ParserSuspensionCause {
+ ParserClassicSource { script: NativeNodeId },
+ ParserClassicStylesheets { script: NativeNodeId },
+ ParserCreatedStylesheet { owner: NativeNodeId },
+ DocumentWriteExternalScript { script: NativeNodeId },
}
-impl ParserInputBuffer {
- pub(crate) fn new() -> Self {
- Self {
- queued_chunks: VecDeque::new(),
- current_chunk: None,
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct ParserSuspension {
+ id: ParserSuspensionId,
+ cause: ParserSuspensionCause,
+ parser_commit_epoch: u64,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct ParserResumePermit {
+ owner_identity: Option<DocumentParserOwnerIdentity>,
+ session_id: ParserSessionId,
+ suspension_id: ParserSuspensionId,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ParserStopReason {
+ DocumentReplacement,
+ MainResourceLoadFailure,
+ OwnerDropped,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum DocumentParserRunState {
+ Ready,
+ Pumping {
+ epoch: u64,
+ },
+ Suspended {
+ id: ParserSuspensionId,
+ cause: ParserSuspensionCause,
+ parser_commit_epoch: u64,
+ },
+ Finishing,
+ Finished,
+ Stopped(ParserStopReason),
+}
+
+impl From<ParserSuspension> for DocumentParserRunState {
+ fn from(suspension: ParserSuspension) -> Self {
+ Self::Suspended {
+ id: suspension.id,
+ cause: suspension.cause,
+ parser_commit_epoch: suspension.parser_commit_epoch,
}
}
+}
- pub(crate) fn queue_arrived_chunk(&mut self, html: String) {
- if !html.is_empty() {
- self.queued_chunks.push_back(html);
+impl DocumentParserRunState {
+ fn suspension(self) -> Option<ParserSuspension> {
+ match self {
+ Self::Suspended {
+ id,
+ cause,
+ parser_commit_epoch,
+ } => Some(ParserSuspension {
+ id,
+ cause,
+ parser_commit_epoch,
+ }),
+ _ => None,
}
}
+}
- pub(crate) fn ensure_current_chunk(&mut self, stream: &DocumentStream) {
- if let Some(script_input_html) = DocumentParserDriver::take_next_script_input(stream) {
- if let Some(network_chunk) = self.current_chunk.take()
- && !network_chunk.is_empty()
- {
- self.queued_chunks.push_front(network_chunk);
- }
- self.current_chunk = Some(script_input_html);
- return;
- }
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ParserResumeApplication {
+ Resumed,
+ RejectedSession,
+ RejectedOwner,
+ RejectedSuspension,
+ ParserNotSuspended,
+}
- if self.current_chunk.is_none() {
- self.current_chunk = self.queued_chunks.pop_front();
+#[derive(Debug)]
+struct DocumentParserSessionControl {
+ session_id: ParserSessionId,
+ owner_identity: Option<DocumentParserOwnerIdentity>,
+ next_suspension_id: u64,
+ next_pump_epoch: u64,
+ parser_commit_epoch: u64,
+ run_state: DocumentParserRunState,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct DocumentParserSessionControlHandle(Rc<RefCell<DocumentParserSessionControl>>);
+
+impl DocumentParserSessionControlHandle {
+ pub(crate) fn new() -> Self {
+ let session_id =
+ ParserSessionId(NEXT_DOCUMENT_PARSER_SESSION_ID.fetch_add(1, Ordering::Relaxed));
+ Self(Rc::new(RefCell::new(DocumentParserSessionControl {
+ session_id,
+ owner_identity: None,
+ next_suspension_id: 1,
+ next_pump_epoch: 1,
+ parser_commit_epoch: 0,
+ run_state: DocumentParserRunState::Ready,
+ })))
+ }
+
+ pub(crate) fn session_id(&self) -> ParserSessionId {
+ self.0.borrow().session_id
+ }
+
+ pub(crate) fn run_state(&self) -> DocumentParserRunState {
+ self.0.borrow().run_state
+ }
+
+ fn bind_owner(&self, owner_identity: DocumentParserOwnerIdentity) {
+ let mut control = self.0.borrow_mut();
+ match control.owner_identity {
+ None => control.owner_identity = Some(owner_identity),
+ Some(current) => assert_eq!(
+ current, owner_identity,
+ "one live parser session cannot be rebound to a different Document owner"
+ ),
}
}
- pub(crate) fn is_empty(&self) -> bool {
- self.current_chunk.is_none() && self.queued_chunks.is_empty()
+ pub(crate) fn suspend(&self, cause: ParserSuspensionCause) -> ParserResumePermit {
+ let mut control = self.0.borrow_mut();
+ assert_eq!(
+ control.run_state,
+ DocumentParserRunState::Ready,
+ "only a ready live parser session can enter a persistent suspension"
+ );
+ let suspension_id = ParserSuspensionId(control.next_suspension_id);
+ control.next_suspension_id = control.next_suspension_id.wrapping_add(1).max(1);
+ let suspension = ParserSuspension {
+ id: suspension_id,
+ cause,
+ parser_commit_epoch: control.parser_commit_epoch,
+ };
+ control.run_state = suspension.into();
+ ParserResumePermit {
+ owner_identity: control.owner_identity,
+ session_id: control.session_id,
+ suspension_id,
+ }
}
- pub(crate) fn current_chunk_len(&self) -> usize {
- self.current_chunk.as_ref().map_or(0, |chunk| chunk.len())
+ pub(crate) fn current_resume_permit(&self) -> Option<ParserResumePermit> {
+ let control = self.0.borrow();
+ let suspension = control.run_state.suspension()?;
+ Some(ParserResumePermit {
+ owner_identity: control.owner_identity,
+ session_id: control.session_id,
+ suspension_id: suspension.id,
+ })
}
- pub(crate) fn current_chunk_is_none(&self) -> bool {
- self.current_chunk.is_none()
+ pub(crate) fn resume(&self, permit: ParserResumePermit) -> ParserResumeApplication {
+ let mut control = self.0.borrow_mut();
+ if permit.session_id != control.session_id {
+ return ParserResumeApplication::RejectedSession;
+ }
+ if permit.owner_identity != control.owner_identity {
+ return ParserResumeApplication::RejectedOwner;
+ }
+ let Some(suspension) = control.run_state.suspension() else {
+ return ParserResumeApplication::ParserNotSuspended;
+ };
+ if suspension.id != permit.suspension_id {
+ return ParserResumeApplication::RejectedSuspension;
+ }
+ control.run_state = DocumentParserRunState::Ready;
+ ParserResumeApplication::Resumed
}
- pub(crate) fn current_chunk_is_empty(&self) -> bool {
- self.current_chunk
- .as_ref()
- .is_some_and(|chunk| chunk.is_empty())
+ pub(crate) fn begin_pump(&self) -> DocumentParserPumpGuard {
+ let mut control = self.0.borrow_mut();
+ assert_eq!(
+ control.run_state,
+ DocumentParserRunState::Ready,
+ "a live parser may only pump from the ready state"
+ );
+ let epoch = control.next_pump_epoch;
+ control.next_pump_epoch = control.next_pump_epoch.wrapping_add(1).max(1);
+ control.parser_commit_epoch = control.parser_commit_epoch.wrapping_add(1);
+ control.run_state = DocumentParserRunState::Pumping { epoch };
+ drop(control);
+ DocumentParserPumpGuard {
+ control: self.clone(),
+ epoch,
+ }
}
- pub(crate) fn take_current_chunk(&mut self) -> String {
- self.current_chunk.take().unwrap_or_default()
+ fn begin_finish(&self) {
+ let mut control = self.0.borrow_mut();
+ assert_eq!(
+ control.run_state,
+ DocumentParserRunState::Ready,
+ "a suspended or stopped live parser cannot finish"
+ );
+ control.run_state = DocumentParserRunState::Finishing;
}
- pub(crate) fn set_current_chunk(&mut self, chunk: Option<String>) {
- self.current_chunk = chunk;
+ fn finish(&self) {
+ let mut control = self.0.borrow_mut();
+ assert_eq!(
+ control.run_state,
+ DocumentParserRunState::Finishing,
+ "parser finish must complete the active finishing transition"
+ );
+ control.run_state = DocumentParserRunState::Finished;
}
- #[cfg(test)]
- pub(crate) fn set_current_chunk_for_testing(&mut self, chunk: Option<String>) {
- self.current_chunk = chunk;
+ pub(crate) fn stop(&self, reason: ParserStopReason) {
+ let mut control = self.0.borrow_mut();
+ if !matches!(
+ control.run_state,
+ DocumentParserRunState::Finished | DocumentParserRunState::Stopped(_)
+ ) {
+ control.run_state = DocumentParserRunState::Stopped(reason);
+ }
}
+}
- #[cfg(test)]
- pub(crate) fn current_chunk_for_testing(&self) -> Option<&str> {
- self.current_chunk.as_deref()
- }
+pub(crate) struct DocumentParserPumpGuard {
+ control: DocumentParserSessionControlHandle,
+ epoch: u64,
+}
- #[cfg(test)]
- pub(crate) fn current_chunk_is_non_empty_for_testing(&self) -> bool {
- self.current_chunk
- .as_ref()
- .is_some_and(|chunk| !chunk.is_empty())
+impl Drop for DocumentParserPumpGuard {
+ fn drop(&mut self) {
+ let mut control = self.control.0.borrow_mut();
+ if control.run_state == (DocumentParserRunState::Pumping { epoch: self.epoch }) {
+ control.run_state = DocumentParserRunState::Ready;
+ }
}
+}
- #[cfg(test)]
- pub(crate) fn queued_chunk_count_for_testing(&self) -> usize {
- self.queued_chunks.len()
+/// The canonical runtime owner of one live document parser.
+///
+/// Root and child documents store this same type. A `ParserInsertionController`
+/// is only a temporary reentrant capability derived from its stream handle; it
+/// does not own parser lifetime or suspension state.
+enum ExecutableDocumentParserBackend {
+ Html(DocumentParserStreamHandle),
+ Xml(XmlDocumentParserStreamHandle),
+}
+
+impl ExecutableDocumentParserBackend {
+ fn name(&self) -> &'static str {
+ match self {
+ Self::Html(_) => "html",
+ Self::Xml(_) => "xml",
+ }
}
+}
- #[cfg(test)]
- pub(crate) fn queued_front_for_testing(&self) -> Option<&str> {
- self.queued_chunks.front().map(String::as_str)
+pub(crate) struct DocumentParserSession {
+ backend: Option<ExecutableDocumentParserBackend>,
+ discovery_signals: LiveDocumentParserDiscoverySignals,
+ lifetime: DocumentParserLifetime,
+ control: DocumentParserSessionControlHandle,
+}
+
+impl std::fmt::Debug for DocumentParserSession {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("DocumentParserSession")
+ .field(
+ "backend",
+ &self
+ .backend
+ .as_ref()
+ .map(ExecutableDocumentParserBackend::name),
+ )
+ .field("lifetime", &self.lifetime)
+ .field("session_id", &self.control.session_id())
+ .field("run_state", &self.control.run_state())
+ .finish_non_exhaustive()
}
}
struct DocumentParserDriver;
impl DocumentParserDriver {
+ #[cfg(test)]
fn advance_step(
stream: &mut DocumentStream,
parser_step: &str,
@@ -268,6 +496,14 @@ impl DocumentParserDriver {
advance_live_document_parser_step(stream, parser_step, owner)
}
+ fn advance_next_step(
+ stream: &mut DocumentStream,
+ max_bytes: usize,
+ owner: &mut impl LiveDocumentParserOwner,
+ ) -> LiveDocumentParserStepAdvance {
+ advance_next_live_document_parser_step(stream, max_bytes, owner)
+ }
+
fn note_defined_autonomous_custom_elements(
stream: &mut DocumentStream,
names: impl IntoIterator<Item = String>,
@@ -285,33 +521,11 @@ impl DocumentParserDriver {
stream.take_processed_insertion_meta_csp_count()
}
- fn take_next_script_input(stream: &DocumentStream) -> Option<String> {
- stream.take_next_script_input()
- }
-
fn has_script_input(stream: &DocumentStream) -> bool {
stream.has_script_input()
}
- fn take_buffered_input(stream: &mut DocumentStream) -> String {
- stream.take_buffered_input()
- }
-
- fn take_buffered_input_with_tail(
- stream: &mut DocumentStream,
- tail: Option<String>,
- ) -> Option<String> {
- let mut input = Self::take_buffered_input(stream);
- if let Some(tail) = tail {
- input.push_str(&tail);
- }
- (!input.is_empty()).then_some(input)
- }
-
- fn peek_buffered_input(stream: &mut DocumentStream) -> String {
- stream.peek_buffered_input()
- }
-
+ #[cfg(test)]
fn take_null_custom_element_registry_elements(
stream: &mut DocumentStream,
) -> Vec<NativeNodeId> {
@@ -328,45 +542,122 @@ impl DocumentParserDriver {
impl DocumentParserSession {
pub(crate) fn start_main_document(document_url: Url) -> Self {
- Self::new(
+ Self::new_html(
HtmlParser.start_document(document_url),
DocumentParserLifetime::Finite,
)
}
+ pub(crate) fn start_main_xml_document(document_url: Url) -> Self {
+ Self::new_xml(
+ XmlDocumentStream::new_top_level_document(document_url),
+ DocumentParserLifetime::Finite,
+ )
+ }
+
pub(crate) fn start_finite_live_document(
document_url: Url,
document_handle: NativeNodeId,
) -> Self {
- Self::new(
+ Self::new_html(
HtmlParser.start_live_document_root(document_url, document_handle),
DocumentParserLifetime::Finite,
)
}
+ pub(crate) fn start_finite_live_xml_document(
+ document_url: Url,
+ document_handle: NativeNodeId,
+ ) -> Self {
+ Self::new_xml(
+ XmlDocumentStream::new_live_document_root(document_url, document_handle),
+ DocumentParserLifetime::Finite,
+ )
+ }
+
pub(crate) fn start_open_live_document(
document_url: Url,
document_handle: NativeNodeId,
) -> Self {
- Self::new(
+ Self::new_html(
HtmlParser.start_live_document_root(document_url, document_handle),
DocumentParserLifetime::Open,
)
}
- fn new(stream: DocumentStream, lifetime: DocumentParserLifetime) -> Self {
+ fn new_html(stream: DocumentStream, lifetime: DocumentParserLifetime) -> Self {
Self {
- stream: new_document_parser_stream_handle(stream),
- input: ParserInputBuffer::new(),
+ backend: Some(ExecutableDocumentParserBackend::Html(
+ new_document_parser_stream_handle(stream),
+ )),
discovery_signals: LiveDocumentParserDiscoverySignals::default(),
lifetime,
- waiting_for_blocking_stylesheet: false,
- waiting_for_parser_script: false,
+ control: DocumentParserSessionControlHandle::new(),
}
}
+ fn new_xml(stream: XmlDocumentStream, lifetime: DocumentParserLifetime) -> Self {
+ Self {
+ backend: Some(ExecutableDocumentParserBackend::Xml(Rc::new(RefCell::new(
+ stream,
+ )))),
+ discovery_signals: LiveDocumentParserDiscoverySignals::default(),
+ lifetime,
+ control: DocumentParserSessionControlHandle::new(),
+ }
+ }
+
+ fn backend(&self) -> &ExecutableDocumentParserBackend {
+ self.backend
+ .as_ref()
+ .expect("a finished parser session no longer owns a backend")
+ }
+
+ pub(crate) fn bind_owner(
+ &mut self,
+ document_owner: FrameDocumentTaskOwner,
+ runtime_generation: u64,
+ ) {
+ self.control.bind_owner(DocumentParserOwnerIdentity::new(
+ document_owner,
+ runtime_generation,
+ ));
+ }
+
+ pub(crate) fn run_state(&self) -> DocumentParserRunState {
+ self.control.run_state()
+ }
+
+ pub(crate) fn control_handle(&self) -> DocumentParserSessionControlHandle {
+ self.control.clone()
+ }
+
+ pub(crate) fn suspend(&mut self, cause: ParserSuspensionCause) -> ParserResumePermit {
+ self.control.suspend(cause)
+ }
+
+ pub(crate) fn current_resume_permit(&self) -> Option<ParserResumePermit> {
+ self.control.current_resume_permit()
+ }
+
+ pub(crate) fn resume(&mut self, permit: ParserResumePermit) -> ParserResumeApplication {
+ self.control.resume(permit)
+ }
+
+ pub(crate) fn stop(&mut self, reason: ParserStopReason) {
+ self.control.stop(reason);
+ }
+
pub(crate) fn stream_handle(&self) -> DocumentParserStreamHandle {
- self.stream.clone()
+ self.html_stream_handle()
+ .expect("HTML parser stream requested from an XML document parser session")
+ }
+
+ pub(crate) fn html_stream_handle(&self) -> Option<DocumentParserStreamHandle> {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => Some(stream.clone()),
+ ExecutableDocumentParserBackend::Xml(_) => None,
+ }
}
pub(crate) fn lifetime(&self) -> DocumentParserLifetime {
@@ -388,58 +679,75 @@ impl DocumentParserSession {
)
}
- pub(crate) fn wait_for_blocking_stylesheet(&mut self) {
- self.waiting_for_blocking_stylesheet = true;
- }
-
- pub(crate) fn take_blocking_stylesheet_wait(&mut self) -> bool {
- std::mem::take(&mut self.waiting_for_blocking_stylesheet)
- }
-
- pub(crate) fn is_waiting_for_blocking_stylesheet(&self) -> bool {
- self.waiting_for_blocking_stylesheet
- }
-
- pub(crate) fn wait_for_parser_script(&mut self) {
- self.waiting_for_parser_script = true;
- }
-
- pub(crate) fn take_parser_script_wait(&mut self) -> bool {
- std::mem::take(&mut self.waiting_for_parser_script)
+ pub(crate) fn is_suspended(&self) -> bool {
+ matches!(self.run_state(), DocumentParserRunState::Suspended { .. })
}
- pub(crate) fn is_waiting_for_parser_script(&self) -> bool {
- self.waiting_for_parser_script
+ pub(crate) fn suspension_cause(&self) -> Option<ParserSuspensionCause> {
+ self.run_state().suspension().map(|pause| pause.cause)
}
pub(crate) fn has_exclusive_stream_handle(&self) -> bool {
- Rc::strong_count(&self.stream) == 1
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => Rc::strong_count(stream) == 1,
+ ExecutableDocumentParserBackend::Xml(stream) => Rc::strong_count(stream) == 1,
+ }
}
pub(crate) fn note_defined_autonomous_custom_elements(
&mut self,
names: impl IntoIterator<Item = String>,
) {
- DocumentParserDriver::note_defined_autonomous_custom_elements(
- &mut self.stream.borrow_mut(),
- names,
- );
+ if let ExecutableDocumentParserBackend::Html(stream) = self.backend() {
+ DocumentParserDriver::note_defined_autonomous_custom_elements(
+ &mut stream.borrow_mut(),
+ names,
+ );
+ }
}
- pub(crate) fn queue_arrived_chunk(&mut self, html: String) {
- self.input.queue_arrived_chunk(html);
+ pub(crate) fn queue_arrived_chunk(&mut self, source: String) {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ stream.borrow_mut().append_to_end(source);
+ }
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ stream.borrow_mut().append_to_end(source);
+ }
+ }
+ }
+
+ pub(crate) fn declare_eof(&mut self) {
+ if let ExecutableDocumentParserBackend::Xml(stream) = self.backend() {
+ stream.borrow_mut().declare_eof();
+ }
}
- pub(crate) fn ensure_current_chunk(&mut self) {
- self.input.ensure_current_chunk(&self.stream.borrow());
+ pub(crate) fn set_xml_document_content_type(&mut self, content_type: String) {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ stream.borrow_mut().set_document_content_type(content_type);
+ }
+ ExecutableDocumentParserBackend::Html(_) => {
+ panic!("XML content type applied to an HTML parser session")
+ }
+ }
}
pub(crate) fn has_script_input(&self) -> bool {
- DocumentParserDriver::has_script_input(&self.stream.borrow())
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ DocumentParserDriver::has_script_input(&stream.borrow())
+ }
+ ExecutableDocumentParserBackend::Xml(_) => false,
+ }
}
pub(crate) fn input_is_empty(&self) -> bool {
- self.input.is_empty()
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => !stream.borrow().has_pending_input(),
+ ExecutableDocumentParserBackend::Xml(stream) => !stream.borrow().has_pending_input(),
+ }
}
#[cfg(test)]
@@ -448,103 +756,173 @@ impl DocumentParserSession {
}
pub(crate) fn current_chunk_len(&self) -> usize {
- self.input.current_chunk_len()
- }
-
- pub(crate) fn current_chunk_is_none(&self) -> bool {
- self.input.current_chunk_is_none()
- }
-
- pub(crate) fn current_chunk_is_empty(&self) -> bool {
- self.input.current_chunk_is_empty()
- }
-
- pub(crate) fn take_current_chunk(&mut self) -> String {
- self.input.take_current_chunk()
- }
-
- pub(crate) fn set_current_chunk(&mut self, chunk: Option<String>) {
- self.input.set_current_chunk(chunk);
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => stream.borrow().next_input_len(),
+ ExecutableDocumentParserBackend::Xml(stream) => stream.borrow().next_input_len(),
+ }
}
pub(crate) fn take_next_insertion_preload_input(&self) -> Option<String> {
- DocumentParserDriver::take_next_insertion_preload_input(&self.stream.borrow())
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ DocumentParserDriver::take_next_insertion_preload_input(&stream.borrow())
+ }
+ ExecutableDocumentParserBackend::Xml(_) => None,
+ }
}
pub(crate) fn take_processed_insertion_meta_csp_count(&self) -> usize {
- DocumentParserDriver::take_processed_insertion_meta_csp_count(&self.stream.borrow())
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ DocumentParserDriver::take_processed_insertion_meta_csp_count(&stream.borrow())
+ }
+ ExecutableDocumentParserBackend::Xml(_) => 0,
+ }
}
- pub(crate) fn take_buffered_input_with_tail(&mut self, tail: Option<String>) -> Option<String> {
- DocumentParserDriver::take_buffered_input_with_tail(&mut self.stream.borrow_mut(), tail)
+ pub(crate) fn snapshot_pending_input(&self) -> String {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ stream.borrow().snapshot_pending_input()
+ }
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ stream.borrow().snapshot_pending_input()
+ }
+ }
}
- pub(crate) fn peek_buffered_input(&mut self) -> String {
- DocumentParserDriver::peek_buffered_input(&mut self.stream.borrow_mut())
+ pub(crate) fn advance_queued_or_resume_step(
+ &mut self,
+ owner: &mut impl LiveDocumentParserOwner,
+ ) -> LiveDocumentParserStepOutcome {
+ self.advance_next_step(0, owner)
}
- pub(crate) fn advance_queued_or_resume_step(
+ pub(crate) fn advance_next_step(
&mut self,
+ max_bytes: usize,
owner: &mut impl LiveDocumentParserOwner,
) -> LiveDocumentParserStepOutcome {
- self.ensure_current_chunk();
- let parser_step = self.input.take_current_chunk();
- self.advance_step(&parser_step, owner)
+ let _pump_guard = self.control.begin_pump();
+ let advance = match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ DocumentParserDriver::advance_next_step(&mut stream.borrow_mut(), max_bytes, owner)
+ }
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ let mut stream = stream.borrow_mut();
+ let outcome =
+ stream.pump_next_parser_step_with_runtime_dom_consumer(max_bytes, owner);
+ let parser_meta_csp_candidates =
+ stream.drain_discovered_parser_meta_csp_candidates();
+ live_document_parser_advance_from_outcome(outcome, parser_meta_csp_candidates)
+ }
+ };
+ self.discovery_signals.extend(advance.discovery_signals);
+ advance.outcome
}
+ #[cfg(test)]
pub(crate) fn advance_step_and_take_null_custom_element_registry_elements(
&mut self,
parser_step: &str,
owner: &mut impl LiveDocumentParserOwner,
) -> (LiveDocumentParserStepOutcome, Vec<NativeNodeId>) {
- let (advance, null_custom_element_registry_elements) =
- self.with_reentrant_stream_step(|stream| {
+ let _pump_guard = self.control.begin_pump();
+ let (advance, null_custom_element_registry_elements) = match self.backend() {
+ ExecutableDocumentParserBackend::Html(_) => self.with_reentrant_stream_step(|stream| {
let advance = DocumentParserDriver::advance_step(stream, parser_step, owner);
let null_custom_element_registry_elements =
DocumentParserDriver::take_null_custom_element_registry_elements(stream);
(advance, null_custom_element_registry_elements)
- });
+ }),
+ ExecutableDocumentParserBackend::Xml(_) => {
+ panic!("XML document parsers do not support HTML insertion input")
+ }
+ };
let (outcome, discovery_signals) = advance.split();
self.discovery_signals.extend(discovery_signals);
(outcome, null_custom_element_registry_elements)
}
- fn advance_step(
+ pub(crate) fn take_discovery_signals(&mut self) -> LiveDocumentParserDiscoverySignals {
+ std::mem::take(&mut self.discovery_signals)
+ }
+
+ pub(crate) fn with_parser_stream_dom_host_for_bootstrap<R>(
&mut self,
- parser_step: &str,
- owner: &mut impl LiveDocumentParserOwner,
- ) -> LiveDocumentParserStepOutcome {
- let advance =
- DocumentParserDriver::advance_step(&mut self.stream.borrow_mut(), parser_step, owner);
- self.discovery_signals.extend(advance.discovery_signals);
- advance.outcome
+ f: impl FnOnce(DomHost) -> std::result::Result<R, Box<(anyhow::Error, DomHost)>>,
+ ) -> anyhow::Result<R> {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => stream
+ .borrow_mut()
+ .with_parser_stream_dom_host_for_bootstrap(f),
+ ExecutableDocumentParserBackend::Xml(stream) => stream
+ .borrow_mut()
+ .with_parser_stream_dom_host_for_bootstrap(f),
+ }
}
- pub(crate) fn take_discovery_signals(&mut self) -> LiveDocumentParserDiscoverySignals {
- std::mem::take(&mut self.discovery_signals)
+ pub(crate) fn take_parser_stream_null_custom_element_registry_elements(
+ &mut self,
+ ) -> Vec<NativeNodeId> {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => stream
+ .borrow_mut()
+ .take_parser_stream_null_custom_element_registry_elements(),
+ ExecutableDocumentParserBackend::Xml(stream) => stream
+ .borrow_mut()
+ .take_parser_stream_null_custom_element_registry_elements(),
+ }
+ }
+
+ pub(crate) fn with_stylesheet_blocking_read_view<R>(
+ &self,
+ f: impl FnOnce(&dyn crate::StylesheetBlockingReadView) -> R,
+ ) -> R {
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ stream.borrow().with_stylesheet_blocking_read_view(f)
+ }
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ stream.borrow().with_stylesheet_blocking_read_view(f)
+ }
+ }
}
pub(crate) fn finish(
- mut self,
+ &mut self,
owner: &mut impl LiveDocumentParserOwner,
) -> DocumentParserFinishSignals {
+ assert!(
+ self.input_is_empty(),
+ "a live document parser may only finish after all parser-owned input is drained"
+ );
+ self.control.begin_finish();
let mut discovery_signals = std::mem::take(&mut self.discovery_signals);
- let stream = match Rc::try_unwrap(self.stream) {
- Ok(stream) => stream.into_inner(),
- Err(_) => {
- panic!(
- "live document parser session must not retain cloned stream handles at finish"
- )
+ let backend = self
+ .backend
+ .take()
+ .expect("one parser session can only finish once");
+ let mut finish_signals = match backend {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ DocumentParserDriver::finish(unwrap_exclusive_parser_stream(stream), owner)
+ }
+ ExecutableDocumentParserBackend::Xml(stream) => {
+ finish_live_xml_document_parser(unwrap_exclusive_xml_parser_stream(stream), owner)
}
};
- let mut finish_signals = DocumentParserDriver::finish(stream, owner);
discovery_signals.extend(finish_signals.discovery_signals);
finish_signals.discovery_signals = discovery_signals;
+ self.control.finish();
finish_signals
}
+ #[cfg(test)]
fn with_reentrant_stream_step<R>(&self, op: impl FnOnce(&mut DocumentStream) -> R) -> R {
- let stream_ptr = self.stream.as_ref().as_ptr();
+ let stream = self
+ .html_stream_handle()
+ .expect("reentrant insertion step requires an HTML parser stream");
+ let stream_ptr = stream.as_ref().as_ptr();
// SAFETY: The Rc keeps the DocumentStream allocation alive for this
// synchronous parser step, and phase-one parser turns run on the
// renderer owner thread. We intentionally avoid a RefCell guard here
@@ -564,12 +942,23 @@ impl DocumentParserSession {
#[cfg(test)]
pub(crate) fn queued_chunk_count_for_testing(&self) -> usize {
- self.input.queued_chunk_count_for_testing()
+ match self.backend() {
+ ExecutableDocumentParserBackend::Html(stream) => {
+ stream.borrow().queued_end_segment_count_for_testing()
+ }
+ ExecutableDocumentParserBackend::Xml(_) => 0,
+ }
}
#[cfg(test)]
pub(crate) fn current_chunk_is_non_empty_for_testing(&self) -> bool {
- self.input.current_chunk_is_non_empty_for_testing()
+ self.current_chunk_len() > 0
+ }
+}
+
+impl Drop for DocumentParserSession {
+ fn drop(&mut self) {
+ self.control.stop(ParserStopReason::OwnerDropped);
}
}
@@ -593,3 +982,139 @@ fn finish_live_document_parser(
},
}
}
+
+fn finish_live_xml_document_parser(
+ stream: XmlDocumentStream,
+ owner: &mut impl LiveDocumentParserOwner,
+) -> DocumentParserFinishSignals {
+ let crate::parser::ParserFinishDiscoverySignals {
+ parser_created_null_registry_elements,
+ discovered_modulepreload_link_candidates,
+ discovered_parser_meta_csp_candidates,
+ discovered_blocking_stylesheet_inputs,
+ } = stream.finish_with_runtime_dom_consumer(owner);
+ DocumentParserFinishSignals {
+ parser_created_null_registry_elements,
+ discovery_signals: LiveDocumentParserDiscoverySignals {
+ modulepreload_link_candidates: discovered_modulepreload_link_candidates,
+ parser_meta_csp_candidates: discovered_parser_meta_csp_candidates,
+ blocking_stylesheet_inputs: discovered_blocking_stylesheet_inputs,
+ ..LiveDocumentParserDiscoverySignals::default()
+ },
+ }
+}
+
+fn unwrap_exclusive_parser_stream(stream: DocumentParserStreamHandle) -> DocumentStream {
+ Rc::try_unwrap(stream)
+ .unwrap_or_else(|_| {
+ panic!("live document parser session must not retain cloned stream handles at finish")
+ })
+ .into_inner()
+}
+
+fn unwrap_exclusive_xml_parser_stream(stream: XmlDocumentParserStreamHandle) -> XmlDocumentStream {
+ Rc::try_unwrap(stream)
+ .unwrap_or_else(|_| {
+ panic!("live XML parser session must not retain cloned stream handles at finish")
+ })
+ .into_inner()
+}
+
+#[cfg(test)]
+mod session_state_tests {
+ use super::*;
+ use crate::frame_owner_model::{DocumentId, FrameSchedulerLaneId, LocalWindowId};
+
+ fn owner(lane: u64, window: u64, document: u64) -> FrameDocumentTaskOwner {
+ FrameDocumentTaskOwner::new(
+ FrameSchedulerLaneId(lane),
+ LocalWindowId(window),
+ DocumentId(document),
+ )
+ }
+
+ fn session() -> DocumentParserSession {
+ DocumentParserSession::start_finite_live_document(
+ Url::parse("https://parser-session.test/").expect("test URL"),
+ NativeNodeId::new(1),
+ )
+ }
+
+ #[test]
+ fn parser_resume_permit_is_exact_and_one_shot() {
+ let mut parser = session();
+ let owner = owner(1, 2, 3);
+ parser.bind_owner(owner, 7);
+ let permit = parser.suspend(ParserSuspensionCause::ParserClassicSource {
+ script: NativeNodeId::new(8),
+ });
+
+ assert_eq!(
+ permit.owner_identity,
+ Some(DocumentParserOwnerIdentity::new(owner, 7))
+ );
+ assert_eq!(permit.session_id, parser.control.session_id());
+ assert_eq!(parser.resume(permit), ParserResumeApplication::Resumed);
+ assert_eq!(
+ parser.resume(permit),
+ ParserResumeApplication::ParserNotSuspended,
+ "a copied permit cannot resume the same suspension twice"
+ );
+ }
+
+ #[test]
+ fn parser_resume_rejects_wrong_owner_session_and_suspension() {
+ let mut parser = session();
+ let parser_owner = owner(1, 2, 3);
+ parser.bind_owner(parser_owner, 11);
+ let first = parser.suspend(ParserSuspensionCause::ParserCreatedStylesheet {
+ owner: NativeNodeId::new(5),
+ });
+
+ let wrong_owner = ParserResumePermit {
+ owner_identity: Some(DocumentParserOwnerIdentity::new(owner(9, 9, 9), 11)),
+ ..first
+ };
+ assert_eq!(
+ parser.resume(wrong_owner),
+ ParserResumeApplication::RejectedOwner
+ );
+
+ let mut other = session();
+ other.bind_owner(parser_owner, 11);
+ assert_eq!(
+ other.resume(first),
+ ParserResumeApplication::RejectedSession
+ );
+
+ assert_eq!(parser.resume(first), ParserResumeApplication::Resumed);
+ let second = parser.suspend(ParserSuspensionCause::DocumentWriteExternalScript {
+ script: NativeNodeId::new(6),
+ });
+ assert_eq!(
+ parser.resume(first),
+ ParserResumeApplication::RejectedSuspension
+ );
+ assert_eq!(parser.resume(second), ParserResumeApplication::Resumed);
+ }
+
+ #[test]
+ fn parser_pump_and_drop_transitions_are_observable_by_derived_capabilities() {
+ let parser = session();
+ let control = parser.control_handle();
+ {
+ let _pump = control.begin_pump();
+ assert!(matches!(
+ control.run_state(),
+ DocumentParserRunState::Pumping { .. }
+ ));
+ }
+ assert_eq!(control.run_state(), DocumentParserRunState::Ready);
+
+ drop(parser);
+ assert_eq!(
+ control.run_state(),
+ DocumentParserRunState::Stopped(ParserStopReason::OwnerDropped)
+ );
+ }
+}
diff --git a/moli-renderer-v8/src/native_bridge/collections/bridge_callbacks.rs b/moli-renderer-v8/src/native_bridge/collections/bridge_callbacks.rs
index bcd6bd5c1..dbe7933ce 100644
--- a/moli-renderer-v8/src/native_bridge/collections/bridge_callbacks.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/bridge_callbacks.rs
@@ -230,6 +230,7 @@ fn bridge_create_live_collection_callback(
query,
include_root,
tag_name_html_document,
+ resolution_cache: Default::default(),
};
let collection = build_live_collection_wrapper(scope, runtime_ptr, descriptor);
diff --git a/moli-renderer-v8/src/native_bridge/collections/builders.rs b/moli-renderer-v8/src/native_bridge/collections/builders.rs
index 39f7be553..1413c2d96 100644
--- a/moli-renderer-v8/src/native_bridge/collections/builders.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/builders.rs
@@ -200,6 +200,7 @@ pub(in crate::native_bridge) fn build_live_collection_for_node<'s>(
query,
include_root,
tag_name_html_document,
+ resolution_cache: Default::default(),
},
)
}
diff --git a/moli-renderer-v8/src/native_bridge/collections/iteration.rs b/moli-renderer-v8/src/native_bridge/collections/iteration.rs
index 736c4ff17..056b3416f 100644
--- a/moli-renderer-v8/src/native_bridge/collections/iteration.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/iteration.rs
@@ -68,6 +68,7 @@ fn collection_named_value<'s>(
query: Some(key.to_owned()),
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
return Some(build_live_collection_wrapper(scope, runtime_ptr, live_descriptor).into());
}
diff --git a/moli-renderer-v8/src/native_bridge/collections/live_handlers.rs b/moli-renderer-v8/src/native_bridge/collections/live_handlers.rs
index bbd59ae98..71d070943 100644
--- a/moli-renderer-v8/src/native_bridge/collections/live_handlers.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/live_handlers.rs
@@ -373,6 +373,7 @@ fn live_collection_named_value<'s>(
query: Some(key),
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
return Some(build_live_collection_wrapper(scope, runtime_ptr, live_descriptor).into());
}
diff --git a/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs b/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
index 92a2b0f6d..faefabebe 100644
--- a/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/radio_node_list.rs
@@ -21,7 +21,7 @@ pub(in crate::native_bridge::collections) fn radio_node_list_value_getter<'s>(
return;
}
let runtime = unsafe { &*runtime_ptr };
- for handle in descriptor.resolve(runtime) {
+ for handle in descriptor.resolve(runtime).iter().copied() {
let Some(element) = runtime.dom_host().node(handle).and_then(Node::as_element) else {
continue;
};
@@ -62,7 +62,7 @@ pub(in crate::native_bridge::collections) fn radio_node_list_value_setter<'s>(
}
let matching_handle = {
let runtime = unsafe { &*runtime_ptr };
- descriptor.resolve(runtime).into_iter().find(|handle| {
+ descriptor.resolve(runtime).iter().copied().find(|handle| {
runtime
.dom_host()
.node(*handle)
diff --git a/moli-renderer-v8/src/native_bridge/collections/shared.rs b/moli-renderer-v8/src/native_bridge/collections/shared.rs
index e73f3e085..c8d942d11 100644
--- a/moli-renderer-v8/src/native_bridge/collections/shared.rs
+++ b/moli-renderer-v8/src/native_bridge/collections/shared.rs
@@ -112,7 +112,8 @@ pub(in crate::native_bridge::collections) fn named_item_matches(
descriptor
.resolve(host)
- .into_iter()
+ .iter()
+ .copied()
.filter(|handle| {
host.dom_host()
.node(*handle)
@@ -136,7 +137,7 @@ pub(in crate::native_bridge::collections) fn named_item_property_names(
}
let mut names = IndexSet::new();
- for handle in descriptor.resolve(host) {
+ for handle in descriptor.resolve(host).iter().copied() {
let Some(element) = host.dom_host().node(handle).and_then(Node::as_element) else {
continue;
};
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs
index 301817b62..633bd4f84 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/commit.rs
@@ -132,80 +132,19 @@ impl JsContextHost {
if !self.child_browsing_contexts.contains_key(&handle) {
return None;
}
- if !snapshot
+ let is_xml_document = snapshot
.content_type
.as_deref()
- .is_some_and(is_dom_parser_xml_mime)
- {
- return self.install_live_child_html_document_from_snapshot(
- scope,
- handle,
- snapshot,
- window_commit,
- preserve_window_event_state,
- navigation_loader,
- );
- }
- let document_handle = self.create_empty_child_xml_document_from_snapshot(snapshot);
- let document_url = self.document_url_for_handle(document_handle);
- let document_base_url = self.document_base_url_for_handle(document_handle);
- let referrer_policy = self
- .child_browsing_context_referrer_policy_for_document_handle(document_handle)
- .map(str::to_owned);
- // Chromium's XML parser builds into the Document selected for this
- // navigation. Keep that same identity here instead of parsing a
- // detached snapshot and transplanting its children. Parse before
- // publishing the owner transition so a rejected target cannot leave a
- // partially initialized current Document behind.
- //
- // Script handles discovered by this full-tree parse are deliberately
- // not scheduled: doing so after parsing would not provide
- // parser-blocking ordering.
- if moli_parser::XmlParser
- .parse_tree_into_document(self.dom_host_mut(), document_handle, &snapshot.markup)
- .is_none()
- {
- tracing::error!(
- ?handle,
- ?document_handle,
- url = %snapshot.url,
- "aborting child XML document commit because its parser target is not an empty XML Document"
- );
- return None;
- }
- let owner_transition = self.commit_child_document_owner(
+ .is_some_and(is_dom_parser_xml_mime);
+ self.install_live_child_document_from_snapshot(
scope,
handle,
- document_handle,
- document_url,
- document_base_url,
- referrer_policy,
- snapshot.policy_container.clone(),
+ snapshot,
window_commit,
preserve_window_event_state,
navigation_loader,
- )?;
- let current_owner = owner_transition
- .current_owner()
- .expect("child document commit must install a current owner");
- let owner_local_window_id = current_owner.local_window_id;
- let owner_document_id = current_owner.document_id;
- self.dom_host_mut()
- .mark_subtree_connected_preserving_owner_document(document_handle);
- self.sync_owner_style_sheet_texts_for_document_tree_scopes(document_handle);
- self.install_empty_child_classic_script_runner_for_current_document(
- handle,
- owner_local_window_id,
- owner_document_id,
- );
- let parser_stop_action = self
- .frame_owner_store
- .finish_current_child_document_parsing(handle, current_owner.document_owner());
- Some(ChildDocumentInstallResult {
- initial_classic_ready_work: None,
- parser_stop_action,
- owner_transition,
- })
+ is_xml_document,
+ )
}
pub(in crate::native_bridge) fn replace_child_custom_elements_registry_for_document_commit(
@@ -221,7 +160,7 @@ impl JsContextHost {
}
}
- fn install_live_child_html_document_from_snapshot(
+ fn install_live_child_document_from_snapshot(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
handle: DomHandle,
@@ -229,20 +168,30 @@ impl JsContextHost {
window_commit: ChildDocumentWindowCommit,
preserve_window_event_state: bool,
navigation_loader: Option<crate::network::navigation::NavigationResourceLoader>,
+ is_xml_document: bool,
) -> Option<ChildDocumentInstallResult> {
- let source = crate::dom_parser::preserve_decoded_bom_only_child_body(
- &snapshot.markup,
- snapshot.content_type.as_deref(),
- );
- let document_handle = self.create_empty_live_child_html_document(
- snapshot.url.clone(),
- snapshot.content_type.as_deref(),
- );
- self.dom_host_mut()
- .set_document_fallback_base_url_for_handle(
- document_handle,
- snapshot.fallback_base_url.clone(),
+ let source = if is_xml_document {
+ std::borrow::Cow::Borrowed(snapshot.markup.as_str())
+ } else {
+ crate::dom_parser::preserve_decoded_bom_only_child_body(
+ &snapshot.markup,
+ snapshot.content_type.as_deref(),
+ )
+ };
+ let document_handle = if is_xml_document {
+ self.create_empty_child_xml_document_from_snapshot(snapshot)
+ } else {
+ let document_handle = self.create_empty_live_child_html_document(
+ snapshot.url.clone(),
+ snapshot.content_type.as_deref(),
);
+ self.dom_host_mut()
+ .set_document_fallback_base_url_for_handle(
+ document_handle,
+ snapshot.fallback_base_url.clone(),
+ );
+ document_handle
+ };
let document_url = self.document_url_for_handle(document_handle);
let document_base_url = self.document_base_url_for_handle(document_handle);
let parser_base_url = document_base_url.clone();
@@ -273,7 +222,7 @@ impl JsContextHost {
owner_local_window_id,
owner_document_id,
);
- let parser_start = self.start_live_child_html_document_parser(
+ let parser_start = self.start_live_child_document_parser(
scope,
handle,
document_handle,
@@ -281,6 +230,7 @@ impl JsContextHost {
owner_document_id,
parser_base_url,
source.as_ref(),
+ is_xml_document,
);
Some(ChildDocumentInstallResult {
initial_classic_ready_work: parser_start.initial_classic_ready_work,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
index 3976bc14b..c8386aacc 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/live_parser.rs
@@ -9,11 +9,13 @@ use crate::{
DocumentId, FrameClassicDocumentScriptExecutionStart,
FrameDocumentClassicCompletionFinishAction, FrameDocumentClassicParserResumeApplication,
FrameDocumentClassicParserResumeSkipReason, FrameDocumentInteractiveLifecycleAction,
- FrameDocumentOwner, FrameScriptJob, FrameScriptSource, LocalWindowId,
+ FrameDocumentOwner, FrameDocumentTaskOwner, FrameScriptJob, FrameScriptSource,
+ LocalWindowId,
},
live_document_parser::{
- DocumentParserLifetime, DocumentParserSession, LiveDocumentParserOwner,
- LiveDocumentParserStepOutcome,
+ DocumentParserLifetime, DocumentParserRunState, DocumentParserSession,
+ LiveDocumentParserOwner, LiveDocumentParserStepOutcome, ParserResumeApplication,
+ ParserSuspensionCause,
},
modulepreload::{
invalid_modulepreload_as_value, invalid_modulepreload_as_warning,
@@ -307,6 +309,10 @@ impl ParserDomMutationConsumer for ChildFrameLiveParserOwner<'_, '_, '_> {
.create_processing_instruction(&target, &data)
}
+ fn create_cdata_section(&mut self, data: String) -> DomHandle {
+ self.host.dom_host_mut().create_cdata_section(&data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -410,19 +416,38 @@ enum ChildLiveDocumentParserProgress {
/// The parser queued a parser-blocking classic script and must be saved until
/// that script completes or reports source failure.
BlockedOnParserScript {
+ cause: ParserSuspensionCause,
ready_work: Option<Box<FrameDocumentClassicScriptSchedulerWork>>,
},
/// The parser stopped immediately after a parser-created blocking
/// stylesheet in the body. The exact parser entry remains resident until
/// that document owner's stylesheet readiness settles.
- BlockedOnStylesheetPause,
+ BlockedOnStylesheetPause { owner: DomHandle },
/// The parser produced a blocking script, but it could not attach that script
/// to the current child document owner; finish the parser without saving it.
FailedToQueueParserScript,
}
impl JsContextHost {
- fn drive_live_child_html_document_parser(
+ fn suspend_live_child_parser_for_progress(
+ parser: &mut DocumentParserSession,
+ progress: &ChildLiveDocumentParserProgress,
+ ) {
+ let cause = match progress {
+ ChildLiveDocumentParserProgress::BlockedOnParserScript { cause, .. } => Some(*cause),
+ ChildLiveDocumentParserProgress::BlockedOnStylesheetPause { owner } => {
+ Some(ParserSuspensionCause::ParserCreatedStylesheet { owner: *owner })
+ }
+ ChildLiveDocumentParserProgress::Continue
+ | ChildLiveDocumentParserProgress::Complete
+ | ChildLiveDocumentParserProgress::FailedToQueueParserScript => None,
+ };
+ if let Some(cause) = cause {
+ let _ = parser.suspend(cause);
+ }
+ }
+
+ fn drive_live_child_document_parser(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
@@ -458,7 +483,11 @@ impl JsContextHost {
self.frame_document_blocking_stylesheets.has_pending(owner)
});
if remains_blocked {
- return ChildLiveDocumentParserProgress::BlockedOnStylesheetPause;
+ let progress = ChildLiveDocumentParserProgress::BlockedOnStylesheetPause {
+ owner: pause.node_id,
+ };
+ Self::suspend_live_child_parser_for_progress(parser, &progress);
+ return progress;
}
}
LiveDocumentParserStepOutcome::ScriptHandoff(handoff) => {
@@ -468,7 +497,10 @@ impl JsContextHost {
*handoff,
) {
ChildLiveDocumentParserProgress::Continue => {}
- progress => return progress,
+ progress => {
+ Self::suspend_live_child_parser_for_progress(parser, &progress);
+ return progress;
+ }
}
}
}
@@ -561,6 +593,7 @@ impl JsContextHost {
script,
..
} => {
+ let waits_for_stylesheets = !blocking_signatures_before.is_empty();
let queued = self.push_child_parser_classic_script_for_current_document(
child_handle,
document_handle,
@@ -572,7 +605,13 @@ impl JsContextHost {
),
);
if let Some(queued) = queued {
+ let cause = if waits_for_stylesheets {
+ ParserSuspensionCause::ParserClassicStylesheets { script: node_id }
+ } else {
+ ParserSuspensionCause::ParserClassicSource { script: node_id }
+ };
ChildLiveDocumentParserProgress::BlockedOnParserScript {
+ cause,
ready_work: queued.ready_work.map(Box::new),
}
} else {
@@ -770,13 +809,13 @@ impl JsContextHost {
ChildLiveDocumentParserProgress::Continue
}
- fn finish_live_child_html_document_parser(
+ fn finish_live_child_document_parser(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
owner: FrameDocumentOwner,
document_handle: DomHandle,
- parser: DocumentParserSession,
+ mut parser: DocumentParserSession,
) -> Option<crate::frame_owner_model::FrameDocumentInteractiveLifecycleAction> {
let finish_signals = {
let mut owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
@@ -805,7 +844,7 @@ impl JsContextHost {
.finish_current_child_document_parsing(child_handle, owner)
}
- fn finish_and_queue_live_child_html_document_parser(
+ fn finish_and_queue_live_child_document_parser(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
@@ -813,7 +852,7 @@ impl JsContextHost {
document_handle: DomHandle,
parser: DocumentParserSession,
) {
- if let Some(action) = self.finish_live_child_html_document_parser(
+ if let Some(action) = self.finish_live_child_document_parser(
scope,
child_handle,
owner,
@@ -955,7 +994,15 @@ impl JsContextHost {
Some(document_handle),
"committed child document-open parser must target the current Document"
);
- let parser = DocumentParserSession::start_open_live_document(document_url, document_handle);
+ let task_owner = self
+ .frame_owner_store
+ .current_child_document_task_owner(child_handle)
+ .expect("committed child document-open parser must have a task owner");
+ assert_eq!(task_owner.document_owner(), owner);
+ let runtime_generation = self.runtime_reset_generation();
+ let mut parser =
+ DocumentParserSession::start_open_live_document(document_url, document_handle);
+ parser.bind_owner(task_owner, runtime_generation);
self.child_document_parsers.replace(owner, parser);
}
@@ -990,17 +1037,6 @@ impl JsContextHost {
&& !close_requested
&& (entry.lifetime() == DocumentParserLifetime::Finite
|| self.child_document_is_executing_parser_script(document_handle));
- if parser_insertion_only && self.child_document_is_executing_parser_script(document_handle)
- {
- let _ = entry.take_parser_script_wait();
- }
- // A finite parser only remains in this store while a parser-blocking script owns the
- // insertion point. An open document.write parser can also synchronously execute one of
- // its own parser-blocking scripts. Keep either parser's buffered tail behind synchronous
- // script input.
- let mut buffered_parser_tail = parser_insertion_only
- .then(|| entry.stream_handle().borrow_mut().take_buffered_input())
- .filter(|tail| !tail.is_empty());
if let Some(chunk) = chunk {
entry
.stream_handle()
@@ -1017,13 +1053,6 @@ impl JsContextHost {
let mut parser_owner = ChildFrameLiveParserOwner::new(self, scope, document_handle);
entry.advance_queued_or_resume_step(&mut parser_owner)
};
- if let Some(network_tail) = buffered_parser_tail.take() {
- let stream = entry.stream_handle();
- let mut parser = stream.borrow_mut();
- let mut insertion_tail = parser.take_buffered_input();
- insertion_tail.push_str(&network_tail);
- parser.prepend_buffered_input(insertion_tail);
- }
let discovery_signals = entry.take_discovery_signals();
self.queue_live_child_parser_discovery_signals(
child_handle,
@@ -1045,7 +1074,7 @@ impl JsContextHost {
entry,
);
} else {
- self.finish_and_queue_live_child_html_document_parser(
+ self.finish_and_queue_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1081,7 +1110,10 @@ impl JsContextHost {
"child document.write parser paused on a body blocking stylesheet"
);
if self.frame_document_blocking_stylesheets.has_pending(owner) {
- entry.wait_for_blocking_stylesheet();
+ let progress = ChildLiveDocumentParserProgress::BlockedOnStylesheetPause {
+ owner: pause.node_id,
+ };
+ Self::suspend_live_child_parser_for_progress(&mut entry, &progress);
self.child_document_parsers.replace(owner, entry);
return false;
}
@@ -1100,7 +1132,7 @@ impl JsContextHost {
let Some(next_entry) = self.child_document_parsers.take(owner) else {
return false;
};
- if next_entry.is_waiting_for_parser_script() {
+ if next_entry.is_suspended() {
self.child_document_parsers.replace(owner, next_entry);
return true;
}
@@ -1115,9 +1147,17 @@ impl JsContextHost {
match progress {
ChildLiveDocumentParserProgress::Continue => entry,
ChildLiveDocumentParserProgress::BlockedOnParserScript {
+ cause,
ready_work,
} => {
- entry.wait_for_parser_script();
+ let progress =
+ ChildLiveDocumentParserProgress::BlockedOnParserScript {
+ cause,
+ ready_work: None,
+ };
+ Self::suspend_live_child_parser_for_progress(
+ &mut entry, &progress,
+ );
self.child_document_parsers.replace(owner, entry);
if let Some(ready_work) = ready_work {
self.push_child_document_script_ready_input(*ready_work);
@@ -1131,8 +1171,16 @@ impl JsContextHost {
);
entry
}
- ChildLiveDocumentParserProgress::BlockedOnStylesheetPause => {
- entry.wait_for_blocking_stylesheet();
+ ChildLiveDocumentParserProgress::BlockedOnStylesheetPause {
+ owner: stylesheet_owner,
+ } => {
+ let progress =
+ ChildLiveDocumentParserProgress::BlockedOnStylesheetPause {
+ owner: stylesheet_owner,
+ };
+ Self::suspend_live_child_parser_for_progress(
+ &mut entry, &progress,
+ );
self.child_document_parsers.replace(owner, entry);
return false;
}
@@ -1148,7 +1196,7 @@ impl JsContextHost {
entry,
);
} else {
- self.finish_and_queue_live_child_html_document_parser(
+ self.finish_and_queue_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1178,7 +1226,7 @@ impl JsContextHost {
document_handle: DomHandle,
parser: DocumentParserSession,
) {
- let Some(interactive) = self.finish_live_child_html_document_parser(
+ let Some(interactive) = self.finish_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1435,7 +1483,7 @@ impl JsContextHost {
document_handle
}
- pub(in crate::native_bridge::context_host) fn start_live_child_html_document_parser(
+ pub(in crate::native_bridge::context_host) fn start_live_child_document_parser(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
@@ -1444,13 +1492,27 @@ impl JsContextHost {
owner_document_id: DocumentId,
document_base_url: Url,
markup: &str,
+ is_xml_document: bool,
) -> ChildLiveDocumentParserStartResult {
let owner = FrameDocumentOwner::new(owner_local_window_id, owner_document_id);
self.child_document_parsers.clear(owner);
- let mut parser =
- DocumentParserSession::start_finite_live_document(document_base_url, document_handle);
+ let mut parser = if is_xml_document {
+ DocumentParserSession::start_finite_live_xml_document(
+ document_base_url,
+ document_handle,
+ )
+ } else {
+ DocumentParserSession::start_finite_live_document(document_base_url, document_handle)
+ };
+ let task_owner = self
+ .frame_owner_store
+ .current_child_document_task_owner(child_handle)
+ .expect("committed child parser must have a current task owner");
+ assert_eq!(task_owner.document_owner(), owner);
+ parser.bind_owner(task_owner, self.runtime_reset_generation());
parser.queue_arrived_chunk(markup.to_owned());
- let outcome = self.drive_live_child_html_document_parser(
+ parser.declare_eof();
+ let outcome = self.drive_live_child_document_parser(
scope,
child_handle,
document_handle,
@@ -1459,7 +1521,7 @@ impl JsContextHost {
match outcome {
ChildLiveDocumentParserProgress::Continue
| ChildLiveDocumentParserProgress::Complete => {
- let parser_stop_action = self.finish_live_child_html_document_parser(
+ let parser_stop_action = self.finish_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1468,18 +1530,16 @@ impl JsContextHost {
);
ChildLiveDocumentParserStartResult::parser_stopped(parser_stop_action)
}
- ChildLiveDocumentParserProgress::BlockedOnParserScript { ready_work } => {
- parser.wait_for_parser_script();
+ ChildLiveDocumentParserProgress::BlockedOnParserScript { ready_work, .. } => {
self.child_document_parsers.replace(owner, parser);
ChildLiveDocumentParserStartResult::parser_blocked(ready_work.map(|work| *work))
}
- ChildLiveDocumentParserProgress::BlockedOnStylesheetPause => {
- parser.wait_for_blocking_stylesheet();
+ ChildLiveDocumentParserProgress::BlockedOnStylesheetPause { .. } => {
self.child_document_parsers.replace(owner, parser);
ChildLiveDocumentParserStartResult::parser_blocked(None)
}
ChildLiveDocumentParserProgress::FailedToQueueParserScript => {
- let parser_stop_action = self.finish_live_child_html_document_parser(
+ let parser_stop_action = self.finish_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1491,7 +1551,7 @@ impl JsContextHost {
}
}
- pub(crate) fn resume_live_child_html_document_parser_after_blocker(
+ pub(crate) fn resume_live_child_document_parser_after_blocker(
&mut self,
scope: &mut v8::PinScope<'_, '_>,
child_handle: DomHandle,
@@ -1517,9 +1577,14 @@ impl JsContextHost {
FrameDocumentClassicParserResumeSkipReason::MissingLiveParser,
);
};
- let _ = entry.take_blocking_stylesheet_wait();
- let was_waiting_for_parser_script = entry.take_parser_script_wait();
- if was_waiting_for_parser_script
+ let parser_was_suspended_for_classic_script = matches!(
+ entry.suspension_cause(),
+ Some(
+ ParserSuspensionCause::ParserClassicSource { .. }
+ | ParserSuspensionCause::ParserClassicStylesheets { .. }
+ )
+ );
+ if parser_was_suspended_for_classic_script
&& self
.frame_parser_classic_scripts
.has_current_parser_blocking_script(owner)
@@ -1527,27 +1592,47 @@ impl JsContextHost {
if let Some(work) =
self.take_child_classic_script_scheduler_work_for_current_document(child_handle)
{
- entry.wait_for_parser_script();
self.child_document_parsers.replace(owner, entry);
return FrameDocumentClassicParserResumeApplication::resumed(Some(work));
}
let _ = self.queue_child_classic_script_source_load_task(child_handle);
- entry.wait_for_parser_script();
self.child_document_parsers.replace(owner, entry);
return FrameDocumentClassicParserResumeApplication::resumed(None);
}
+ match entry.run_state() {
+ DocumentParserRunState::Ready => {}
+ DocumentParserRunState::Suspended { .. } => {
+ let Some(permit) = entry.current_resume_permit() else {
+ self.child_document_parsers.replace(owner, entry);
+ return FrameDocumentClassicParserResumeApplication::skipped(
+ FrameDocumentClassicParserResumeSkipReason::StaleParserSuspension,
+ );
+ };
+ if entry.resume(permit) != ParserResumeApplication::Resumed {
+ self.child_document_parsers.replace(owner, entry);
+ return FrameDocumentClassicParserResumeApplication::skipped(
+ FrameDocumentClassicParserResumeSkipReason::StaleParserSuspension,
+ );
+ }
+ }
+ DocumentParserRunState::Pumping { .. }
+ | DocumentParserRunState::Finishing
+ | DocumentParserRunState::Finished
+ | DocumentParserRunState::Stopped(_) => {
+ self.child_document_parsers.replace(owner, entry);
+ return FrameDocumentClassicParserResumeApplication::skipped(
+ FrameDocumentClassicParserResumeSkipReason::StaleParserSuspension,
+ );
+ }
+ }
let document_handle = snapshot.document_handle;
- let outcome = self.drive_live_child_html_document_parser(
- scope,
- child_handle,
- document_handle,
- &mut entry,
- );
+ let outcome =
+ self.drive_live_child_document_parser(scope, child_handle, document_handle, &mut entry);
match outcome {
ChildLiveDocumentParserProgress::Continue
| ChildLiveDocumentParserProgress::Complete => {
if entry.finishes_when_drained() {
- self.finish_and_queue_live_child_html_document_parser(
+ self.finish_and_queue_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1559,19 +1644,17 @@ impl JsContextHost {
}
FrameDocumentClassicParserResumeApplication::resumed(None)
}
- ChildLiveDocumentParserProgress::BlockedOnParserScript { ready_work } => {
- entry.wait_for_parser_script();
+ ChildLiveDocumentParserProgress::BlockedOnParserScript { ready_work, .. } => {
self.child_document_parsers.replace(owner, entry);
FrameDocumentClassicParserResumeApplication::resumed(ready_work.map(|work| *work))
}
- ChildLiveDocumentParserProgress::BlockedOnStylesheetPause => {
- entry.wait_for_blocking_stylesheet();
+ ChildLiveDocumentParserProgress::BlockedOnStylesheetPause { .. } => {
self.child_document_parsers.replace(owner, entry);
FrameDocumentClassicParserResumeApplication::resumed(None)
}
ChildLiveDocumentParserProgress::FailedToQueueParserScript => {
if entry.finishes_when_drained() {
- self.finish_and_queue_live_child_html_document_parser(
+ self.finish_and_queue_live_child_document_parser(
scope,
child_handle,
owner,
@@ -1585,4 +1668,44 @@ impl JsContextHost {
}
}
}
+
+ pub(crate) fn resume_live_child_document_parser_for_classic_execution(
+ &mut self,
+ child_handle: DomHandle,
+ task_owner: FrameDocumentTaskOwner,
+ script_handle: DomHandle,
+ ) -> bool {
+ if self.current_child_document_task_owner(child_handle) != Some(task_owner) {
+ return false;
+ }
+ let owner = task_owner.document_owner();
+ let Some(mut entry) = self.child_document_parsers.take(owner) else {
+ return false;
+ };
+ let resumed = match entry.run_state() {
+ // Source completion may already have consumed the exact permit
+ // while promoting ready scheduler work. The current task owner and
+ // realm gate still authorize this parser execution.
+ DocumentParserRunState::Ready => true,
+ DocumentParserRunState::Suspended { .. }
+ if matches!(
+ entry.suspension_cause(),
+ Some(ParserSuspensionCause::ParserClassicSource { script }
+ | ParserSuspensionCause::ParserClassicStylesheets { script })
+ if script == script_handle
+ ) =>
+ {
+ entry
+ .current_resume_permit()
+ .is_some_and(|permit| entry.resume(permit) == ParserResumeApplication::Resumed)
+ }
+ DocumentParserRunState::Pumping { .. }
+ | DocumentParserRunState::Suspended { .. }
+ | DocumentParserRunState::Finishing
+ | DocumentParserRunState::Finished
+ | DocumentParserRunState::Stopped(_) => false,
+ };
+ self.child_document_parsers.replace(owner, entry);
+ resumed
+ }
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
index 6ec792721..d720cb2cf 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_documents/parser_store.rs
@@ -1,6 +1,12 @@
#[cfg(test)]
use crate::live_document_parser::DocumentParserLifetime;
-use crate::{frame_owner_model::FrameDocumentOwner, live_document_parser::DocumentParserSession};
+use crate::{
+ frame_owner_model::FrameDocumentOwner,
+ live_document_parser::{
+ DocumentParserSession, ParserResumeApplication, ParserResumePermit, ParserStopReason,
+ ParserSuspensionCause,
+ },
+};
use std::collections::HashMap;
#[derive(Default)]
@@ -10,7 +16,9 @@ pub(in crate::native_bridge::context_host) struct ChildDocumentParserStore {
impl ChildDocumentParserStore {
pub(in crate::native_bridge::context_host) fn clear(&mut self, owner: FrameDocumentOwner) {
- self.sessions.remove(&owner);
+ if let Some(mut parser) = self.sessions.remove(&owner) {
+ parser.stop(ParserStopReason::DocumentReplacement);
+ }
}
pub(in crate::native_bridge::context_host) fn replace(
@@ -18,7 +26,9 @@ impl ChildDocumentParserStore {
owner: FrameDocumentOwner,
parser: DocumentParserSession,
) {
- self.sessions.insert(owner, parser);
+ if let Some(mut replaced) = self.sessions.insert(owner, parser) {
+ replaced.stop(ParserStopReason::DocumentReplacement);
+ }
}
pub(in crate::native_bridge::context_host) fn take(
@@ -48,13 +58,47 @@ impl ChildDocumentParserStore {
self.sessions.contains_key(&owner)
}
- pub(in crate::native_bridge::context_host) fn is_waiting_for_blocking_stylesheet(
+ pub(in crate::native_bridge::context_host) fn parser_script_resume_permit(
+ &self,
+ owner: FrameDocumentOwner,
+ script: crate::document_runtime::DomHandle,
+ ) -> Option<ParserResumePermit> {
+ let parser = self.sessions.get(&owner)?;
+ if !matches!(
+ parser.suspension_cause(),
+ Some(
+ ParserSuspensionCause::ParserClassicSource {
+ script: suspended_script,
+ } | ParserSuspensionCause::ParserClassicStylesheets {
+ script: suspended_script,
+ }
+ ) if suspended_script == script
+ ) {
+ return None;
+ }
+ parser.current_resume_permit()
+ }
+
+ pub(in crate::native_bridge::context_host) fn resume_parser_script_for_execution(
+ &mut self,
+ owner: FrameDocumentOwner,
+ permit: ParserResumePermit,
+ ) -> Option<ParserResumeApplication> {
+ self.sessions
+ .get_mut(&owner)
+ .map(|parser| parser.resume(permit))
+ }
+
+ pub(in crate::native_bridge::context_host) fn is_suspended_on_parser_created_stylesheet(
&self,
owner: FrameDocumentOwner,
) -> bool {
self.sessions
.get(&owner)
- .is_some_and(DocumentParserSession::is_waiting_for_blocking_stylesheet)
+ .and_then(DocumentParserSession::suspension_cause)
+ .is_some_and(|cause| {
+ matches!(cause, ParserSuspensionCause::ParserCreatedStylesheet { .. })
+ })
}
#[cfg(test)]
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/ids.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/ids.rs
index 0cc1536bd..7ae56583d 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/ids.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frame_snapshots/ids.rs
@@ -3,11 +3,10 @@ use crate::{document_runtime::DomHandle, dom::NodeId};
impl JsContextHost {
pub(in crate::native_bridge::context_host) fn allocate_child_document_loader_id(
- &mut self,
+ &self,
) -> String {
- let next_id = self.next_child_document_loader_id;
- self.next_child_document_loader_id = self.next_child_document_loader_id.wrapping_add(1);
- format!("LID-CHILD-{next_id:010}")
+ self.browser_context_runtime
+ .allocate_child_document_loader_id()
}
pub(crate) fn child_browsing_context_owner_node_id_by_frame_id(
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
index 1b9657470..72e730fdc 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/classic_scripts.rs
@@ -27,6 +27,7 @@ use crate::{
FrameRequestKind, FrameScriptJob, LocalWindowId, PendingChildExternalClassicDocumentScript,
frame_script_job_kind_from_parser_classic_ready_kind,
},
+ live_document_parser::ParserResumeApplication,
page_task_queue::RendererPageChildClassicScriptSourceLoadTarget,
parser_script::action::{
ParserPendingClassicScriptExecution, ParserPendingClassicScriptNotification,
@@ -1690,6 +1691,20 @@ impl JsContextHost {
FrameDocumentClassicPrepareDropReason::StaleDocumentOwner,
);
}
+ let parser_resume_permit = (target.scheduling()
+ == FrameDocumentClassicScriptScheduling::ParserBlocking)
+ .then(|| {
+ self.child_document_parsers
+ .parser_script_resume_permit(owner, script_handle)
+ })
+ .flatten();
+ if target.scheduling() == FrameDocumentClassicScriptScheduling::ParserBlocking
+ && parser_resume_permit.is_none()
+ {
+ return FrameDocumentClassicPrepareApplication::dropped(
+ FrameDocumentClassicPrepareDropReason::StaleParserSuspension,
+ );
+ }
let Some(execution_entry) = self.frame_parser_classic_scripts.begin_ready_execution(
owner,
child_handle,
@@ -1710,6 +1725,24 @@ impl JsContextHost {
FrameDocumentClassicPrepareDropReason::BeginExecutionUnavailable,
);
};
+ if let Some(permit) = parser_resume_permit
+ && self
+ .child_document_parsers
+ .resume_parser_script_for_execution(owner, permit)
+ != Some(ParserResumeApplication::Resumed)
+ {
+ tracing::debug!(
+ child_handle = ?child_handle,
+ owner = ?owner,
+ script_handle = ?script_handle,
+ ?permit,
+ "dropping child parser script with a stale parser suspension permit"
+ );
+ self.child_document_parsers.clear(owner);
+ return FrameDocumentClassicPrepareApplication::dropped(
+ FrameDocumentClassicPrepareDropReason::StaleParserSuspension,
+ );
+ }
let (target, execution, executable) = execution_entry.into_parts();
let Some(action) = self.child_classic_script_execution_action(
target,
@@ -1942,7 +1975,7 @@ impl JsContextHost {
FrameDocumentClassicParserResumeSkipReason::StaleRealm,
);
}
- self.resume_live_child_html_document_parser_after_blocker(scope, child_handle, owner)
+ self.resume_live_child_document_parser_after_blocker(scope, child_handle, owner)
}
}
diff --git a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs
index 8c14874db..605cfc5aa 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/child_frames/stylesheets.rs
@@ -338,12 +338,12 @@ impl JsContextHost {
let document_owner = completion.owner.document_owner();
if self
.child_document_parsers
- .is_waiting_for_blocking_stylesheet(document_owner)
+ .is_suspended_on_parser_created_stylesheet(document_owner)
&& !self
.frame_document_blocking_stylesheets
.has_pending(document_owner)
{
- let resume = self.resume_live_child_html_document_parser_after_blocker(
+ let resume = self.resume_live_child_document_parser_after_blocker(
scope,
completion.child_handle,
document_owner,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/core.rs b/moli-renderer-v8/src/native_bridge/context_host/core.rs
index bcdd6d140..bc2317e44 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/core.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/core.rs
@@ -264,7 +264,6 @@ impl JsContextHost {
child_browsing_context_document_handles: HashMap::new(),
document_domain_override: None,
next_child_browsing_context_id: 1,
- next_child_document_loader_id: 1,
next_child_document_load_id: 0,
next_child_classic_script_load_id: 0,
pending_child_document_navigations: HashMap::new(),
@@ -519,7 +518,6 @@ impl JsContextHost {
{
let runtime: &mut DocumentRuntime = self;
runtime.open_document();
- runtime.start_root_document_parser_stream();
}
let retired_descendant_count =
descendant_count_before.saturating_sub(self.child_browsing_contexts.len());
@@ -530,6 +528,10 @@ impl JsContextHost {
.frame_owner_store
.replace_main_document(document_handle, document_url, document_base_url)
.expect("main document owner must exist before document.open() replacement");
+ {
+ let runtime: &mut DocumentRuntime = self;
+ runtime.start_root_document_parser_stream(transition.current_owner());
+ }
self.dom_agent_state
.reset_for_document_replacement(transition.current_owner().document_id);
self.replace_main_document_resource_loader(transition);
diff --git a/moli-renderer-v8/src/native_bridge/context_host/file_chooser.rs b/moli-renderer-v8/src/native_bridge/context_host/file_chooser.rs
index 1c4042449..df1cb8611 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/file_chooser.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/file_chooser.rs
@@ -13,6 +13,12 @@ impl JsContextHost {
};
activation.backend_node_id = backend_node_id;
activation.node_id = Some(handle);
+ assert!(
+ self.backend_node_registry
+ .borrow_mut()
+ .retain_detached_resolution(backend_node_id),
+ "file chooser backend node id must exist before it is exposed"
+ );
}
let published = self.append_live_turn_owner_action(
crate::runtime::RendererOwnerAction::FileChooser(activation.clone()),
diff --git a/moli-renderer-v8/src/native_bridge/context_host/mod.rs b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
index 928db944a..a553a15d9 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/mod.rs
@@ -868,7 +868,6 @@ pub(crate) struct JsContextHost {
child_browsing_context_document_handles: HashMap<DomHandle, DomHandle>,
document_domain_override: Option<String>,
next_child_browsing_context_id: u64,
- next_child_document_loader_id: u64,
next_child_document_load_id: u64,
next_child_classic_script_load_id: u64,
pending_child_document_navigations: HashMap<u64, PendingChildDocumentNavigation>,
diff --git a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
index e789fa668..692d759ba 100644
--- a/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
+++ b/moli-renderer-v8/src/native_bridge/context_host/resource_loading.rs
@@ -494,10 +494,15 @@ impl JsContextHost {
})
}
- fn record_pending_subresource_request_started(&mut self, info: &PendingSubresourceFetchInfo) {
+ fn record_pending_subresource_request_started(
+ &mut self,
+ info: &PendingSubresourceFetchInfo,
+ disposition: ResourceLoadDisposition,
+ ) {
self.record_pending_subresource_request_started_with_initiator(
info,
SubresourceRequestInitiatorType::Script,
+ disposition,
);
}
@@ -505,6 +510,7 @@ impl JsContextHost {
&mut self,
info: &PendingSubresourceFetchInfo,
initiator_type: SubresourceRequestInitiatorType,
+ disposition: ResourceLoadDisposition,
) {
let Some(handle) = info.network_request_handle else {
return;
@@ -522,7 +528,8 @@ impl JsContextHost {
initiator_type,
info.request_cookie_report.clone(),
)
- .with_request_body_bytes(info.request_body_bytes.clone()),
+ .with_request_body_bytes(info.request_body_bytes.clone())
+ .with_keepalive(disposition == ResourceLoadDisposition::Keepalive),
);
}
@@ -533,7 +540,7 @@ impl JsContextHost {
if !pending.deferred_request_started {
return;
}
- self.record_pending_subresource_request_started(&pending.info);
+ self.record_pending_subresource_request_started(&pending.info, pending.load.disposition());
pending.deferred_request_started = false;
}
@@ -827,7 +834,7 @@ impl JsContextHost {
cancel_handle.clone(),
);
if !defer_request_started {
- self.record_pending_subresource_request_started(&info);
+ self.record_pending_subresource_request_started(&info, load.disposition());
}
self.pending_subresource_fetches.insert(
internal_id,
@@ -877,7 +884,7 @@ impl JsContextHost {
)
.expect("active Document authority required for EventSource load");
if request_started {
- self.record_pending_subresource_request_started(&info);
+ self.record_pending_subresource_request_started(&info, load.disposition());
} else {
self.push_pending_subresource_fetch_info(info.clone());
}
@@ -931,6 +938,7 @@ impl JsContextHost {
self.record_pending_subresource_request_started_with_initiator(
&info,
SubresourceRequestInitiatorType::Other,
+ load.disposition(),
);
self.pending_subresource_fetches.insert(
internal_id,
@@ -997,6 +1005,7 @@ impl JsContextHost {
self.record_pending_subresource_request_started_with_initiator(
&info,
request_initiator_type,
+ load.disposition(),
);
}
}
@@ -1113,6 +1122,7 @@ impl JsContextHost {
self.record_pending_subresource_request_started_with_initiator(
&info,
SubresourceRequestInitiatorType::Other,
+ load.disposition(),
);
self.pending_subresource_fetches.insert(
internal_id,
@@ -1166,6 +1176,7 @@ impl JsContextHost {
self.record_pending_subresource_request_started_with_initiator(
&info,
SubresourceRequestInitiatorType::Css,
+ load.disposition(),
);
self.pending_subresource_fetches.insert(
internal_id,
@@ -1204,7 +1215,7 @@ impl JsContextHost {
ResourceLoadDisposition::Keepalive,
cancel_handle.clone(),
);
- self.record_pending_subresource_request_started(&info);
+ self.record_pending_subresource_request_started(&info, load.disposition());
self.pending_subresource_fetches.insert(
internal_id,
PendingSubresourceFetchState {
@@ -1241,7 +1252,7 @@ impl JsContextHost {
crate::network::loads::ResourceLoadKind::CspReport
);
debug_assert_eq!(load.disposition(), ResourceLoadDisposition::Keepalive);
- self.record_pending_subresource_request_started(&info);
+ self.record_pending_subresource_request_started(&info, load.disposition());
self.pending_subresource_fetches.insert(
internal_id,
PendingSubresourceFetchState {
@@ -1422,7 +1433,7 @@ impl JsContextHost {
ResourceLoadDisposition::Ordinary,
cancel_handle.clone(),
);
- self.record_pending_subresource_request_started(&info);
+ self.record_pending_subresource_request_started(&info, load.disposition());
self.pending_subresource_fetches.insert(
internal_id,
PendingSubresourceFetchState {
diff --git a/moli-renderer-v8/src/native_bridge/document.rs b/moli-renderer-v8/src/native_bridge/document.rs
index 605ca455a..a8027e4b2 100644
--- a/moli-renderer-v8/src/native_bridge/document.rs
+++ b/moli-renderer-v8/src/native_bridge/document.rs
@@ -1260,6 +1260,7 @@ fn document_html_collection_getter<'s>(
query,
include_root: true,
tag_name_html_document,
+ resolution_cache: Default::default(),
};
let collection = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(collection.into());
diff --git a/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs b/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs
index c5fd78d78..3ca89c837 100644
--- a/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs
+++ b/moli-renderer-v8/src/native_bridge/document/live_collections/all/items.rs
@@ -11,11 +11,10 @@ pub(super) fn document_all_items_array<'s>(
document_handle: DomHandle,
) -> Option<v8::Local<'s, v8::Array>> {
let runtime = unsafe { &mut *runtime_ptr };
- let handles = runtime.filter_parser_visible_handles(
+ let handles =
runtime
.dom_host()
- .resolve_live_collection(document_handle, "tagName", Some("*"), true)?,
- );
+ .resolve_live_collection(document_handle, "tagName", Some("*"), true)?;
let array = v8::Array::new(scope, handles.len() as i32);
let mut visible_index = 0u32;
for handle in handles {
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs b/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
index 7b44d81f4..7721ccca9 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/form_element.rs
@@ -264,6 +264,7 @@ pub(in crate::native_bridge) fn form_elements_getter_function<'s>(
query: None,
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let collection = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(collection.into());
@@ -448,6 +449,7 @@ pub(in crate::native_bridge) fn fieldset_elements_getter_function<'s>(
query: None,
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let collection = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(collection.into());
@@ -573,6 +575,7 @@ pub(in crate::native_bridge) fn form_named_getter(
query: Some(key),
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let list = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(list.into());
@@ -632,6 +635,7 @@ pub(in crate::native_bridge) fn form_named_descriptor(
query: Some(key),
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let list = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
list.into()
diff --git a/moli-renderer-v8/src/native_bridge/element/forms/select/select_element.rs b/moli-renderer-v8/src/native_bridge/element/forms/select/select_element.rs
index 29a67325f..d03dc5a80 100644
--- a/moli-renderer-v8/src/native_bridge/element/forms/select/select_element.rs
+++ b/moli-renderer-v8/src/native_bridge/element/forms/select/select_element.rs
@@ -566,6 +566,7 @@ pub(in crate::native_bridge) fn select_options_getter_function<'s>(
query: None,
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let collection = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(collection.into());
@@ -590,6 +591,7 @@ pub(in crate::native_bridge) fn select_selected_options_getter_function<'s>(
query: None,
include_root: false,
tag_name_html_document: None,
+ resolution_cache: Default::default(),
};
let collection = collections::build_live_collection_wrapper(scope, runtime_ptr, descriptor);
rv.set(collection.into());
diff --git a/moli-renderer-v8/src/native_bridge/identity.rs b/moli-renderer-v8/src/native_bridge/identity.rs
index 378f51e46..4eafc658f 100644
--- a/moli-renderer-v8/src/native_bridge/identity.rs
+++ b/moli-renderer-v8/src/native_bridge/identity.rs
@@ -1,4 +1,9 @@
-use std::{cell::RefCell, collections::HashMap, rc::Rc};
+use std::{
+ cell::RefCell,
+ collections::HashMap,
+ hash::{Hash, Hasher},
+ rc::Rc,
+};
use super::super::{
document_runtime::DomHandle,
@@ -213,7 +218,7 @@ impl LiveCollectionQueryKind {
}
}
-#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+#[derive(Debug, Clone)]
pub(super) struct LiveCollectionDescriptor {
pub(super) collection_kind: CollectionKind,
pub(super) query_kind: LiveCollectionQueryKind,
@@ -222,10 +227,67 @@ pub(super) struct LiveCollectionDescriptor {
pub(super) query: Option<String>,
pub(super) include_root: bool,
pub(super) tag_name_html_document: Option<bool>,
+ pub(super) resolution_cache: LiveCollectionResolutionCache,
+}
+
+#[derive(Debug, Clone, Default)]
+pub(super) struct LiveCollectionResolutionCache(
+ Rc<RefCell<Option<LiveCollectionResolutionCacheEntry>>>,
+);
+
+#[derive(Debug)]
+struct LiveCollectionResolutionCacheEntry {
+ runtime_generation: u64,
+ query_version: u64,
+ handles: Rc<[DomHandle]>,
+}
+
+impl PartialEq for LiveCollectionDescriptor {
+ fn eq(&self, other: &Self) -> bool {
+ self.collection_kind == other.collection_kind
+ && self.query_kind == other.query_kind
+ && self.root == other.root
+ && self.generation == other.generation
+ && self.query == other.query
+ && self.include_root == other.include_root
+ && self.tag_name_html_document == other.tag_name_html_document
+ }
+}
+
+impl Eq for LiveCollectionDescriptor {}
+
+impl Hash for LiveCollectionDescriptor {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.collection_kind.hash(state);
+ self.query_kind.hash(state);
+ self.root.hash(state);
+ self.generation.hash(state);
+ self.query.hash(state);
+ self.include_root.hash(state);
+ self.tag_name_html_document.hash(state);
+ }
}
impl LiveCollectionDescriptor {
- pub(super) fn resolve(&self, host: &JsContextHost) -> Vec<DomHandle> {
+ pub(super) fn resolve(&self, host: &JsContextHost) -> Rc<[DomHandle]> {
+ let runtime_generation = host.runtime_reset_generation();
+ if self.generation != runtime_generation {
+ return Rc::from(Vec::<DomHandle>::new());
+ }
+ let query_version = host.dom_host().query_version();
+ if let Some(handles) = self
+ .resolution_cache
+ .0
+ .borrow()
+ .as_ref()
+ .filter(|entry| {
+ entry.runtime_generation == runtime_generation
+ && entry.query_version == query_version
+ })
+ .map(|entry| entry.handles.clone())
+ {
+ return handles;
+ }
let handles = if self.query_kind == LiveCollectionQueryKind::TagName {
let query = self.query.as_deref().unwrap_or("*");
match self.tag_name_html_document {
@@ -269,7 +331,13 @@ impl LiveCollectionDescriptor {
)
.unwrap_or_default()
};
- host.filter_parser_visible_handles(handles)
+ let handles = Rc::<[DomHandle]>::from(handles);
+ *self.resolution_cache.0.borrow_mut() = Some(LiveCollectionResolutionCacheEntry {
+ runtime_generation,
+ query_version,
+ handles: handles.clone(),
+ });
+ handles
}
}
diff --git a/moli-renderer-v8/src/network/navigation/loader.rs b/moli-renderer-v8/src/network/navigation/loader.rs
index b12da6f46..37ba14da5 100644
--- a/moli-renderer-v8/src/network/navigation/loader.rs
+++ b/moli-renderer-v8/src/network/navigation/loader.rs
@@ -61,12 +61,27 @@ impl NavigationResourceLoader {
request_client: ResourceRequestClient,
requested_url: url::Url,
task_runner: RendererResourceTaskRunner,
+ ) -> Self {
+ Self::new_with_cancel_handle(
+ request_client,
+ requested_url,
+ task_runner,
+ FetchCancelHandle::new(),
+ )
+ }
+
+ pub fn new_with_cancel_handle(
+ request_client: ResourceRequestClient,
+ requested_url: url::Url,
+ task_runner: RendererResourceTaskRunner,
+ cancel: FetchCancelHandle,
) -> Self {
Self::new_with_committed_document_browser_site_context(
request_client,
requested_url,
task_runner,
None,
+ cancel,
)
}
@@ -81,6 +96,7 @@ impl NavigationResourceLoader {
requested_url,
task_runner,
browser_site_context,
+ FetchCancelHandle::new(),
)
}
@@ -89,6 +105,7 @@ impl NavigationResourceLoader {
requested_url: url::Url,
task_runner: RendererResourceTaskRunner,
committed_document_browser_site_context: Option<Arc<BrowserCookieFacadeContext>>,
+ cancel: FetchCancelHandle,
) -> Self {
Self {
request_client,
@@ -100,7 +117,7 @@ impl NavigationResourceLoader {
.fetch_add(1, Ordering::Relaxed)
.saturating_add(1),
state: Mutex::new(NavigationResourceLoaderState::Created),
- cancel: FetchCancelHandle::new(),
+ cancel,
}),
}
}
diff --git a/moli-renderer-v8/src/page_task_queue/resource_completions.rs b/moli-renderer-v8/src/page_task_queue/resource_completions.rs
index 49ba973ef..4286b81d7 100644
--- a/moli-renderer-v8/src/page_task_queue/resource_completions.rs
+++ b/moli-renderer-v8/src/page_task_queue/resource_completions.rs
@@ -49,6 +49,10 @@ pub(crate) enum RendererOwnerWake {
token: RendererPageToken,
document: RendererDocumentLifecycleIdentity,
},
+ /// The browser-side commit response has crossed its release boundary.
+ /// Parser work parked at DocumentCommit may now resume without racing
+ /// ahead of target installation, old-Page retirement, or the response.
+ CommittedDocumentParserUnblocked { token: RendererPageToken },
/// A concrete late Inspector response that became ready inside a Page
/// owner turn. It is committed only after that turn has published all
/// protocol-visible output, and never schedules or executes Page work.
@@ -84,6 +88,10 @@ impl RendererOwnerWake {
Self::PostResponseDocumentLifecycle { token, document }
}
+ pub(crate) fn committed_document_parser_unblocked(token: RendererPageToken) -> Self {
+ Self::CommittedDocumentParserUnblocked { token }
+ }
+
pub(crate) fn runtime_inspector_response_publication(
token: RendererPageToken,
publication: RendererRuntimeInspectorResponsePublication,
@@ -113,6 +121,7 @@ impl RendererOwnerWake {
match self {
Self::Page { token, .. }
| Self::PostResponseDocumentLifecycle { token, .. }
+ | Self::CommittedDocumentParserUnblocked { token }
| Self::RuntimeInspectorResponsePublication { token, .. }
| Self::TopLevelNavigationHandoff { token, .. }
| Self::ReplacementDocumentViewSettled { token, .. } => token.page_id(),
@@ -126,6 +135,9 @@ impl RendererOwnerWake {
Self::PostResponseDocumentLifecycle { .. } => RendererOwnerWakeSource::Runtime(
RendererOwnerRuntimeActivitySource::DocumentLifecycleTurn,
),
+ Self::CommittedDocumentParserUnblocked { .. } => panic!(
+ "a committed-Document parser release is an owner continuation gate, not a Page source wake"
+ ),
Self::RuntimeInspectorResponsePublication { .. } => {
panic!("a concrete Runtime response publication is not a Page scheduling wake")
}
diff --git a/moli-renderer-v8/src/runtime/browser_context_runtime.rs b/moli-renderer-v8/src/runtime/browser_context_runtime.rs
index 1b8d5543a..dfc5138ba 100644
--- a/moli-renderer-v8/src/runtime/browser_context_runtime.rs
+++ b/moli-renderer-v8/src/runtime/browser_context_runtime.rs
@@ -178,6 +178,7 @@ struct RendererBrowserContextRuntimeInner {
service_worker_runtime: crate::service_worker_runtime::ServiceWorkerRuntimeService,
storage_partition_identity: RendererStoragePartitionIdentity,
next_web_storage_opaque_context_nonce: AtomicU64,
+ next_child_document_loader_id: AtomicU64,
next_detached_parser_script_fetch_id: AtomicU64,
next_dedicated_worker_instance_id: AtomicU64,
dedicated_worker_devtools_senders:
@@ -517,6 +518,7 @@ impl RendererBrowserContextRuntime {
service_worker_runtime,
storage_partition_identity,
next_web_storage_opaque_context_nonce: AtomicU64::default(),
+ next_child_document_loader_id: AtomicU64::default(),
next_detached_parser_script_fetch_id: AtomicU64::default(),
next_dedicated_worker_instance_id: AtomicU64::default(),
dedicated_worker_devtools_senders: Mutex::new(HashMap::new()),
@@ -647,6 +649,16 @@ impl RendererBrowserContextRuntime {
)
}
+ pub(crate) fn allocate_child_document_loader_id(&self) -> String {
+ let next_id = self
+ .inner
+ .next_child_document_loader_id
+ .fetch_add(1, Ordering::Relaxed)
+ .checked_add(1)
+ .expect("browser-context child Document loader id space exhausted");
+ format!("LID-CHILD-{next_id:010}")
+ }
+
pub(crate) fn prepare_detached_parser_script_fetch(
&self,
mut info: crate::protocol_types::PendingSubresourceFetchInfo,
@@ -917,6 +929,21 @@ mod tests {
assert!(runtime.shares_state_with(&clone));
}
+ #[test]
+ fn cloned_runtime_shares_child_document_loader_id_sequence() {
+ let runtime = RendererBrowserContextRuntime::new();
+ let clone = runtime.clone();
+
+ assert_eq!(
+ runtime.allocate_child_document_loader_id(),
+ "LID-CHILD-0000000001"
+ );
+ assert_eq!(
+ clone.allocate_child_document_loader_id(),
+ "LID-CHILD-0000000002"
+ );
+ }
+
#[test]
fn fresh_runtime_gets_isolated_partition_state() {
let left = RendererBrowserContextRuntime::new();
diff --git a/moli-renderer-v8/src/runtime/document_lifecycle.rs b/moli-renderer-v8/src/runtime/document_lifecycle.rs
index c9b945d7b..d93f36f05 100644
--- a/moli-renderer-v8/src/runtime/document_lifecycle.rs
+++ b/moli-renderer-v8/src/runtime/document_lifecycle.rs
@@ -43,6 +43,7 @@ pub enum RendererDocumentTerminationReason {
SupersededByCrossDocumentNavigation,
RestartedByDocumentOpen,
ReplacedByJavascriptResult,
+ MainResourceLoadFailed,
Stopped,
Detached,
}
diff --git a/moli-renderer-v8/src/runtime/mod.rs b/moli-renderer-v8/src/runtime/mod.rs
index df9af5c79..e4804745c 100644
--- a/moli-renderer-v8/src/runtime/mod.rs
+++ b/moli-renderer-v8/src/runtime/mod.rs
@@ -11,8 +11,10 @@ use std::{
use super::native_bridge::element::ClientRect;
use crate::DocumentStartScript;
+#[cfg(test)]
+use crate::dom::native::NativeDom;
use crate::{
- dom::{NodeId, native::NativeDom},
+ dom::NodeId,
network::{ResourceRequestClient, context::DocumentResourceLoader},
};
use anyhow::{Result, anyhow, ensure};
@@ -68,13 +70,13 @@ mod page_turn_scheduler;
mod page_vm;
pub(crate) use page_vm::dom_agent_state::RendererDomAgentState;
mod phase_one;
-mod post_parse_runtime_inputs;
mod protocol_output;
mod script_preloads;
mod service_worker_run;
pub(crate) use self::script_preloads::{
- BufferedScriptPreloadKey, BufferedScriptPreloadRequest, IncrementalBufferedScriptPreloadScanner,
+ BufferedScriptPreloadKey, BufferedScriptPreloadRequest, DocumentScriptPreloadStore,
+ IncrementalBufferedScriptPreloadScanner,
};
pub(crate) use self::browser_context_runtime::RendererOutputTransportSenderSlot;
@@ -384,10 +386,11 @@ pub(in crate::runtime) use self::phase_one::{
};
pub(crate) use self::protocol_output::{PendingRendererOutputRecord, RendererTurnOutputJournal};
pub use self::protocol_output::{
- RendererOutputCursor, RendererOutputFence, RendererOutputFenceLeaseId, RendererOutputItem,
- RendererOutputPublication, RendererOutputPublicationOrdering, RendererOutputRecord,
- RendererOutputResidenceIdentity, RendererOutputStreamCloseReason, RendererOutputStreamControl,
- RendererOutputStreamEpoch, RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,
+ RendererDocumentTitleChanged, RendererOutputCursor, RendererOutputFence,
+ RendererOutputFenceLeaseId, RendererOutputItem, RendererOutputPublication,
+ RendererOutputPublicationOrdering, RendererOutputRecord, RendererOutputResidenceIdentity,
+ RendererOutputStreamCloseReason, RendererOutputStreamControl, RendererOutputStreamEpoch,
+ RendererOutputStreamIdentity, RendererOutputTransportDiagnostics,
RendererOutputTransportMessage, RendererOutputTransportReceiver,
RendererOutputTransportSendError, RendererOutputTransportSender, RendererOwnerAction,
RendererProtocolObservation, renderer_output_transport_channel,
diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rs
index 043463f20..3ec85f3d2 100644
--- a/moli-renderer-v8/src/runtime/owner.rs
+++ b/moli-renderer-v8/src/runtime/owner.rs
@@ -13,8 +13,7 @@ use super::owner_local_store::{
RendererPageCommandDispatch, RendererPageCreationResolution, RendererPageLocalEntry,
RendererPageLocalEntryCheckoutError, RendererPageScheduledTurn, RendererPageToken,
RendererPageTurnAdmission, RendererPageTurnCheckoutError, RendererPendingPageCreation,
- RendererPreparedDocumentRequest, RendererPreparedDocumentResidence,
- advance_document_lifecycle_one_page_turn_via_local_task,
+ RendererPreparedDocumentResidence, advance_document_lifecycle_one_page_turn_via_local_task,
advance_dom_stable_wait_turn_on_entry_via_local_task,
advance_network_idle_wait_turn_on_entry_via_local_task,
advance_page_owner_one_turn_via_local_task,
@@ -65,9 +64,7 @@ use super::phase_one::{
StreamingHtmlPageCreationResult, StreamingNavigationPageCreationResult,
response_headers_indicate_download,
};
-use super::post_parse_runtime_inputs::InitialDocumentScriptOwnerInput;
use super::*;
-use crate::DocumentOwnedBlockingStylesheetDiscoveryInput;
use crate::RendererTopLevelNavigationDispatch;
use crate::document_runtime::{
response_content_security_policies_from_headers,
@@ -207,56 +204,12 @@ pub struct RendererCreateStreamingRawPageRequest {
pub reserved_service_worker_client: Option<RendererReservedServiceWorkerClient>,
}
-#[derive(Debug, Clone)]
-pub struct RendererCreateDocumentPageRequest {
- pub root_frame_id: Option<String>,
- pub main_document_commit: Option<RendererMainDocumentCommit>,
- pub requested_url: Url,
- pub navigation_initiator_url: Option<Url>,
- pub navigation_redirected: bool,
- pub navigation_redirect_count: usize,
- pub response_status: u16,
- pub response_headers: Vec<(String, String)>,
- pub loader: ResourceRequestClient,
- pub web_storage: crate::RendererWebStorageHandles,
- pub document: NativeDom,
- pub parser_document_handoffs: Vec<crate::parser::ParserDocumentHandoff>,
- pub parser_blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
- pub document_start_scripts: Vec<DocumentStartScript>,
- pub runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,
- pub runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
- pub runtime_isolated_worlds: Vec<crate::protocol_types::RuntimeIsolatedWorldDefinition>,
- pub permission_overrides: Vec<crate::protocol_types::PermissionOverrideRegistration>,
- pub extra_http_headers: Vec<(String, String)>,
- pub locale_override: Option<String>,
- pub timezone_override: Option<String>,
- pub script_execution_disabled: bool,
- pub bypass_content_security_policy: bool,
- pub emulated_media: crate::protocol_types::EmulatedMediaOverrides,
- pub idle_override: Option<crate::protocol_types::EmulatedIdleOverride>,
- pub viewport_surface: Option<crate::protocol_types::ViewportSurface>,
- pub cpu_throttling_rate: f64,
- pub network_offline: bool,
- pub blocked_url_patterns: Vec<String>,
- pub indexed_db_manager: Option<crate::context_bootstrap::WeakIndexedDbManager>,
- pub storage_bucket_store: Option<crate::context_bootstrap::SharedStorageBucketStore>,
- pub fetch_subresource_interception_enabled: bool,
- pub fetch_subresource_interception_resource_type: Option<crate::SubresourceResourceType>,
- pub layout_policy: LayoutPolicy,
- pub wpt_extensions_enabled: bool,
- pub stage: PageVmInitStage,
-}
-
pub enum RendererOwnerCommand {
CreateHtmlPage(RendererCreateHtmlPageRequest),
PrepareStreamingRawDocument {
token: RendererPageReservationToken,
request: RendererCreateStreamingRawPageRequest,
},
- PrepareNativeDomDocument {
- token: RendererPageReservationToken,
- request: RendererCreateDocumentPageRequest,
- },
UpdatePreparedRendererDocumentCommitConfiguration {
token: RendererPageReservationToken,
configuration: RendererPreparedDocumentCommitConfiguration,
@@ -329,7 +282,7 @@ enum RenderRuntimeDispatchOutcome {
Reply(Box<Result<RendererOwnerReply>>),
PageCreatedAndContinueNavigation {
page: Box<RendererAttachedPage>,
- turn: Box<RenderRuntimeTurn>,
+ continuation: RenderRuntimePageCreationContinuation,
},
BackgroundComplete(Result<()>),
PageCreationNavigationFailurePublished {
@@ -346,6 +299,40 @@ enum RenderRuntimeDispatchOutcome {
turn: Box<RenderRuntimeTurn>,
wake_token: RendererPageToken,
},
+ ContinueCommittedDocumentParserAfterPageWake {
+ turn: Box<RenderRuntimeTurn>,
+ wake_token: RendererPageToken,
+ },
+}
+
+enum RenderRuntimePageCreationContinuation {
+ NextTurn(Box<RenderRuntimeTurn>),
+ AfterCommittedDocumentResponse {
+ turn: Box<RenderRuntimeTurn>,
+ wake_token: RendererPageToken,
+ },
+}
+
+impl RenderRuntimePageCreationContinuation {
+ fn next_turn(turn: RenderRuntimeTurn) -> Self {
+ Self::NextTurn(Box::new(turn))
+ }
+
+ fn into_turn(self) -> RenderRuntimeTurn {
+ match self {
+ Self::NextTurn(turn) | Self::AfterCommittedDocumentResponse { turn, .. } => *turn,
+ }
+ }
+
+ fn turn(&self) -> &RenderRuntimeTurn {
+ match self {
+ Self::NextTurn(turn) | Self::AfterCommittedDocumentResponse { turn, .. } => turn,
+ }
+ }
+
+ fn requires_committed_document_response_release(&self) -> bool {
+ matches!(self, Self::AfterCommittedDocumentResponse { .. })
+ }
}
enum LivePageNavigationFailureDisposition {
@@ -371,6 +358,7 @@ struct RenderRuntimePendingTurn {
reply_tx: Option<oneshot::Sender<Result<RendererOwnerReply>>>,
turn: RenderRuntimeTurn,
allow_command_overtake: bool,
+ command_admission_output_predecessor: Option<RendererOutputFence>,
}
impl RenderRuntimePendingTurn {
@@ -432,17 +420,58 @@ struct RenderRuntimeParkedTurn {
wake_token: RendererPageToken,
ready_at: Option<Instant>,
condition: RenderRuntimeParkCondition,
+ command_admission_output_predecessor: Option<RendererOutputFence>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RenderRuntimeParkCondition {
PageActivity,
+ CommittedDocumentParserContinuation { parser_unblocked: bool },
ReplacementDocumentViewSettlement { expected_vm_creation_id: u64 },
}
impl RenderRuntimeParkCondition {
const fn admits_page_activity(self) -> bool {
- matches!(self, Self::PageActivity)
+ matches!(
+ self,
+ Self::PageActivity
+ | Self::CommittedDocumentParserContinuation {
+ parser_unblocked: true
+ }
+ )
+ }
+
+ const fn blocks_page_activity_until_parser_unblocked(self) -> bool {
+ matches!(
+ self,
+ Self::CommittedDocumentParserContinuation {
+ parser_unblocked: false
+ }
+ )
+ }
+
+ const fn allows_command_overtake(self) -> bool {
+ !matches!(self, Self::CommittedDocumentParserContinuation { .. })
+ }
+
+ const fn is_unblocked_committed_document_parser_continuation(self) -> bool {
+ matches!(
+ self,
+ Self::CommittedDocumentParserContinuation {
+ parser_unblocked: true
+ }
+ )
+ }
+
+ fn unblock_committed_document_parser(&mut self) -> bool {
+ let Self::CommittedDocumentParserContinuation { parser_unblocked } = self else {
+ return false;
+ };
+ if *parser_unblocked {
+ return false;
+ }
+ *parser_unblocked = true;
+ true
}
const fn admits_replacement_view_settlement(self, vm_creation_id: u64) -> bool {
@@ -501,18 +530,6 @@ enum RenderRuntimeTurn {
target_stage: PageVmInitStage,
navigation_reply_policy: PageCreationNavigationReplyPolicy,
},
- FinishDocumentCreatePage {
- requested_url: Url,
- navigation_initiator_url: Option<Url>,
- navigation_redirected: bool,
- navigation_redirect_count: usize,
- response_status: u16,
- response_headers: Vec<(String, String)>,
- page_vm: Box<PageVm>,
- script_owner_input: Box<InitialDocumentScriptOwnerInput>,
- stage: PageVmInitStage,
- started: Instant,
- },
DrainSharedWorkerServiceLane,
DrainServiceWorkerServiceLane,
RunPageTurn {
@@ -784,6 +801,30 @@ impl From<Result<RendererOwnerReply>> for RenderRuntimeDispatchOutcome {
}
}
+fn renderer_command_admission_page_token(
+ command: &RendererOwnerCommand,
+) -> Option<RendererPageToken> {
+ match command {
+ RendererOwnerCommand::RunAsyncPageCommand { token, .. }
+ | RendererOwnerCommand::RunProtocolPageCommand { token, .. }
+ | RendererOwnerCommand::WaitForNetworkIdle { token, .. }
+ | RendererOwnerCommand::WaitForDomStable { token, .. } => Some(*token),
+ _ => None,
+ }
+}
+
+fn merge_command_admission_output_predecessor(
+ mut result: Result<RendererOwnerReply>,
+ predecessor: Option<RendererOutputFence>,
+) -> Result<RendererOwnerReply> {
+ if let (Some(predecessor), Ok(RendererOwnerReply::AsyncPageCommandRan(output))) =
+ (predecessor, &mut result)
+ {
+ output.merge_renderer_output_predecessor(predecessor);
+ }
+ result
+}
+
#[derive(Debug)]
pub(super) struct RendererOwnerState {
pub(super) page_table: RendererPageTable,
@@ -1198,8 +1239,6 @@ impl RendererOwnerHandle {
};
entry.set_top_level_navigation_dispatch(top_level_navigation_dispatch);
self.restore_live_page_entry(token, entry);
- let admission = pending_phase_one_admission_after_restore_on_bound_owner_local_store(token);
- self.signal_pending_phase_one_admission(token, admission);
if matches!(
reply_boundary,
@@ -1207,16 +1246,25 @@ impl RendererOwnerHandle {
) {
self.publish_pending_page_creation_and_continue(
pending,
- RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
- token,
- follow_count: 0,
- completion: LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy,
- },
+ RenderRuntimePageCreationContinuation::AfterCommittedDocumentResponse {
+ turn: Box::new(
+ RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
+ token,
+ follow_count: 0,
+ completion:
+ LivePagePendingNavigationCompletion::PublishedPageCreation {
+ navigation_reply_policy,
+ },
+ },
+ ),
+ wake_token: token,
},
)
.await
} else {
+ let admission =
+ pending_phase_one_admission_after_restore_on_bound_owner_local_store(token);
+ self.signal_pending_phase_one_admission(token, admission);
RenderRuntimeDispatchOutcome::ContinueAfterPageWake {
turn: Box::new(
RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
@@ -1293,14 +1341,16 @@ impl RendererOwnerHandle {
self.restore_live_page_entry(token, entry);
self.publish_pending_page_creation_and_continue(
pending,
- RenderRuntimeTurn::FollowLivePagePendingLocationNavigation {
- token,
- stage,
- follow_count: 0,
- completion: LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy,
+ RenderRuntimePageCreationContinuation::next_turn(
+ RenderRuntimeTurn::FollowLivePagePendingLocationNavigation {
+ token,
+ stage,
+ follow_count: 0,
+ completion: LivePagePendingNavigationCompletion::PublishedPageCreation {
+ navigation_reply_policy,
+ },
},
- },
+ ),
)
.await
} else {
@@ -1344,7 +1394,7 @@ impl RendererOwnerHandle {
if should_resume_lifecycle {
RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation {
page: Box::new(attached_page),
- turn: Box::new(
+ continuation: RenderRuntimePageCreationContinuation::next_turn(
RenderRuntimeTurn::ResumeLivePageDocumentLifecycleAfterReply {
token,
document,
@@ -1372,11 +1422,11 @@ impl RendererOwnerHandle {
async fn publish_pending_page_creation_and_continue(
&self,
pending: RendererPendingPageCreation,
- turn: RenderRuntimeTurn,
+ continuation: RenderRuntimePageCreationContinuation,
) -> RenderRuntimeDispatchOutcome {
let token = pending.token;
if matches!(
- &turn,
+ continuation.turn(),
RenderRuntimeTurn::FollowLivePagePendingLocationNavigation {
follow_count: 0,
..
@@ -1395,7 +1445,7 @@ impl RendererOwnerHandle {
{
Ok(attached_page) => RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation {
page: Box::new(attached_page),
- turn: Box::new(turn),
+ continuation,
},
Err(error) => self.retire_failed_page_creation(token, error).await,
}
@@ -1986,76 +2036,6 @@ impl RendererOwnerHandle {
}
}
- pub fn build_create_document_page_request(
- &self,
- requested_url: Url,
- navigation_initiator_url: Option<Url>,
- navigation_redirected: bool,
- navigation_redirect_count: usize,
- response_status: u16,
- response_headers: Vec<(String, String)>,
- loader: &ResourceRequestClient,
- web_storage: crate::RendererWebStorageHandles,
- document: NativeDom,
- parser_document_handoffs: Vec<crate::parser::ParserDocumentHandoff>,
- parser_blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
- document_start_scripts: Vec<DocumentStartScript>,
- runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,
- runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
- extra_http_headers: Vec<(String, String)>,
- locale_override: Option<String>,
- timezone_override: Option<String>,
- script_execution_disabled: bool,
- bypass_content_security_policy: bool,
- cpu_throttling_rate: f64,
- emulated_media: crate::protocol_types::EmulatedMediaOverrides,
- viewport_surface: Option<crate::protocol_types::ViewportSurface>,
- network_offline: bool,
- blocked_url_patterns: Vec<String>,
- fetch_subresource_interception_enabled: bool,
- fetch_subresource_interception_resource_type: Option<crate::SubresourceResourceType>,
- stage: PageVmInitStage,
- ) -> RendererCreateDocumentPageRequest {
- RendererCreateDocumentPageRequest {
- root_frame_id: None,
- main_document_commit: None,
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- loader: loader.clone(),
- web_storage,
- document,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- document_start_scripts,
- runtime_bindings,
- runtime_inspector_session_restore_snapshots,
- runtime_isolated_worlds: Vec::new(),
- permission_overrides: Vec::new(),
- extra_http_headers,
- locale_override,
- timezone_override,
- script_execution_disabled,
- bypass_content_security_policy,
- cpu_throttling_rate,
- emulated_media,
- idle_override: None,
- viewport_surface,
- network_offline,
- blocked_url_patterns,
- indexed_db_manager: None,
- storage_bucket_store: None,
- fetch_subresource_interception_enabled,
- fetch_subresource_interception_resource_type,
- layout_policy: self.seal_layout_policy_for_page_creation(),
- wpt_extensions_enabled: false,
- stage,
- }
- }
-
pub fn refresh_page_view_on_slot_for_testing(
&self,
slot: &RendererPageSlotHandle,
@@ -2184,8 +2164,7 @@ impl RendererOwnerHandle {
fn release_rejected_command_output_reservation(&self, command: &RendererOwnerCommand) {
let reservation = match command {
RendererOwnerCommand::CreateHtmlPage(request) => Some(request.page_reservation),
- RendererOwnerCommand::PrepareStreamingRawDocument { token, .. }
- | RendererOwnerCommand::PrepareNativeDomDocument { token, .. } => Some(*token),
+ RendererOwnerCommand::PrepareStreamingRawDocument { token, .. } => Some(*token),
_ => None,
};
if let Some(reservation) = reservation {
@@ -2214,18 +2193,7 @@ impl RendererOwnerHandle {
let outcome = self
.prepare_renderer_document_on_owner_local_store(
token,
- RendererPreparedDocumentRequest::StreamingRaw(request),
- owner_local_store,
- )
- .await;
- self.release_page_output_reservation(token);
- outcome
- }
- RendererOwnerCommand::PrepareNativeDomDocument { token, request } => {
- let outcome = self
- .prepare_renderer_document_on_owner_local_store(
- token,
- RendererPreparedDocumentRequest::NativeDom(request),
+ request,
owner_local_store,
)
.await;
@@ -2511,6 +2479,34 @@ impl RendererOwnerHandle {
);
continue;
}
+ if let Some(token) = pending_turn.turn.committed_page_view_command_token()
+ && parked_turns.iter().any(|turn| {
+ turn.wake_token == token
+ && matches!(
+ turn.condition,
+ RenderRuntimeParkCondition::CommittedDocumentParserContinuation {
+ ..
+ }
+ )
+ })
+ {
+ // A command observed the committed Page through the
+ // browser-side response path, but its parser handoff
+ // has not run yet. Park the command on the same durable
+ // Page activity edge. The response-release wake puts
+ // the parser turn and continuation in front of it.
+ parked_turns.push_back(RenderRuntimeParkedTurn {
+ reply_tx: pending_turn.reply_tx,
+ turn: pending_turn.turn,
+ wake_token: token,
+ ready_at: None,
+ condition: RenderRuntimeParkCondition::PageActivity,
+ command_admission_output_predecessor: pending_turn
+ .command_admission_output_predecessor
+ .take(),
+ });
+ continue;
+ }
if let Some(token) = pending_turn.turn.committed_page_view_command_token()
&& let Some(expected_vm_creation_id) =
owner_local_store.page_uncommitted_vm_creation_id(token)
@@ -2534,6 +2530,9 @@ impl RendererOwnerHandle {
RenderRuntimeParkCondition::ReplacementDocumentViewSettlement {
expected_vm_creation_id,
},
+ command_admission_output_predecessor: pending_turn
+ .command_admission_output_predecessor
+ .take(),
});
continue;
}
@@ -2543,7 +2542,10 @@ impl RendererOwnerHandle {
.await;
match outcome {
RenderRuntimeDispatchOutcome::Reply(result) => {
- let result = *result;
+ let result = merge_command_admission_output_predecessor(
+ *result,
+ pending_turn.command_admission_output_predecessor.take(),
+ );
if let Some(reply_tx) = pending_turn.reply_tx {
let _ = reply_tx.send(result);
} else if let Err(error) = result {
@@ -2553,22 +2555,36 @@ impl RendererOwnerHandle {
}
}
RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation {
- page,
- turn,
+ mut page,
+ continuation,
} => {
match pending_turn.reply_tx {
Some(reply_tx) => {
+ let token = page.token;
+ if continuation.requires_committed_document_response_release() {
+ page.defer_committed_document_parser_until_response(
+ self.state.page_wake_tx.clone(),
+ );
+ }
if reply_tx
.send(Ok(RendererOwnerReply::PageCreated(page)))
.is_ok()
{
- pending_turns.push_back(RenderRuntimePendingTurn {
- reply_tx: None,
- turn: *turn,
- allow_command_overtake: true,
- });
+ self.enqueue_page_creation_continuation(
+ continuation,
+ &mut pending_turns,
+ &mut parked_turns,
+ );
} else {
- self.cancel_pending_turn_on_owner_local_store(*turn);
+ // The attached Page never crossed its
+ // ownership handoff, so there is no
+ // browser-side handle that can retire
+ // it later. This differs from a live
+ // navigation command observer going
+ // away after Page publication: that
+ // continuation is detached below and
+ // keeps running in the background.
+ remove_page_on_bound_owner_local_store(token);
}
}
None => {
@@ -2584,8 +2600,9 @@ impl RendererOwnerHandle {
drop(page);
pending_turns.push_back(RenderRuntimePendingTurn {
reply_tx: None,
- turn: *turn,
+ turn: continuation.into_turn(),
allow_command_overtake: true,
+ command_admission_output_predecessor: None,
});
}
}
@@ -2639,6 +2656,9 @@ impl RendererOwnerHandle {
reply_tx: pending_turn.reply_tx,
turn: *turn,
allow_command_overtake: true,
+ command_admission_output_predecessor: pending_turn
+ .command_admission_output_predecessor
+ .take(),
});
}
}
@@ -2647,53 +2667,54 @@ impl RendererOwnerHandle {
wake_token,
ready_at,
} => {
- if pending_turn
- .reply_tx
- .as_ref()
- .is_some_and(|tx| tx.is_closed())
- {
- self.detach_navigation_or_cancel_pending_turn(
- *turn,
- &mut pending_turns,
- );
- } else {
- parked_turns.push_back(RenderRuntimeParkedTurn {
- reply_tx: pending_turn.reply_tx,
- turn: *turn,
- wake_token,
- ready_at: Some(ready_at),
- condition: RenderRuntimeParkCondition::PageActivity,
- });
- }
+ self.park_or_cancel_turn(
+ pending_turn.reply_tx,
+ *turn,
+ wake_token,
+ Some(ready_at),
+ RenderRuntimeParkCondition::PageActivity,
+ pending_turn.command_admission_output_predecessor.take(),
+ &mut parked_turns,
+ &mut pending_turns,
+ );
}
RenderRuntimeDispatchOutcome::ContinueAfterPageWake {
turn,
wake_token,
} => {
- if pending_turn
- .reply_tx
- .as_ref()
- .is_some_and(|tx| tx.is_closed())
- {
- self.detach_navigation_or_cancel_pending_turn(
- *turn,
- &mut pending_turns,
- );
- } else {
- parked_turns.push_back(RenderRuntimeParkedTurn {
- reply_tx: pending_turn.reply_tx,
- turn: *turn,
- wake_token,
- ready_at: None,
- condition: RenderRuntimeParkCondition::PageActivity,
- });
- }
+ self.park_or_cancel_turn(
+ pending_turn.reply_tx,
+ *turn,
+ wake_token,
+ None,
+ RenderRuntimeParkCondition::PageActivity,
+ pending_turn.command_admission_output_predecessor.take(),
+ &mut parked_turns,
+ &mut pending_turns,
+ );
}
- }
- if let Some(token) = completed_page_turn_token {
- // A bounded Page turn may have published the exact
- // lifecycle milestone page creation is waiting for.
- // Re-admit only that one-shot observer at this owner
+ RenderRuntimeDispatchOutcome::ContinueCommittedDocumentParserAfterPageWake {
+ turn,
+ wake_token,
+ } => {
+ self.park_or_cancel_turn(
+ pending_turn.reply_tx,
+ *turn,
+ wake_token,
+ None,
+ RenderRuntimeParkCondition::CommittedDocumentParserContinuation {
+ parser_unblocked: true,
+ },
+ pending_turn.command_admission_output_predecessor.take(),
+ &mut parked_turns,
+ &mut pending_turns,
+ );
+ }
+ }
+ if let Some(token) = completed_page_turn_token {
+ // A bounded Page turn may have published the exact
+ // lifecycle milestone page creation is waiting for.
+ // Re-admit only that one-shot observer at this owner
// boundary, before a producer wake can advance the
// Page through a follow-up turn. Other waits retain
// their existing wake/deadline contracts.
@@ -2829,6 +2850,9 @@ impl RendererOwnerHandle {
RendererOwnerCommand::RemovePage { token } => Some(*token),
_ => None,
};
+ let mut command_admission_output_predecessor =
+ renderer_command_admission_page_token(&envelope.command)
+ .and_then(renderer_output_fence_for_tail_on_bound_owner_local_store);
let command_future = Box::pin(
self.dispatch_command_inline_on_owner_local_store(envelope.command, owner_local_store),
);
@@ -2842,21 +2866,34 @@ impl RendererOwnerHandle {
}
match outcome {
RenderRuntimeDispatchOutcome::Reply(result) => {
- let _ = envelope.reply_tx.send(*result);
+ let result = merge_command_admission_output_predecessor(
+ *result,
+ command_admission_output_predecessor.take(),
+ );
+ let _ = envelope.reply_tx.send(result);
}
- RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation { page, turn } => {
+ RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation {
+ mut page,
+ continuation,
+ } => {
+ let token = page.token;
+ if continuation.requires_committed_document_response_release() {
+ page.defer_committed_document_parser_until_response(
+ self.state.page_wake_tx.clone(),
+ );
+ }
if envelope
.reply_tx
.send(Ok(RendererOwnerReply::PageCreated(page)))
.is_ok()
{
- pending_turns.push_back(RenderRuntimePendingTurn {
- reply_tx: None,
- turn: *turn,
- allow_command_overtake: true,
- });
+ self.enqueue_page_creation_continuation(
+ continuation,
+ pending_turns,
+ parked_turns,
+ );
} else {
- self.cancel_pending_turn_on_owner_local_store(*turn);
+ remove_page_on_bound_owner_local_store(token);
}
}
RenderRuntimeDispatchOutcome::BackgroundComplete(result) => {
@@ -2890,6 +2927,8 @@ impl RendererOwnerHandle {
// by the command cannot inherit an already-pending
// command and then yield to a second one.
allow_command_overtake: false,
+ command_admission_output_predecessor: command_admission_output_predecessor
+ .take(),
});
}
}
@@ -2898,30 +2937,45 @@ impl RendererOwnerHandle {
wake_token,
ready_at,
} => {
- if envelope.reply_tx.is_closed() {
- self.detach_navigation_or_cancel_pending_turn(*turn, pending_turns);
- } else {
- parked_turns.push_back(RenderRuntimeParkedTurn {
- reply_tx: Some(envelope.reply_tx),
- turn: *turn,
- wake_token,
- ready_at: Some(ready_at),
- condition: RenderRuntimeParkCondition::PageActivity,
- });
- }
+ self.park_or_cancel_turn(
+ Some(envelope.reply_tx),
+ *turn,
+ wake_token,
+ Some(ready_at),
+ RenderRuntimeParkCondition::PageActivity,
+ command_admission_output_predecessor.take(),
+ parked_turns,
+ pending_turns,
+ );
}
RenderRuntimeDispatchOutcome::ContinueAfterPageWake { turn, wake_token } => {
- if envelope.reply_tx.is_closed() {
- self.detach_navigation_or_cancel_pending_turn(*turn, pending_turns);
- } else {
- parked_turns.push_back(RenderRuntimeParkedTurn {
- reply_tx: Some(envelope.reply_tx),
- turn: *turn,
- wake_token,
- ready_at: None,
- condition: RenderRuntimeParkCondition::PageActivity,
- });
- }
+ self.park_or_cancel_turn(
+ Some(envelope.reply_tx),
+ *turn,
+ wake_token,
+ None,
+ RenderRuntimeParkCondition::PageActivity,
+ command_admission_output_predecessor.take(),
+ parked_turns,
+ pending_turns,
+ );
+ }
+ RenderRuntimeDispatchOutcome::ContinueCommittedDocumentParserAfterPageWake {
+ turn,
+ wake_token,
+ } => {
+ self.park_or_cancel_turn(
+ Some(envelope.reply_tx),
+ *turn,
+ wake_token,
+ None,
+ RenderRuntimeParkCondition::CommittedDocumentParserContinuation {
+ parser_unblocked: true,
+ },
+ command_admission_output_predecessor.take(),
+ parked_turns,
+ pending_turns,
+ );
}
}
if let Some(token) = removed_page_token {
@@ -2931,13 +2985,20 @@ impl RendererOwnerHandle {
fn cancel_dispatch_outcome_for_context_shutdown(&self, outcome: RenderRuntimeDispatchOutcome) {
match outcome {
- RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation { page, turn } => {
+ RenderRuntimeDispatchOutcome::PageCreatedAndContinueNavigation {
+ page,
+ continuation,
+ } => {
drop(page);
- self.cancel_pending_turn_on_owner_local_store(*turn);
+ self.cancel_pending_turn_on_owner_local_store(continuation.into_turn());
}
RenderRuntimeDispatchOutcome::ContinueNextTurn(turn)
| RenderRuntimeDispatchOutcome::ContinueAfterPageWakeOrDeadline { turn, .. }
- | RenderRuntimeDispatchOutcome::ContinueAfterPageWake { turn, .. } => {
+ | RenderRuntimeDispatchOutcome::ContinueAfterPageWake { turn, .. }
+ | RenderRuntimeDispatchOutcome::ContinueCommittedDocumentParserAfterPageWake {
+ turn,
+ ..
+ } => {
self.cancel_pending_turn_on_owner_local_store(*turn);
}
RenderRuntimeDispatchOutcome::Reply(_)
@@ -3070,6 +3131,64 @@ impl RendererOwnerHandle {
next_owner_maintenance_deadline_on_bound_owner_local_store()
}
+ fn enqueue_page_creation_continuation(
+ &self,
+ continuation: RenderRuntimePageCreationContinuation,
+ pending_turns: &mut RenderRuntimePendingTurnQueue,
+ parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,
+ ) {
+ match continuation {
+ RenderRuntimePageCreationContinuation::NextTurn(turn) => {
+ pending_turns.push_back(RenderRuntimePendingTurn {
+ reply_tx: None,
+ turn: *turn,
+ allow_command_overtake: true,
+ command_admission_output_predecessor: None,
+ });
+ }
+ RenderRuntimePageCreationContinuation::AfterCommittedDocumentResponse {
+ turn,
+ wake_token,
+ } => {
+ parked_turns.push_back(RenderRuntimeParkedTurn {
+ reply_tx: None,
+ turn: *turn,
+ wake_token,
+ ready_at: None,
+ condition: RenderRuntimeParkCondition::CommittedDocumentParserContinuation {
+ parser_unblocked: false,
+ },
+ command_admission_output_predecessor: None,
+ });
+ }
+ }
+ }
+
+ fn park_or_cancel_turn(
+ &self,
+ reply_tx: Option<oneshot::Sender<Result<RendererOwnerReply>>>,
+ turn: RenderRuntimeTurn,
+ wake_token: RendererPageToken,
+ ready_at: Option<Instant>,
+ condition: RenderRuntimeParkCondition,
+ command_admission_output_predecessor: Option<RendererOutputFence>,
+ parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,
+ pending_turns: &mut RenderRuntimePendingTurnQueue,
+ ) {
+ if reply_tx.as_ref().is_some_and(|tx| tx.is_closed()) {
+ self.detach_navigation_or_cancel_pending_turn(turn, pending_turns);
+ return;
+ }
+ parked_turns.push_back(RenderRuntimeParkedTurn {
+ reply_tx,
+ turn,
+ wake_token,
+ ready_at,
+ condition,
+ command_admission_output_predecessor,
+ });
+ }
+
/// Admit one detached page turn. Producer wakes remain in the
/// owner channel while a page turn is pending, so every legacy wake gets a
/// bounded adapter turn without being merged into an inferred continuation.
@@ -3078,8 +3197,31 @@ impl RendererOwnerHandle {
&self,
token: RendererPageToken,
trigger: PageTurnTrigger,
+ allow_command_overtake: bool,
pending_turns: &mut RenderRuntimePendingTurnQueue,
) {
+ if let Some(turn) = self.admit_page_turn(token, trigger, allow_command_overtake) {
+ pending_turns.push_back(turn);
+ }
+ }
+
+ fn enqueue_page_turn_before_commands(
+ &self,
+ token: RendererPageToken,
+ trigger: PageTurnTrigger,
+ pending_turns: &mut RenderRuntimePendingTurnQueue,
+ ) {
+ if let Some(turn) = self.admit_page_turn(token, trigger, false) {
+ pending_turns.push_front(turn);
+ }
+ }
+
+ fn admit_page_turn(
+ &self,
+ token: RendererPageToken,
+ trigger: PageTurnTrigger,
+ allow_command_overtake: bool,
+ ) -> Option<RenderRuntimePendingTurn> {
match schedule_page_turn_on_bound_owner_local_store(token, trigger) {
RendererPageTurnAdmission::EnqueueOwnerTurn => {}
RendererPageTurnAdmission::AlreadyScheduled => {
@@ -3094,14 +3236,15 @@ impl RendererOwnerHandle {
?trigger,
"discarded stale page turn trigger"
);
- return;
+ return None;
}
}
- pending_turns.push_back(RenderRuntimePendingTurn {
+ Some(RenderRuntimePendingTurn {
reply_tx: None,
turn: RenderRuntimeTurn::RunPageTurn { token },
- allow_command_overtake: true,
- });
+ allow_command_overtake,
+ command_admission_output_predecessor: None,
+ })
}
fn handle_page_owner_wake(
@@ -3112,6 +3255,26 @@ impl RendererOwnerHandle {
) {
match wake {
RendererOwnerWake::Page { token, source } => {
+ if parked_turns.iter().any(|turn| {
+ turn.wake_token == token
+ && turn.condition.blocks_page_activity_until_parser_unblocked()
+ }) {
+ // The source payload remains resident. Its edge wake is
+ // reconciled after the commit caller observes the Page,
+ // so parser work cannot outrun the DocumentCommit reply.
+ return;
+ }
+ let allow_command_overtake = !parked_turns.iter().any(|turn| {
+ turn.wake_token == token
+ && turn.condition.admits_page_activity()
+ && !turn.condition.allows_command_overtake()
+ });
+ let committed_document_parser_handoff = self
+ .enqueue_unblocked_committed_document_parser_continuation_before_commands(
+ token,
+ parked_turns,
+ pending_turns,
+ );
if matches!(source, RendererOwnerWakeSource::ParseTimeDocumentScriptWork) {
// Parse-time script payloads live inside the parked
// continuation. Admitting a generic Page turn for this
@@ -3141,10 +3304,29 @@ impl RendererOwnerHandle {
// lifecycle observers capture that settled boundary
// before the next lifecycle turn can advance into load.
self.enqueue_parked_turns_for_wake(token, parked_turns, pending_turns);
- self.enqueue_page_turn(token, PageTurnTrigger::producer(source), pending_turns);
+ self.enqueue_page_turn(
+ token,
+ PageTurnTrigger::producer(source),
+ allow_command_overtake,
+ pending_turns,
+ );
+ return;
+ }
+ if committed_document_parser_handoff {
+ self.enqueue_page_turn_before_commands(
+ token,
+ PageTurnTrigger::producer(source),
+ pending_turns,
+ );
+ self.enqueue_parked_turns_for_wake(token, parked_turns, pending_turns);
return;
}
- self.enqueue_page_turn(token, PageTurnTrigger::producer(source), pending_turns);
+ self.enqueue_page_turn(
+ token,
+ PageTurnTrigger::producer(source),
+ allow_command_overtake,
+ pending_turns,
+ );
self.enqueue_parked_turns_for_wake(token, parked_turns, pending_turns);
}
RendererOwnerWake::PostResponseDocumentLifecycle { token, document } => {
@@ -3167,6 +3349,7 @@ impl RendererOwnerHandle {
reply_tx: None,
turn: RenderRuntimeTurn::RunPageTurn { token },
allow_command_overtake: true,
+ command_admission_output_predecessor: None,
});
}
RendererPageTurnAdmission::AlreadyScheduled => {
@@ -3179,6 +3362,25 @@ impl RendererOwnerHandle {
}
self.enqueue_parked_turns_for_wake(token, parked_turns, pending_turns);
}
+ RendererOwnerWake::CommittedDocumentParserUnblocked { token } => {
+ let mut unblocked = false;
+ for parked_turn in parked_turns
+ .iter_mut()
+ .filter(|turn| turn.wake_token == token)
+ {
+ unblocked |= parked_turn.condition.unblock_committed_document_parser();
+ }
+ if !unblocked {
+ tracing::trace!(
+ page_id = token.page_id.as_u64(),
+ "discarded stale committed-Document parser release"
+ );
+ return;
+ }
+ let admission =
+ pending_phase_one_admission_after_restore_on_bound_owner_local_store(token);
+ self.signal_pending_phase_one_admission(token, admission);
+ }
RendererOwnerWake::RuntimeInspectorResponsePublication { token, publication } => {
let renderer_output_predecessor =
renderer_output_fence_for_tail_on_bound_owner_local_store(token);
@@ -3204,6 +3406,7 @@ impl RendererOwnerHandle {
handoff,
},
allow_command_overtake: false,
+ command_admission_output_predecessor: None,
});
}
RendererOwnerWake::ReplacementDocumentViewSettled {
@@ -3331,6 +3534,7 @@ impl RendererOwnerHandle {
reply_tx: None,
turn: RenderRuntimeTurn::DrainSharedWorkerServiceLane,
allow_command_overtake: false,
+ command_admission_output_predecessor: None,
});
}
@@ -3342,6 +3546,7 @@ impl RendererOwnerHandle {
reply_tx: None,
turn: RenderRuntimeTurn::DrainServiceWorkerServiceLane,
allow_command_overtake: false,
+ command_admission_output_predecessor: None,
});
}
@@ -3381,21 +3586,67 @@ impl RendererOwnerHandle {
parked_turn: RenderRuntimeParkedTurn,
pending_turns: &mut RenderRuntimePendingTurnQueue,
) {
+ if let Some(turn) = self.pending_turn_from_parked(parked_turn, pending_turns) {
+ pending_turns.push_back(turn);
+ }
+ }
+
+ fn pending_turn_from_parked(
+ &self,
+ parked_turn: RenderRuntimeParkedTurn,
+ pending_turns: &mut RenderRuntimePendingTurnQueue,
+ ) -> Option<RenderRuntimePendingTurn> {
if parked_turn
.reply_tx
.as_ref()
.is_some_and(|tx| tx.is_closed())
{
self.detach_navigation_or_cancel_pending_turn(parked_turn.turn, pending_turns);
+ None
} else {
- pending_turns.push_back(RenderRuntimePendingTurn {
+ let allow_command_overtake = parked_turn.condition.allows_command_overtake();
+ Some(RenderRuntimePendingTurn {
reply_tx: parked_turn.reply_tx,
turn: parked_turn.turn,
- allow_command_overtake: true,
- });
+ allow_command_overtake,
+ command_admission_output_predecessor: parked_turn
+ .command_admission_output_predecessor,
+ })
}
}
+ fn enqueue_unblocked_committed_document_parser_continuation_before_commands(
+ &self,
+ token: RendererPageToken,
+ parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,
+ pending_turns: &mut RenderRuntimePendingTurnQueue,
+ ) -> bool {
+ let mut index = 0;
+ let mut admitted = 0usize;
+ while index < parked_turns.len() {
+ let matches = parked_turns[index].wake_token == token
+ && parked_turns[index]
+ .condition
+ .is_unblocked_committed_document_parser_continuation();
+ if matches {
+ let parked_turn = parked_turns
+ .remove(index)
+ .expect("matching committed-Document continuation must remain parked");
+ if let Some(turn) = self.pending_turn_from_parked(parked_turn, pending_turns) {
+ pending_turns.push_front(turn);
+ admitted += 1;
+ }
+ } else {
+ index += 1;
+ }
+ }
+ debug_assert!(
+ admitted <= 1,
+ "one Page cannot retain multiple committed-Document parser continuations"
+ );
+ admitted != 0
+ }
+
fn enqueue_due_parked_turns(
&self,
parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,
@@ -3893,7 +4144,7 @@ impl RendererOwnerHandle {
let tokens = snapshot_due_page_task_tokens_on_bound_owner_local_store(due_at_or_before);
let admitted = !tokens.is_empty();
for token in tokens {
- self.enqueue_page_turn(token, PageTurnTrigger::Deadline, pending_turns);
+ self.enqueue_page_turn(token, PageTurnTrigger::Deadline, true, pending_turns);
}
admitted
}
@@ -3914,6 +4165,7 @@ impl RendererOwnerHandle {
reply_tx: None,
turn: RenderRuntimeTurn::RunOwnerMaintenance { task },
allow_command_overtake: true,
+ command_admission_output_predecessor: None,
});
true
}
@@ -3949,6 +4201,7 @@ impl RendererOwnerHandle {
reply_tx: None,
turn,
allow_command_overtake: true,
+ command_admission_output_predecessor: None,
});
} else {
self.cancel_pending_turn_on_owner_local_store(turn);
@@ -3992,14 +4245,8 @@ impl RendererOwnerHandle {
}
}
RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
- token,
- completion,
- ..
+ token, ..
} => {
- debug_assert!(
- completion.retires_page_on_navigation_failure(),
- "detached phase-one navigation must continue as background work"
- );
if let Some(mut entry) = self.checkout_live_page_entry_for_cancellation(
token,
"phase-one location navigation",
@@ -4013,19 +4260,10 @@ impl RendererOwnerHandle {
self.restore_live_page_entry(token, entry);
}
}
- RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
- token,
- completion,
- ..
- } => {
- debug_assert!(
- completion.retires_page_on_navigation_failure(),
- "live navigation with a detached command observer should continue as background work"
- );
+ RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle { token, .. } => {
remove_page_on_bound_owner_local_store(token);
}
RenderRuntimeTurn::FinishHtmlCreatePage { .. }
- | RenderRuntimeTurn::FinishDocumentCreatePage { .. }
| RenderRuntimeTurn::DrainSharedWorkerServiceLane
| RenderRuntimeTurn::DrainServiceWorkerServiceLane
| RenderRuntimeTurn::RunPageTurn { .. }
@@ -4098,14 +4336,14 @@ impl RendererOwnerHandle {
"renderer command records must settle into the concrete Page stream before completion"
);
// Chromium flushes every notification already queued by the current
- // DevTools command before exposing its response. The concrete batch
+ // DevTools command before exposing its response. The concrete batch
// settled here is the exact Moli equivalent of that queue
- // prefix. Do not require a Runtime-only causal marker: DOM commands
+ // prefix. Do not require a Runtime-only causal marker: DOM commands
// and WebAPI side effects (for example mutation, CSP and Log records)
// are produced during this owner turn but do not all carry a
// `RendererRuntimeCommandCausalIdentity`.
//
- // This remains a narrow fence. It names this command turn's one
+ // This remains a narrow fence. It names this command turn's one
// publication, not a Page-wide watermark, and a later independent
// task necessarily settles into a later stream sequence.
let renderer_output_cursor = concrete_output
@@ -5593,16 +5831,18 @@ impl RendererOwnerHandle {
self.signal_internal_document_lifecycle_turn(token);
self.publish_pending_page_creation_and_continue(
pending,
- RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
- token,
- document,
- target_stage,
- follow_count: 0,
- completion:
- LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy,
- },
- },
+ RenderRuntimePageCreationContinuation::next_turn(
+ RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
+ token,
+ document,
+ target_stage,
+ follow_count: 0,
+ completion:
+ LivePagePendingNavigationCompletion::PublishedPageCreation {
+ navigation_reply_policy,
+ },
+ },
+ ),
)
.await
} else {
@@ -5633,16 +5873,18 @@ impl RendererOwnerHandle {
let token = pending.token;
self.publish_pending_page_creation_and_continue(
pending,
- RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
- token,
- document,
- target_stage,
- follow_count: 0,
- completion:
- LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy,
- },
- },
+ RenderRuntimePageCreationContinuation::next_turn(
+ RenderRuntimeTurn::ContinueLivePageNavigationPostParseLifecycle {
+ token,
+ document,
+ target_stage,
+ follow_count: 0,
+ completion:
+ LivePagePendingNavigationCompletion::PublishedPageCreation {
+ navigation_reply_policy,
+ },
+ },
+ ),
)
.await
} else {
@@ -5674,15 +5916,17 @@ impl RendererOwnerHandle {
let token = pending.token;
self.publish_pending_page_creation_and_continue(
pending,
- RenderRuntimeTurn::FollowLivePagePendingLocationNavigation {
- token,
- stage,
- follow_count: 0,
- completion:
- LivePagePendingNavigationCompletion::PublishedPageCreation {
- navigation_reply_policy,
- },
- },
+ RenderRuntimePageCreationContinuation::next_turn(
+ RenderRuntimeTurn::FollowLivePagePendingLocationNavigation {
+ token,
+ stage,
+ follow_count: 0,
+ completion:
+ LivePagePendingNavigationCompletion::PublishedPageCreation {
+ navigation_reply_policy,
+ },
+ },
+ ),
)
.await
}
@@ -5727,69 +5971,6 @@ impl RendererOwnerHandle {
)
.await
}
- RenderRuntimeTurn::FinishDocumentCreatePage {
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- page_vm,
- script_owner_input,
- stage,
- started,
- } => {
- let (page_vm, page_tasks) = match self
- .run_owner_lane_local_task(async move {
- let mut page_vm = *page_vm;
- if page_vm.vm().has_pending_location_navigation() {
- return Ok((page_vm, None));
- }
- let page_tasks = (*script_owner_input).finalize(&mut page_vm).await;
- Ok((page_vm, Some(page_tasks)))
- })
- .await
- {
- Ok(outcome) => outcome,
- Err(error) => return Err(error).into(),
- };
- let Some(page_tasks) = page_tasks else {
- return self
- .continue_page_creation_with_pending_navigation(
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- page_vm,
- stage,
- crate::RendererPageCreationReplyBoundary::LifecycleTarget,
- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- PageCreationNavigationReplyPolicy::FollowBeforeReply,
- )
- .await;
- };
- RenderRuntimeDispatchOutcome::ContinueNextTurn(Box::new(
- RenderRuntimeTurn::FinishHtmlCreatePage {
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- page_vm: Box::new(page_vm),
- page_tasks,
- stage,
- started,
- reply_boundary: crate::RendererPageCreationReplyBoundary::LifecycleTarget,
- top_level_navigation_dispatch:
- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
- navigation_reply_policy:
- PageCreationNavigationReplyPolicy::FollowBeforeReply,
- },
- ))
- }
RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
token,
follow_count,
@@ -5813,16 +5994,24 @@ impl RendererOwnerHandle {
pending_phase_one_admission_after_restore_on_bound_owner_local_store(
wake_token,
);
+ let continues_committed_document_parser_prefix = completion
+ .continues_committed_document_parser_prefix()
+ && admission == PhaseOneResidenceAdmission::ReadyPageTurn;
self.signal_pending_phase_one_admission(wake_token, admission);
- RenderRuntimeDispatchOutcome::ContinueAfterPageWake {
- turn: Box::new(
- RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
- token,
- follow_count,
- completion,
- },
- ),
- wake_token,
+ let turn = Box::new(
+ RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {
+ token,
+ follow_count,
+ completion,
+ },
+ );
+ if continues_committed_document_parser_prefix {
+ RenderRuntimeDispatchOutcome::ContinueCommittedDocumentParserAfterPageWake {
+ turn,
+ wake_token,
+ }
+ } else {
+ RenderRuntimeDispatchOutcome::ContinueAfterPageWake { turn, wake_token }
}
}
Ok(LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation { stage }) => {
@@ -6295,7 +6484,7 @@ impl RendererOwnerHandle {
async fn prepare_renderer_document_on_owner_local_store(
&self,
token: RendererPageReservationToken,
- request: RendererPreparedDocumentRequest,
+ request: RendererCreateStreamingRawPageRequest,
owner_local_store: &mut RendererOwnerLocalStore,
) -> RenderRuntimeDispatchOutcome {
if token.local_host_id() != self.state.owner_local_host_id {
@@ -6354,30 +6543,15 @@ impl RendererOwnerHandle {
isolate_bootstrap,
isolate_reservation,
} = residence;
- match request {
- RendererPreparedDocumentRequest::StreamingRaw(request) => {
- self.create_page_reply_from_streaming_raw_request_on_owner_local_store(
- page_id,
- request,
- isolate_allocator,
- isolate_bootstrap,
- isolate_reservation,
- owner_local_store,
- )
- .await
- }
- RendererPreparedDocumentRequest::NativeDom(request) => {
- self.create_page_reply_from_prepared_document_request_on_owner_local_store(
- page_id,
- request,
- isolate_allocator,
- isolate_bootstrap,
- isolate_reservation,
- owner_local_store,
- )
- .await
- }
- }
+ self.create_page_reply_from_streaming_raw_request_on_owner_local_store(
+ page_id,
+ request,
+ isolate_allocator,
+ isolate_bootstrap,
+ isolate_reservation,
+ owner_local_store,
+ )
+ .await
}
#[allow(clippy::too_many_arguments)]
@@ -6533,7 +6707,7 @@ impl RendererOwnerHandle {
};
let bootstrap = Box::pin(async move {
let started = Instant::now();
- ConcurrentParseTimeRuntime::finish_creation_from_external_raw_document_response(
+ ConcurrentParseTimeRuntime::create_external_raw_document_response_at_reply_boundary(
page_id,
local_executor,
&loader,
@@ -6545,6 +6719,7 @@ impl RendererOwnerHandle {
response_status,
response_headers,
raw_body,
+ reply_boundary,
)
.await
});
@@ -6631,210 +6806,6 @@ impl RendererOwnerHandle {
}
}
- #[allow(clippy::too_many_arguments)]
- async fn create_page_reply_from_prepared_document_request_on_owner_local_store(
- &self,
- page_id: PageId,
- request: RendererCreateDocumentPageRequest,
- allocator: RendererDocumentIsolateAllocator,
- bootstrap: RendererDocumentIsolateBootstrap,
- reservation: RendererDocumentIsolateReservation,
- _owner_local_store: &mut RendererOwnerLocalStore,
- ) -> RenderRuntimeDispatchOutcome {
- let RendererCreateDocumentPageRequest {
- root_frame_id,
- main_document_commit,
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- loader,
- web_storage,
- document,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- document_start_scripts,
- runtime_bindings,
- runtime_inspector_session_restore_snapshots,
- runtime_isolated_worlds,
- permission_overrides,
- extra_http_headers,
- locale_override,
- timezone_override,
- script_execution_disabled,
- bypass_content_security_policy,
- cpu_throttling_rate,
- emulated_media,
- idle_override,
- viewport_surface,
- network_offline,
- blocked_url_patterns,
- indexed_db_manager,
- storage_bucket_store,
- fetch_subresource_interception_enabled,
- fetch_subresource_interception_resource_type,
- layout_policy,
- wpt_extensions_enabled,
- stage,
- } = request;
- let loader = loader_for_new_page(
- &loader,
- &extra_http_headers,
- network_offline,
- &blocked_url_patterns,
- );
- let document_content_security_policies = if bypass_content_security_policy {
- Vec::new()
- } else {
- crate::content_security_policy::content_security_policy_headers(&response_headers)
- };
- let response_content_security_policies = if bypass_content_security_policy {
- Vec::new()
- } else {
- response_content_security_policies_from_headers(&response_headers)
- };
- let response_content_security_report_only_policies = if bypass_content_security_policy {
- Vec::new()
- } else {
- response_content_security_report_only_policies_from_headers(&response_headers)
- };
- let response_referrer_policy = response_referrer_policy_from_headers(&response_headers);
- let reporting_endpoint_base_url = document
- .final_url()
- .cloned()
- .unwrap_or_else(|| requested_url.clone());
- let content_security_reporting_endpoints = if bypass_content_security_policy {
- Default::default()
- } else {
- crate::content_security_policy::content_security_policy_reporting_endpoints_from_headers(
- &response_headers,
- &reporting_endpoint_base_url,
- )
- };
- let cross_origin_embedder_policy =
- crate::cross_origin_isolation::cross_origin_embedder_policy_from_headers(
- &response_headers,
- );
- let document_isolation_policy =
- crate::cross_origin_isolation::document_isolation_policy_from_headers(
- &response_headers,
- );
- let cross_origin_isolated =
- crate::cross_origin_isolation::response_headers_enable_cross_origin_isolation(
- &reporting_endpoint_base_url,
- &response_headers,
- );
- let document_default_language =
- crate::document_language::document_default_language_from_headers(&response_headers);
- let document_last_modified =
- crate::document_last_modified::document_last_modified_from_headers(&response_headers);
- let owner = self.clone();
- match self
- .run_owner_lane_local_task(async move {
- let owner_local_context = owner.owner_local_context()?;
- let owner_wake = owner.owner_wake_sender_for_page(&owner_local_context, page_id);
- let runtime_hooks = PageVmRuntimeHooks::with_owner_wake(
- owner_wake,
- owner.state.browser_context_runtime.clone(),
- )
- .with_renderer_document_isolate_allocator(allocator)
- .with_prepared_renderer_document_isolate(bootstrap, reservation)?;
- debug!(stage = ?stage, "starting page VM creation from document");
- let started = Instant::now();
- let env = PageVmEnvConfig {
- web_storage,
- document_start_scripts,
- runtime_bindings,
- runtime_inspector_session_restore_snapshots,
- runtime_isolated_worlds,
- permission_overrides,
- extra_http_headers,
- document_content_security_policies,
- response_content_security_policies,
- response_content_security_report_only_policies,
- response_referrer_policy,
- content_security_reporting_endpoints,
- cross_origin_embedder_policy,
- document_isolation_policy,
- cross_origin_isolated,
- document_default_language,
- document_last_modified,
- locale_override,
- timezone_override,
- script_execution_disabled,
- bypass_content_security_policy,
- cpu_throttling_rate,
- emulated_media,
- idle_override,
- viewport_surface,
- network_offline,
- blocked_url_patterns,
- indexed_db_manager,
- storage_bucket_store,
- fetch_subresource_interception_enabled,
- fetch_subresource_interception_resource_type,
- layout_policy,
- wpt_extensions_enabled,
- root_frame_id,
- main_document_commit,
- top_level_storage_key: None,
- navigation_bootstrap_entry: None,
- reserved_service_worker_client_id: None,
- };
- let mut page_vm = PageVm::new(
- page_id,
- owner.state.local_executor.clone(),
- &loader,
- &env,
- runtime_hooks,
- crate::dom::native::DomHost::from_dom(document),
- started,
- )?;
- let script_owner_input = InitialDocumentScriptOwnerInput::accept(
- &mut page_vm,
- &loader,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- )?;
- page_vm.set_target_stage(stage);
- page_vm.install_stored_runtime_isolated_worlds_on_named_owner_lane()?;
- page_vm.install_stored_runtime_bindings_on_named_owner_lane()?;
- let document_start_scripts = page_vm.document_start_scripts.clone();
- let _ = page_vm.run_document_start_scripts_on_named_owner_lane(
- &document_start_scripts,
- |_| {},
- )?;
- debug!(
- phase = "document start scripts",
- elapsed_ms = started.elapsed().as_millis(),
- "document start scripts finished"
- );
- Ok((page_vm, script_owner_input, started))
- })
- .await
- {
- Ok((page_vm, script_owner_input, started)) => {
- RenderRuntimeDispatchOutcome::ContinueNextTurn(Box::new(
- RenderRuntimeTurn::FinishDocumentCreatePage {
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- page_vm: Box::new(page_vm),
- script_owner_input: Box::new(script_owner_input),
- stage,
- started,
- },
- ))
- }
- Err(error) => Err(error).into(),
- }
- }
-
pub fn record(&self, page_id: PageId) -> Option<RendererPageRecord> {
self.state.page_table.record(page_id)
}
@@ -6948,6 +6919,7 @@ mod tests {
reply_tx: None,
turn: RenderRuntimeTurn::RunOwnerMaintenance { task },
allow_command_overtake: true,
+ command_admission_output_predecessor: None,
});
assert!(pending.has_owner_maintenance_turn());
diff --git a/moli-renderer-v8/src/runtime/owner_local.rs b/moli-renderer-v8/src/runtime/owner_local.rs
index eb5ecf0f0..3ce62b39e 100644
--- a/moli-renderer-v8/src/runtime/owner_local.rs
+++ b/moli-renderer-v8/src/runtime/owner_local.rs
@@ -5,6 +5,7 @@ use super::owner_local_store::{
remove_page_on_bound_owner_local_store,
};
use super::*;
+use crate::page_task_queue::RendererOwnerWake;
use crate::render_runtime::RenderRuntimeHandle;
use anyhow::anyhow;
use tokio::sync::oneshot;
@@ -25,9 +26,29 @@ pub struct RendererAttachedPage {
pub(super) creation_diagnostics: RendererPageCreationDiagnostics,
pub(super) creation_artifacts: RendererPageCreationArtifacts,
pub(super) pending_download: Option<RendererPendingDownloadActivation>,
+ pub(super) committed_document_post_response_continuation:
+ Option<RendererPageCommandPostResponseContinuation>,
}
impl RendererAttachedPage {
+ pub(super) fn defer_committed_document_parser_until_response(
+ &mut self,
+ page_wake_tx: tokio::sync::mpsc::UnboundedSender<RendererOwnerWake>,
+ ) {
+ debug_assert!(
+ self.committed_document_post_response_continuation.is_none(),
+ "committed-Document parser continuation can only be armed once"
+ );
+ let token = self.token;
+ self.committed_document_post_response_continuation = Some(
+ RendererPageCommandPostResponseContinuation::new(move || {
+ let _ = page_wake_tx.send(RendererOwnerWake::committed_document_parser_unblocked(
+ token,
+ ));
+ }),
+ );
+ }
+
pub(super) fn into_parts(
self,
local_executor: JsLocalExecutor,
@@ -48,6 +69,8 @@ impl RendererAttachedPage {
page_context_cancel_tx: self.page_context_cancel_tx,
javascript_dialog_broker: self.javascript_dialog_broker,
inspector_pause_bridge: self.inspector_pause_bridge,
+ committed_document_post_response_continuation: self
+ .committed_document_post_response_continuation,
_not_send: PhantomData,
},
self.page_state,
@@ -66,6 +89,8 @@ pub struct RendererPageHandle {
page_context_cancel_tx: RendererPageContextCancelSender,
javascript_dialog_broker: RendererJavaScriptDialogBroker,
inspector_pause_bridge: crate::script_vm::inspector_pause::RendererInspectorPauseBridge,
+ committed_document_post_response_continuation:
+ Option<RendererPageCommandPostResponseContinuation>,
_not_send: PhantomData<Rc<()>>,
}
@@ -127,6 +152,13 @@ impl RendererPageHandle {
self.devtools_agent_token
}
+ #[doc(hidden)]
+ pub fn take_committed_document_post_response_continuation(
+ &mut self,
+ ) -> Option<RendererPageCommandPostResponseContinuation> {
+ self.committed_document_post_response_continuation.take()
+ }
+
pub fn take_pending_modal_javascript_dialogs(&self) -> Vec<RendererPendingJavaScriptDialog> {
self.javascript_dialog_broker.take_pending()
}
diff --git a/moli-renderer-v8/src/runtime/owner_local_store.rs b/moli-renderer-v8/src/runtime/owner_local_store.rs
index bd80468d7..25ca47668 100644
--- a/moli-renderer-v8/src/runtime/owner_local_store.rs
+++ b/moli-renderer-v8/src/runtime/owner_local_store.rs
@@ -14,7 +14,7 @@ use super::navigation::{
PageCreationNavigationFailurePublisher, PageCreationResolution, PageCreationRetirement,
PageNavigationOwnerFailure, page_creation_navigation_failure_scope,
};
-use super::owner::{RendererCreateDocumentPageRequest, RendererCreateStreamingRawPageRequest};
+use super::owner::RendererCreateStreamingRawPageRequest;
use super::owner_deadline_index::OwnerDeadlineIndex;
use super::owner_local::RendererAttachedPage;
use super::owner_maintenance::{
@@ -30,7 +30,7 @@ use super::page_vm::{
PageVmRuntimeCommandLifecycleAdvance, PageVmRuntimeCommandOutputScopeId,
renderer_document_lifecycle_milestone_for_stage,
};
-use super::phase_one::ParseTimePageVmCreationOutcome;
+use super::phase_one::{ParseTimePageVmCreationOutcome, PendingPhaseOneResumeOutcome};
use super::*;
use crate::page_task_queue::{
PostParsePageOwnedWork, RendererPageOwnedTaskSources, RendererPageSchedulerTask,
@@ -412,6 +412,10 @@ pub(super) enum LivePageNavigationFailureRecipient {
}
impl LivePagePendingNavigationCompletion {
+ pub(super) fn continues_committed_document_parser_prefix(&self) -> bool {
+ matches!(self, Self::PublishedPageCreation { .. })
+ }
+
pub(super) fn chain_limit_error_context(&self) -> &'static str {
match self {
Self::Background | Self::PublishedPageCreation { .. } => {
@@ -540,17 +544,12 @@ pub(super) struct RendererOwnerLocalStore {
}
pub(super) struct RendererPreparedDocumentResidence {
- pub(super) request: RendererPreparedDocumentRequest,
+ pub(super) request: RendererCreateStreamingRawPageRequest,
pub(super) isolate_allocator: RendererDocumentIsolateAllocator,
pub(super) isolate_bootstrap: RendererDocumentIsolateBootstrap,
pub(super) isolate_reservation: RendererDocumentIsolateReservation,
}
-pub(super) enum RendererPreparedDocumentRequest {
- StreamingRaw(RendererCreateStreamingRawPageRequest),
- NativeDom(RendererCreateDocumentPageRequest),
-}
-
pub(super) struct RendererOwnerLocalStoreSession<'a> {
store: &'a mut RendererOwnerLocalStore,
}
@@ -889,9 +888,6 @@ impl RendererPageLocalEntry {
}
pub(super) fn settle_standalone_navigation_follow(&mut self, succeeded: bool) {
- // A failed phase-one resume consumes its pending residence before
- // returning the entry, so the failure boundary can legitimately own
- // an empty shell with neither an installed nor a pending PageVm.
let current = self
.active_page_vm()
.and_then(|page_vm| page_vm.vm().pending_location_navigation_handoff());
@@ -1201,6 +1197,15 @@ impl RendererPageLocalEntry {
Ok(wake_token)
}
+ fn install_resumed_phase_one_page_vm(&mut self, page_vm: PageVm) {
+ debug_assert!(
+ self.pending_phase_one_navigation.is_none(),
+ "a resumed phase-one PageVm cannot coexist with its consumed residence"
+ );
+ self.retire_document_lifecycle_turn();
+ self.vm = Some(page_vm);
+ }
+
fn reject_pending_phase_one_navigation_state(
pending: &mut PageVmPendingPhaseOneNavigation,
message: String,
@@ -1946,6 +1951,18 @@ pub(super) async fn advance_pending_phase_one_navigation_on_entry_via_local_task
return Err(error);
}
};
+ let phase_one_outcome = match phase_one_outcome {
+ PendingPhaseOneResumeOutcome::Progress(outcome) => outcome,
+ PendingPhaseOneResumeOutcome::MainResourceLoadFailed { page_vm, error } => {
+ metadata.reject(
+ None,
+ &browser_context_runtime,
+ format!("Cannot navigate to URL: {error}"),
+ );
+ entry.install_resumed_phase_one_page_vm(page_vm);
+ return Err(error);
+ }
+ };
match phase_one_outcome {
ParseTimePageVmCreationOutcome::PendingPhaseOne(residence) => {
let pending = PageVmPendingPhaseOneNavigation::new(residence, metadata);
@@ -1954,8 +1971,7 @@ pub(super) async fn advance_pending_phase_one_navigation_on_entry_via_local_task
}
ParseTimePageVmCreationOutcome::TriggeredNavigation { mut page_vm, stage } => {
metadata.complete_service_worker_follow(&mut page_vm);
- entry.retire_document_lifecycle_turn();
- entry.vm = Some(page_vm);
+ entry.install_resumed_phase_one_page_vm(page_vm);
Ok(LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation { stage })
}
ParseTimePageVmCreationOutcome::ContinuePhaseTwo {
@@ -1965,8 +1981,7 @@ pub(super) async fn advance_pending_phase_one_navigation_on_entry_via_local_task
started,
} => {
metadata.complete_service_worker_follow(&mut page_vm);
- entry.retire_document_lifecycle_turn();
- entry.vm = Some(page_vm);
+ entry.install_resumed_phase_one_page_vm(page_vm);
let (page_vm, pending_document_lifecycle_turn) =
entry.page_vm_and_document_lifecycle_turn_mut();
let outcome = page_vm
@@ -2486,14 +2501,7 @@ impl RendererOwnerLocalStore {
configuration.fetch_subresource_interception_resource_type;
}};
}
- match &mut residence.request {
- RendererPreparedDocumentRequest::StreamingRaw(request) => {
- apply_configuration!(request);
- }
- RendererPreparedDocumentRequest::NativeDom(request) => {
- apply_configuration!(request);
- }
- }
+ apply_configuration!(&mut residence.request);
Ok(())
}
@@ -3392,6 +3400,7 @@ impl RendererOwnerLocalStore {
creation_diagnostics,
creation_artifacts,
pending_download,
+ committed_document_post_response_continuation: None,
},
resume_parked_page_turn,
}
diff --git a/moli-renderer-v8/src/runtime/page.rs b/moli-renderer-v8/src/runtime/page.rs
index 2ab2db9c0..4c733879e 100644
--- a/moli-renderer-v8/src/runtime/page.rs
+++ b/moli-renderer-v8/src/runtime/page.rs
@@ -12,7 +12,6 @@ use tracing::debug;
use url::Url;
use crate::{
- dom::native::NativeDom,
local_executor::{JsLocalExecutor, is_on_named_owner_execution_lane_for},
network::ResourceRequestClient,
render_runtime::RenderRuntimeOwner,
@@ -322,186 +321,6 @@ impl JsRuntime {
.set_renderer_output_transport_sender(sender);
}
- pub async fn create_document_page_best_effort(
- &self,
- requested_url: Url,
- navigation_initiator_url: Option<Url>,
- navigation_redirected: bool,
- navigation_redirect_count: usize,
- response_status: u16,
- response_headers: Vec<(String, String)>,
- loader: &ResourceRequestClient,
- web_storage: crate::RendererWebStorageHandles,
- document: NativeDom,
- parser_document_handoffs: Vec<crate::parser::ParserDocumentHandoff>,
- parser_blocking_stylesheet_inputs: Vec<
- crate::DocumentOwnedBlockingStylesheetDiscoveryInput,
- >,
- indexed_db_manager: Option<crate::context_bootstrap::WeakIndexedDbManager>,
- storage_bucket_store: Option<crate::context_bootstrap::SharedStorageBucketStore>,
- document_start_scripts: Vec<DocumentStartScript>,
- runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,
- runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
- extra_http_headers: Vec<(String, String)>,
- locale_override: Option<String>,
- timezone_override: Option<String>,
- script_execution_disabled: bool,
- cpu_throttling_rate: f64,
- emulated_media: crate::protocol_types::EmulatedMediaOverrides,
- viewport_surface: Option<crate::protocol_types::ViewportSurface>,
- network_offline: bool,
- blocked_url_patterns: Vec<String>,
- fetch_subresource_interception_enabled: bool,
- fetch_subresource_interception_resource_type: Option<crate::SubresourceResourceType>,
- ) -> Result<(
- RendererPageHandle,
- Arc<RendererPageState>,
- RendererPageCreationDiagnostics,
- RendererPageCreationArtifacts,
- Option<RendererPendingDownloadActivation>,
- )> {
- let prepared = self
- .prepare_document_page_with_inspector_session_restores(
- self.reserve_page_for_creation(),
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- loader,
- web_storage,
- document,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- indexed_db_manager,
- storage_bucket_store,
- document_start_scripts,
- runtime_bindings,
- runtime_inspector_session_restore_snapshots,
- extra_http_headers,
- locale_override,
- timezone_override,
- script_execution_disabled,
- false,
- cpu_throttling_rate,
- emulated_media,
- viewport_surface,
- network_offline,
- blocked_url_patterns,
- fetch_subresource_interception_enabled,
- fetch_subresource_interception_resource_type,
- false,
- PageVmInitStage::Load,
- None,
- None,
- )
- .await?;
- let permit = prepared.issue_commit_permit();
- prepared.commit(permit).await
- }
-
- /// Moves an already parsed document and its bootstrap inputs onto the
- /// renderer owner lane without creating execution contexts or running
- /// document scripts.
- #[allow(clippy::too_many_arguments)]
- pub async fn prepare_document_page_with_inspector_session_restores(
- &self,
- page_reservation: RendererPageReservationToken,
- requested_url: Url,
- navigation_initiator_url: Option<Url>,
- navigation_redirected: bool,
- navigation_redirect_count: usize,
- response_status: u16,
- response_headers: Vec<(String, String)>,
- loader: &ResourceRequestClient,
- web_storage: crate::RendererWebStorageHandles,
- document: NativeDom,
- parser_document_handoffs: Vec<crate::parser::ParserDocumentHandoff>,
- parser_blocking_stylesheet_inputs: Vec<
- crate::DocumentOwnedBlockingStylesheetDiscoveryInput,
- >,
- indexed_db_manager: Option<crate::context_bootstrap::WeakIndexedDbManager>,
- storage_bucket_store: Option<crate::context_bootstrap::SharedStorageBucketStore>,
- document_start_scripts: Vec<DocumentStartScript>,
- runtime_bindings: Vec<crate::protocol_types::RuntimeBindingRegistration>,
- runtime_inspector_session_restore_snapshots: Vec<RendererInspectorSessionRestoreSnapshot>,
- extra_http_headers: Vec<(String, String)>,
- locale_override: Option<String>,
- timezone_override: Option<String>,
- script_execution_disabled: bool,
- bypass_content_security_policy: bool,
- cpu_throttling_rate: f64,
- emulated_media: crate::protocol_types::EmulatedMediaOverrides,
- viewport_surface: Option<crate::protocol_types::ViewportSurface>,
- network_offline: bool,
- blocked_url_patterns: Vec<String>,
- fetch_subresource_interception_enabled: bool,
- fetch_subresource_interception_resource_type: Option<crate::SubresourceResourceType>,
- wpt_extensions_enabled: bool,
- stage: PageVmInitStage,
- root_frame_id: Option<String>,
- main_document_commit: Option<crate::RendererMainDocumentCommit>,
- ) -> Result<PreparedRendererDocument> {
- let mut request = self
- .inner
- .renderer_owner
- .build_create_document_page_request(
- requested_url,
- navigation_initiator_url,
- navigation_redirected,
- navigation_redirect_count,
- response_status,
- response_headers,
- loader,
- web_storage,
- document,
- parser_document_handoffs,
- parser_blocking_stylesheet_inputs,
- document_start_scripts,
- runtime_bindings,
- runtime_inspector_session_restore_snapshots,
- extra_http_headers,
- locale_override,
- timezone_override,
- script_execution_disabled,
- bypass_content_security_policy,
- cpu_throttling_rate,
- emulated_media,
- viewport_surface,
- network_offline,
- blocked_url_patterns,
- fetch_subresource_interception_enabled,
- fetch_subresource_interception_resource_type,
- stage,
- );
- request.indexed_db_manager = indexed_db_manager;
- request.storage_bucket_store = storage_bucket_store;
- request.root_frame_id = root_frame_id;
- request.main_document_commit = main_document_commit;
- request.wpt_extensions_enabled = wpt_extensions_enabled;
- let reply = self
- .inner
- .renderer_owner
- .dispatch_command(RendererOwnerCommand::PrepareNativeDomDocument {
- token: page_reservation,
- request,
- })
- .await?;
- match reply {
- RendererOwnerReply::PreparedRendererDocumentStored {
- renderer_devtools_agent_token,
- } => Ok(PreparedRendererDocument::new(
- self.clone(),
- page_reservation,
- renderer_devtools_agent_token,
- )),
- _ => Err(anyhow!(
- "renderer owner returned non-prepare reply for prepared NativeDom document request"
- )),
- }
- }
-
pub async fn create_html_page_from_response(
&self,
requested_url: Url,
diff --git a/moli-renderer-v8/src/runtime/page_surface.rs b/moli-renderer-v8/src/runtime/page_surface.rs
index 27bc86c00..c4c7ccd87 100644
--- a/moli-renderer-v8/src/runtime/page_surface.rs
+++ b/moli-renderer-v8/src/runtime/page_surface.rs
@@ -1610,13 +1610,17 @@ impl RendererCommandTurnOutput {
/// before the matching protocol response is exposed.
///
/// This is deliberately a stream cursor, not a process-global watermark.
- /// It is present only when the separately transported Page publication
- /// contains command-owned records; unrelated records cannot make a
- /// response wait for a broader Page watermark.
+ /// It covers the Page-stream prefix that preceded command admission plus
+ /// any records settled by the command itself. Later Page work receives a
+ /// later cursor and cannot delay this response.
pub fn renderer_output_predecessor(&self) -> Option<RendererOutputFence> {
self.renderer_output_predecessor.clone()
}
+ pub(crate) fn merge_renderer_output_predecessor(&mut self, predecessor: RendererOutputFence) {
+ predecessor.merge_into_same_stream_tail(&mut self.renderer_output_predecessor);
+ }
+
pub fn runtime_inspector_output(&self) -> Option<&RendererRuntimeCommandOutput> {
self.completion.runtime_inspector_output()
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/backend_node_registry.rs b/moli-renderer-v8/src/runtime/page_vm/backend_node_registry.rs
index 7d6e30437..efc1666fb 100644
--- a/moli-renderer-v8/src/runtime/page_vm/backend_node_registry.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/backend_node_registry.rs
@@ -14,6 +14,7 @@ pub(crate) struct RendererBackendNodeKey {
#[derive(Clone, Copy, Debug)]
struct RendererBackendNodeRecord {
key: RendererBackendNodeKey,
+ resolves_while_detached: bool,
}
pub(crate) struct RendererBackendNodeRegistry {
@@ -72,8 +73,13 @@ impl RendererBackendNodeRegistry {
.checked_add(1)
.expect("renderer backend node id namespace exhausted");
self.node_ids.insert(key, backend_node_id);
- self.nodes
- .insert(backend_node_id, RendererBackendNodeRecord { key });
+ self.nodes.insert(
+ backend_node_id,
+ RendererBackendNodeRecord {
+ key,
+ resolves_while_detached: false,
+ },
+ );
backend_node_id
}
@@ -81,6 +87,28 @@ impl RendererBackendNodeRegistry {
Some(self.nodes.get(&backend_node_id)?.key)
}
+ /// Keeps an event-exposed node id resolvable after its Document detaches
+ /// the node without destroying the underlying DOM object.
+ ///
+ /// Blink freezes the input node's DOMNodeId synchronously when
+ /// `Page.fileChooserOpened` is emitted. If the same script then calls
+ /// `document.open()`, the event id still resolves to that detached input.
+ /// This bit is intentionally per-record: ordinary ids keep the stricter
+ /// Document-generation validation used elsewhere in Lightmount.
+ pub(crate) fn retain_detached_resolution(&mut self, backend_node_id: u32) -> bool {
+ let Some(record) = self.nodes.get_mut(&backend_node_id) else {
+ return false;
+ };
+ record.resolves_while_detached = true;
+ true
+ }
+
+ pub(crate) fn resolves_while_detached(&self, backend_node_id: u32) -> bool {
+ self.nodes
+ .get(&backend_node_id)
+ .is_some_and(|record| record.resolves_while_detached)
+ }
+
pub(crate) fn remove_stale_id(&mut self, backend_node_id: u32, key: RendererBackendNodeKey) {
self.nodes.remove(&backend_node_id);
if self.node_ids.get(&key).copied() == Some(backend_node_id) {
@@ -205,4 +233,16 @@ mod tests {
let second = registry.id_for_node(key.document_id, key.handle);
assert_ne!(first, second);
}
+
+ #[test]
+ fn detached_resolution_is_opt_in_per_backend_node_record() {
+ let mut registry = RendererBackendNodeRegistry::default();
+ let retained = registry.id_for_node(document_id(1), dom_handle(7));
+ let ordinary = registry.id_for_node(document_id(1), dom_handle(8));
+
+ assert!(registry.retain_detached_resolution(retained));
+ assert!(registry.resolves_while_detached(retained));
+ assert!(!registry.resolves_while_detached(ordinary));
+ assert!(!registry.retain_detached_resolution(u32::MAX));
+ }
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/dom_agent_state.rs b/moli-renderer-v8/src/runtime/page_vm/dom_agent_state.rs
index 544890f85..16362a045 100644
--- a/moli-renderer-v8/src/runtime/page_vm/dom_agent_state.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/dom_agent_state.rs
@@ -284,6 +284,20 @@ impl RendererDomAgentState {
backend_nodes.borrow().key_for_id(backend_node_id)
}
+ pub(crate) fn retain_detached_backend_node_resolution(&self, backend_node_id: u32) -> bool {
+ let backend_nodes = self.inner.borrow().backend_nodes.clone();
+ backend_nodes
+ .borrow_mut()
+ .retain_detached_resolution(backend_node_id)
+ }
+
+ pub(crate) fn backend_node_resolves_while_detached(&self, backend_node_id: u32) -> bool {
+ let backend_nodes = self.inner.borrow().backend_nodes.clone();
+ backend_nodes
+ .borrow()
+ .resolves_while_detached(backend_node_id)
+ }
+
pub(crate) fn remove_stale_backend_node_id(
&self,
backend_node_id: u32,
diff --git a/moli-renderer-v8/src/runtime/page_vm/main_document_lifecycle_completion.rs b/moli-renderer-v8/src/runtime/page_vm/main_document_lifecycle_completion.rs
index 1b5d01b9f..2e66209eb 100644
--- a/moli-renderer-v8/src/runtime/page_vm/main_document_lifecycle_completion.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/main_document_lifecycle_completion.rs
@@ -189,6 +189,7 @@ async fn execute_main_document_lifecycle_body_on_owner_local_task(
page_vm.prepare_dom_agent_for_main_document_dom_content_loaded(
document_lifecycle_identity,
);
+ page_vm.record_document_title_change_if_needed();
}
let waits_for_descendants = milestone == RendererDocumentLifecycleMilestone::Load
&& page_vm
diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rs
index 8d2b38031..373ffb153 100644
--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs
@@ -14,6 +14,7 @@ use crate::document_script_scheduler::{
use crate::dom::native::DomHost;
use crate::dynamic_script_owner::{DynamicScriptOwnerId, DynamicScriptPageTaskClaim};
use crate::frame_owner_model::DocumentId;
+use crate::live_document_parser::DocumentParserSession;
use crate::local_executor::is_on_named_owner_execution_lane_for;
use crate::module_script_continuation::{
ModuleScriptCompletionOwner, ModuleScriptContinuation, ModuleScriptContinuationGraphAdvance,
@@ -24,7 +25,6 @@ use crate::page_task_queue::{
PostParseLifecycleWork, PostParsePageOwnedWork, RendererOwnerWakeSender,
RendererResourceCompletionSender,
};
-use crate::parser::DocumentStream;
use crate::script_vm::{
MainDocumentLifecycleBody, MainDocumentLifecycleCallbackEffect,
MainDocumentLifecycleCompletion, MainDocumentLifecycleFollowup,
@@ -1534,6 +1534,7 @@ pub(crate) struct PageVm {
)>,
dom_agent_state: RendererDomAgentState,
pending_dom_mutation_event_batches: Vec<RendererDomMutationEventBatch>,
+ last_published_document_title: String,
css_agent_sessions: HashMap<Option<String>, RendererCssAgentSessionState>,
// Page-owned task queue lives on the page VM itself so parse-time turns and later lifecycle
// turns share one owner-lane carrier. The runtime still uses it in narrow slices today, but
@@ -1781,9 +1782,33 @@ impl PageVm {
// call is therefore a no-op for that suffix and a safety boundary for
// ordinary, lifecycle, error, and maintenance turns.
self.absorb_pending_dom_mutations_into_output_journal();
+ self.record_document_title_change_if_needed();
self.vm_mut().settle_renderer_output_publication()
}
+ fn record_document_title_change_if_needed(&mut self) {
+ // A PageVm can exist without a DevTools-facing Page residence in
+ // standalone embeddings and owner-boundary unit tests. Lifecycle
+ // progress must not depend on an observer being installed. Keep the
+ // last-published value untouched so a later binding still publishes
+ // the current title on its first owner settlement.
+ if !self.vm().has_renderer_output_journal() {
+ return;
+ }
+ let title = self.vm().document_runtime.dom_host().dom().document_title();
+ if title == self.last_published_document_title {
+ return;
+ }
+ self.last_published_document_title.clone_from(&title);
+ self.append_renderer_output_records(vec![PendingRendererOutputRecord::observation(
+ None,
+ RendererProtocolObservation::DocumentTitleChanged(RendererDocumentTitleChanged {
+ source_document: self.document_lifecycle.identity(),
+ title,
+ }),
+ )]);
+ }
+
pub(super) fn append_renderer_output_records(&self, records: Vec<PendingRendererOutputRecord>) {
self.vm().append_renderer_output_records(records);
}
@@ -4603,6 +4628,7 @@ impl PageVm {
.refresh_top_level_document_url_from_world_locations();
}
+ #[cfg(test)]
pub(super) fn new(
page_id: PageId,
local_executor: JsLocalExecutor,
@@ -4762,6 +4788,7 @@ impl PageVm {
report_snapshot_cache: None,
dom_agent_state,
pending_dom_mutation_event_batches: Vec::new(),
+ last_published_document_title: String::new(),
css_agent_sessions: HashMap::new(),
page_task_queue,
next_module_script_evaluation_reaction_id: 0,
@@ -4904,7 +4931,7 @@ impl PageVm {
loader: &ResourceRequestClient,
env: &PageVmEnvConfig,
runtime_hooks: PageVmRuntimeHooks,
- stream: &mut DocumentStream,
+ parser_session: &mut DocumentParserSession,
started: Instant,
before_document_start: impl FnOnce(&mut Self) -> Result<()>,
) -> Result<(Self, bool)> {
@@ -4914,13 +4941,13 @@ impl PageVm {
loader,
env,
runtime_hooks,
- stream,
+ parser_session,
started,
)?;
page_vm.install_stored_runtime_isolated_worlds_on_named_owner_lane()?;
page_vm.install_stored_runtime_bindings_on_named_owner_lane()?;
let null_custom_element_registry_elements =
- stream.take_parser_stream_null_custom_element_registry_elements();
+ parser_session.take_parser_stream_null_custom_element_registry_elements();
page_vm
.vm_mut()
.apply_parser_created_null_registry_associations_in_default_context(
@@ -5077,11 +5104,11 @@ impl PageVm {
loader: &ResourceRequestClient,
env: &PageVmEnvConfig,
runtime_hooks: PageVmRuntimeHooks,
- stream: &mut DocumentStream,
+ parser_session: &mut DocumentParserSession,
started: Instant,
) -> Result<PageVm> {
let mut page_vm =
- stream.with_parser_stream_dom_host_for_bootstrap(|bootstrap_document| {
+ parser_session.with_parser_stream_dom_host_for_bootstrap(|bootstrap_document| {
PageVm::new_with_bootstrap_document_recovery(
page_id,
local_executor,
@@ -5165,9 +5192,13 @@ impl PageVm {
.backend_node_key_for_id(backend_node_id)?;
let handle = key.handle;
let current_document_id = self.vm().document_id_for_live_node_handle(handle);
- let still_current = current_document_id == Some(key.document_id)
- && self.vm().document_runtime.dom_host().node(handle).is_some();
- if still_current {
+ let node_exists = self.vm().document_runtime.dom_host().node(handle).is_some();
+ let still_current = current_document_id == Some(key.document_id) && node_exists;
+ let retained_detached = node_exists
+ && self
+ .dom_agent_state
+ .backend_node_resolves_while_detached(backend_node_id);
+ if still_current || retained_detached {
return Some(key);
}
@@ -5490,6 +5521,11 @@ impl PageVm {
activation.node_id = Some(handle);
activation.backend_node_id =
self.renderer_backend_node_id_for_node_key(document_id, handle);
+ assert!(
+ self.dom_agent_state
+ .retain_detached_backend_node_resolution(activation.backend_node_id),
+ "file chooser backend node id must exist before it is exposed"
+ );
true
}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index e03416a50..b519a765b 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -36,14 +36,14 @@ use crate::page_task_queue::{
RendererPageNetworkingSource,
};
use crate::page_task_queue::{PostParseLifecycleWork, PostParsePageOwnedWork};
-use crate::parser::{HtmlParser, XmlParser};
+use crate::parser::HtmlParser;
use crate::planning::{
PreparedScript, PreparedScriptRuntimeGeneration, PreparedScriptSourceLoadOutcome,
ScriptFetchMetadata, ScriptSource, SharedScriptSourceLoad,
};
use crate::runtime::{
RendererOwnerResourceActivitySource, RendererPageCommand, RendererRuntimeObservableSourceItem,
- RendererSharedWorkerTargetEvent, post_parse_runtime_inputs::InitialDocumentScriptOwnerInput,
+ RendererSharedWorkerTargetEvent,
};
use crate::script_vm::{PostParseLifecycleAdvance, PostParseLifecycleCompletionAction};
use crate::types::{
@@ -1829,167 +1829,6 @@ fn test_page_vm_with_loader_dom_host_hooks_and_response_referrer_policy(
.expect("page vm")
}
-#[tokio::test]
-async fn initial_xml_scripts_use_prepared_handoffs_after_dom_mutation() {
- let loader =
- crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
- let (document, handoffs) = XmlParser.parse_with_document_handoffs(
- Url::parse("https://static-owner.test/page.xhtml").expect("document URL"),
- concat!(
- "<html xmlns='http://www.w3.org/1999/xhtml'><head>",
- "<link id='blocking' rel='stylesheet' href='/before.css' />",
- "<script type='importmap'>{\"imports\":{\"dep\":\"/dep.js\"}}</script>",
- "<script id='normal'>globalThis.initialNormal = 'prepared';</script>",
- "<script defer='defer' src='data:text/javascript,globalThis.initialDefer=1'></script>",
- "<script type='module'>export const value = 1;</script>",
- "<script async='async' src='data:text/javascript,globalThis.initialAsync=1'></script>",
- "<script id='invalid' src='http://[::1'></script>",
- "</head><body /></html>",
- )
- .to_owned(),
- );
- let (handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
- let expected_blocking_stylesheet_inputs = blocking_stylesheet_inputs.clone();
- assert_eq!(expected_blocking_stylesheet_inputs.len(), 1);
- let mut page_vm = test_page_vm_with_loader_and_dom_host(&loader, DomHost::from_dom(document));
- let input = InitialDocumentScriptOwnerInput::accept(
- &mut page_vm,
- &loader,
- handoffs,
- blocking_stylesheet_inputs,
- )
- .expect("initial document handoffs should bind to the bootstrap owner");
-
- let blocking = page_vm
- .vm()
- .document_runtime
- .get_element_by_id("blocking")
- .expect("blocking stylesheet link");
- assert!(
- page_vm
- .vm_mut()
- .document_runtime
- .dom_host_mut()
- .set_attribute(blocking, "href", "/after.css")
- );
-
- let normal = page_vm
- .vm()
- .document_runtime
- .get_element_by_id("normal")
- .expect("normal script");
- assert!(
- page_vm
- .vm_mut()
- .document_runtime
- .dom_host_mut()
- .set_text_content(normal, "globalThis.initialNormal = 'mutated';")
- );
- let invalid = page_vm
- .vm()
- .document_runtime
- .get_element_by_id("invalid")
- .expect("invalid script");
- assert!(
- page_vm
- .vm_mut()
- .document_runtime
- .dom_host_mut()
- .set_attribute(invalid, "src", "/fixed-after-acceptance.js")
- );
-
- let work = input.finalize(&mut page_vm).await;
- assert!(work.iter().any(|work| {
- matches!(
- work,
- PostParsePageOwnedWork::Lifecycle(lifecycle)
- if matches!(
- lifecycle.as_ref(),
- PostParseLifecycleWork::SeedDocumentOwnedBlockingStylesheets(inputs)
- if inputs == &expected_blocking_stylesheet_inputs
- )
- )
- }));
- assert!(work.iter().any(|work| matches!(
- work.as_lifecycle_work(),
- Some(PostParseLifecycleWork::AdvanceMainParserDeferredScripts {
- initial_count: 2,
- ..
- })
- )));
- assert!(work.iter().any(|work| {
- work.as_script()
- .is_some_and(|script| script.position == 4 && script.mode == ScriptMode::Async)
- }));
- assert_eq!(
- page_vm
- .vm_mut()
- .document_runtime
- .resolve_module_specifier(
- "dep",
- &Url::parse("https://static-owner.test/module.js").expect("module base URL"),
- )
- .expect("prepared import map should be registered before module acceptance"),
- Url::parse("https://static-owner.test/dep.js").expect("mapped URL")
- );
-
- assert!(work.iter().any(|work| {
- work.as_script().is_some_and(|script| {
- script.position == 1
- && matches!(
- &script.source,
- ScriptSource::Inline(source)
- if source == "globalThis.initialNormal = 'prepared';"
- )
- })
- }));
- assert!(work.iter().any(|work| {
- matches!(
- work.as_lifecycle_work(),
- Some(PostParseLifecycleWork::ReportWindowScriptFailure(task))
- if task.message.contains("failed to resolve script src")
- )
- }));
-}
-
-#[tokio::test]
-async fn initial_static_script_input_drops_after_document_owner_replacement() {
- let loader =
- crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");
- let (dom_host, handoffs) = HtmlParser.parse_dom_host_with_document_handoffs(
- Url::parse("https://static-owner.test/page.html").expect("document URL"),
- concat!(
- "<!doctype html><link rel='stylesheet' href='/stale.css'>",
- "<script defer src='data:text/javascript,globalThis.staleDefer=1'></script>",
- )
- .to_owned(),
- );
- let (handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
- assert_eq!(blocking_stylesheet_inputs.len(), 1);
- let mut page_vm = test_page_vm_with_loader_and_dom_host(&loader, dom_host);
- let owner_before = page_vm
- .vm()
- .current_main_document_task_owner()
- .expect("initial owner");
- let input = InitialDocumentScriptOwnerInput::accept(
- &mut page_vm,
- &loader,
- handoffs,
- blocking_stylesheet_inputs,
- )
- .expect("initial document handoffs should bind to the bootstrap owner");
-
- page_vm
- .vm_mut()
- .eval("document.open(); 'replaced'")
- .expect("document.open should replace the main document owner");
- assert_ne!(
- page_vm.vm().current_main_document_task_owner(),
- Some(owner_before)
- );
- assert!(input.finalize(&mut page_vm).await.is_empty());
-}
-
fn prepared_external_module_for_page_vm_test(page_vm: &PageVm, url: Url) -> PreparedScript {
prepared_external_module_for_page_vm_test_with_node(page_vm, 9001, url)
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs b/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
index 213fcb645..c1d166b90 100644
--- a/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/bootstrap.rs
@@ -23,8 +23,6 @@ impl ConcurrentParseTimeRuntime {
let bootstrap_executor = local_executor.clone();
let bootstrap = Box::pin(async move {
let (page_vm, triggered_navigation) = {
- let stream = state.parser_session.stream_handle();
- let mut stream = stream.borrow_mut();
let buffered_document_preloads = &mut state.buffered_document_preloads;
let service_worker_preload_context = state.service_worker_preload_context.as_ref();
PageVm::new_from_parser_stream_and_run_document_start(
@@ -33,7 +31,7 @@ impl ConcurrentParseTimeRuntime {
&loader,
&env,
runtime_hooks,
- &mut stream,
+ &mut state.parser_session,
started,
|page_vm| {
admit_pending_preloads(
@@ -133,4 +131,84 @@ impl ConcurrentParseTimeRuntime {
)
.await
}
+
+ pub(in crate::runtime) async fn finish_creation_from_xml_bootstrap(
+ page_id: PageId,
+ local_executor: JsLocalExecutor,
+ loader: &ResourceRequestClient,
+ env: &PageVmEnvConfig,
+ runtime_hooks: PageVmRuntimeHooks,
+ final_url: Url,
+ document_content_type: String,
+ stage: PageVmInitStage,
+ source: String,
+ started: Instant,
+ ) -> Result<ParseTimePageVmCreationOutcome> {
+ let mut state = ParseTimeDriverState::new_xml(final_url.clone());
+ state
+ .parser_session
+ .set_xml_document_content_type(document_content_type);
+ state
+ .buffered_document_preloads
+ .set_script_fetch_interception_enabled(
+ env.fetch_subresource_interception_enabled
+ && env.fetch_subresource_interception_resource_type.is_none_or(
+ |resource_type| {
+ resource_type.has_same_cdp_fetch_interception_type(
+ crate::types::SubresourceResourceType::Script,
+ )
+ },
+ ),
+ );
+ state
+ .buffered_document_preloads
+ .set_response_csp_requires_parser_admission(
+ !env.response_content_security_policies.is_empty(),
+ );
+ state.buffered_document_preloads.bind_resource_runtime(
+ runtime_hooks.owner_wake(),
+ runtime_hooks.resource_task_runner(),
+ );
+ let service_worker_preload_context =
+ env.reserved_service_worker_client_id.map(|client_id| {
+ ServiceWorkerScriptPreloadContext::new(
+ runtime_hooks.browser_context_runtime.clone(),
+ client_id,
+ final_url.clone(),
+ runtime_hooks.owner_wake(),
+ )
+ });
+ state.service_worker_preload_context = service_worker_preload_context.clone();
+ state
+ .buffered_document_preloads
+ .append_to_main_document_scan_with_service_worker_context(
+ &final_url,
+ &source,
+ loader,
+ service_worker_preload_context.as_ref(),
+ );
+ state.parser_session.queue_arrived_chunk(source);
+ state.parser_session.declare_eof();
+ state.input_closed = true;
+ let (state, page_vm, triggered_navigation) =
+ Self::bootstrap_page_vm_from_state_on_fresh_local_task(
+ page_id,
+ local_executor.clone(),
+ loader.clone(),
+ env.clone(),
+ runtime_hooks,
+ state,
+ started,
+ "XML bootstrap local task channel closed",
+ )
+ .await?;
+ if triggered_navigation {
+ return Ok(ParseTimePageVmCreationOutcome::TriggeredNavigation { page_vm, stage });
+ }
+ finish_phase_one_creation_on_execution_context(
+ Self::new_parser_owner(loader.clone(), stage, state, page_vm),
+ started,
+ )
+ .await
+ }
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/document_turn.rs b/moli-renderer-v8/src/runtime/phase_one/document_turn.rs
index 2f4ac4c04..eaf478da7 100644
--- a/moli-renderer-v8/src/runtime/phase_one/document_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/document_turn.rs
@@ -8,7 +8,7 @@ use crate::document_script_scheduler::{
pub(super) struct DocumentTurnContext<'driver> {
pub(super) scheduler: &'driver mut DocumentScriptScheduler,
- pub(super) stream: ParserStreamHandle,
+ pub(super) parser_session: &'driver DocumentParserSession,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -73,8 +73,7 @@ impl<'driver> DocumentTurnContext<'driver> {
vm.as_mut()
.expect("PageVm must retain a live ScriptVm until drop")
.prime_document_lifecycle_processing_and_record_stylesheet_network_results();
- self.stream
- .borrow()
+ self.parser_session
.with_stylesheet_blocking_read_view(|document| {
vm.as_mut()
.expect("PageVm must retain a live ScriptVm until drop")
diff --git a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
index 4387d2e39..7c2071e87 100644
--- a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs
@@ -523,6 +523,101 @@ globalThis.__documentWriteEvents.push('inline-after');
});
}
+#[test]
+fn document_write_external_script_live_collection_walk_uses_incremental_parser_frontier() {
+ super::tests::run_phase_one_large_stack_test("document-write-live-collection", || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("current-thread runtime should build");
+ runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
+ let _js_runtime = crate::JsRuntime::initialize();
+ let (script_url, server) = spawn_document_write_script_server(
+ r#"
+const nodes = document.getElementsByTagName("*");
+const ids = [];
+for (let index = 0; index < nodes.length; index++) {
+ if (nodes[index].id) ids.push(nodes[index].id);
+}
+globalThis.__documentWriteVisibleIds = ids.join("|");
+"#,
+ )
+ .await;
+ let document_url = script_url.join("page.html").expect("document URL");
+ let before = (0..256)
+ .map(|index| format!(r#"<div id="before-{index}"><span></span></div>"#))
+ .collect::<String>();
+ let future = (0..256)
+ .map(|index| format!(r#"<article id="future-{index}"><i></i></article>"#))
+ .collect::<String>();
+ let html = format!(
+ r#"<!doctype html><html><body>{before}<script>document.write(`<script src="{script_url}"><\/script>`);</script>{future}</body></html>"#,
+ );
+
+ let page_vm = finish_standalone_document_write_page(html, document_url).await;
+ let result = evaluate_on_owner_local_task(
+ page_vm,
+ r#"JSON.stringify({
+ sawFirst: __documentWriteVisibleIds.includes("before-0"),
+ sawLast: __documentWriteVisibleIds.includes("before-255"),
+ hidFuture: !__documentWriteVisibleIds.includes("future-0"),
+ parserResumed: !!document.getElementById("future-255")
+})"#,
+ )
+ .await;
+ assert_eq!(
+ result.get("value").and_then(serde_json::Value::as_str),
+ Some(
+ r#"{"sawFirst":true,"sawLast":true,"hidFuture":true,"parserResumed":true}"#
+ ),
+ "a repeated live-collection indexed walk must observe only parser-committed DOM and let parsing resume"
+ );
+ server
+ .await
+ .expect("document.write script server should finish");
+ }));
+ });
+}
+
+#[test]
+fn document_write_external_runaway_script_is_terminated_and_parser_recovers() {
+ super::tests::run_phase_one_large_stack_test("document-write-script-watchdog", || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .expect("current-thread runtime should build");
+ runtime.block_on(tokio::task::LocalSet::new().run_until(async move {
+ let _js_runtime = crate::JsRuntime::initialize();
+ let (script_url, server) =
+ spawn_document_write_script_server("for (;;) {}").await;
+ let document_url = script_url.join("page.html").expect("document URL");
+ let html = format!(
+ r#"<!doctype html><script>document.write(`<script src="{script_url}"><\/script>`);</script><main id="parser-recovered">ready</main>"#,
+ );
+
+ let started = Instant::now();
+ let page_vm = finish_standalone_document_write_page(html, document_url).await;
+ assert!(
+ started.elapsed() < std::time::Duration::from_secs(4),
+ "the document.write script watchdog should interrupt the runaway turn promptly"
+ );
+ let result = evaluate_on_owner_local_task(
+ page_vm,
+ "String(!!document.getElementById('parser-recovered'))",
+ )
+ .await;
+ assert_eq!(
+ result.get("value").and_then(serde_json::Value::as_str),
+ Some("true"),
+ "the parser and isolate must remain usable after terminating the written script"
+ );
+ server
+ .await
+ .expect("document.write script server should finish");
+ }));
+ });
+}
+
#[test]
fn resident_queue_phase_one_continuation_uses_the_exact_owner_arbiter() {
super::tests::run_phase_one_large_stack_test("document-write-resident-queue", || {
diff --git a/moli-renderer-v8/src/runtime/phase_one/mod.rs b/moli-renderer-v8/src/runtime/phase_one/mod.rs
index 9fc36f1be..e2ea952e4 100644
--- a/moli-renderer-v8/src/runtime/phase_one/mod.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/mod.rs
@@ -1,18 +1,13 @@
use super::*;
#[cfg(test)]
use crate::DocumentBlockingStylesheetSignature;
-use crate::document_runtime::ParserStreamHandle;
use crate::document_script_scheduler::{
ParseTimeTurn, ParseTimeTurnTrigger, ParseVisibleReadyTurnDisposition,
ParseVisibleReadyTurnPhase,
};
-use crate::live_document_parser::DocumentParserSession;
-#[cfg(test)]
-use crate::live_document_parser::ParserInputBuffer;
+use crate::live_document_parser::{DocumentParserSession, ParserStopReason};
use crate::page_task_queue::PostParsePageOwnedWork;
#[cfg(test)]
-use crate::parser::HtmlParser;
-#[cfg(test)]
use crate::parser::ScriptSource;
#[cfg(test)]
use crate::parser::{ParserPumpStep, ParserScriptHandoff, ParserYield, PreparedScript};
@@ -81,7 +76,7 @@ use self::parser_turn::{PageTaskTurnResult, ParserDriver};
use self::parser_turn::{
ParserStepAdvanceOutcome, ScriptHandoffOutcome, bind_parser_owned_script_handle,
};
-pub(super) use self::pending_residence::PendingPhaseOneResidence;
+pub(super) use self::pending_residence::{PendingPhaseOneResidence, PendingPhaseOneResumeOutcome};
pub(super) use self::state::ConcurrentParseTimeRuntime;
use self::state::{ParseTimeDriverState, ParseTimeOwner, PendingParsingBlockingWait};
pub use self::streaming::ExternalRawDocumentBodyStream;
@@ -1437,7 +1432,7 @@ document.body.setAttribute('data-error-state', [
assert!(matches!(
parser_blocking_execution::resolve_main_parser_blocking_classic_after_runtime_gate(
- harness.state.parser_session.stream_handle(),
+ &mut harness.state.parser_session,
&mut harness.page_vm,
&mut runner,
"stale owner test must not execute",
@@ -1806,6 +1801,29 @@ document.body.setAttribute('data-error-state', [
});
}
+ #[test]
+ fn buffered_module_script_scan_waits_for_native_module_map_admission() {
+ let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
+ let loader = ResourceRequestClient::new(&FetchConfig::default()).expect("default loader");
+ let mut cache = BufferedDocumentPreloadState::default();
+
+ cache.append_to_main_document_scan(
+ &final_url,
+ r#"<script type="module" src="/entry.mjs"></script>"#,
+ &loader,
+ );
+
+ assert!(
+ cache.entries.is_empty(),
+ "module scripts must not start in the legacy SharedScriptSourceLoad cache"
+ );
+ assert_eq!(
+ preload_request_urls(cache.take_pending_script_preloads_for_test()),
+ vec![Url::parse("https://example.test/entry.mjs").expect("module url")],
+ "PageVm bootstrap must receive the scanned module and register it in the native module map"
+ );
+ }
+
#[test]
fn prebootstrap_preload_filter_skips_async_classic_scripts() {
let final_url = Url::parse("https://example.test/docs/page.html").expect("test url");
@@ -4160,11 +4178,14 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
);
let mut pending_runner =
PendingParsingBlockingClassicScriptRunner::new_parser_blocking(Vec::new());
- let stream = state.parser_session.stream_handle();
+ let parser_insertion_controller =
+ crate::document_runtime::ParserInsertionController::for_session(
+ &state.parser_session,
+ );
let mut owner = super::parser_blocking_document_script::MainParserBlockingDocumentScriptOwner::new(
&mut page_vm,
&mut pending_runner,
- stream,
+ parser_insertion_controller,
"test source failure",
);
@@ -4477,10 +4498,8 @@ queueMicrotask(() => window.__mainParserClassicCheckpointEvents.push('script-mic
let preload = state
.buffered_document_preloads
.entries
- .get(&classic_preload_key(script_url.as_str()))
- .expect("preload scanner should start the parser-blocking script")
- .load
- .clone();
+ .load_for_key(&classic_preload_key(script_url.as_str()))
+ .expect("preload scanner should start the parser-blocking script");
let preload_outcome = tokio::time::timeout(
std::time::Duration::from_secs(2),
preload.wait_outcome(),
@@ -4965,10 +4984,8 @@ globalThis.__outerDocumentWriteScriptContinued = true;
let preload = cache
.entries
- .get(&classic_preload_key(script_url.as_str()))
- .expect("main-document scan should create script preload")
- .load
- .clone();
+ .load_for_key(&classic_preload_key(script_url.as_str()))
+ .expect("main-document scan should create script preload");
let outcome =
tokio::time::timeout(std::time::Duration::from_secs(2), preload.wait_outcome())
.await
@@ -5056,10 +5073,8 @@ globalThis.__outerDocumentWriteScriptContinued = true;
let preload = driver
.buffered_document_preloads
.entries
- .get(&classic_preload_key(script_url.as_str()))
- .expect("document.write insertion should create script preload")
- .load
- .clone();
+ .load_for_key(&classic_preload_key(script_url.as_str()))
+ .expect("document.write insertion should create script preload");
let outcome =
tokio::time::timeout(std::time::Duration::from_secs(2), preload.wait_outcome())
.await
@@ -5337,16 +5352,17 @@ globalThis.__outerDocumentWriteScriptContinued = true;
let local_executor = page_vm.local_executor.clone();
let page_vm_ptr: *mut PageVm = &mut page_vm;
let scheduler_ptr = &mut state.scheduler as *mut _;
- let stream = state.parser_session.stream_handle().clone();
+ let parser_session_ptr = &state.parser_session as *const DocumentParserSession;
let result = super::access::run_named_owner_local_task(
local_executor,
"phase-one async credit document drain local task channel closed",
async move {
let page_vm = unsafe { &mut *page_vm_ptr };
let scheduler = unsafe { &mut *scheduler_ptr };
+ let parser_session = unsafe { &*parser_session_ptr };
let mut context = DocumentTurnContext {
scheduler,
- stream,
+ parser_session,
};
let result = tokio::time::timeout(
std::time::Duration::from_millis(50),
diff --git a/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs b/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs
index 1d1a3fe3e..3e8e7e6c6 100644
--- a/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs
@@ -98,7 +98,7 @@ impl ConcurrentParseTimeRuntime {
.has_parser_blocking_script();
let mut context = DocumentTurnContext {
scheduler: &mut state.scheduler,
- stream: state.parser_session.stream_handle(),
+ parser_session: &state.parser_session,
};
let wait_for_wake = parsing_blocking_wait.waits_for_legacy_document_processing();
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_document_script.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_document_script.rs
index e07f969e5..be74b076d 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_document_script.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_document_script.rs
@@ -14,7 +14,7 @@ use super::parser_blocking_task::{
MainParserBlockingNextAction,
};
use super::*;
-use crate::document_runtime::{ParserInsertionController, ParserStreamHandle};
+use crate::document_runtime::ParserInsertionController;
use crate::document_script_scheduler::{
DocumentScriptExecutionOutcome, ParserClassicDocumentScriptCompletionPlan,
ParserClassicDocumentScriptContinuation, ParserClassicDocumentScriptExecutionHooks,
@@ -33,7 +33,7 @@ use crate::script_vm::{
pub(super) struct MainParserBlockingDocumentScriptOwner<'page, 'runner> {
page_vm: &'page mut PageVm,
pending_runner: &'runner mut PendingParsingBlockingClassicScriptRunner,
- stream: ParserStreamHandle,
+ parser_insertion_controller: Option<ParserInsertionController>,
log_message: &'static str,
}
@@ -59,13 +59,13 @@ impl<'page, 'runner> MainParserBlockingDocumentScriptOwner<'page, 'runner> {
pub(super) fn new(
page_vm: &'page mut PageVm,
pending_runner: &'runner mut PendingParsingBlockingClassicScriptRunner,
- stream: ParserStreamHandle,
+ parser_insertion_controller: Option<ParserInsertionController>,
log_message: &'static str,
) -> Self {
Self {
page_vm,
pending_runner,
- stream,
+ parser_insertion_controller,
log_message,
}
}
@@ -149,8 +149,7 @@ impl ParserClassicDocumentScriptExecutionHooks
let owner = &mut **self;
let script_handle = ready_script.script_handle();
let completion_target = *ready_script.target();
- let parser_insertion_controller =
- ParserInsertionController::for_stream(owner.stream.clone());
+ let parser_insertion_controller = owner.parser_insertion_controller.clone();
let mut begin_owner = MainParserBlockingBeginExecutionOwner {
parser_insertion_controller,
completion_target,
@@ -273,7 +272,7 @@ impl ParserClassicDocumentScriptExecutionHooks
let completion = MainParserBlockingClassicScriptCompletionAction::new(
target,
ParserOwnedClassicScriptCompletion::parser_blocking_source_failure(
- ParserInsertionController::for_stream(owner.stream.clone()),
+ owner.parser_insertion_controller.clone(),
event,
),
);
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_execution.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_execution.rs
index 564ed0c31..b00d516fd 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_execution.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_execution.rs
@@ -3,8 +3,11 @@ use super::parser_blocking_owner::MainParserBlockingExecutionGateOwner;
use super::parser_blocking_pending::PendingParsingBlockingClassicScriptRunner;
use super::parser_blocking_task::PendingParsingBlockingClassicScriptBlockedOnExecution;
use super::*;
-use crate::document_runtime::ParserStreamHandle;
+use crate::document_runtime::ParserInsertionController;
use crate::document_script_scheduler::DocumentScriptExecutionOutcome;
+use crate::live_document_parser::{
+ DocumentParserSession, ParserResumeApplication, ParserStopReason,
+};
use crate::parser_script::owner::ParserScriptExecutionBlocker;
use crate::parser_script::projection::{
ParserClassicScriptExecutionGateProjection, ParserClassicScriptNextActionWithBlockedScript,
@@ -18,7 +21,7 @@ pub(super) enum MainParserBlockingExecutionOutcome {
}
pub(super) async fn resolve_main_parser_blocking_classic_after_runtime_gate(
- stream: ParserStreamHandle,
+ parser_session: &mut DocumentParserSession,
page_vm: &mut PageVm,
pending_runner: &mut PendingParsingBlockingClassicScriptRunner,
log_message: &'static str,
@@ -46,14 +49,32 @@ pub(super) async fn resolve_main_parser_blocking_classic_after_runtime_gate(
return Ok(MainParserBlockingExecutionOutcome::StoppedCurrentDocument);
}
}
+ if let Some(permit) = pending_runner
+ .current_parser_blocking_context()
+ .and_then(|context| context.resume_permit())
+ && parser_session.resume(permit) != ParserResumeApplication::Resumed
+ {
+ tracing::debug!(
+ ?permit,
+ run_state = ?parser_session.run_state(),
+ "canceling stale main parser-blocking continuation permit"
+ );
+ parser_session.stop(ParserStopReason::DocumentReplacement);
+ return Ok(MainParserBlockingExecutionOutcome::StoppedCurrentDocument);
+ }
+ let parser_insertion_controller = ParserInsertionController::for_session(parser_session);
page_vm.vm_mut().sync_live_document_style_sources();
let next_projection = {
let mut owner = MainParserBlockingExecutionGateOwner { page_vm };
pending_runner
.take_current_parser_blocking_next_action_or_blocked_script_with_owner(&mut owner)
};
- let mut document_script_owner =
- MainParserBlockingDocumentScriptOwner::new(page_vm, pending_runner, stream, log_message);
+ let mut document_script_owner = MainParserBlockingDocumentScriptOwner::new(
+ page_vm,
+ pending_runner,
+ parser_insertion_controller,
+ log_message,
+ );
let action = match next_projection {
ParserClassicScriptNextActionWithBlockedScript::Action(action) => action,
ParserClassicScriptNextActionWithBlockedScript::Blocked(blocked) => {
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_owner.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_owner.rs
index 0b3a38e99..0829bd77a 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_owner.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_owner.rs
@@ -44,7 +44,7 @@ pub(super) struct MainParserBlockingExecutionGateOwner<'a> {
}
pub(super) struct MainParserBlockingBeginExecutionOwner {
- pub(super) parser_insertion_controller: ParserInsertionController,
+ pub(super) parser_insertion_controller: Option<ParserInsertionController>,
pub(super) completion_target: MainDocumentClassicScriptTarget,
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_pending.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_pending.rs
index b5a94d776..b71da969b 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_pending.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_pending.rs
@@ -1,6 +1,7 @@
use super::parser_blocking_owner::MainParserBlockingExternalLoadOwner;
use crate::DocumentBlockingStylesheetSignature;
use crate::frame_owner_model::FrameDocumentTaskOwner;
+use crate::live_document_parser::ParserResumePermit;
use crate::parser_script::context::{
ParserClassicScriptDocumentOwnerState, ParserClassicScriptExecutionGateState,
ParserClassicScriptSourceLoadOutcomeState, ParserClassicScriptSourceLoadStartState,
@@ -27,6 +28,7 @@ pub(super) struct PendingParsingBlockingClassicScriptContext {
owner: FrameDocumentTaskOwner,
pub(super) blocking_signatures_before: HashSet<DocumentBlockingStylesheetSignature>,
pub(super) source_load: Option<PendingParserBlockingSourceLoad>,
+ resume_permit: Option<ParserResumePermit>,
}
#[derive(Debug, Clone)]
@@ -53,8 +55,20 @@ impl PendingParsingBlockingClassicScriptContext {
owner,
blocking_signatures_before,
source_load,
+ resume_permit: None,
}
}
+
+ pub(super) fn install_resume_permit(&mut self, permit: ParserResumePermit) {
+ assert!(
+ self.resume_permit.replace(permit).is_none(),
+ "one parser-blocking script context can own only one parser resume permit"
+ );
+ }
+
+ pub(super) fn resume_permit(&self) -> Option<ParserResumePermit> {
+ self.resume_permit
+ }
}
impl ParserClassicScriptDocumentOwnerState for PendingParsingBlockingClassicScriptContext {
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_task.rs b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_task.rs
index 7dff79f43..00b0d2b93 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_blocking_task.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_blocking_task.rs
@@ -61,13 +61,13 @@ impl MainParserBlockingClassicScriptCompletionAction {
#[derive(Clone)]
pub(super) struct MainParserBlockingClassicScriptExecutionTarget {
- parser_insertion_controller: ParserInsertionController,
+ parser_insertion_controller: Option<ParserInsertionController>,
completion_target: MainDocumentClassicScriptTarget,
}
impl MainParserBlockingClassicScriptExecutionTarget {
pub(super) fn new(
- parser_insertion_controller: ParserInsertionController,
+ parser_insertion_controller: Option<ParserInsertionController>,
completion_target: MainDocumentClassicScriptTarget,
) -> Self {
Self {
@@ -76,7 +76,7 @@ impl MainParserBlockingClassicScriptExecutionTarget {
}
}
- pub(super) fn parser_insertion_controller(&self) -> ParserInsertionController {
+ pub(super) fn parser_insertion_controller(&self) -> Option<ParserInsertionController> {
self.parser_insertion_controller.clone()
}
@@ -94,7 +94,7 @@ pub(super) fn main_parser_blocking_ready_action(
}
pub(super) fn main_parser_blocking_begin_execution_action(
- parser_insertion_controller: ParserInsertionController,
+ parser_insertion_controller: Option<ParserInsertionController>,
completion_target: MainDocumentClassicScriptTarget,
action: ParserPendingClassicScriptBeginExecutionAction,
) -> MainParserBlockingClassicScriptExecutionEntry {
diff --git a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
index 2178d8ef5..eecd90d5f 100644
--- a/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/parser_turn.rs
@@ -18,7 +18,10 @@ use super::parser_blocking_task::{
use super::*;
use crate::document_runtime::parser_script_preparation_failure_page_owned_work;
use crate::dom::native::{Attribute, DomMutationEffects, NativeNodeId};
-use crate::live_document_parser::{LiveDocumentParserOwner, LiveDocumentParserStepOutcome};
+use crate::live_document_parser::{
+ LiveDocumentParserOwner, LiveDocumentParserStepOutcome, ParserResumeApplication,
+ ParserSuspensionCause,
+};
use crate::parser::{
ParserDomMutation, ParserDomMutationConsumer, ParserDomReadConsumer,
ParserElementCreationConsumer, ParserElementCreationRequest, ParserMutationEffectConsumer,
@@ -43,6 +46,10 @@ impl ParserMutationEffectConsumer for PhaseOneParserOwner<'_> {
}
impl ParserDomReadConsumer for PhaseOneParserOwner<'_> {
+ fn snapshot_parser_document(&mut self) -> Option<crate::dom::native::NativeDom> {
+ Some(self.vm.document_runtime.snapshot_document())
+ }
+
fn node_exists(&mut self, node_id: NativeNodeId) -> bool {
self.vm
.document_runtime
@@ -235,6 +242,12 @@ impl ParserDomMutationConsumer for PhaseOneParserOwner<'_> {
.create_processing_instruction_in_live_dom_host(target, data)
}
+ fn create_cdata_section(&mut self, data: String) -> NativeNodeId {
+ self.vm
+ .document_runtime
+ .create_cdata_section_in_live_dom_host(data)
+ }
+
fn create_document_type(
&mut self,
name: String,
@@ -450,10 +463,6 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
);
}
- fn stream_handle(&self) -> ParserStreamHandle {
- self.parser_session.stream_handle()
- }
-
fn sync_parser_defined_custom_elements(&mut self, page_vm: &mut PageVm) {
let names = page_vm
.vm_mut()
@@ -499,6 +508,55 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
);
return Ok(owner_step_progress_after_current_document_stop(page_vm));
}
+ match self.parser_session.suspension_cause() {
+ Some(ParserSuspensionCause::ParserCreatedStylesheet { .. }) => {
+ if !page_vm
+ .vm()
+ .document_runtime
+ .has_all_blocking_stylesheets_resolved()
+ {
+ return Ok(suspend_parser_for_stylesheet_page_task(
+ owner,
+ pending_parsing_blocking_wait,
+ ));
+ }
+ let permit = self
+ .parser_session
+ .current_resume_permit()
+ .expect("a stylesheet-suspended parser must retain its resume permit");
+ assert_eq!(
+ self.parser_session.resume(permit),
+ ParserResumeApplication::Resumed,
+ "the admitted stylesheet continuation must resume its exact parser suspension"
+ );
+ }
+ Some(ParserSuspensionCause::DocumentWriteExternalScript { .. }) => {
+ if page_vm
+ .vm()
+ .document_runtime
+ .has_pending_document_write_external_script_load()
+ {
+ *owner = ParseTimeOwner::Document;
+ *pending_parsing_blocking_wait =
+ PendingParsingBlockingWait::PageNetworkingDocumentWriteExternalScript;
+ return Ok(OwnerStepProgress::BlockedOnPageTask);
+ }
+ let permit = self
+ .parser_session
+ .current_resume_permit()
+ .expect("a document.write-suspended parser must retain its resume permit");
+ assert_eq!(
+ self.parser_session.resume(permit),
+ ParserResumeApplication::Resumed,
+ "the admitted document.write continuation must resume its exact parser suspension"
+ );
+ }
+ Some(
+ ParserSuspensionCause::ParserClassicSource { .. }
+ | ParserSuspensionCause::ParserClassicStylesheets { .. },
+ )
+ | None => {}
+ }
debug_assert!(
!pending_parsing_blocking_wait.is_pending(),
"parser owner should not enqueue a new parsing turn while a blocking-wait document turn is still pending"
@@ -507,15 +565,12 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
.pending_parsing_blocking_script
.has_parser_blocking_script()
{
- self.parser_session.ensure_current_chunk();
- if self.parser_session.current_chunk_is_none()
- && !self.parser_session.has_script_input()
- {
- return Ok(if *self.input_closed {
- OwnerStepProgress::AdvancePhase
- } else {
- OwnerStepProgress::NeedMoreInput
- });
+ if self.parser_session.input_is_empty() {
+ if *self.input_closed {
+ self.finish_main_parser(page_vm, parser_document_owner);
+ return Ok(OwnerStepProgress::AdvancePhase);
+ }
+ return Ok(OwnerStepProgress::NeedMoreInput);
}
if !*parser_step_ready {
*owner = ParseTimeOwner::Document;
@@ -574,7 +629,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
return Ok(OwnerStepProgress::BlockedOnParserScriptSourceLoad);
}
let progress = match resolve_main_parser_blocking_classic_after_runtime_gate(
- self.stream_handle(),
+ self.parser_session,
page_vm,
self.pending_parsing_blocking_script,
"executing stylesheet-unblocked parser-blocking classic script",
@@ -635,124 +690,96 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
default_chunk_bytes,
});
*parser_step_ready = false;
- self.parser_session.ensure_current_chunk();
- let progress = if self.parser_session.current_chunk_is_empty() {
- OwnerStepProgress::AdvancePhase
- } else {
- let remaining_chunk = self.parser_session.take_current_chunk();
- if remaining_chunk.is_empty() {
+ let progress = if self.parser_session.input_is_empty() {
+ if *self.input_closed {
+ self.finish_main_parser(page_vm, parser_document_owner);
OwnerStepProgress::AdvancePhase
} else {
- let parser_step_bytes =
- parser_step_bytes.expect("BeforeParserStep turn must retain parser step size");
- page_vm
- .page_task_queue
- .enqueue_parse_time_document_script_task(ready_task);
- let (parser_step, rest) =
- split_first_by_char_boundary(&remaining_chunk, parser_step_bytes);
- let remaining_chunk = (!rest.is_empty()).then(|| rest.to_owned());
-
- match self
- .advance_parser_step_for_owner(
- page_vm,
- parser_document_owner,
- parser_step,
- remaining_chunk.as_deref(),
- )
- .await?
- {
- ParserStepAdvanceOutcome::Continue => {
- let parser_budget_exhausted = remaining_chunk.is_some();
- self.parser_session.set_current_chunk(remaining_chunk);
- if !parser_budget_exhausted {
- // This bounded step consumed the complete current
- // chunk. The owner loop can immediately observe
- // EOF, another already-buffered chunk, or the next
- // real wait without manufacturing a continuation.
- OwnerStepProgress::Continue
- } else if page_vm
- .vm()
- .document_runtime
- .request_main_parser_continuation_if_active()
+ OwnerStepProgress::NeedMoreInput
+ }
+ } else {
+ let parser_step_bytes =
+ parser_step_bytes.expect("BeforeParserStep turn must retain parser step size");
+ let parser_budget_exhausted =
+ parser_step_bytes > 0 && default_chunk_bytes > parser_step_bytes;
+ page_vm
+ .page_task_queue
+ .enqueue_parse_time_document_script_task(ready_task);
+
+ match self
+ .advance_next_parser_step_for_owner(
+ page_vm,
+ parser_document_owner,
+ parser_step_bytes,
+ )
+ .await?
+ {
+ ParserStepAdvanceOutcome::Continue => {
+ if !parser_budget_exhausted {
+ // This bounded step consumed the complete current
+ // chunk. The owner loop can immediately observe
+ // EOF, another already-buffered chunk, or the next
+ // real wait without manufacturing a continuation.
+ OwnerStepProgress::Continue
+ } else if page_vm
+ .vm()
+ .document_runtime
+ .request_main_parser_continuation_if_active()
+ {
+ // One bounded tokenizer turn has spent its parser
+ // budget. The exact parser state remains in this
+ // runtime; the Networking task only grants the next
+ // opportunity through the common Page scheduler.
+ OwnerStepProgress::BlockedOnPageTask
+ } else {
+ #[cfg(test)]
{
- // One bounded tokenizer turn has spent its parser
- // budget. The exact parser state remains in this
- // runtime; the Networking task only grants the next
- // opportunity through the common Page scheduler.
- OwnerStepProgress::BlockedOnPageTask
- } else {
- #[cfg(test)]
- {
- assert!(
- page_vm.permits_direct_parser_budget_continuation_for_test(),
- "only an explicit standalone parser fixture may bypass the Networking continuation"
- );
- OwnerStepProgress::Continue
- }
- #[cfg(not(test))]
- {
- panic!(
- "an active production parser spent its budget without a bound Networking continuation"
- );
- }
+ assert!(
+ page_vm.permits_direct_parser_budget_continuation_for_test(),
+ "only an explicit standalone parser fixture may bypass the Networking continuation"
+ );
+ OwnerStepProgress::Continue
}
- }
- ParserStepAdvanceOutcome::StoppedCurrentDocument => {
- owner_step_progress_after_current_document_stop(page_vm)
- }
- ParserStepAdvanceOutcome::BlockedOnStylesheet(script) => {
- let current_chunk = self
- .parser_session
- .take_buffered_input_with_tail(remaining_chunk);
- self.parser_session.set_current_chunk(current_chunk);
- self.pending_parsing_blocking_script
- .install_parser_blocking_script_blocked_on_execution(*script);
- suspend_parser_for_stylesheet_page_task(
- owner,
- pending_parsing_blocking_wait,
- )
- }
- ParserStepAdvanceOutcome::BlockedOnStylesheetParserPause => {
- let current_chunk = self
- .parser_session
- .take_buffered_input_with_tail(remaining_chunk);
- self.parser_session.set_current_chunk(current_chunk);
- suspend_parser_for_stylesheet_page_task(
- owner,
- pending_parsing_blocking_wait,
- )
- }
- ParserStepAdvanceOutcome::BlockedOnExternalSource(script) => {
- let current_chunk = self
- .parser_session
- .take_buffered_input_with_tail(remaining_chunk);
- self.parser_session.set_current_chunk(current_chunk);
- self.pending_parsing_blocking_script
- .install_parser_blocking_script_blocked_on_source_load(*script);
- *pending_parsing_blocking_wait = PendingParsingBlockingWait::None;
- *owner = ParseTimeOwner::Parser;
- OwnerStepProgress::NeedMoreInput
- }
- ParserStepAdvanceOutcome::BlockedOnDocumentWriteExternalLoad => {
- let current_chunk = self
- .parser_session
- .take_buffered_input_with_tail(remaining_chunk);
- self.parser_session.set_current_chunk(current_chunk);
- *pending_parsing_blocking_wait = if page_vm
- .has_page_resource_completion_route()
+ #[cfg(not(test))]
{
- PendingParsingBlockingWait::PageNetworkingDocumentWriteExternalScript
- } else {
- PendingParsingBlockingWait::LegacyDocumentProcessing
- };
- *owner = ParseTimeOwner::Document;
- if pending_parsing_blocking_wait.waits_for_page_task() {
- OwnerStepProgress::BlockedOnPageTask
- } else {
- OwnerStepProgress::Continue
+ panic!(
+ "an active production parser spent its budget without a bound Networking continuation"
+ );
}
}
}
+ ParserStepAdvanceOutcome::StoppedCurrentDocument => {
+ owner_step_progress_after_current_document_stop(page_vm)
+ }
+ ParserStepAdvanceOutcome::BlockedOnStylesheet(script) => {
+ self.pending_parsing_blocking_script
+ .install_parser_blocking_script_blocked_on_execution(*script);
+ suspend_parser_for_stylesheet_page_task(owner, pending_parsing_blocking_wait)
+ }
+ ParserStepAdvanceOutcome::BlockedOnStylesheetParserPause => {
+ suspend_parser_for_stylesheet_page_task(owner, pending_parsing_blocking_wait)
+ }
+ ParserStepAdvanceOutcome::BlockedOnExternalSource(script) => {
+ self.pending_parsing_blocking_script
+ .install_parser_blocking_script_blocked_on_source_load(*script);
+ *pending_parsing_blocking_wait = PendingParsingBlockingWait::None;
+ *owner = ParseTimeOwner::Parser;
+ OwnerStepProgress::NeedMoreInput
+ }
+ ParserStepAdvanceOutcome::BlockedOnDocumentWriteExternalLoad => {
+ *pending_parsing_blocking_wait = if page_vm.has_page_resource_completion_route()
+ {
+ PendingParsingBlockingWait::PageNetworkingDocumentWriteExternalScript
+ } else {
+ PendingParsingBlockingWait::LegacyDocumentProcessing
+ };
+ *owner = ParseTimeOwner::Document;
+ if pending_parsing_blocking_wait.waits_for_page_task() {
+ OwnerStepProgress::BlockedOnPageTask
+ } else {
+ OwnerStepProgress::Continue
+ }
+ }
}
};
Ok(progress)
@@ -764,7 +791,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
final_url: &Url,
parser_tail_after_step: Option<&str>,
) {
- let mut upcoming_html = self.parser_session.peek_buffered_input();
+ let mut upcoming_html = self.parser_session.snapshot_pending_input();
if let Some(tail) = parser_tail_after_step {
upcoming_html.push_str(tail);
}
@@ -874,33 +901,39 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
still_blocked
};
if still_blocked_on_stylesheet {
- return Ok(ScriptHandoffOutcome::BlockedOnStylesheet(Box::new(
- stylesheet_blocked_main_parser_blocking_classic_script(
- main_parser_blocking_classic_script_item(
- parser_document_owner,
- ParserPreparedClassicScript::new(
- ParserClassicScriptMetadata::new(handle, start_line),
- script,
- ),
- blocking_signatures_before,
- source_load,
- ),
+ let resume_permit = self.parser_session.suspend(
+ ParserSuspensionCause::ParserClassicStylesheets { script: handle },
+ );
+ let mut pending = main_parser_blocking_classic_script_item(
+ parser_document_owner,
+ ParserPreparedClassicScript::new(
+ ParserClassicScriptMetadata::new(handle, start_line),
+ script,
),
+ blocking_signatures_before,
+ source_load,
+ );
+ pending.context_mut().install_resume_permit(resume_permit);
+ return Ok(ScriptHandoffOutcome::BlockedOnStylesheet(Box::new(
+ stylesheet_blocked_main_parser_blocking_classic_script(pending),
)));
}
if let Some(source_load) = source_load {
- return Ok(ScriptHandoffOutcome::BlockedOnExternalSource(Box::new(
- source_load_blocked_main_parser_blocking_classic_script(
- main_parser_blocking_classic_script_item(
- parser_document_owner,
- ParserPreparedClassicScript::new(
- ParserClassicScriptMetadata::new(handle, start_line),
- script,
- ),
- blocking_signatures_before,
- Some(source_load),
- ),
+ let resume_permit = self
+ .parser_session
+ .suspend(ParserSuspensionCause::ParserClassicSource { script: handle });
+ let mut pending = main_parser_blocking_classic_script_item(
+ parser_document_owner,
+ ParserPreparedClassicScript::new(
+ ParserClassicScriptMetadata::new(handle, start_line),
+ script,
),
+ blocking_signatures_before,
+ Some(source_load),
+ );
+ pending.context_mut().install_resume_permit(resume_permit);
+ return Ok(ScriptHandoffOutcome::BlockedOnExternalSource(Box::new(
+ source_load_blocked_main_parser_blocking_classic_script(pending),
)));
}
let mut pending_runner =
@@ -917,7 +950,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
);
let outcome = script_handoff_from_main_parser_blocking_execution(
resolve_main_parser_blocking_classic_after_runtime_gate(
- self.stream_handle(),
+ self.parser_session,
page_vm,
&mut pending_runner,
"executing parser-inserted classic script during parse",
@@ -1192,6 +1225,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
///
/// Returns only the flow-control signal (ScriptHandoff or InputDrained).
/// Parser-discovery signals are processed internally before returning.
+ #[cfg(test)]
pub(super) fn pump_parse_step_with_signals(
&mut self,
page_vm: &mut PageVm,
@@ -1208,6 +1242,107 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
&mut parser_owner,
)
});
+ self.finish_parser_pump_step(
+ page_vm,
+ parser_document_owner,
+ outcome,
+ null_custom_element_registry_elements,
+ )
+ }
+
+ fn pump_next_parse_step_with_signals(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ max_bytes: usize,
+ ) -> LiveDocumentParserStepOutcome {
+ self.sync_parser_defined_custom_elements(page_vm);
+ let (outcome, null_custom_element_registry_elements) =
+ page_vm.vm_mut().with_dom_host_parse_step(|vm| {
+ let mut parser_owner = PhaseOneParserOwner { vm };
+ let outcome = self
+ .parser_session
+ .advance_next_step(max_bytes, &mut parser_owner);
+ let null_custom_element_registry_elements = self
+ .parser_session
+ .take_parser_stream_null_custom_element_registry_elements();
+ (outcome, null_custom_element_registry_elements)
+ });
+ self.finish_parser_pump_step(
+ page_vm,
+ parser_document_owner,
+ outcome,
+ null_custom_element_registry_elements,
+ )
+ }
+
+ fn pump_queued_or_resume_parse_step_with_signals(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ ) -> LiveDocumentParserStepOutcome {
+ self.sync_parser_defined_custom_elements(page_vm);
+ let (outcome, null_custom_element_registry_elements) =
+ page_vm.vm_mut().with_dom_host_parse_step(|vm| {
+ let mut parser_owner = PhaseOneParserOwner { vm };
+ let outcome = self
+ .parser_session
+ .advance_queued_or_resume_step(&mut parser_owner);
+ let null_custom_element_registry_elements = self
+ .parser_session
+ .take_parser_stream_null_custom_element_registry_elements();
+ (outcome, null_custom_element_registry_elements)
+ });
+ self.finish_parser_pump_step(
+ page_vm,
+ parser_document_owner,
+ outcome,
+ null_custom_element_registry_elements,
+ )
+ }
+
+ fn finish_parser_pump_step(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ outcome: LiveDocumentParserStepOutcome,
+ null_custom_element_registry_elements: Vec<NativeNodeId>,
+ ) -> LiveDocumentParserStepOutcome {
+ let discovery_signals = self.parser_session.take_discovery_signals();
+ self.apply_parser_step_outputs(
+ page_vm,
+ parser_document_owner,
+ null_custom_element_registry_elements,
+ discovery_signals,
+ );
+ outcome
+ }
+
+ fn finish_main_parser(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ ) {
+ self.sync_parser_defined_custom_elements(page_vm);
+ let finish_signals = page_vm.vm_mut().with_dom_host_parse_step(|vm| {
+ let mut parser_owner = PhaseOneParserOwner { vm };
+ self.parser_session.finish(&mut parser_owner)
+ });
+ self.apply_parser_step_outputs(
+ page_vm,
+ parser_document_owner,
+ finish_signals.parser_created_null_registry_elements,
+ finish_signals.discovery_signals,
+ );
+ }
+
+ fn apply_parser_step_outputs(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ null_custom_element_registry_elements: Vec<NativeNodeId>,
+ discovery_signals: crate::live_document_parser::LiveDocumentParserDiscoverySignals,
+ ) {
let _ = page_vm
.vm_mut()
.apply_parser_created_null_registry_associations_in_default_context(
@@ -1224,7 +1359,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
modulepreload_link_candidates,
parser_meta_csp_candidates,
blocking_stylesheet_inputs,
- } = self.parser_session.take_discovery_signals();
+ } = discovery_signals;
self.buffered_document_preloads
.claim_pending_stylesheet_preloads_for_parser(&blocking_stylesheet_inputs);
for handle in &parser_meta_csp_candidates {
@@ -1288,8 +1423,100 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
parser_document_owner,
&blocking_stylesheet_inputs,
);
+ }
- outcome
+ async fn advance_next_parser_step_for_owner(
+ &mut self,
+ page_vm: &mut PageVm,
+ parser_document_owner: crate::frame_owner_model::FrameDocumentTaskOwner,
+ max_bytes: usize,
+ ) -> Result<ParserStepAdvanceOutcome> {
+ self.bind_page_resource_runtime(page_vm);
+ let mut first_step = true;
+ let outcome = loop {
+ if page_vm.vm().current_main_document_task_owner() != Some(parser_document_owner) {
+ tracing::debug!(
+ ?parser_document_owner,
+ current_owner = ?page_vm.vm().current_main_document_task_owner(),
+ "stopping stale main parser owner before advancing parser-owned input"
+ );
+ break ParserStepAdvanceOutcome::StoppedCurrentDocument;
+ }
+ let outcome = if first_step {
+ first_step = false;
+ self.pump_next_parse_step_with_signals(page_vm, parser_document_owner, max_bytes)
+ } else {
+ // Continue only bytes already admitted to the active backend for
+ // this bounded parser turn. The next end segment remains owned by
+ // the parser session until the scheduler grants another turn.
+ self.pump_queued_or_resume_parse_step_with_signals(page_vm, parser_document_owner)
+ };
+ if page_vm
+ .run_pending_parser_post_step_runtime_work_on_named_owner_local_task()
+ .await?
+ {
+ break ParserStepAdvanceOutcome::StoppedCurrentDocument;
+ }
+
+ match outcome {
+ LiveDocumentParserStepOutcome::Continue => {
+ break ParserStepAdvanceOutcome::Continue;
+ }
+ LiveDocumentParserStepOutcome::CustomElementConstructionHandoff(handoff) => {
+ page_vm
+ .construct_parser_custom_element_handoff_on_named_owner_local_task(*handoff)
+ .await?;
+ }
+ LiveDocumentParserStepOutcome::BlockingStylesheetPause(pause) => {
+ tracing::debug!(
+ stylesheet_node_id = pause.node_id.index(),
+ "main document parser paused on a body blocking stylesheet"
+ );
+ let final_url = self.final_url.clone();
+ self.catch_up_main_document_preload_scan(page_vm, &final_url, None);
+ let _ = self.parser_session.suspend(
+ ParserSuspensionCause::ParserCreatedStylesheet {
+ owner: pause.node_id,
+ },
+ );
+ break ParserStepAdvanceOutcome::BlockedOnStylesheetParserPause;
+ }
+ LiveDocumentParserStepOutcome::ScriptHandoff(handoff) => {
+ match self
+ .handle_parse_time_script_handoff_for_owner(
+ page_vm,
+ parser_document_owner,
+ *handoff,
+ None,
+ )
+ .await?
+ {
+ ScriptHandoffOutcome::StoppedCurrentDocument => {
+ break ParserStepAdvanceOutcome::StoppedCurrentDocument;
+ }
+ ScriptHandoffOutcome::NoNavigation => {
+ if let Some(outcome) = self.document_write_suspension_step_outcome() {
+ break outcome;
+ }
+ }
+ ScriptHandoffOutcome::BlockedOnDocumentWriteExternalLoad => {
+ break ParserStepAdvanceOutcome::BlockedOnDocumentWriteExternalLoad;
+ }
+ ScriptHandoffOutcome::BlockedOnStylesheet(script) => {
+ break ParserStepAdvanceOutcome::BlockedOnStylesheet(script);
+ }
+ ScriptHandoffOutcome::BlockedOnExternalSource(script) => {
+ break ParserStepAdvanceOutcome::BlockedOnExternalSource(script);
+ }
+ }
+ }
+ }
+ };
+
+ page_vm
+ .drain_deferred_page_tasks_on_named_owner_local_task()
+ .await?;
+ Ok(outcome)
}
#[cfg(test)]
@@ -1312,6 +1539,7 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
.await
}
+ #[cfg(test)]
async fn advance_parser_step_for_owner(
&mut self,
page_vm: &mut PageVm,
@@ -1365,6 +1593,11 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
&final_url,
handoff_tail.take(),
);
+ let _ = self.parser_session.suspend(
+ ParserSuspensionCause::ParserCreatedStylesheet {
+ owner: pause.node_id,
+ },
+ );
break ParserStepAdvanceOutcome::BlockedOnStylesheetParserPause;
}
LiveDocumentParserStepOutcome::ScriptHandoff(handoff) => {
@@ -1381,7 +1614,11 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
ScriptHandoffOutcome::StoppedCurrentDocument => {
break ParserStepAdvanceOutcome::StoppedCurrentDocument;
}
- ScriptHandoffOutcome::NoNavigation => {}
+ ScriptHandoffOutcome::NoNavigation => {
+ if let Some(outcome) = self.document_write_suspension_step_outcome() {
+ break outcome;
+ }
+ }
ScriptHandoffOutcome::BlockedOnDocumentWriteExternalLoad => {
break ParserStepAdvanceOutcome::BlockedOnDocumentWriteExternalLoad;
}
@@ -1401,54 +1638,20 @@ impl<'loader, 'state> ParserDriver<'loader, 'state> {
.await?;
Ok(outcome)
}
-}
-
-fn split_first_by_char_boundary(input: &str, max_bytes: usize) -> (&str, &str) {
- if max_bytes == 0 || input.len() <= max_bytes {
- return (input, "");
- }
- let mut current_len = 0;
- for (index, ch) in input.char_indices() {
- let ch_len = ch.len_utf8();
- if current_len > 0 && current_len + ch_len > max_bytes {
- return (&input[..index], &input[index..]);
+ fn document_write_suspension_step_outcome(&self) -> Option<ParserStepAdvanceOutcome> {
+ match self.parser_session.suspension_cause() {
+ Some(ParserSuspensionCause::ParserCreatedStylesheet { .. }) => {
+ Some(ParserStepAdvanceOutcome::BlockedOnStylesheetParserPause)
+ }
+ Some(ParserSuspensionCause::DocumentWriteExternalScript { .. }) => {
+ Some(ParserStepAdvanceOutcome::BlockedOnDocumentWriteExternalLoad)
+ }
+ Some(
+ ParserSuspensionCause::ParserClassicSource { .. }
+ | ParserSuspensionCause::ParserClassicStylesheets { .. },
+ )
+ | None => None,
}
- current_len += ch_len;
- }
-
- (input, "")
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn parser_input_buffer_prioritizes_script_input_before_current_network_chunk() {
- let final_url = Url::parse("https://example.test/").expect("test url");
- let stream = std::rc::Rc::new(std::cell::RefCell::new(
- HtmlParser.start_document(final_url),
- ));
- let mut input = ParserInputBuffer::new();
-
- input.set_current_chunk_for_testing(Some("<main>network</main>".to_owned()));
- stream
- .borrow()
- .script_input_session()
- .enqueue_script_input_html("<span>script</span>".to_owned());
-
- input.ensure_current_chunk(&stream.borrow());
-
- assert_eq!(
- input.current_chunk_for_testing(),
- Some("<span>script</span>"),
- "document.write/script input must be consumed at the parser insertion point first"
- );
- assert_eq!(
- input.queued_front_for_testing(),
- Some("<main>network</main>"),
- "unconsumed network input must remain after script input"
- );
}
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/pending_residence.rs b/moli-renderer-v8/src/runtime/phase_one/pending_residence.rs
index 392a12a39..96c1be038 100644
--- a/moli-renderer-v8/src/runtime/phase_one/pending_residence.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/pending_residence.rs
@@ -7,6 +7,30 @@ use super::{
PendingStreamingPhaseOneContinuation, PhaseOneRestoreRequirement,
};
+pub(in crate::runtime) enum PendingPhaseOneResumeOutcome {
+ Progress(ParseTimePageVmCreationOutcome),
+ MainResourceLoadFailed {
+ page_vm: PageVm,
+ error: anyhow::Error,
+ },
+}
+
+impl PendingPhaseOneResumeOutcome {
+ pub(super) fn progress(outcome: ParseTimePageVmCreationOutcome) -> Self {
+ Self::Progress(outcome)
+ }
+
+ pub(super) fn main_resource_load_failed(
+ runtime: ConcurrentParseTimeRuntime,
+ error: anyhow::Error,
+ ) -> Self {
+ Self::MainResourceLoadFailed {
+ page_vm: runtime.into_main_resource_load_failed_page_vm(),
+ error,
+ }
+ }
+}
+
/// Stable Page-slot residence for a parser that has yielded phase one.
///
/// Closed-input runtimes and open streaming responses have different state
@@ -106,13 +130,14 @@ impl PendingPhaseOneResidence {
}
}
- pub(in crate::runtime) async fn resume(self) -> Result<ParseTimePageVmCreationOutcome> {
+ pub(in crate::runtime) async fn resume(self) -> Result<PendingPhaseOneResumeOutcome> {
match self {
Self::ParserBlockingSourceLoad { runtime, started }
| Self::ClosedInputPageWork { runtime, started } => {
- (*runtime)
+ let outcome = (*runtime)
.continue_creation_from_phase_one_runtime(started)
- .await
+ .await?;
+ Ok(PendingPhaseOneResumeOutcome::progress(outcome))
}
Self::OpenStreaming(continuation) => continuation.resume().await,
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/phase_two.rs b/moli-renderer-v8/src/runtime/phase_one/phase_two.rs
index d24d8d985..cd6c143e0 100644
--- a/moli-renderer-v8/src/runtime/phase_one/phase_two.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/phase_two.rs
@@ -17,18 +17,8 @@ impl ConcurrentParseTimeRuntime {
&self.page_vm.local_executor,
"parse-time phase transition handoff",
);
- self.page_vm
- .vm_mut()
- .document_runtime
- .deactivate_main_parser_continuation();
- let stranded_parse_time_document_script_events = self
- .page_vm
- .page_task_queue
- .take_parse_time_document_script_events();
- let stranded_parse_time_lifecycle_work = self
- .page_vm
- .page_task_queue
- .take_parse_time_lifecycle_work();
+ let (stranded_parse_time_document_script_events, stranded_parse_time_lifecycle_work) =
+ self.retire_main_parser_continuation();
self.page_vm
.vm_mut()
.document_runtime
@@ -41,6 +31,16 @@ impl ConcurrentParseTimeRuntime {
scheduler.absorb_stranded_parse_time_document_script_events(
stranded_parse_time_document_script_events,
);
+ // A parser-inserted external script can suspend the main
+ // parser and let the document.write continuation consume its
+ // remaining input. Defer-like handoffs discovered by that
+ // continuation are accepted synchronously but leave their
+ // source/graph starts queued. Ordinary ParserDriver handoffs
+ // start immediately, so this EOF boundary must normalize both
+ // paths before sealing the one parser-deferred queue.
+ self.page_vm
+ .vm_mut()
+ .start_pending_main_parser_deferred_scripts()?;
let parser_deferred_marker = self
.page_vm
.seal_main_parser_deferred_scripts(self.parser_document_owner);
diff --git a/moli-renderer-v8/src/runtime/phase_one/state.rs b/moli-renderer-v8/src/runtime/phase_one/state.rs
index 32403c15e..6a3032080 100644
--- a/moli-renderer-v8/src/runtime/phase_one/state.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/state.rs
@@ -1,5 +1,6 @@
use super::parser_blocking_owner::MainParserBlockingSourceLoadWaitOwner;
use super::*;
+use crate::document_script_scheduler::ParseTimeDocumentScriptEvent;
pub(super) struct ParseTimeDriverState {
pub(super) final_url: Url,
@@ -25,6 +26,19 @@ impl ParseTimeDriverState {
input_closed: false,
}
}
+
+ pub(super) fn new_xml(final_url: Url) -> Self {
+ Self {
+ parser_session: DocumentParserSession::start_main_xml_document(final_url.clone()),
+ final_url,
+ document_character_set: "UTF-8".to_owned(),
+ scheduler: DocumentScriptScheduler::new(),
+ pending_parsing_blocking_script: PendingParsingBlockingClassicScriptRunner::empty(),
+ buffered_document_preloads: Box::default(),
+ service_worker_preload_context: None,
+ input_closed: false,
+ }
+ }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -78,17 +92,69 @@ impl ConcurrentParseTimeRuntime {
&mut self.page_vm
}
+ pub(super) fn retire_main_parser_continuation(
+ &mut self,
+ ) -> (
+ Vec<ParseTimeDocumentScriptEvent>,
+ Vec<PostParsePageOwnedWork>,
+ ) {
+ self.page_vm
+ .vm_mut()
+ .document_runtime
+ .deactivate_main_parser_continuation();
+ (
+ self.page_vm
+ .page_task_queue
+ .take_parse_time_document_script_events(),
+ self.page_vm
+ .page_task_queue
+ .take_parse_time_lifecycle_work(),
+ )
+ }
+
+ /// Stop a committed parser after its main-resource body reaches a failed
+ /// terminal while retaining the partial Document as the active Page.
+ ///
+ /// Blink's `DocumentLoader::LoadFailed` stops parsing and reports a failed
+ /// navigation; it does not destroy the committed LocalFrame. Mirror that
+ /// ownership transition here: parser-only state is discarded, while the
+ /// PageVm and its observable DOM remain resident for automation and a
+ /// subsequent navigation.
+ pub(super) fn into_main_resource_load_failed_page_vm(mut self) -> PageVm {
+ self.state
+ .parser_session
+ .stop(ParserStopReason::MainResourceLoadFailure);
+ drop(self.retire_main_parser_continuation());
+ let _ = self.page_vm.document_lifecycle.request_termination(
+ self.page_vm.document_lifecycle.identity(),
+ RendererDocumentTerminationReason::MainResourceLoadFailed,
+ );
+ self.page_vm
+ }
+
pub(super) fn new_parser_owner(
loader: ResourceRequestClient,
stage: PageVmInitStage,
- state: ParseTimeDriverState,
+ mut state: ParseTimeDriverState,
mut page_vm: PageVm,
) -> Self {
page_vm.set_target_stage(stage);
+ page_vm
+ .vm_mut()
+ .document_runtime
+ .bind_main_document_script_preload_store(
+ state
+ .buffered_document_preloads
+ .document_script_preload_store(),
+ );
let parser_document_owner = page_vm
.vm()
.current_main_document_task_owner()
.expect("phase-one parser runtime requires an installed main document owner");
+ state.parser_session.bind_owner(
+ parser_document_owner,
+ page_vm.vm().document_runtime.runtime_reset_generation(),
+ );
page_vm
.vm_mut()
.document_runtime
@@ -149,7 +215,7 @@ impl ConcurrentParseTimeRuntime {
let ConcurrentParseTimeRuntime { state, page_vm, .. } = self;
let mut context = DocumentTurnContext {
scheduler: &mut state.scheduler,
- stream: state.parser_session.stream_handle(),
+ parser_session: &state.parser_session,
};
context.run_parse_time_turn(page_vm).await
}
diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming.rs b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
index fa8f8e939..9114d8034 100644
--- a/moli-renderer-v8/src/runtime/phase_one/streaming.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/streaming.rs
@@ -212,7 +212,7 @@ impl ConcurrentParseTimeRuntime {
)))
}
- pub(in crate::runtime) async fn finish_creation_from_external_raw_document_response(
+ pub(in crate::runtime) async fn create_external_raw_document_response_at_reply_boundary(
page_id: PageId,
local_executor: JsLocalExecutor,
loader: &ResourceRequestClient,
@@ -224,6 +224,7 @@ impl ConcurrentParseTimeRuntime {
response_status: u16,
response_headers: Vec<(String, String)>,
raw_body: ExternalRawDocumentBodyStream,
+ reply_boundary: crate::RendererPageCreationReplyBoundary,
) -> Result<StreamingNavigationPageCreationResult> {
if response_headers_indicate_download(&response_headers) {
let mut body_source = RawDocumentBodySource::External(raw_body);
@@ -242,7 +243,15 @@ impl ConcurrentParseTimeRuntime {
));
}
- Self::finish_creation_from_committed_external_raw_document_response(
+ let bootstrap_boundary = match reply_boundary {
+ crate::RendererPageCreationReplyBoundary::LifecycleTarget => {
+ CommittedNavigationBootstrapBoundary::ContinuePhaseOne
+ }
+ crate::RendererPageCreationReplyBoundary::DocumentCommit => {
+ CommittedNavigationBootstrapBoundary::DocumentCommit
+ }
+ };
+ Self::create_from_committed_external_raw_document_response(
page_id,
local_executor,
loader,
@@ -254,10 +263,12 @@ impl ConcurrentParseTimeRuntime {
response_status,
response_headers,
raw_body,
+ bootstrap_boundary,
)
.await
}
+ #[cfg(test)]
pub(in crate::runtime) async fn finish_creation_from_committed_external_raw_document_response(
page_id: PageId,
local_executor: JsLocalExecutor,
@@ -378,6 +389,32 @@ impl ConcurrentParseTimeRuntime {
&final_url,
&response_headers,
);
+ if response_headers_indicate_xml_document(&response_headers) {
+ let body = collect_streaming_raw_body(&mut body_source).await?;
+ let source = String::from_utf8_lossy(&body).into_owned();
+ let content_type = moli_web_mime::response_document_content_type(&response_headers)
+ .unwrap_or_else(|| "application/xml".to_owned());
+ let outcome = Self::finish_creation_from_xml_bootstrap(
+ page_id,
+ local_executor,
+ loader,
+ &env,
+ runtime_hooks,
+ final_url,
+ content_type,
+ stage,
+ source,
+ started,
+ )
+ .await?;
+ return Ok(StreamingNavigationPageCreationResult::Html(Box::new(
+ StreamingHtmlPageCreationResult {
+ response_status,
+ response_headers,
+ outcome,
+ },
+ )));
+ }
let mut state = ParseTimeDriverState::new(final_url);
state
.buffered_document_preloads
@@ -524,6 +561,11 @@ impl ConcurrentParseTimeRuntime {
}
}
+fn response_headers_indicate_xml_document(headers: &[(String, String)]) -> bool {
+ moli_web_mime::response_document_content_type(headers)
+ .is_some_and(|mime| moli_web_mime::is_dom_parser_xml_mime(&mime))
+}
+
const EXTERNAL_RAW_DOCUMENT_BODY_BUFFERED_CHUNKS: usize = 8;
pub struct ExternalRawDocumentBodyStream {
@@ -552,6 +594,15 @@ impl ExternalRawDocumentBodyStream {
}
}
+ pub fn from_bytes(body: Vec<u8>) -> Self {
+ let (completion_tx, completion_rx) = oneshot::channel();
+ let (body_tx, body_stream) = Self::channel(completion_rx);
+ let _ = body_tx.try_send(body);
+ drop(body_tx);
+ let _ = completion_tx.send(Ok(()));
+ body_stream
+ }
+
fn body_chunk_stream_is_exhausted(&self) -> bool {
self.body_chunks.is_closed() && self.body_chunks.is_empty()
}
@@ -1307,10 +1358,8 @@ mod tests {
.state
.buffered_document_preloads
.entries
- .get(&classic_preload_key_for_streaming_test(script_url.as_str()))
- .expect("ready chunk should create script preload")
- .load
- .clone();
+ .load_for_key(&classic_preload_key_for_streaming_test(script_url.as_str()))
+ .expect("ready chunk should create script preload");
let outcome =
tokio::time::timeout(std::time::Duration::from_secs(2), preload.wait_outcome())
.await
diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming_admission_tests.rs b/moli-renderer-v8/src/runtime/phase_one/streaming_admission_tests.rs
index 50f7de0bd..e30087354 100644
--- a/moli-renderer-v8/src/runtime/phase_one/streaming_admission_tests.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/streaming_admission_tests.rs
@@ -104,6 +104,9 @@ async fn resume_open_stream(
super::access::run_named_owner_local_task(executor, operation, residence.resume())
.await
.expect("open-stream continuation should resume");
+ let PendingPhaseOneResumeOutcome::Progress(outcome) = outcome else {
+ panic!("successful open-stream fixture must not fail its main resource");
+ };
let ParseTimePageVmCreationOutcome::PendingPhaseOne(residence) = outcome else {
panic!("open body and its ready Page task should keep phase one resident");
};
@@ -203,9 +206,14 @@ async fn resume_phase_one_once(
operation: &'static str,
) -> ParseTimePageVmCreationOutcome {
let executor = residence.page_vm().local_executor.clone();
- super::access::run_named_owner_local_task(executor, operation, residence.resume())
- .await
- .expect("phase-one continuation should resume")
+ let outcome =
+ super::access::run_named_owner_local_task(executor, operation, residence.resume())
+ .await
+ .expect("phase-one continuation should resume");
+ let PendingPhaseOneResumeOutcome::Progress(outcome) = outcome else {
+ panic!("successful phase-one fixture must not fail its main resource");
+ };
+ outcome
}
#[test]
diff --git a/moli-renderer-v8/src/runtime/phase_one/streaming_residence.rs b/moli-renderer-v8/src/runtime/phase_one/streaming_residence.rs
index 37b611855..96557ba94 100644
--- a/moli-renderer-v8/src/runtime/phase_one/streaming_residence.rs
+++ b/moli-renderer-v8/src/runtime/phase_one/streaming_residence.rs
@@ -8,7 +8,8 @@ use super::streaming::{
use super::streaming_input::{StreamingDocumentInputEvent, StreamingDocumentInputSource};
use super::{
ConcurrentParseTimeRuntime, PageVm, ParseTimePageVmCreationOutcome,
- ParseTimePageVmStreamingProgress, PendingPhaseOneResidence, ServiceWorkerScriptPreloadContext,
+ ParseTimePageVmStreamingProgress, PendingPhaseOneResidence, PendingPhaseOneResumeOutcome,
+ ServiceWorkerScriptPreloadContext,
};
/// Exact, parkable continuation for an open main-Document response.
@@ -23,6 +24,7 @@ pub(in crate::runtime) struct PendingStreamingPhaseOneContinuation {
decoder: HtmlDocumentStreamingDecoder,
service_worker_preload_context: Option<ServiceWorkerScriptPreloadContext>,
started: Instant,
+ deferred_main_resource_failure: Option<anyhow::Error>,
}
impl PendingStreamingPhaseOneContinuation {
@@ -48,6 +50,7 @@ impl PendingStreamingPhaseOneContinuation {
decoder,
service_worker_preload_context,
started,
+ deferred_main_resource_failure: None,
})
}
@@ -67,43 +70,80 @@ impl PendingStreamingPhaseOneContinuation {
self.input.has_ready_input()
}
- pub(in crate::runtime) async fn resume(self) -> Result<ParseTimePageVmCreationOutcome> {
+ pub(in crate::runtime) async fn resume(self) -> Result<PendingPhaseOneResumeOutcome> {
let Self {
runtime,
mut input,
mut decoder,
service_worker_preload_context,
started,
+ mut deferred_main_resource_failure,
} = self;
let mut runtime = *runtime;
let mut input_finished = false;
- let mut observed_input = false;
- while let Some(event) = input.try_next()? {
- observed_input = true;
- match event {
- StreamingDocumentInputEvent::Chunks(chunks) => {
- for chunk in chunks {
- enqueue_streaming_raw_chunk(
- &mut runtime,
- &mut decoder,
- chunk,
- service_worker_preload_context.as_ref(),
- );
+ let mut observed_input = deferred_main_resource_failure.is_some();
+ if deferred_main_resource_failure.is_none() {
+ while let Some(event) = input.try_next()? {
+ observed_input = true;
+ match event {
+ StreamingDocumentInputEvent::Chunks(chunks) => {
+ for chunk in chunks {
+ enqueue_streaming_raw_chunk(
+ &mut runtime,
+ &mut decoder,
+ chunk,
+ service_worker_preload_context.as_ref(),
+ );
+ }
}
- }
- StreamingDocumentInputEvent::Finished(result) => {
- result.map_err(|message| anyhow!(message))?;
- if let Some(tail) = decoder.finish() {
- runtime.enqueue_streaming_html_chunk(tail);
+ StreamingDocumentInputEvent::Finished(result) => {
+ if let Err(message) = result {
+ deferred_main_resource_failure = Some(anyhow!(message));
+ break;
+ }
+ if let Some(tail) = decoder.finish() {
+ runtime.enqueue_streaming_html_chunk(tail);
+ }
+ sync_document_character_set_from_decoder(&mut runtime, &decoder);
+ runtime.close_streaming_html_input();
+ input_finished = true;
+ break;
}
- sync_document_character_set_from_decoder(&mut runtime, &decoder);
- runtime.close_streaming_html_input();
- input_finished = true;
- break;
}
}
}
+ // A body terminal is sequenced after every chunk produced before it.
+ // If those bytes are resident but their Networking continuation has
+ // not yet been selected by the stable Page scheduler, keep the failed
+ // terminal with this exact parser residence. Applying it now would
+ // destroy parser state before the already-delivered partial DOM can be
+ // materialized. This is an ordering edge, not a retry: the existing
+ // parser task owns the only wake and admission needed to resume us.
+ let selected_main_parser_continuation = runtime
+ .page_vm()
+ .vm()
+ .document_runtime
+ .has_main_parser_continuation_admission();
+ if deferred_main_resource_failure.is_some()
+ && !selected_main_parser_continuation
+ && !runtime.state.parser_session.input_is_empty()
+ {
+ let continuation = Self {
+ runtime: Box::new(runtime),
+ input,
+ decoder,
+ service_worker_preload_context,
+ started,
+ deferred_main_resource_failure,
+ };
+ return Ok(PendingPhaseOneResumeOutcome::progress(
+ ParseTimePageVmCreationOutcome::PendingPhaseOne(
+ PendingPhaseOneResidence::open_streaming(Box::new(continuation)),
+ ),
+ ));
+ }
+
// Body input and parse-time script terminals wake the same parked
// continuation, but they do not grant the same owner transition.
// Input (including EOF) belongs to the parser and must reach its fresh
@@ -117,7 +157,36 @@ impl PendingStreamingPhaseOneContinuation {
let progress = runtime
.continue_streaming_creation_on_execution_context(started)
.await?;
- match progress {
+ if let Some(error) = deferred_main_resource_failure {
+ return Ok(match progress {
+ ParseTimePageVmStreamingProgress::NeedMoreInput(runtime)
+ | ParseTimePageVmStreamingProgress::PendingPageTask(runtime) => {
+ PendingPhaseOneResumeOutcome::main_resource_load_failed(*runtime, error)
+ }
+ // Script in the bytes delivered before the failed terminal may
+ // replace the Document or start a navigation. The replacement
+ // owns the Page; do not apply the old loader's terminal to it.
+ ParseTimePageVmStreamingProgress::TriggeredNavigation { page_vm, stage } => {
+ PendingPhaseOneResumeOutcome::progress(
+ ParseTimePageVmCreationOutcome::TriggeredNavigation { page_vm, stage },
+ )
+ }
+ ParseTimePageVmStreamingProgress::ContinuePhaseTwo {
+ page_vm,
+ page_tasks,
+ stage,
+ started,
+ } => PendingPhaseOneResumeOutcome::progress(
+ ParseTimePageVmCreationOutcome::ContinuePhaseTwo {
+ page_vm,
+ page_tasks,
+ stage,
+ started,
+ },
+ ),
+ });
+ }
+ let outcome = match progress {
ParseTimePageVmStreamingProgress::NeedMoreInput(runtime) if !input_finished => {
let continuation = Self {
runtime,
@@ -125,10 +194,11 @@ impl PendingStreamingPhaseOneContinuation {
decoder,
service_worker_preload_context,
started,
+ deferred_main_resource_failure: None,
};
- Ok(ParseTimePageVmCreationOutcome::PendingPhaseOne(
+ ParseTimePageVmCreationOutcome::PendingPhaseOne(
PendingPhaseOneResidence::open_streaming(Box::new(continuation)),
- ))
+ )
}
ParseTimePageVmStreamingProgress::PendingPageTask(runtime) if !input_finished => {
let continuation = Self {
@@ -137,40 +207,44 @@ impl PendingStreamingPhaseOneContinuation {
decoder,
service_worker_preload_context,
started,
+ deferred_main_resource_failure: None,
};
- Ok(ParseTimePageVmCreationOutcome::PendingPhaseOne(
+ ParseTimePageVmCreationOutcome::PendingPhaseOne(
PendingPhaseOneResidence::open_streaming(Box::new(continuation)),
- ))
+ )
}
ParseTimePageVmStreamingProgress::NeedMoreInput(runtime)
if runtime.has_pending_parser_blocking_source_load() =>
{
- Ok(ParseTimePageVmCreationOutcome::PendingPhaseOne(
+ ParseTimePageVmCreationOutcome::PendingPhaseOne(
PendingPhaseOneResidence::parser_blocking_source_load(runtime, started),
- ))
+ )
}
ParseTimePageVmStreamingProgress::PendingPageTask(runtime) => {
- Ok(ParseTimePageVmCreationOutcome::PendingPhaseOne(
+ ParseTimePageVmCreationOutcome::PendingPhaseOne(
PendingPhaseOneResidence::closed_input_page_work(runtime, started),
- ))
+ )
+ }
+ ParseTimePageVmStreamingProgress::NeedMoreInput(_) => {
+ return Err(anyhow!(
+ "closed streaming html input should not stall waiting for more input"
+ ));
}
- ParseTimePageVmStreamingProgress::NeedMoreInput(_) => Err(anyhow!(
- "closed streaming html input should not stall waiting for more input"
- )),
ParseTimePageVmStreamingProgress::TriggeredNavigation { page_vm, stage } => {
- Ok(ParseTimePageVmCreationOutcome::TriggeredNavigation { page_vm, stage })
+ ParseTimePageVmCreationOutcome::TriggeredNavigation { page_vm, stage }
}
ParseTimePageVmStreamingProgress::ContinuePhaseTwo {
page_vm,
page_tasks,
stage,
started,
- } => Ok(ParseTimePageVmCreationOutcome::ContinuePhaseTwo {
+ } => ParseTimePageVmCreationOutcome::ContinuePhaseTwo {
page_vm,
page_tasks,
stage,
started,
- }),
- }
+ },
+ };
+ Ok(PendingPhaseOneResumeOutcome::progress(outcome))
}
}
diff --git a/moli-renderer-v8/src/runtime/post_parse_runtime_inputs.rs b/moli-renderer-v8/src/runtime/post_parse_runtime_inputs.rs
deleted file mode 100644
index c1a616243..000000000
--- a/moli-renderer-v8/src/runtime/post_parse_runtime_inputs.rs
+++ /dev/null
@@ -1,252 +0,0 @@
-use super::page_vm::PageVm;
-use crate::{
- DocumentOwnedBlockingStylesheetDiscoveryInput,
- document_runtime::{
- parser_prepared_script_page_owned_work, parser_script_preparation_failure_page_owned_work,
- },
- document_script_scheduler::DocumentScriptScheduler,
- frame_owner_model::FrameDocumentTaskOwner,
- host::ScriptHandleSource,
- network::ResourceRequestClient,
- page_task_queue::PostParsePageOwnedWork,
- parser::{ParserDocumentHandoff, ParserScriptHandoff},
- types::ScriptKind,
-};
-use anyhow::{Result, anyhow};
-
-pub(in crate::runtime) struct InitialDocumentScriptOwnerInput {
- owner: FrameDocumentTaskOwner,
- scheduler: DocumentScriptScheduler,
- page_owned_work: Vec<PostParsePageOwnedWork>,
- blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
-}
-
-impl InitialDocumentScriptOwnerInput {
- pub(in crate::runtime) fn accept(
- page_vm: &mut PageVm,
- loader: &ResourceRequestClient,
- handoffs: Vec<ParserDocumentHandoff>,
- blocking_stylesheet_inputs: Vec<DocumentOwnedBlockingStylesheetDiscoveryInput>,
- ) -> Result<Self> {
- let owner = page_vm
- .vm()
- .current_main_document_task_owner()
- .ok_or_else(|| anyhow!("initial document script acceptance requires a main owner"))?;
- let document_character_set = page_vm
- .vm()
- .document_runtime
- .document_character_set()
- .to_owned();
- let mut scheduler = DocumentScriptScheduler::new();
- let mut page_owned_work = Vec::new();
-
- for handoff in handoffs {
- let ParserDocumentHandoff::Script(handoff) = handoff else {
- let ParserDocumentHandoff::ModulepreloadLink(link_handle) = handoff else {
- unreachable!("parser document handoff variants are exhaustive")
- };
- page_vm
- .vm_mut()
- .accept_parser_discovered_native_modulepreloads(std::iter::once(link_handle));
- continue;
- };
- match *handoff {
- ParserScriptHandoff::BlockingClassic {
- node_id,
- start_line,
- start_column,
- blocking_signatures_before,
- mut script,
- } => {
- bind_initial_parser_script(
- page_vm,
- node_id,
- start_line,
- start_column,
- &mut script,
- );
- page_owned_work.push(parser_prepared_script_page_owned_work(
- script,
- blocking_signatures_before,
- ));
- }
- ParserScriptHandoff::AsyncPostParse {
- node_id,
- start_line,
- start_column,
- mut script,
- } => {
- bind_initial_parser_script(
- page_vm,
- node_id,
- start_line,
- start_column,
- &mut script,
- );
- if script.kind == ScriptKind::Module {
- let accepted = page_vm
- .vm_mut()
- .accept_main_parser_async_module_script(owner, &script)?;
- if !accepted {
- return Err(anyhow!(
- "initial parser async module could not bind its document owner"
- ));
- }
- continue;
- }
- let resource_task_runner = page_vm.resource_task_runner();
- if !scheduler
- .accept_parser_discovered_async_candidate(
- script.clone(),
- loader,
- resource_task_runner,
- None,
- Some(&document_character_set),
- |_| {
- page_vm
- .vm_mut()
- .accept_main_document_script_load_delay_binding(
- owner,
- crate::frame_owner_model::MainDocumentScriptLoadDelayKind::Classic,
- )
- .expect("initial parser async classic must bind lifecycle ownership")
- },
- )
- || !scheduler.claim_existing_parse_time_async_handoff(script.node_id)
- {
- return Err(anyhow!(
- "initial document async parser handoff could not establish discovery ownership"
- ));
- }
- }
- ParserScriptHandoff::NonAsyncPostParse {
- node_id,
- start_line,
- start_column,
- mut script,
- blocking_signatures_before,
- } => {
- bind_initial_parser_script(
- page_vm,
- node_id,
- start_line,
- start_column,
- &mut script,
- );
- let accepted = page_vm.vm_mut().claim_main_parser_deferred_script(
- owner,
- script,
- None,
- Some(&document_character_set),
- blocking_signatures_before,
- )?;
- if !accepted {
- return Err(anyhow!(
- "initial parser-deferred handoff could not bind its document owner"
- ));
- }
- }
- ParserScriptHandoff::ImportMap {
- node_id,
- start_line,
- start_column,
- import_map,
- } => crate::module_runtime::accept_parser_owned_import_map_handoff(
- page_vm.vm_mut(),
- node_id,
- start_line,
- start_column,
- import_map,
- ),
- ParserScriptHandoff::NoExecution {
- node_id,
- start_line,
- start_column,
- outcome,
- } => {
- crate::host::apply_parser_script_element_state_transition(
- page_vm.vm_mut().document_runtime.dom_host_mut(),
- node_id,
- outcome.element_state_transition(),
- );
- page_vm
- .vm_mut()
- .document_runtime
- .note_parser_script_start_position(node_id, start_line, start_column);
- if let (_, _, Some(run)) = outcome.into_parts() {
- page_vm.report.runs.push(run);
- }
- }
- ParserScriptHandoff::PreparationFailure {
- node_id,
- start_line,
- start_column,
- failure,
- } => {
- crate::host::apply_parser_script_element_state_transition(
- page_vm.vm_mut().document_runtime.dom_host_mut(),
- node_id,
- failure.element_state_transition(),
- );
- page_vm
- .vm_mut()
- .document_runtime
- .note_parser_script_start_position(node_id, start_line, start_column);
- page_owned_work
- .push(parser_script_preparation_failure_page_owned_work(failure));
- }
- }
- }
-
- Ok(Self {
- owner,
- scheduler,
- page_owned_work,
- blocking_stylesheet_inputs,
- })
- }
-
- pub(in crate::runtime) async fn finalize(
- self,
- page_vm: &mut PageVm,
- ) -> Vec<PostParsePageOwnedWork> {
- if page_vm.vm().current_main_document_task_owner() != Some(self.owner) {
- return Vec::new();
- }
- let marker = page_vm.seal_main_parser_deferred_scripts(self.owner);
- if page_vm.vm().current_main_document_task_owner() != Some(self.owner) {
- return Vec::new();
- }
- let handoff = self
- .scheduler
- .finalize_parser_prepared_post_parse_handoff(self.blocking_stylesheet_inputs)
- .await;
- let mut work = self.page_owned_work;
- work.extend(handoff.into_page_owned_work());
- if let Some(marker) = marker {
- work.push(marker);
- }
- work
- }
-}
-
-fn bind_initial_parser_script(
- page_vm: &mut PageVm,
- node_id: crate::dom::native::NativeNodeId,
- start_line: u64,
- start_column: u64,
- script: &mut crate::planning::PreparedScript,
-) {
- page_vm
- .vm_mut()
- .document_runtime
- .note_parser_script_start_position(node_id, start_line, start_column);
- page_vm
- .vm_mut()
- .bind_prepared_script_if_needed(script, ScriptHandleSource::ParserOwned);
- let _ = page_vm
- .vm_mut()
- .document_runtime
- .dom_host_mut()
- .set_script_already_started(node_id, true);
-}
diff --git a/moli-renderer-v8/src/runtime/protocol_output/item.rs b/moli-renderer-v8/src/runtime/protocol_output/item.rs
index 7f121bf12..a5755adc5 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/item.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/item.rs
@@ -18,6 +18,12 @@ use moli_page_types::{
ScriptNetworkOutputItem,
};
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct RendererDocumentTitleChanged {
+ pub source_document: RendererDocumentLifecycleIdentity,
+ pub title: String,
+}
+
/// A renderer-neutral browser-owner action.
///
/// Variants move here as their old pending queue is removed. Keeping actions
@@ -74,6 +80,7 @@ pub enum RendererOwnerAction {
#[derive(Clone, Debug, PartialEq)]
pub enum RendererProtocolObservation {
MainDocumentCommit(RendererMainDocumentCommit),
+ DocumentTitleChanged(RendererDocumentTitleChanged),
DocumentLifecycle(RendererDocumentLifecycleEvent),
Network {
source_document: RendererDocumentLifecycleIdentity,
diff --git a/moli-renderer-v8/src/runtime/protocol_output/mod.rs b/moli-renderer-v8/src/runtime/protocol_output/mod.rs
index b8b266d31..6ae4bd07c 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/mod.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/mod.rs
@@ -13,7 +13,8 @@ pub use identity::{
};
pub(crate) use item::PendingRendererOutputRecord;
pub use item::{
- RendererOutputItem, RendererOutputRecord, RendererOwnerAction, RendererProtocolObservation,
+ RendererDocumentTitleChanged, RendererOutputItem, RendererOutputRecord, RendererOwnerAction,
+ RendererProtocolObservation,
};
pub use transport::{
RendererOutputTransportDiagnostics, RendererOutputTransportMessage,
diff --git a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
index 262ed2b6d..73c4dfc5f 100644
--- a/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
+++ b/moli-renderer-v8/src/runtime/protocol_output/transport_memory.rs
@@ -69,6 +69,7 @@ fn observation_transport_charge_bytes(observation: &RendererProtocolObservation)
.into_iter()
.map(string_charge)
.sum(),
+ RendererProtocolObservation::DocumentTitleChanged(change) => string_charge(&change.title),
RendererProtocolObservation::DocumentLifecycle(_) => 0,
RendererProtocolObservation::Network { item, .. } => item.renderer_transport_charge_bytes(),
RendererProtocolObservation::RuntimeBinding(call) => {
diff --git a/moli-renderer-v8/src/runtime/script_preloads.rs b/moli-renderer-v8/src/runtime/script_preloads.rs
index 07def109a..4aaf634a5 100644
--- a/moli-renderer-v8/src/runtime/script_preloads.rs
+++ b/moli-renderer-v8/src/runtime/script_preloads.rs
@@ -1,5 +1,6 @@
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
use html5ever::{
Attribute,
@@ -11,6 +12,8 @@ use html5ever::{
};
use url::Url;
+use parking_lot::Mutex;
+
use crate::network::ResourceRequestClient;
use crate::page_task_queue::RendererOwnerWakeSender;
use crate::parser::{PreparedScript, ScriptSource};
@@ -41,7 +44,7 @@ pub(super) enum ParserBlockingPreloadDisposition {
}
pub(super) struct BufferedDocumentPreloadState {
- pub(super) entries: HashMap<BufferedScriptPreloadKey, BufferedScriptPreloadEntry>,
+ pub(super) entries: DocumentScriptPreloadStore,
document_character_set: String,
script_fetch_interception_enabled: bool,
response_csp_requires_parser_admission: bool,
@@ -89,6 +92,80 @@ pub(super) struct BufferedScriptPreloadEntry {
pub(super) load: SharedScriptSourceLoad,
}
+/// Document-scoped residence for classic script loads started by the HTML
+/// preload scanner.
+///
+/// The scanner itself remains phase-one state, while its in-flight loads must
+/// also be visible to nested parser re-entry in `DocumentRuntime`. Sharing only
+/// this resource map keeps one physical fetch owner without moving tokenizer
+/// or scanner state into the live Document.
+#[derive(Clone, Default)]
+pub(crate) struct DocumentScriptPreloadStore {
+ entries: Arc<Mutex<HashMap<BufferedScriptPreloadKey, BufferedScriptPreloadEntry>>>,
+}
+
+impl std::fmt::Debug for DocumentScriptPreloadStore {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_struct("DocumentScriptPreloadStore")
+ .field("entry_count", &self.len())
+ .finish()
+ }
+}
+
+impl DocumentScriptPreloadStore {
+ pub(super) fn contains_key(&self, key: &BufferedScriptPreloadKey) -> bool {
+ self.entries.lock().contains_key(key)
+ }
+
+ pub(super) fn insert(
+ &mut self,
+ key: BufferedScriptPreloadKey,
+ entry: BufferedScriptPreloadEntry,
+ ) {
+ self.entries.lock().insert(key, entry);
+ }
+
+ pub(super) fn len(&self) -> usize {
+ self.entries.lock().len()
+ }
+
+ #[cfg(test)]
+ pub(super) fn is_empty(&self) -> bool {
+ self.entries.lock().is_empty()
+ }
+
+ #[cfg(test)]
+ pub(super) fn load_for_key(
+ &self,
+ key: &BufferedScriptPreloadKey,
+ ) -> Option<SharedScriptSourceLoad> {
+ self.entries.lock().get(key).map(|entry| entry.load.clone())
+ }
+
+ fn preload_for_script(
+ &self,
+ script: &PreparedScript,
+ ) -> Option<(SharedScriptSourceLoad, moli_fetch::RequestResourceType)> {
+ if !matches!(script.source, ScriptSource::External) {
+ return None;
+ }
+ let key = BufferedScriptPreloadKey::from_script(script)?;
+ let entries = self.entries.lock();
+ let entry = entries
+ .get(&key)
+ .filter(|entry| entry.request.matches_script(script))?;
+ Some((entry.load.clone(), entry.request.resource_type_hint))
+ }
+
+ pub(crate) fn shared_preload_for_script(
+ &self,
+ script: &PreparedScript,
+ ) -> Option<SharedScriptSourceLoad> {
+ self.preload_for_script(script).map(|(load, _)| load)
+ }
+}
+
#[derive(Clone)]
pub(super) struct ServiceWorkerScriptPreloadContext {
browser_context_runtime: RendererBrowserContextRuntime,
@@ -116,7 +193,7 @@ impl ServiceWorkerScriptPreloadContext {
impl Default for BufferedDocumentPreloadState {
fn default() -> Self {
Self {
- entries: HashMap::new(),
+ entries: DocumentScriptPreloadStore::default(),
document_character_set: "UTF-8".to_owned(),
script_fetch_interception_enabled: false,
response_csp_requires_parser_admission: false,
@@ -133,6 +210,10 @@ impl Default for BufferedDocumentPreloadState {
}
impl BufferedDocumentPreloadState {
+ pub(super) fn document_script_preload_store(&self) -> DocumentScriptPreloadStore {
+ self.entries.clone()
+ }
+
pub(super) fn bind_resource_runtime(
&mut self,
owner_wake: Option<RendererOwnerWakeSender>,
@@ -235,14 +316,20 @@ impl BufferedDocumentPreloadState {
loader: &ResourceRequestClient,
service_worker_context: Option<&ServiceWorkerScriptPreloadContext>,
) {
- if self.script_fetch_interception_enabled
+ let requires_owner_admission = self.script_fetch_interception_enabled
|| self.response_csp_requires_parser_admission
- || self.meta_csp_preload_gate.has_seen_meta_csp()
- {
- self.queue_script_preloads_for_owner_admission(requests);
- return;
- }
- self.start_preloads_for_requests(requests, loader, service_worker_context);
+ || self.meta_csp_preload_gate.has_seen_meta_csp();
+ let (owner_admitted, legacy_preloads): (Vec<_>, Vec<_>) =
+ requests.into_iter().partition(|request| {
+ requires_owner_admission || request.kind_hint == crate::types::ScriptKind::Module
+ });
+ // Native module graphs share fetches through the Document's module
+ // map. They cannot enter the legacy SharedScriptSourceLoad cache: a
+ // parser module would have no way to join that in-flight request and
+ // would issue a second fetch. PageVm bootstrap drains these descriptors
+ // into the native module map as soon as the Document owner exists.
+ self.queue_script_preloads_for_owner_admission(owner_admitted);
+ self.start_preloads_for_requests(legacy_preloads, loader, service_worker_context);
}
pub(super) fn set_document_character_set(&mut self, document_character_set: &str) {
@@ -453,21 +540,7 @@ impl BufferedDocumentPreloadState {
&self,
script: &PreparedScript,
) -> Option<SharedScriptSourceLoad> {
- self.preload_entry_for_script(script)
- .map(|entry| entry.load.clone())
- }
-
- fn preload_entry_for_script(
- &self,
- script: &PreparedScript,
- ) -> Option<&BufferedScriptPreloadEntry> {
- if !matches!(script.source, ScriptSource::External) {
- return None;
- }
- let key = BufferedScriptPreloadKey::from_script(script)?;
- self.entries
- .get(&key)
- .filter(|entry| entry.request.matches_script(script))
+ self.entries.shared_preload_for_script(script)
}
pub(super) fn parser_blocking_preload_disposition_for_script(
@@ -478,11 +551,9 @@ impl BufferedDocumentPreloadState {
return ParserBlockingPreloadDisposition::Missing;
}
- let Some(entry) = self.preload_entry_for_script(script) else {
+ let Some((load, resource_type_hint)) = self.entries.preload_for_script(script) else {
return ParserBlockingPreloadDisposition::Missing;
};
- let load = entry.load.clone();
- let resource_type_hint = entry.request.resource_type_hint;
if parser_blocking_consumer_should_refetch_pending_late_preload(
script,
resource_type_hint,
@@ -523,9 +594,7 @@ impl BufferedDocumentPreloadState {
return None;
}
- let entry = self.preload_entry_for_script(script)?;
- let load = entry.load.clone();
- let resource_type_hint = entry.request.resource_type_hint;
+ let (load, resource_type_hint) = self.entries.preload_for_script(script)?;
let probe_started = (wait_for_pending && moli_trace::defer_wait_probe_enabled())
.then(std::time::Instant::now);
if probe_started.is_some() {
@@ -877,7 +946,7 @@ fn admit_image_preloads(page_vm: &mut PageVm, requests: Vec<BufferedImagePreload
}
fn admit_script_preloads(
- page_vm: &PageVm,
+ page_vm: &mut PageVm,
state: &mut BufferedDocumentPreloadState,
requests: Vec<BufferedScriptPreloadRequest>,
loader: &ResourceRequestClient,
@@ -904,7 +973,21 @@ fn admit_script_preloads(
}
}
let admitted_count = admitted.len();
- state.start_preloads_for_requests(admitted, loader, service_worker_context);
+ let (native_modules, legacy_preloads): (Vec<_>, Vec<_>) = admitted
+ .into_iter()
+ .partition(|request| request.kind_hint == crate::types::ScriptKind::Module);
+ state.start_preloads_for_requests(legacy_preloads, loader, service_worker_context);
+ for request in native_modules {
+ let request_url = request.url.clone();
+ if let Err(error) = page_vm
+ .vm_mut()
+ .register_native_modulepreload_for_owner(request.into_native_module_preload())
+ {
+ page_vm.vm_mut().record_runtime_warning(format_args!(
+ "preload-scanned module script `{request_url}` failed before fetch scheduling: {error}"
+ ));
+ }
+ }
if let Some(started) = timing_started
&& discovered_count > 0
{
@@ -964,6 +1047,22 @@ impl BufferedScriptPreloadRequest {
}
}
+ fn into_native_module_preload(self) -> crate::module_runtime::NativeModuleSingleFetchRequest {
+ debug_assert_eq!(self.kind_hint, crate::types::ScriptKind::Module);
+ let module_key = crate::module_runtime::ModuleMapKey::java_script(self.url.clone());
+ let fetch_metadata =
+ crate::module_runtime::ModuleFetchMetadata::from_top_level_script_fetch_metadata(
+ &self.fetch_metadata,
+ );
+ crate::module_runtime::NativeModuleSingleFetchRequest::new(
+ self.url.clone(),
+ self.url,
+ self.initiator_url,
+ module_key,
+ fetch_metadata,
+ )
+ }
+
pub(crate) fn matches_script(&self, script: &PreparedScript) -> bool {
script.source_kind == crate::types::ScriptSourceKind::External
&& self.url == script.url
diff --git a/moli-renderer-v8/src/runtime/tests.rs b/moli-renderer-v8/src/runtime/tests.rs
index c671e7812..a5f6556ba 100644
--- a/moli-renderer-v8/src/runtime/tests.rs
+++ b/moli-renderer-v8/src/runtime/tests.rs
@@ -12,7 +12,6 @@ use super::{
};
use crate::local_executor::{is_on_script_execution_lane_for, scope_on_scaffold_js_local_executor};
use crate::network::ResourceRequestClient;
-use crate::parser::XmlParser;
use crate::{
RendererDocumentLifecycleEventKind, RendererDocumentLifecycleMilestone,
RendererPageCreationNavigationReplyPolicy, RendererPageCreationReplyBoundary,
@@ -34,6 +33,42 @@ async fn prepare_test_external_raw_document(
loader: &ResourceRequestClient,
url: url::Url,
raw_body: ExternalRawDocumentBodyStream,
+) -> PreparedRendererDocument {
+ prepare_test_external_raw_document_with_content_type(
+ runtime,
+ loader,
+ url,
+ "text/html",
+ raw_body,
+ )
+ .await
+}
+
+async fn prepare_test_external_raw_document_with_content_type(
+ runtime: &JsRuntime,
+ loader: &ResourceRequestClient,
+ url: url::Url,
+ content_type: &str,
+ raw_body: ExternalRawDocumentBodyStream,
+) -> PreparedRendererDocument {
+ prepare_test_external_raw_document_with_content_type_and_reply_boundary(
+ runtime,
+ loader,
+ url,
+ content_type,
+ raw_body,
+ RendererPageCreationReplyBoundary::LifecycleTarget,
+ )
+ .await
+}
+
+async fn prepare_test_external_raw_document_with_content_type_and_reply_boundary(
+ runtime: &JsRuntime,
+ loader: &ResourceRequestClient,
+ url: url::Url,
+ content_type: &str,
+ raw_body: ExternalRawDocumentBodyStream,
+ reply_boundary: RendererPageCreationReplyBoundary,
) -> PreparedRendererDocument {
runtime
.prepare_streaming_raw_document_from_external_body_with_inspector_session_restores(
@@ -44,7 +79,7 @@ async fn prepare_test_external_raw_document(
false,
0,
200,
- vec![("content-type".to_owned(), "text/html".to_owned())],
+ vec![("content-type".to_owned(), content_type.to_owned())],
loader,
crate::RendererWebStorageHandles::ephemeral(),
raw_body,
@@ -67,7 +102,7 @@ async fn prepare_test_external_raw_document(
Vec::new(),
false,
PageVmInitStage::Load,
- RendererPageCreationReplyBoundary::LifecycleTarget,
+ reply_boundary,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
None,
@@ -1227,75 +1262,147 @@ navigator.webkitTemporaryStorage.queryUsageAndQuota((usage, quota) => {
}
#[tokio::test(flavor = "multi_thread")]
-async fn create_document_page_executes_initial_xhtml_parser_handoff() {
+async fn streaming_xml_document_executes_parser_blocking_xhtml_script() {
let runtime = JsRuntime::initialize();
let loader =
ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
let url = url::Url::parse("https://example.test/initial.xhtml").unwrap();
- let (document, handoffs) = XmlParser.parse_with_document_handoffs(
- url.clone(),
- concat!(
- "<html xmlns='http://www.w3.org/1999/xhtml'><head>",
- "<script>globalThis.__initialXhtmlHandoff = 'executed';</script>",
- "</head><body /></html>",
- )
- .to_owned(),
- );
- let (document_handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- let (mut page, _, _, _, pending_download) = runtime
- .create_document_page_best_effort(
- url.clone(),
- None,
- false,
- 0,
- 200,
- vec![(
- "content-type".to_owned(),
- "application/xhtml+xml".to_owned(),
- )],
- &loader,
- crate::RendererWebStorageHandles::ephemeral(),
- document,
- document_handoffs,
- blocking_stylesheet_inputs,
- None,
- None,
- Vec::new(),
- Vec::new(),
- Vec::new(),
- Vec::new(),
- None,
- None,
- false,
- 1.0,
- Default::default(),
- None,
- false,
- Vec::new(),
- false,
- None,
- )
+ let source = concat!(
+ "<html xmlns='http://www.w3.org/1999/xhtml'><head>",
+ "<script>try { document.write('&lt;future/&gt;'); } ",
+ "catch (error) { globalThis.__xmlWriteError = error.name; } ",
+ "globalThis.__initialXhtmlHandoff = 'executed';</script>",
+ "</head><body /></html>",
+ );
+ let prepared = prepare_test_external_raw_document_with_content_type(
+ &runtime,
+ &loader,
+ url,
+ "application/xhtml+xml",
+ ExternalRawDocumentBodyStream::from_bytes(source.as_bytes().to_vec()),
+ )
+ .await;
+ let permit = prepared.issue_commit_permit();
+ let (mut page, page_state, _, _, pending_download) = prepared
+ .commit(permit)
.await
- .expect("XHTML document page should load from prepared parser handoffs");
+ .expect("incremental XHTML document should commit");
assert!(pending_download.is_none());
let (reply, _) = page
.run_async_command(RendererPageCommand::EvaluateExpression {
- expression: "String(globalThis.__initialXhtmlHandoff)".to_owned(),
+ expression: concat!(
+ "JSON.stringify([document.contentType, ",
+ "document.getElementsByTagName('script').length, ",
+ "String(globalThis.__initialXhtmlHandoff), ",
+ "String(globalThis.__xmlWriteError), ",
+ "document.getElementsByTagName('future').length])",
+ )
+ .to_owned(),
await_promise: false,
})
.await
.expect("initial XHTML script side effect should be observable");
assert_eq!(
renderer_json_value(reply),
- Some(serde_json::json!("executed"))
+ Some(serde_json::json!(
+ r#"["application/xhtml+xml",1,"executed","InvalidStateError",0]"#
+ )),
+ "XML script report: {:#?}",
+ page_state.script_execution.runs,
);
page.close_async().await.expect("XHTML page should close");
}
#[tokio::test(flavor = "multi_thread")]
-async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configuration() {
+async fn streaming_unstyled_xml_converts_live_document_before_domcontentloaded() {
+ let runtime = JsRuntime::initialize();
+ let loader =
+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
+ let url = url::Url::parse("https://example.test/document.xml").unwrap();
+ let source = "<semantic-root id='source'><child>xml-ready</child></semantic-root>";
+ let prepared = prepare_test_external_raw_document_with_content_type(
+ &runtime,
+ &loader,
+ url,
+ "application/xml",
+ ExternalRawDocumentBodyStream::from_bytes(source.as_bytes().to_vec()),
+ )
+ .await;
+ prepared
+ .update_commit_configuration(RendererPreparedDocumentCommitConfiguration {
+ document_start_scripts: vec![crate::DocumentStartScript {
+ registry_key: None,
+ source: concat!(
+ "globalThis.__xmlViewerDcl = null;",
+ "document.addEventListener('DOMContentLoaded', () => {",
+ " const source = document.getElementById('source');",
+ " globalThis.__xmlViewerDcl = [",
+ " document.documentElement.localName,",
+ " source && source.parentNode && source.parentNode.id,",
+ " source && source.textContent",
+ " ];",
+ "});",
+ )
+ .to_owned(),
+ world_name: None,
+ has_bidi_channel_argument: false,
+ bidi_channel_handoffs: Vec::new(),
+ }],
+ runtime_bindings: Vec::new(),
+ runtime_inspector_session_restore_snapshots: Vec::new(),
+ runtime_isolated_worlds: Vec::new(),
+ permission_overrides: Vec::new(),
+ extra_http_headers: Vec::new(),
+ locale_override: None,
+ timezone_override: None,
+ script_execution_disabled: false,
+ bypass_content_security_policy: false,
+ cpu_throttling_rate: 1.0,
+ emulated_media: Default::default(),
+ idle_override: None,
+ viewport_surface: None,
+ network_offline: false,
+ blocked_url_patterns: Vec::new(),
+ fetch_subresource_interception_enabled: false,
+ fetch_subresource_interception_resource_type: None,
+ })
+ .await
+ .expect("prepared XML should accept the lifecycle probe");
+
+ let permit = prepared.issue_commit_permit();
+ let (mut page, _, _, _, pending_download) = prepared
+ .commit(permit)
+ .await
+ .expect("unstyled XML document should commit");
+ assert!(pending_download.is_none());
+ let (reply, _) = page
+ .run_async_command(RendererPageCommand::EvaluateExpression {
+ expression: concat!(
+ "JSON.stringify([",
+ "document.documentElement.localName,",
+ "document.documentElement.namespaceURI,",
+ "globalThis.__xmlViewerDcl",
+ "])",
+ )
+ .to_owned(),
+ await_promise: false,
+ })
+ .await
+ .expect("live XML viewer state should evaluate");
+ assert_eq!(
+ renderer_json_value(reply),
+ Some(serde_json::json!(
+ r#"["html","http://www.w3.org/1999/xhtml",["html","webkit-xml-viewer-source-xml","xml-ready"]]"#
+ ))
+ );
+ page.close_async()
+ .await
+ .expect("unstyled XML page should close");
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn prepared_streaming_xml_document_waits_for_permit_and_uses_latest_configuration() {
let runtime = JsRuntime::initialize();
let baseline_isolates = runtime.document_isolate_accounting_for_diagnostics();
let loader =
@@ -1308,60 +1415,21 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
)
.await;
let url = url::Url::parse(&format!("{base_url}/prepared.xhtml")).expect("prepared XHTML url");
- let (document, handoffs) = XmlParser.parse_with_document_handoffs(
+ let source = concat!(
+ "<html xmlns='http://www.w3.org/1999/xhtml'><head><script>",
+ "globalThis.__nativeCommitObserved = JSON.stringify([",
+ "globalThis.__nativePreload, typeof nativeBinding]);",
+ "fetch('/native-author-side-effect');",
+ "</script></head><body /></html>",
+ );
+ let prepared = prepare_test_external_raw_document_with_content_type(
+ &runtime,
+ &loader,
url.clone(),
- concat!(
- "<html xmlns='http://www.w3.org/1999/xhtml'><head><script>",
- "globalThis.__nativeCommitObserved = JSON.stringify([",
- "globalThis.__nativePreload, typeof nativeBinding]);",
- "fetch('/native-author-side-effect');",
- "</script></head><body /></html>",
- )
- .to_owned(),
- );
- let (document_handoffs, blocking_stylesheet_inputs) = handoffs.into_parts();
-
- let prepared = runtime
- .prepare_document_page_with_inspector_session_restores(
- runtime.reserve_page_for_creation(),
- url.clone(),
- None,
- false,
- 0,
- 200,
- vec![(
- "content-type".to_owned(),
- "application/xhtml+xml".to_owned(),
- )],
- &loader,
- crate::RendererWebStorageHandles::ephemeral(),
- document,
- document_handoffs,
- blocking_stylesheet_inputs,
- None,
- None,
- Vec::new(),
- Vec::new(),
- Vec::new(),
- Vec::new(),
- None,
- None,
- false,
- false,
- 1.0,
- Default::default(),
- None,
- false,
- Vec::new(),
- false,
- None,
- false,
- PageVmInitStage::Load,
- None,
- None,
- )
- .await
- .expect("NativeDom document should prepare");
+ "application/xhtml+xml",
+ ExternalRawDocumentBodyStream::from_bytes(source.as_bytes().to_vec()),
+ )
+ .await;
let prepared_agent = prepared.renderer_devtools_agent_token();
let prepared_isolates = runtime.document_isolate_accounting_for_diagnostics();
assert_eq!(prepared_isolates.created, baseline_isolates.created + 1);
@@ -1370,7 +1438,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
assert_eq!(
runtime.renderer_owner_handle().len(),
0,
- "preparing a NativeDom must not install a Page"
+ "preparing a streaming XML document must not install a Page"
);
assert!(
tokio::time::timeout(Duration::from_millis(100), &mut side_effect_request_seen)
@@ -1430,7 +1498,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
fetch_subresource_interception_resource_type: None,
})
.await
- .expect("prepared NativeDom should accept live commit configuration");
+ .expect("prepared streaming XML should accept live commit configuration");
let permit = prepared.issue_commit_permit();
let (mut page, _, diagnostics, _, pending_download) =
@@ -1439,7 +1507,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
assert_eq!(
page.devtools_agent_token(),
prepared_agent,
- "NativeDom commit must attach the agent reserved during prepare"
+ "streaming XML commit must attach the agent reserved during prepare"
);
tokio::time::timeout(Duration::from_secs(2), &mut side_effect_request_seen)
.await
@@ -1465,7 +1533,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
.iter()
.find(|realm| realm.name == "native-world")
.map(|realm| realm.context_id)
- .expect("the NativeDom named world should exist at initial commit");
+ .expect("the streaming XML named world should exist at initial commit");
let (world_marker, _) = page
.run_async_command(RendererPageCommand::EvaluateExpressionInExecutionContext {
execution_context_id: world_context_id,
@@ -1473,7 +1541,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
await_promise: false,
})
.await
- .expect("NativeDom named-world preload marker should evaluate");
+ .expect("streaming XML named-world preload marker should evaluate");
assert_eq!(
renderer_json_value(world_marker),
Some(serde_json::json!("ready"))
@@ -1481,7 +1549,7 @@ async fn prepared_native_dom_document_waits_for_permit_and_uses_latest_configura
page.close_async()
.await
- .expect("committed NativeDom page should close");
+ .expect("committed streaming XML page should close");
server
.await
.expect("NativeDom author side-effect server should finish");
@@ -1988,6 +2056,159 @@ async fn external_raw_streaming_page_command_builds_phase_one_page() {
assert!(html.contains("data-streamed=\"yes\""));
}
+#[tokio::test(flavor = "multi_thread")]
+async fn external_raw_streaming_body_failure_preserves_committed_document_and_owner() {
+ let runtime = JsRuntime::initialize();
+ let (output_tx, mut output_rx) = renderer_external_activity_test_channel();
+ runtime.set_renderer_output_transport_sender(output_tx);
+ let loader =
+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
+ let url = url::Url::parse("https://example.test/failed-main-document")
+ .expect("failed main document url");
+ let (completion_tx, completion_rx) = oneshot::channel();
+ let (body_tx, raw_body) = ExternalRawDocumentBodyStream::channel(completion_rx);
+ body_tx
+ .send(
+ b"<!doctype html><main id='partial'>partial body before transport failure</main>"
+ .to_vec(),
+ )
+ .await
+ .expect("partial main document body should send");
+ let prepared = prepare_test_external_raw_document_with_content_type_and_reply_boundary(
+ &runtime,
+ &loader,
+ url,
+ "text/html",
+ raw_body,
+ RendererPageCreationReplyBoundary::DocumentCommit,
+ )
+ .await;
+ drop(body_tx);
+ completion_tx
+ .send(Err(anyhow::anyhow!(
+ "synthetic partial main document body failure"
+ )))
+ .expect("main document body failure should send");
+ let permit = prepared.issue_commit_permit();
+ let (mut page, _, _, creation_artifacts, pending_download) =
+ tokio::time::timeout(Duration::from_secs(5), prepared.commit(permit))
+ .await
+ .expect("partial main document should reach its response commit boundary")
+ .expect("partial main document should attach before its body terminal");
+ assert!(pending_download.is_none());
+ assert!(
+ creation_artifacts.lifecycle_snapshot.load.is_none(),
+ "open main document must attach before load"
+ );
+ page.take_committed_document_post_response_continuation()
+ .expect("DocumentCommit should retain parser work until its response boundary")
+ .release();
+
+ let failure_events = tokio::time::timeout(Duration::from_secs(5), async {
+ let mut events = Vec::new();
+ loop {
+ let publication = output_rx
+ .recv()
+ .await
+ .expect("renderer output transport should stay open");
+ if !publication_is_for_page(&publication, &page) {
+ continue;
+ }
+ let publication_events = publication_document_lifecycle_events(&publication)
+ .copied()
+ .collect::<Vec<_>>();
+ let main_resource_failed = publication_events.iter().any(|event| {
+ event.kind
+ == RendererDocumentLifecycleEventKind::Terminated {
+ last_reached: None,
+ reason: super::RendererDocumentTerminationReason::MainResourceLoadFailed,
+ }
+ });
+ events.extend(publication_events);
+ if main_resource_failed {
+ return events;
+ }
+ }
+ })
+ .await
+ .expect("main-resource failure should terminate the parser lifecycle");
+ assert!(failure_events.iter().all(|event| {
+ event.kind
+ != RendererDocumentLifecycleEventKind::Milestone(
+ RendererDocumentLifecycleMilestone::DomContentLoaded,
+ )
+ && event.kind
+ != RendererDocumentLifecycleEventKind::Milestone(
+ RendererDocumentLifecycleMilestone::Load,
+ )
+ }));
+ assert_eq!(
+ runtime.renderer_owner_handle().len(),
+ 1,
+ "a committed partial Document should remain resident like Blink's failed DocumentLoader"
+ );
+
+ let (reply, _) = page
+ .run_async_command(RendererPageCommand::EvaluateExpression {
+ expression: "document.querySelector('#partial').textContent".to_owned(),
+ await_promise: false,
+ })
+ .await
+ .expect("committed partial Document should remain script-observable");
+ assert_eq!(
+ renderer_json_value(reply),
+ Some(serde_json::json!("partial body before transport failure"))
+ );
+ let (reply, _) = tokio::time::timeout(
+ Duration::from_secs(2),
+ page.run_async_command(RendererPageCommand::EvaluateExpression {
+ expression: "new Promise(resolve => setTimeout(() => resolve(document.readyState), 0))"
+ .to_owned(),
+ await_promise: true,
+ }),
+ )
+ .await
+ .expect("a failed committed Document should keep running ordinary Page tasks")
+ .expect("a failed committed Document should resolve a newly scheduled timer");
+ assert_eq!(
+ renderer_json_value(reply),
+ Some(serde_json::json!("loading")),
+ "stopping a failed parser must not synthesize DCL or a successful EOF"
+ );
+ page.close_async()
+ .await
+ .expect("failed committed page should close normally");
+
+ let recovery_url =
+ url::Url::parse("https://example.test/recovery-after-body-failure").expect("recovery url");
+ let mut recovery_page = tokio::time::timeout(
+ Duration::from_secs(5),
+ create_test_html_page(
+ &runtime,
+ &loader,
+ recovery_url,
+ "<!doctype html><main id='recovered'>recovered</main>",
+ ),
+ )
+ .await
+ .expect("renderer owner should accept a page after the failed candidate");
+ let (reply, _) = recovery_page
+ .run_async_command(RendererPageCommand::EvaluateExpression {
+ expression: "document.querySelector('#recovered').textContent".to_owned(),
+ await_promise: false,
+ })
+ .await
+ .expect("recovery page should remain usable");
+ assert_eq!(
+ renderer_json_value(reply),
+ Some(serde_json::json!("recovered"))
+ );
+ recovery_page
+ .close_async()
+ .await
+ .expect("recovery page should close");
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn prepared_external_raw_document_waits_for_matching_commit_permit() {
let runtime = JsRuntime::initialize();
@@ -3055,6 +3276,9 @@ async fn renderer_owned_navigation_survives_page_creation_observer_detach() {
producer.await.expect("producer should finish");
assert!(pending_download.is_none());
assert!(creation_artifacts.lifecycle_snapshot.load.is_none());
+ page.take_committed_document_post_response_continuation()
+ .expect("DocumentCommit should defer parser continuation")
+ .release();
let initial_document = creation_artifacts.active_document;
let replacement_document = tokio::time::timeout(Duration::from_secs(2), async {
@@ -15512,6 +15736,9 @@ async fn document_commit_background_dcl_completion_resumes_owner_to_load() {
.close_async()
.await
.expect("predecessor page should close after replacement attach");
+ page.take_committed_document_post_response_continuation()
+ .expect("DocumentCommit should defer parser continuation")
+ .release();
let observed = tokio::time::timeout(
Duration::from_millis(500),
@@ -15543,6 +15770,81 @@ async fn document_commit_background_dcl_completion_resumes_owner_to_load() {
.expect("document-commit DCL-tail page should close");
}
+#[tokio::test(flavor = "multi_thread")]
+async fn document_title_observation_precedes_dcl_for_exact_document() {
+ let runtime = JsRuntime::initialize();
+ let (activity_wake_tx, mut activity_wake_rx) = renderer_external_activity_test_channel();
+ runtime.set_renderer_output_transport_sender(activity_wake_tx);
+ let loader =
+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
+ let page_url = url::Url::parse("https://example.test/title-before-dcl").expect("page url");
+ let mut page = create_test_html_page_at_document_commit(
+ &runtime,
+ &loader,
+ page_url,
+ "<!doctype html><title>committed title</title><main>ready</main>",
+ )
+ .await;
+
+ let (observed, title_identity, dcl_identity) =
+ tokio::time::timeout(Duration::from_secs(2), async {
+ let mut observed = Vec::new();
+ let mut title_identity = None;
+ loop {
+ let publication = activity_wake_rx
+ .recv()
+ .await
+ .expect("renderer output channel should stay open");
+ if !publication_is_for_page(&publication, &page) {
+ continue;
+ }
+ for record in publication.records() {
+ match record.item() {
+ RendererOutputItem::Observation(
+ RendererProtocolObservation::DocumentTitleChanged(change),
+ ) => {
+ assert_eq!(change.title, "committed title");
+ assert!(
+ title_identity.replace(change.source_document).is_none(),
+ "an unchanged title must not be published twice"
+ );
+ observed.push("title");
+ }
+ RendererOutputItem::Observation(
+ RendererProtocolObservation::DocumentLifecycle(event),
+ ) if event.kind
+ == RendererDocumentLifecycleEventKind::Milestone(
+ RendererDocumentLifecycleMilestone::DomContentLoaded,
+ ) =>
+ {
+ observed.push("dcl");
+ let identity = super::RendererDocumentLifecycleIdentity {
+ frame: event.frame,
+ document: event.document,
+ epoch: event.epoch,
+ };
+ return (observed, title_identity, identity);
+ }
+ _ => {}
+ }
+ }
+ }
+ })
+ .await
+ .expect("title and DCL observations should be published");
+
+ assert_eq!(observed, vec!["title", "dcl"]);
+ assert_eq!(
+ title_identity,
+ Some(dcl_identity),
+ "the title observation must be sourced from the exact DCL document"
+ );
+
+ page.close_async()
+ .await
+ .expect("title observation page should close");
+}
+
// This witness needs one renderer-owner worker and one observer worker.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn lifecycle_record_precedes_handler_navigation_action_record() {
@@ -15566,6 +15868,7 @@ document.addEventListener("DOMContentLoaded", () => {
page_url,
html,
RendererTopLevelNavigationDispatch::DelegateToBrowser,
+ RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
)
.await;
@@ -15618,6 +15921,51 @@ document.addEventListener("DOMContentLoaded", () => {
.expect("DCL handler navigation page should close");
}
+#[tokio::test(flavor = "multi_thread")]
+async fn document_commit_release_runs_parser_script_location_handoff_in_background() {
+ let runtime = JsRuntime::initialize();
+ let (activity_wake_tx, mut activity_wake_rx) = renderer_external_activity_test_channel();
+ runtime.set_renderer_output_transport_sender(activity_wake_tx);
+ let loader =
+ ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).expect("default loader");
+ let page_url =
+ url::Url::parse("https://example.test/parser-location-source").expect("page url");
+ let mut page = create_test_html_page_at_document_commit_with_navigation_dispatch(
+ &runtime,
+ &loader,
+ page_url,
+ r#"<!doctype html><script>location.href = "/final"</script>"#,
+ RendererTopLevelNavigationDispatch::DelegateToBrowser,
+ RendererPageCreationNavigationReplyPolicy::ReturnWithPendingNavigation,
+ )
+ .await;
+
+ tokio::time::timeout(Duration::from_secs(2), async {
+ while let Some(publication) = activity_wake_rx.recv().await {
+ if !publication_is_for_page(&publication, &page) {
+ continue;
+ }
+ if publication.records().iter().any(|record| {
+ matches!(
+ record.item(),
+ super::RendererOutputItem::OwnerAction(
+ super::RendererOwnerAction::TopLevelLocationNavigation(_)
+ )
+ )
+ }) {
+ return;
+ }
+ }
+ panic!("renderer output channel closed before parser location handoff");
+ })
+ .await
+ .expect("released parser continuation should publish its location handoff");
+
+ page.close_async()
+ .await
+ .expect("parser location handoff page should close");
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn owner_loop_completes_post_dcl_async_script_without_wait_command() {
let runtime = JsRuntime::initialize();
@@ -16651,6 +16999,7 @@ async fn create_test_html_page_at_document_commit(
url,
html,
RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,
+ RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
)
.await
}
@@ -16661,6 +17010,7 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
url: url::Url,
html: &str,
top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,
+ navigation_reply_policy: RendererPageCreationNavigationReplyPolicy,
) -> RendererPageHandle {
let (completion_tx, completion_rx) = oneshot::channel();
let (body_tx, raw_body) = ExternalRawDocumentBodyStream::channel(completion_rx);
@@ -16675,7 +17025,7 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
.send(Ok(()))
.expect("document-commit HTML body should complete");
});
- let (page, _, _, creation_artifacts, pending_download) = runtime
+ let (mut page, _, _, creation_artifacts, pending_download) = runtime
.create_streaming_raw_page_from_external_body_with_inspector_session_restores(
url.clone(),
url,
@@ -16708,7 +17058,7 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
PageVmInitStage::Load,
RendererPageCreationReplyBoundary::DocumentCommit,
top_level_navigation_dispatch,
- RendererPageCreationNavigationReplyPolicy::FollowBeforeReply,
+ navigation_reply_policy,
None,
None,
None,
@@ -16723,6 +17073,9 @@ async fn create_test_html_page_at_document_commit_with_navigation_dispatch(
creation_artifacts.lifecycle_snapshot.load.is_none(),
"document-commit fixture must return before load"
);
+ page.take_committed_document_post_response_continuation()
+ .expect("DocumentCommit should defer parser continuation")
+ .release();
page
}
diff --git a/moli-renderer-v8/src/runtime/tests/open_streaming.rs b/moli-renderer-v8/src/runtime/tests/open_streaming.rs
index fb86467dd..2f34291ce 100644
--- a/moli-renderer-v8/src/runtime/tests/open_streaming.rs
+++ b/moli-renderer-v8/src/runtime/tests/open_streaming.rs
@@ -175,7 +175,7 @@ impl OpenStreamingPage {
.await
.expect("first open-stream body chunk should send");
- let (page, _, _, creation_artifacts, pending_download) = tokio::time::timeout(
+ let (mut page, _, _, creation_artifacts, pending_download) = tokio::time::timeout(
Duration::from_secs(2),
runtime.create_streaming_raw_page_from_external_body_with_inspector_session_restores(
page_url.clone(),
@@ -220,6 +220,9 @@ impl OpenStreamingPage {
.expect("open main-Document stream should create a Page");
assert!(pending_download.is_none());
assert!(creation_artifacts.lifecycle_snapshot.load.is_none());
+ page.take_committed_document_post_response_continuation()
+ .expect("DocumentCommit should defer parser continuation")
+ .release();
Self {
page,
diff --git a/moli-renderer-v8/src/script_vm.rs b/moli-renderer-v8/src/script_vm.rs
index e1b3132e8..cb5303985 100644
--- a/moli-renderer-v8/src/script_vm.rs
+++ b/moli-renderer-v8/src/script_vm.rs
@@ -6485,6 +6485,10 @@ impl ScriptVm {
environment.output_journal().append_records(records);
}
+ pub(super) fn has_renderer_output_journal(&self) -> bool {
+ self.renderer_page_script_environment.is_some()
+ }
+
#[cfg(test)]
pub(crate) fn bind_renderer_output_journal_for_test(
&mut self,
@@ -7838,22 +7842,18 @@ impl ScriptVm {
execution_context.parser_insertion_controller(),
) {
(Some(_), true, Some(controller)) => Some(controller.clone()),
- (Some(_), true, None) => {
- return ParserOwnedClassicScriptExecutionReport::new(
- Err(ParserOwnedClassicScriptExecutionError::new(
- "parser-connected classic execution has no insertion controller",
- )),
- None,
- ParserOwnedClassicScriptEvaluationSettlement::NotSettled,
- PreparedScriptBodyActivity::NotEntered,
- );
- }
_ => None,
};
+ // XML parser-blocking scripts have a currentScript and use the same
+ // execution/lifecycle coordinator, but XML has no HTML insertion point.
+ // Absence of a controller therefore means document.write is inactive;
+ // it must not suppress otherwise valid XHTML/SVG script execution.
+ let parser_write_insertion_point_active =
+ run_input.parser_write_insertion_point_active && parser_insertion_controller.is_some();
self.document_runtime
.set_current_script_context(CurrentScriptContextSpec {
handle: run_input.current_script,
- parser_write_insertion_point_active: run_input.parser_write_insertion_point_active,
+ parser_write_insertion_point_active,
parser_insertion_controller,
});
let runtime_reset_generation_before_run = self.document_runtime.runtime_reset_generation();
diff --git a/moli-renderer-v8/src/script_vm/child_classic_document_script/action_owner.rs b/moli-renderer-v8/src/script_vm/child_classic_document_script/action_owner.rs
index e9e6473d1..4c548f2ff 100644
--- a/moli-renderer-v8/src/script_vm/child_classic_document_script/action_owner.rs
+++ b/moli-renderer-v8/src/script_vm/child_classic_document_script/action_owner.rs
@@ -24,19 +24,28 @@ impl<'vm> ChildClassicExecutionActionOwner<'vm> {
> {
let mut followup = FrameDocumentClassicExecutionFollowup::default();
let (job, finish) = action.into_parts();
- let _parser_script_nesting = matches!(
+ let parser_blocking = matches!(
finish.scheduling,
FrameDocumentClassicScriptScheduling::ParserBlocking
- )
- .then(|| {
- ChildDocumentScriptOwnerHooks::new(self.vm)
- .enter_parser_script_nesting(finish.child_handle, finish.task_owner)
- })
- .flatten();
+ );
+ let parser_ready = !parser_blocking
+ || ChildDocumentScriptOwnerHooks::new(self.vm).resume_parser_for_classic_execution(
+ finish.child_handle,
+ finish.task_owner,
+ finish.script_handle,
+ );
+ let _parser_script_nesting = (parser_blocking && parser_ready)
+ .then(|| {
+ ChildDocumentScriptOwnerHooks::new(self.vm)
+ .enter_parser_script_nesting(finish.child_handle, finish.task_owner)
+ })
+ .flatten();
followup.note_script_job_attempted();
- if let Err(error) = ChildDocumentScriptOwnerHooks::new(self.vm)
- .execute_frame_script_job_selected_task_body(job)
- {
+ let execution = parser_ready.then(|| {
+ ChildDocumentScriptOwnerHooks::new(self.vm)
+ .execute_frame_script_job_selected_task_body(job)
+ });
+ if let Some(Err(error)) = execution {
tracing::warn!(
error = %error,
child_handle = ?finish.child_handle,
@@ -46,6 +55,13 @@ impl<'vm> ChildClassicExecutionActionOwner<'vm> {
"child classic script execution failed"
);
followup.note_script_job_failed();
+ } else if !parser_ready {
+ tracing::debug!(
+ child_handle = ?finish.child_handle,
+ script_handle = ?finish.script_handle,
+ "dropping child parser-blocking classic execution with a stale parser resume permit"
+ );
+ followup.note_script_job_failed();
}
let completion = ChildDocumentScriptOwnerHooks::new(self.vm)
.finish_child_classic_script_execution(finish);
diff --git a/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs b/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
index 2e1f12985..f93a0f54c 100644
--- a/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
+++ b/moli-renderer-v8/src/script_vm/child_document_script_owner_hooks.rs
@@ -76,6 +76,22 @@ impl<'vm> ChildDocumentScriptOwnerHooks<'vm> {
})
}
+ pub(in crate::script_vm) fn resume_parser_for_classic_execution(
+ &mut self,
+ child_handle: DomHandle,
+ owner: FrameDocumentTaskOwner,
+ script_handle: DomHandle,
+ ) -> bool {
+ self.vm
+ ._context_host
+ .borrow_mut()
+ .resume_live_child_document_parser_for_classic_execution(
+ child_handle,
+ owner,
+ script_handle,
+ )
+ }
+
pub(in crate::script_vm) fn select_current_realm(
&mut self,
child_handle: DomHandle,
diff --git a/moli-renderer-v8/src/script_vm/eval_exec.rs b/moli-renderer-v8/src/script_vm/eval_exec.rs
index 0e37db069..a4c44828e 100644
--- a/moli-renderer-v8/src/script_vm/eval_exec.rs
+++ b/moli-renderer-v8/src/script_vm/eval_exec.rs
@@ -1,5 +1,4 @@
use std::pin::pin;
-use std::time::Duration;
use anyhow::{Result, anyhow};
use tracing::debug;
@@ -22,17 +21,10 @@ use crate::util::{
script_base_url_continuation_data, v8_string,
};
use crate::v8_execution_watchdog::{
- V8ExecutionWatchdog, V8ExecutionWatchdogKind, V8ExecutionWatchdogOutcome,
+ SCRIPT_TURN_WATCHDOG_TIMEOUT, V8ExecutionWatchdog, V8ExecutionWatchdogKind,
+ V8ExecutionWatchdogOutcome,
};
-#[cfg(not(test))]
-const SCRIPT_TURN_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(8);
-#[cfg(test)]
-// Keep runaway-script tests substantially faster than production without
-// terminating finite debug-build checkpoints merely because workspace
-// nextest is concurrently running other V8-heavy processes.
-const SCRIPT_TURN_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(2);
-
/// Source-neutral result of one bounded runtime-script owner flush.
///
/// `WaitingForSource` means the exact runtime owner still retains work but no
diff --git a/moli-renderer-v8/src/script_vm/parser_owned_classic.rs b/moli-renderer-v8/src/script_vm/parser_owned_classic.rs
index aaa1082ea..de6c046f0 100644
--- a/moli-renderer-v8/src/script_vm/parser_owned_classic.rs
+++ b/moli-renderer-v8/src/script_vm/parser_owned_classic.rs
@@ -79,7 +79,7 @@ impl ParserOwnedClassicScriptExecutionReport {
#[derive(Clone, Debug)]
pub(crate) enum ParserOwnedClassicScriptExecutionContext {
ParserBlocking {
- insertion_controller: ParserInsertionController,
+ insertion_controller: Option<ParserInsertionController>,
},
Deferred,
}
@@ -93,7 +93,7 @@ impl ParserOwnedClassicScriptExecutionContext {
match self {
Self::ParserBlocking {
insertion_controller,
- } => Some(insertion_controller),
+ } => insertion_controller.as_ref(),
Self::Deferred => None,
}
}
@@ -119,7 +119,7 @@ impl ParserOwnedClassicScriptCompletion {
}
pub(crate) fn parser_blocking_source_failure(
- parser_insertion_controller: ParserInsertionController,
+ parser_insertion_controller: Option<ParserInsertionController>,
script_element_event: Option<ScriptEventTask>,
) -> Self {
Self {
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index ffc1e9117..b2c6e94d8 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2573,6 +2573,44 @@ fn window_fetch_retirement_covers_every_host_stage() {
);
}
+#[test]
+fn window_fetch_request_start_records_keepalive_disposition() {
+ let mut vm = new_storage_test_vm("https://fetch-keepalive-output.test/");
+ vm.with_default_context_scope_and_checkpoint_for_test(|scope, host_ptr| {
+ let host = unsafe { &mut *host_ptr };
+ let _ordinary = register_pending_window_fetch_for_test(
+ scope,
+ host,
+ false,
+ PendingWindowFetchTestStage::Pending,
+ );
+ let _keepalive = register_pending_window_fetch_for_test(
+ scope,
+ host,
+ true,
+ PendingWindowFetchTestStage::Pending,
+ );
+ Ok(())
+ })
+ .expect("ordinary and keepalive Fetches should register");
+
+ let starts = vm
+ .take_network_output()
+ .into_items()
+ .filter_map(|item| match item {
+ crate::types::ScriptNetworkOutputItem::SubresourceRequestStarted(request) => {
+ Some(request.keepalive())
+ }
+ _ => None,
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ starts,
+ vec![false, true],
+ "renderer network start facts must preserve the resource teardown disposition"
+ );
+}
+
#[test]
fn cancel_pending_window_fetch_auth_preserves_401_for_response_stage() {
let mut vm = new_storage_test_vm("https://fetch-auth-cancel.test/");
@@ -6835,7 +6873,7 @@ async fn child_external_classic_script_load_executes_as_frame_script_job() {
assert_eq!(
vm.eval("__childExternalClassicJobEvents.join('|')")
.expect("child external classic events before HostLoad should evaluate"),
- "external:true|external-current:external-classic|script-load",
+ "external:true|external-current:external-classic|external-write:true|script-load",
"the parser-blocking load event must ignore document.open() and finish without firing iframe load"
);
run_page_realm_prerequisite_then_expected_child_frame_semantic_turn(
@@ -6848,7 +6886,7 @@ async fn child_external_classic_script_load_executes_as_frame_script_job() {
assert_eq!(
vm.eval("__childExternalClassicJobEvents.join('|')")
.expect("child external classic parser-continuation events should evaluate"),
- "external:true|external-current:external-classic|script-load|inline-current:after-external-classic|inline:73",
+ "external:true|external-current:external-classic|external-write:true|script-load|inline-current:after-external-classic|inline:73",
"ignored document.open() must leave the parser owner alive for the following inline script"
);
for transition in ["interactive", "DOMContentLoaded", "complete"] {
@@ -6881,7 +6919,7 @@ async fn child_external_classic_script_load_executes_as_frame_script_job() {
assert_eq!(
vm.eval("__childExternalClassicJobEvents.join('|')")
.expect("child external classic events should evaluate"),
- "external:true|external-current:external-classic|script-load|inline-current:after-external-classic|inline:73|load"
+ "external:true|external-current:external-classic|external-write:true|script-load|inline-current:after-external-classic|inline:73|load"
);
assert_eq!(
vm.eval("String(__childExternalClassicJobFrame.contentDocument.currentScript)")
@@ -6964,7 +7002,7 @@ async fn child_external_classic_script_load_executes_as_frame_script_job() {
assert_eq!(
vm.eval("__childExternalClassicJobEvents.join('|')")
.expect("child external classic events should still evaluate"),
- "external:true|external-current:external-classic|script-load|inline-current:after-external-classic|inline:73|load",
+ "external:true|external-current:external-classic|external-write:true|script-load|inline-current:after-external-classic|inline:73|load",
"stale owner-token event must not fire the script load listener again"
);
assert_eq!(
@@ -8920,6 +8958,10 @@ async fn spawn_child_external_classic_frame_script_job_server() -> (
let _ = path_tx.send(request_path);
let body = r#"parent.__childExternalClassicJobEvents.push("external:" + (globalThis === self));
parent.__childExternalClassicJobEvents.push("external-current:" + document.currentScript.id);
+document.write("<span id='external-write'>written</span>");
+parent.__childExternalClassicJobEvents.push(
+ "external-write:" + (document.getElementById("external-write") !== null)
+);
document.currentScript.addEventListener("load", () => {
parent.__childExternalClassicJobEvents.push("script-load");
document.open();
diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
index 50c01b34f..aed67f44f 100644
--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs
+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs
@@ -2504,10 +2504,9 @@ mod tests {
crate::dom::native::NativeDom,
Vec<crate::DocumentOwnedBlockingStylesheetDiscoveryInput>,
) {
- let (document, handoffs) =
- HtmlParser.parse_dom_host_with_document_handoffs(final_url, html.into());
- let (_, inputs) = handoffs.into_parts();
- (document.into_dom(), inputs)
+ let (document, _, inputs) =
+ crate::parse_html_test_fixture_with_parser_outputs(final_url, html.into());
+ (document, inputs)
}
#[test]
diff --git a/moli-renderer-v8/src/v8_execution_watchdog.rs b/moli-renderer-v8/src/v8_execution_watchdog.rs
index 4e3dfe3da..3e639ed52 100644
--- a/moli-renderer-v8/src/v8_execution_watchdog.rs
+++ b/moli-renderer-v8/src/v8_execution_watchdog.rs
@@ -17,6 +17,14 @@ use std::time::{Duration, Instant};
use parking_lot::{Condvar, Mutex};
+#[cfg(not(test))]
+pub(crate) const SCRIPT_TURN_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(8);
+#[cfg(test)]
+// Keep runaway-script tests substantially faster than production without
+// terminating finite debug-build checkpoints merely because workspace
+// nextest is concurrently running other V8-heavy processes.
+pub(crate) const SCRIPT_TURN_WATCHDOG_TIMEOUT: Duration = Duration::from_secs(2);
+
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum V8ExecutionWatchdogKind {
ScriptTurn,
diff --git a/moli-test-support/src/lib.rs b/moli-test-support/src/lib.rs
index a95c74535..7648ef119 100644
--- a/moli-test-support/src/lib.rs
+++ b/moli-test-support/src/lib.rs
@@ -712,6 +712,8 @@ const DOCUMENT_WRITE_NESTED_WRITER_RESTORES_OUTER_INSERTION_POINT_HTML: &str = i
);
const DOCUMENT_WRITE_NESTED_EXTERNAL_SCRIPT_SERIALIZES_OUTER_RESUME_HTML: &str = r#"<!doctype html><html><head><script>window.documentWriteNestedExternalOrder=[];document.write('<script src="/assets/document_write_nested_external_parent.js"><\/script><script src="/assets/document_write_nested_external_outer_after.js"><\/script><script>window.documentWriteNestedExternalOrder.push("outer-inline");window.documentWriteNestedExternalResult=window.documentWriteNestedExternalOrder.join(",");<\/script>');</script></head><body><main id="after">after</main></body></html>"#;
const DOCUMENT_WRITE_EXTERNAL_SPLIT_SCRIPT_PARSER_SESSION_HTML: &str = r#"<!doctype html><html><head><script>window.documentWriteExternalSplitSessionOrder=[];</script><script src="/assets/document_write_external_split_session_parent.js"></script><script>window.documentWriteExternalSplitSessionOrder.push("after-parent");window.documentWriteExternalSplitSessionResult=window.documentWriteExternalSplitSessionOrder.join(",");</script></head><body><main id="tail">tail</main></body></html>"#;
+const DOCUMENT_WRITE_INSERTED_EXTERNAL_CHUNKED_HEAD: &str = r#"<!doctype html><html><head><script>window.documentWriteInsertedChunkedOrder=["before-write"];document.write('<script src="/assets/document_write_inserted_chunked_external.js"><\/script>');window.documentWriteInsertedChunkedOrder.push("after-write");</script></head><body>"#;
+const DOCUMENT_WRITE_INSERTED_EXTERNAL_CHUNKED_TAIL: &str = r#"<main id="document-write-inserted-chunked-tail">tail</main><script>window.documentWriteInsertedChunkedOrder.push("tail-script");window.documentWriteInsertedChunkedResult=window.documentWriteInsertedChunkedOrder.join(",");</script></body></html>"#;
const DOCUMENT_WRITE_PARSER_VISIBLE_DOM_BOUNDARY_HTML: &str = include_str!(
"../../moli-core/tests/fixtures/runtime/document_write_parser_visible_dom_boundary.html"
);
@@ -1356,6 +1358,8 @@ const DOCUMENT_WRITE_NESTED_EXTERNAL_CHILD_JS: &str =
const DOCUMENT_WRITE_NESTED_EXTERNAL_OUTER_AFTER_JS: &str =
r#"window.documentWriteNestedExternalOrder.push("outer-after");"#;
const DOCUMENT_WRITE_EXTERNAL_SPLIT_SESSION_PARENT_JS: &str = r#"window.documentWriteExternalSplitSessionOrder.push("parent");document.write('<script>window.documentWriteExternalSplitSessionOrder.push("written-inline");window.documentWriteExternalSplitSessionSawTail=!!document.getElementById("tail")');document.write(';window.documentWriteExternalSplitSessionOrder.push(window.documentWriteExternalSplitSessionSawTail?"tail-visible":"tail-hidden")<\/script>');window.documentWriteExternalSplitSessionOrder.push("parent-after-write");"#;
+const DOCUMENT_WRITE_INSERTED_CHUNKED_EXTERNAL_JS: &str =
+ r#"window.documentWriteInsertedChunkedOrder.push("inserted-external");"#;
const BLOCKING_STYLESHEET_PARSER_BLOCKING_JS: &str = "window.blockingStylesheetParserElapsed = Date.now() - window.blockingStylesheetStart; window.blockingStylesheetParserBlockedEnough = window.blockingStylesheetParserElapsed >= 50; window.blockingStylesheetParserSawLate = !!document.getElementById('late'); window.blockingStylesheetParserSawDcl = window.blockingStylesheetDclSeen === true; window.blockingStylesheetOrder.push('parser');";
const BLOCKING_STYLESHEET_PARSER_BLOCKING_DOCUMENT_WRITE_JS: &str = "window.blockingStylesheetParserWriteRan = true; window.blockingStylesheetParserWriteElapsed = Date.now() - window.blockingStylesheetStart; window.blockingStylesheetParserWriteBlockedEnough = window.blockingStylesheetParserWriteElapsed >= 50; window.blockingStylesheetParserWriteSawLate = !!document.getElementById('late'); document.write('<span id=\"written-before-late\">written</span>'); window.blockingStylesheetParserWriteSawWrittenDuringScript = !!document.getElementById('written-before-late'); window.blockingStylesheetOrder.push('parser-write');";
const BLOCKING_STYLESHEET_DEFER_JS: &str = "window.blockingStylesheetDeferElapsed = Date.now() - window.blockingStylesheetStart; window.blockingStylesheetDeferBlockedEnough = window.blockingStylesheetDeferElapsed >= 50; window.blockingStylesheetDeferSawLate = !!document.getElementById('late'); window.blockingStylesheetDeferSawDcl = window.blockingStylesheetDeferOrder.includes('dcl'); window.blockingStylesheetDeferOrder.push('defer');";
diff --git a/moli-test-support/src/routes_core.rs b/moli-test-support/src/routes_core.rs
index 70c3eac29..0b70b60be 100644
--- a/moli-test-support/src/routes_core.rs
+++ b/moli-test-support/src/routes_core.rs
@@ -2149,6 +2149,34 @@ pub(super) async fn document_write_external_split_script_parser_session_page() -
Html(DOCUMENT_WRITE_EXTERNAL_SPLIT_SCRIPT_PARSER_SESSION_HTML)
}
+pub(super) async fn document_write_inserted_external_resumes_chunked_root_page() -> Response {
+ let (tx, rx) = tokio::sync::mpsc::channel(2);
+ tokio::spawn(async move {
+ if tx
+ .send(Ok::<Bytes, std::convert::Infallible>(Bytes::from_static(
+ DOCUMENT_WRITE_INSERTED_EXTERNAL_CHUNKED_HEAD.as_bytes(),
+ )))
+ .await
+ .is_err()
+ {
+ return;
+ }
+ sleep(Duration::from_millis(5)).await;
+ let _ = tx
+ .send(Ok::<Bytes, std::convert::Infallible>(Bytes::from_static(
+ DOCUMENT_WRITE_INSERTED_EXTERNAL_CHUNKED_TAIL.as_bytes(),
+ )))
+ .await;
+ });
+
+ Response::builder()
+ .header(CONTENT_TYPE, "text/html; charset=utf-8")
+ .body(Body::from_stream(
+ tokio_stream::wrappers::ReceiverStream::new(rx),
+ ))
+ .expect("chunked document.write external-script response should build")
+}
+
pub(super) async fn document_write_parser_visible_dom_boundary_page() -> Html<&'static str> {
Html(DOCUMENT_WRITE_PARSER_VISIBLE_DOM_BOUNDARY_HTML)
}
@@ -4466,6 +4494,11 @@ pub(super) async fn asset_document_write_external_split_session_parent_script()
javascript_response(DOCUMENT_WRITE_EXTERNAL_SPLIT_SESSION_PARENT_JS)
}
+pub(super) async fn asset_document_write_inserted_chunked_external_script() -> Response {
+ sleep(Duration::from_millis(50)).await;
+ javascript_response(DOCUMENT_WRITE_INSERTED_CHUNKED_EXTERNAL_JS)
+}
+
pub(super) async fn asset_dynamic_preparation_context_stale_script() -> Response {
sleep(Duration::from_millis(40)).await;
javascript_response(DYNAMIC_PREPARATION_CONTEXT_STALE_JS)
diff --git a/moli-test-support/src/server_routes.rs b/moli-test-support/src/server_routes.rs
index 43fa0a20f..abd4bf973 100644
--- a/moli-test-support/src/server_routes.rs
+++ b/moli-test-support/src/server_routes.rs
@@ -1212,6 +1212,10 @@ pub(super) fn build_router() -> Router {
"/compat/document-write-external-split-script-parser-session",
get(document_write_external_split_script_parser_session_page),
)
+ .route(
+ "/compat/document-write-inserted-external-resumes-chunked-root",
+ get(document_write_inserted_external_resumes_chunked_root_page),
+ )
.route(
"/compat/document-write-parser-visible-dom-boundary",
get(document_write_parser_visible_dom_boundary_page),
@@ -2265,6 +2269,10 @@ pub(super) fn build_router() -> Router {
"/assets/document_write_external_split_session_parent.js",
get(asset_document_write_external_split_session_parent_script),
)
+ .route(
+ "/assets/document_write_inserted_chunked_external.js",
+ get(asset_document_write_inserted_chunked_external_script),
+ )
.route(
"/assets/dynamic_preparation_context_stale.js",
get(asset_dynamic_preparation_context_stale_script),
diff --git a/moli/src/cdp_scheduler.rs b/moli/src/cdp_scheduler.rs
index ed2e1a480..a9cad0b6d 100644
--- a/moli/src/cdp_scheduler.rs
+++ b/moli/src/cdp_scheduler.rs
@@ -1,5 +1,5 @@
use std::{
- collections::{HashMap, HashSet, VecDeque},
+ collections::{HashMap, VecDeque},
sync::{Arc, atomic::AtomicU64},
time::{Duration, Instant},
};
@@ -10,11 +10,11 @@ use moli_core::{
runtime::NavigationRuntimeConfig,
};
use moli_protocol::{
- BackgroundNavigationCompletion, BackgroundNavigationGateKey, BackgroundProtocolEvent,
- CdpCommandTaskStep, CdpConnection, CdpInitialStoragePartition, CdpRendererCommandAccess,
- CdpSchedulerEvent, CdpTargetHostLifecycleObserver, CommandDispatchContext,
- CompletedCdpCommandDispatch, CompletedDeferredMainDocumentLoadCompletion,
- DeferredMainDocumentLoadCompletionOutputAction,
+ BackgroundNavigationCancellation, BackgroundNavigationCompletion, BackgroundNavigationGateKey,
+ BackgroundProtocolEvent, CdpCommandTaskStep, CdpConnection, CdpInitialStoragePartition,
+ CdpRendererCommandAccess, CdpSchedulerEvent, CdpTargetHostLifecycleObserver,
+ CommandDispatchContext, CompletedCdpCommandDispatch,
+ CompletedDeferredMainDocumentLoadCompletion, DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadObservationId,
DeferredMainDocumentLoadPredecessorCandidate, PageScreencastCaptureCompletion,
PageScreencastCaptureStart, PageScreencastRegistration, PageScreencastSubscriptionStatus,
@@ -137,7 +137,7 @@ struct BackgroundNavigationGate {
/// `BackgroundNavigationCompletion` has not yet been drained. The command
/// response may be produced independently; this gate does not claim where
/// that response falls relative to response-head or body EOF.
- pending: HashSet<BackgroundNavigationGateKey>,
+ pending: HashMap<BackgroundNavigationGateKey, BackgroundNavigationCancellation>,
}
impl BackgroundNavigationGate {
@@ -145,12 +145,35 @@ impl BackgroundNavigationGate {
!self.pending.is_empty()
}
- fn note_navigation_started(&mut self, key: BackgroundNavigationGateKey) {
- self.pending.insert(key);
+ fn note_navigation_started(
+ &mut self,
+ key: BackgroundNavigationGateKey,
+ cancellation: BackgroundNavigationCancellation,
+ ) {
+ if self.pending.contains_key(&key) {
+ return;
+ }
+ let pending_before = self.pending.len();
+ self.pending.retain(|pending, pending_cancellation| {
+ if !key.supersedes(pending) {
+ return true;
+ }
+ pending_cancellation.cancel();
+ false
+ });
+ let superseded = pending_before - self.pending.len();
+ if superseded > 0 {
+ tracing::debug!(
+ superseded,
+ ?key,
+ "retired superseded background navigation gate"
+ );
+ }
+ self.pending.insert(key, cancellation);
}
fn note_navigation_completion_drained(&mut self, key: &BackgroundNavigationGateKey) {
- if !self.pending.remove(key) {
+ if self.pending.remove(key).is_none() {
tracing::debug!(
?key,
"background navigation completion did not match any pending gate"
@@ -1862,6 +1885,16 @@ impl CdpScheduler {
ProtocolOutputSequence::from_background_events(events)
}
+ fn append_navigation_gate_release_before_renderer_boundary(
+ &mut self,
+ prefix: &mut ProtocolOutputSequence,
+ ) {
+ if self.has_inflight_background_navigation() {
+ return;
+ }
+ prefix.append(self.drain_pending_navigation_background_events());
+ }
+
fn apply_scheduler_events(&mut self, events: Vec<CdpSchedulerEvent>) {
self.apply_scheduler_events_with_load_predecessors(events, &[], None);
}
@@ -1882,8 +1915,9 @@ impl CdpScheduler {
);
}
match event {
- CdpSchedulerEvent::BackgroundNavigationStarted { key } => {
- self.background_navigation_gate.note_navigation_started(key);
+ CdpSchedulerEvent::BackgroundNavigationStarted { key, cancellation } => {
+ self.background_navigation_gate
+ .note_navigation_started(key, cancellation);
}
CdpSchedulerEvent::ProtocolWorkPublished { work } => {
if moli_trace::cdp_nav_timing_enabled() {
@@ -2449,9 +2483,12 @@ impl CdpScheduler {
"navigation completion must use its exact insertion boundary, not a command predecessor"
);
prefix.append(completion_prefix);
- if !self.has_inflight_background_navigation() {
- suffix.append(self.drain_pending_navigation_background_events());
- }
+ // The completion can still carry a renderer insertion boundary. While
+ // that boundary is projected, later publications may contain the
+ // response or terminal for a request whose start is parked behind the
+ // navigation gate. Release the parked FIFO into the pre-boundary
+ // prefix so those later publications cannot overtake it.
+ self.append_navigation_gate_release_before_renderer_boundary(&mut prefix);
suffix.append(self.drain_background_events_around_inflight_navigation(background_event_rx));
(prefix, suffix, renderer_output_boundary)
}
diff --git a/moli/src/cdp_scheduler/tests.rs b/moli/src/cdp_scheduler/tests.rs
index 91afc4cca..139171daf 100644
--- a/moli/src/cdp_scheduler/tests.rs
+++ b/moli/src/cdp_scheduler/tests.rs
@@ -11,15 +11,15 @@ use moli_core::{
},
};
use moli_protocol::{
- BackgroundNavigationGateKey, BackgroundProtocolEvent, CdpConnection, CdpSchedulerEvent,
- DeferredMainDocumentLoadCompletionOutputAction,
+ BackgroundNavigationCancellation, BackgroundNavigationGateKey, BackgroundProtocolEvent,
+ CdpConnection, CdpSchedulerEvent, DeferredMainDocumentLoadCompletionOutputAction,
DeferredMainDocumentLoadCompletionOutputInterest, DeferredMainDocumentLoadPredecessorCandidate,
ProtocolSchedulerWork,
conn::RuntimeInspectorResponseReady,
devtools_runtime::{
AutomationEvent, BrowserDownloadWillBeginEvent, DevToolsFrameId, DevToolsLoaderId,
- DevToolsNavigationWait, DevToolsRequestId, DevToolsTargetId, NavigationFrameEvent,
- NavigationFrameEventKind, NetworkRequestEvent,
+ DevToolsNavigationWait, DevToolsNetworkResourceType, DevToolsRequestId, DevToolsTargetId,
+ NavigationFrameEvent, NavigationFrameEventKind, NetworkRequestEvent,
},
test_support::{
background_navigation_gate_key as make_background_navigation_gate_key,
@@ -30,8 +30,8 @@ use moli_protocol::{
use serde_json::json;
use super::{
- CdpScheduler, ForegroundNavigationNetworkBarrier, ProtocolOutputSequence,
- ProtocolSchedulerResidence, ProtocolSchedulerStep, SchedulerQueues,
+ BackgroundNavigationGate, CdpScheduler, ForegroundNavigationNetworkBarrier,
+ ProtocolOutputSequence, ProtocolSchedulerResidence, ProtocolSchedulerStep, SchedulerQueues,
devtools_navigation_lifecycle_milestone, drain_pending_background_events,
next_page_screencast_deadline, page_screencast_interval,
};
@@ -120,7 +120,7 @@ fn protocol_output_sequence_preserves_background_event_sidecar() {
#[test]
fn load_ordering_splits_network_observations_from_page_side_effects() {
- let network = network_response_event("EventSource", "REQ-sse");
+ let network = network_response_event(DevToolsNetworkResourceType::EventSource, "REQ-sse");
let page_effect = download_will_begin_event("FRAME-nav", "download-after-load");
let output =
ProtocolOutputSequence::from_background_events(vec![network.clone(), page_effect.clone()]);
@@ -262,12 +262,15 @@ fn protocol_output_loose_response_split_ignores_typed_runtime_response() {
assert_eq!(response.command_id(), 42);
}
-fn network_response_event(resource_type: &str, request_id: &str) -> BackgroundProtocolEvent {
+fn network_response_event(
+ resource_type: DevToolsNetworkResourceType,
+ request_id: &str,
+) -> BackgroundProtocolEvent {
let message = json!({
"method": "Network.responseReceived",
"params": {
"requestId": request_id,
- "type": resource_type,
+ "type": resource_type.as_cdp_type(),
"response": {
"url": "https://example.test/resource",
"status": 200,
@@ -290,7 +293,7 @@ fn network_response_event(resource_type: &str, request_id: &str) -> BackgroundPr
redirect_response: None,
redirect_has_extra_info: false,
request_cookie_report: None,
- resource_type: Some(resource_type.to_owned()),
+ resource_type: Some(resource_type),
timestamp: Some(1.0),
wall_time: None,
status: Some(200),
@@ -312,6 +315,56 @@ fn network_response_event(resource_type: &str, request_id: &str) -> BackgroundPr
BackgroundProtocolEvent::immediate_automation_event(message, automation_event)
}
+fn network_request_event(
+ resource_type: DevToolsNetworkResourceType,
+ request_id: &str,
+) -> BackgroundProtocolEvent {
+ let (_, Some(AutomationEvent::NetworkResponseStarted(mut network_event))) =
+ network_response_event(resource_type, request_id).into_parts()
+ else {
+ unreachable!("network response fixture should retain its typed sidecar")
+ };
+ network_event.status = None;
+ network_event.encoded_data_length = None;
+ BackgroundProtocolEvent::immediate_automation_event(
+ json!({
+ "method": "Network.requestWillBeSent",
+ "params": {
+ "requestId": request_id,
+ "loaderId": "LOADER-nav",
+ "type": resource_type.as_cdp_type(),
+ "request": {
+ "url": "https://example.test/resource",
+ "method": "GET"
+ }
+ }
+ }),
+ AutomationEvent::NetworkBeforeRequestSent(network_event),
+ )
+}
+
+fn network_finished_event(
+ resource_type: DevToolsNetworkResourceType,
+ request_id: &str,
+) -> BackgroundProtocolEvent {
+ let (_, Some(AutomationEvent::NetworkResponseStarted(network_event))) =
+ network_response_event(resource_type, request_id).into_parts()
+ else {
+ unreachable!("network response fixture should retain its typed sidecar")
+ };
+ BackgroundProtocolEvent::immediate_automation_event(
+ json!({
+ "method": "Network.loadingFinished",
+ "params": {
+ "requestId": request_id,
+ "timestamp": 2.0,
+ "encodedDataLength": 0
+ }
+ }),
+ AutomationEvent::NetworkResponseCompleted(network_event),
+ )
+}
+
fn output_request_ids(output: ProtocolOutputSequence) -> Vec<String> {
output
.into_background_events()
@@ -400,12 +453,22 @@ fn root_document_lifecycle_identity(
}
fn background_navigation_gate_key() -> BackgroundNavigationGateKey {
+ background_navigation_gate_key_for("TID-nav", "SID-nav", "FRAME-nav", "LOADER-nav", 1)
+}
+
+fn background_navigation_gate_key_for(
+ target_id: &str,
+ session_id: &str,
+ frame_id: &str,
+ loader_id: &str,
+ navigation_request_id: u64,
+) -> BackgroundNavigationGateKey {
make_background_navigation_gate_key(
- Some("TID-nav".to_owned()),
- Some("SID-nav".to_owned()),
- "FRAME-nav".to_owned(),
- "LOADER-nav".to_owned(),
- Some(1),
+ Some(target_id.to_owned()),
+ Some(session_id.to_owned()),
+ frame_id.to_owned(),
+ loader_id.to_owned(),
+ Some(navigation_request_id),
)
}
@@ -1030,7 +1093,10 @@ fn background_navigation_blocks_concrete_protocol_residence_not_renderer_ingress
let mut scheduler = CdpScheduler::new(CdpConnection::new());
scheduler
.background_navigation_gate
- .note_navigation_started(background_navigation_gate_key());
+ .note_navigation_started(
+ background_navigation_gate_key(),
+ BackgroundNavigationCancellation::new(),
+ );
scheduler.apply_scheduler_events(vec![CdpSchedulerEvent::ProtocolWorkPublished {
work: root_frame_stopped_loading_work(1, "FRAME-1"),
}]);
@@ -1041,30 +1107,152 @@ fn background_navigation_blocks_concrete_protocol_residence_not_renderer_ingress
);
}
+#[test]
+fn replacement_navigation_retires_only_the_superseded_frame_gate() {
+ let mut gate = BackgroundNavigationGate::default();
+ let source = background_navigation_gate_key_for(
+ "TID-nav",
+ "SID-source",
+ "FRAME-nav",
+ "LOADER-source",
+ 1,
+ );
+ let replacement = background_navigation_gate_key_for(
+ "TID-nav",
+ "SID-replacement",
+ "FRAME-nav",
+ "LOADER-replacement",
+ 2,
+ );
+ let unrelated = background_navigation_gate_key_for(
+ "TID-other",
+ "SID-other",
+ "FRAME-other",
+ "LOADER-other",
+ 3,
+ );
+ let source_cancellation = BackgroundNavigationCancellation::new();
+ let replacement_cancellation = BackgroundNavigationCancellation::new();
+ let unrelated_cancellation = BackgroundNavigationCancellation::new();
+
+ gate.note_navigation_started(source.clone(), source_cancellation.clone());
+ gate.note_navigation_started(unrelated.clone(), unrelated_cancellation.clone());
+ gate.note_navigation_started(replacement.clone(), replacement_cancellation.clone());
+ assert!(source_cancellation.is_cancelled());
+ assert!(!replacement_cancellation.is_cancelled());
+ assert!(!unrelated_cancellation.is_cancelled());
+
+ gate.note_navigation_completion_drained(&source);
+ assert!(
+ gate.has_inflight_navigation(),
+ "a stale completion must not clear either live navigation gate"
+ );
+ gate.note_navigation_completion_drained(&replacement);
+ assert!(
+ gate.has_inflight_navigation(),
+ "replacing one frame must not clear an unrelated target's gate"
+ );
+ gate.note_navigation_completion_drained(&unrelated);
+ assert!(!gate.has_inflight_navigation());
+}
+
#[test]
fn scheduler_defers_subresource_network_events_until_background_navigation_gate_clears() {
let mut scheduler = CdpScheduler::new(CdpConnection::new());
let key = background_navigation_gate_key();
scheduler
.background_navigation_gate
- .note_navigation_started(key.clone());
+ .note_navigation_started(key.clone(), BackgroundNavigationCancellation::new());
let document_output = scheduler.route_background_event_around_inflight_navigation(
- network_response_event("Document", "REQ-document"),
+ network_response_event(DevToolsNetworkResourceType::Document, "REQ-document"),
);
assert_eq!(output_request_ids(document_output), ["REQ-document"]);
let script_output = scheduler.route_background_event_around_inflight_navigation(
- network_response_event("Script", "REQ-script"),
+ network_response_event(DevToolsNetworkResourceType::Script, "REQ-script"),
);
assert!(script_output.is_empty());
- assert_eq!(scheduler.pending_navigation_background_events.len(), 1);
+ let script_terminal = scheduler.route_background_event_around_inflight_navigation(
+ network_finished_event(DevToolsNetworkResourceType::Script, "REQ-script"),
+ );
+ assert!(script_terminal.is_empty());
+ assert_eq!(scheduler.pending_navigation_background_events.len(), 2);
scheduler
.background_navigation_gate
.note_navigation_completion_drained(&key);
let released = scheduler.drain_pending_navigation_background_events();
- assert_eq!(output_request_ids(released), ["REQ-script"]);
+ let released = released
+ .into_background_events()
+ .into_iter()
+ .map(BackgroundProtocolEvent::into_protocol_message)
+ .map(|message| {
+ (
+ message["method"].as_str().unwrap().to_owned(),
+ message["params"]["requestId"].as_str().unwrap().to_owned(),
+ )
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ released,
+ [
+ (
+ "Network.responseReceived".to_owned(),
+ "REQ-script".to_owned()
+ ),
+ (
+ "Network.loadingFinished".to_owned(),
+ "REQ-script".to_owned()
+ ),
+ ]
+ );
+}
+
+#[test]
+fn navigation_gate_release_precedes_later_renderer_boundary_network_output() {
+ let mut scheduler = CdpScheduler::new(CdpConnection::new());
+ let key = background_navigation_gate_key();
+ scheduler
+ .background_navigation_gate
+ .note_navigation_started(key.clone(), BackgroundNavigationCancellation::new());
+
+ let request_id = "REQ-boundary-race";
+ assert!(
+ scheduler
+ .route_background_event_around_inflight_navigation(network_request_event(
+ DevToolsNetworkResourceType::Xhr,
+ request_id,
+ ))
+ .is_empty()
+ );
+
+ scheduler
+ .background_navigation_gate
+ .note_navigation_completion_drained(&key);
+ let mut output = ProtocolOutputSequence::empty();
+ scheduler.append_navigation_gate_release_before_renderer_boundary(&mut output);
+ output.append(ProtocolOutputSequence::from_background_event(
+ network_response_event(DevToolsNetworkResourceType::Xhr, request_id),
+ ));
+ output.append(ProtocolOutputSequence::from_background_event(
+ network_finished_event(DevToolsNetworkResourceType::Xhr, request_id),
+ ));
+
+ let methods = output
+ .into_background_events()
+ .into_iter()
+ .map(BackgroundProtocolEvent::into_protocol_message)
+ .map(|message| message["method"].as_str().unwrap().to_owned())
+ .collect::<Vec<_>>();
+ assert_eq!(
+ methods,
+ [
+ "Network.requestWillBeSent",
+ "Network.responseReceived",
+ "Network.loadingFinished",
+ ]
+ );
}
#[test]
@@ -1072,16 +1260,25 @@ fn foreground_load_wait_network_barrier_releases_document_response_before_subres
let mut barrier =
ForegroundNavigationNetworkBarrier::for_navigation_wait(Some(DevToolsNavigationWait::Load));
- let script_output = barrier.route_event(network_response_event("Script", "REQ-script"));
+ let script_output = barrier.route_event(network_response_event(
+ DevToolsNetworkResourceType::Script,
+ "REQ-script",
+ ));
assert!(script_output.is_empty());
- let document_output = barrier.route_event(network_response_event("Document", "REQ-document"));
+ let document_output = barrier.route_event(network_response_event(
+ DevToolsNetworkResourceType::Document,
+ "REQ-document",
+ ));
assert_eq!(
output_request_ids(document_output),
["REQ-document", "REQ-script"]
);
- let image_output = barrier.route_event(network_response_event("Image", "REQ-image"));
+ let image_output = barrier.route_event(network_response_event(
+ DevToolsNetworkResourceType::Image,
+ "REQ-image",
+ ));
assert_eq!(output_request_ids(image_output), ["REQ-image"]);
assert!(barrier.finish().is_empty());
}
@@ -1091,7 +1288,10 @@ fn foreground_load_wait_network_barrier_drains_subresources_if_document_response
let mut barrier =
ForegroundNavigationNetworkBarrier::for_navigation_wait(Some(DevToolsNavigationWait::Load));
- let script_output = barrier.route_event(network_response_event("Script", "REQ-script"));
+ let script_output = barrier.route_event(network_response_event(
+ DevToolsNetworkResourceType::Script,
+ "REQ-script",
+ ));
assert!(script_output.is_empty());
assert_eq!(output_request_ids(barrier.finish()), ["REQ-script"]);
diff --git a/moli/src/protocol_server/tests/websocket.rs b/moli/src/protocol_server/tests/websocket.rs
index 10b2a4f36..123d1018d 100644
--- a/moli/src/protocol_server/tests/websocket.rs
+++ b/moli/src/protocol_server/tests/websocket.rs
@@ -1956,6 +1956,155 @@ async fn websocket_cdp_navigation_suspension_matches_chromium_io_command_routing
fixture_server.abort();
}
+#[tokio::test]
+async fn websocket_cdp_replacement_retires_hanging_precommit_navigation() {
+ const REPLACEMENT_TIMEOUT: Duration = Duration::from_secs(3);
+
+ let hanging_request_received = Arc::new(tokio::sync::Notify::new());
+ let request_received_for_route = Arc::clone(&hanging_request_received);
+ let fixture_app = Router::new().route(
+ "/hang",
+ get(move || {
+ let request_received_for_route = Arc::clone(&request_received_for_route);
+ async move {
+ request_received_for_route.notify_one();
+ std::future::pending::<()>().await;
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],
+ "unreachable",
+ )
+ }
+ }),
+ );
+ let (fixture_addr, fixture_server) =
+ spawn_dedicated_fixture_server(fixture_app, "hanging-precommit-replacement");
+
+ let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
+ let (mut socket, _) = connect_async(format!(
+ "ws://{cdp_addr}/devtools/browser/{DEFAULT_BROWSER_ID}"
+ ))
+ .await
+ .expect("connect to cdp websocket");
+ let browser_context_id = cdp_create_browser_context(&mut socket, 1).await;
+ let session = cdp_create_attached_target(&mut socket, 2, &browser_context_id).await;
+ for (id, method, params) in [
+ (4_u64, "Page.enable", json!({})),
+ (
+ 5_u64,
+ "Page.setLifecycleEventsEnabled",
+ json!({ "enabled": true }),
+ ),
+ ] {
+ let _ = send_cdp_command(&mut socket, id, method, Some(&session.session_id), params).await;
+ }
+
+ socket
+ .send(WsMessage::Text(
+ json!({
+ "id": 6_u64,
+ "method": "Page.navigate",
+ "sessionId": session.session_id,
+ "params": { "url": format!("http://{fixture_addr}/hang") }
+ })
+ .to_string()
+ .into(),
+ ))
+ .await
+ .expect("send hanging Page.navigate");
+ timeout(REPLACEMENT_TIMEOUT, hanging_request_received.notified())
+ .await
+ .expect("hanging main-document request should reach the fixture");
+
+ let marker = "moli-hanging-precommit-replacement";
+ let replacement_url =
+ format!("data:text/html,<title>{marker}</title><main id='marker'>{marker}</main>");
+ socket
+ .send(WsMessage::Text(
+ json!({
+ "id": 7_u64,
+ "method": "Page.navigate",
+ "sessionId": session.session_id,
+ "params": { "url": replacement_url }
+ })
+ .to_string()
+ .into(),
+ ))
+ .await
+ .expect("send replacement Page.navigate");
+
+ let mut replacement_messages = timeout(REPLACEMENT_TIMEOUT, async {
+ let mut messages = Vec::new();
+ let mut replacement_loader_id = None::<String>;
+ loop {
+ let message = recv_ws_json(&mut socket).await;
+ if message["id"] == json!(7_u64) {
+ assert!(
+ message.get("error").is_none(),
+ "replacement Page.navigate must succeed: {message:#?}"
+ );
+ replacement_loader_id = message["result"]["loaderId"].as_str().map(str::to_owned);
+ }
+ let reached_replacement_load = replacement_loader_id.as_deref().is_some_and(|loader| {
+ message["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message["method"] == json!("Page.lifecycleEvent")
+ && message["params"]["name"] == json!("load")
+ && message["params"]["loaderId"].as_str() == Some(loader)
+ });
+ messages.push(message);
+ if reached_replacement_load {
+ break messages;
+ }
+ }
+ })
+ .await
+ .expect("replacement Document must reach its own load without the hanging response");
+ let replacement_loader_id = replacement_messages
+ .iter()
+ .find(|message| message["id"] == json!(7_u64))
+ .and_then(|message| message["result"]["loaderId"].as_str())
+ .expect("replacement Page.navigate loaderId");
+ assert!(
+ replacement_messages.iter().any(|message| {
+ message["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message["method"] == json!("Page.lifecycleEvent")
+ && message["params"]["name"] == json!("DOMContentLoaded")
+ && message["params"]["loaderId"].as_str() == Some(replacement_loader_id)
+ }),
+ "replacement DCL must precede its load: {replacement_messages:#?}"
+ );
+ if !replacement_messages
+ .iter()
+ .any(|message| message["id"] == json!(6_u64))
+ {
+ replacement_messages.extend(
+ timeout(REPLACEMENT_TIMEOUT, recv_until_id(&mut socket, 6))
+ .await
+ .expect("superseded Page.navigate must receive a terminal response"),
+ );
+ }
+ let superseded_response = replacement_messages
+ .iter()
+ .find(|message| message["id"] == json!(6_u64))
+ .expect("superseded Page.navigate response");
+ assert_eq!(superseded_response["error"]["code"], json!(-32000));
+ assert_eq!(
+ superseded_response["error"]["message"],
+ json!("Navigation aborted")
+ );
+ let replacement_document = cdp_runtime_evaluate_string(
+ &mut socket,
+ &session.session_id,
+ 8,
+ "document.querySelector('#marker')?.textContent",
+ )
+ .await;
+ assert_eq!(replacement_document, marker);
+
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+ drop(fixture_server);
+}
+
#[tokio::test]
async fn websocket_cdp_runtime_evaluate_after_dcl_is_not_blocked_by_pending_load_stylesheet() {
async fn page() -> impl IntoResponse {
@@ -2983,6 +3132,166 @@ addEventListener('DOMContentLoaded', () => {
drop(fixture_server);
}
+#[tokio::test]
+async fn websocket_cdp_external_writer_with_two_document_writes_reaches_defer_and_dcl() {
+ async fn page() -> impl IntoResponse {
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],
+ r#"<!doctype html>
+<html>
+<head>
+<script>
+globalThis.documentWriteOrder = ['head'];
+document.addEventListener('DOMContentLoaded', () => documentWriteOrder.push('dcl'));
+</script>
+<script src="/writer.js"></script>
+<script>documentWriteOrder.push('tail');</script>
+<script defer src="/defer.js"></script>
+<script>documentWriteOrder.push('after-defer');</script>
+</head>
+<body><main id="ready">ready</main></body>
+</html>"#,
+ )
+ }
+
+ async fn writer() -> impl IntoResponse {
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/javascript")],
+ r#"documentWriteOrder.push('writer-start');
+document.write('<script src="/first.js"></' + 'script>');
+document.write('<script src="/second.js"></' + 'script>');
+documentWriteOrder.push('writer-end');"#,
+ )
+ }
+
+ async fn first() -> impl IntoResponse {
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/javascript")],
+ "documentWriteOrder.push('first');",
+ )
+ }
+
+ async fn second() -> impl IntoResponse {
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/javascript")],
+ "documentWriteOrder.push('second');",
+ )
+ }
+
+ let defer_requests = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+ let defer_requests_for_route = Arc::clone(&defer_requests);
+ let fixture_app = Router::new()
+ .route("/", get(page))
+ .route("/writer.js", get(writer))
+ .route("/first.js", get(first))
+ .route("/second.js", get(second))
+ .route(
+ "/defer.js",
+ get(move || {
+ let defer_requests_for_route = Arc::clone(&defer_requests_for_route);
+ async move {
+ defer_requests_for_route.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/javascript")],
+ "documentWriteOrder.push('defer');",
+ )
+ }
+ }),
+ );
+ let (fixture_addr, fixture_server) =
+ spawn_dedicated_fixture_server(fixture_app, "external-writer-two-document-writes");
+
+ let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
+ let (mut socket, _) = connect_async(format!(
+ "ws://{cdp_addr}/devtools/browser/{DEFAULT_BROWSER_ID}"
+ ))
+ .await
+ .expect("connect to cdp websocket");
+
+ let browser_context_id = cdp_create_browser_context(&mut socket, 1).await;
+ let session = cdp_create_attached_target(&mut socket, 2, &browser_context_id).await;
+ for (id, method, params) in [
+ (4_u64, "Runtime.enable", json!({})),
+ (5_u64, "Page.enable", json!({})),
+ (
+ 6_u64,
+ "Page.setLifecycleEventsEnabled",
+ json!({ "enabled": true }),
+ ),
+ ] {
+ let _ = send_cdp_command(&mut socket, id, method, Some(&session.session_id), params).await;
+ }
+
+ socket
+ .send(WsMessage::Text(
+ json!({
+ "id": 7_u64,
+ "method": "Page.navigate",
+ "sessionId": session.session_id,
+ "params": { "url": format!("http://{fixture_addr}/") }
+ })
+ .to_string()
+ .into(),
+ ))
+ .await
+ .expect("send Page.navigate");
+ let dcl_messages = timeout(
+ Duration::from_secs(3),
+ recv_until_match(&mut socket, |message| {
+ message["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message["method"] == json!("Page.lifecycleEvent")
+ && message["params"]["name"] == json!("DOMContentLoaded")
+ }),
+ )
+ .await
+ .expect("nested written scripts must not strand the main parser before DCL");
+ let loader_id = dcl_messages
+ .iter()
+ .find(|message| message["id"] == json!(7_u64))
+ .and_then(|message| message["result"]["loaderId"].as_str())
+ .expect("Page.navigate should return the committed loaderId");
+ assert!(
+ dcl_messages.iter().any(|message| {
+ message["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message["method"] == json!("Page.lifecycleEvent")
+ && message["params"]["name"] == json!("DOMContentLoaded")
+ && message["params"]["loaderId"].as_str() == Some(loader_id)
+ }),
+ "DCL must belong to the exact navigation loader: {dcl_messages:#?}"
+ );
+ assert_eq!(
+ defer_requests.load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "the parser-deferred source must join the document preload and execute before DCL"
+ );
+
+ let evaluate_messages = send_cdp_command(
+ &mut socket,
+ 8,
+ "Runtime.evaluate",
+ Some(&session.session_id),
+ json!({
+ "expression": "JSON.stringify(documentWriteOrder)",
+ "returnByValue": true
+ }),
+ )
+ .await;
+ let response = evaluate_messages
+ .iter()
+ .find(|message| message["id"] == json!(8_u64))
+ .expect("Runtime.evaluate response");
+ assert_eq!(
+ response["result"]["result"]["value"],
+ json!(
+ "[\"head\",\"writer-start\",\"writer-end\",\"first\",\"second\",\"tail\",\"after-defer\",\"defer\",\"dcl\"]"
+ )
+ );
+
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+ drop(fixture_server);
+}
+
#[tokio::test]
async fn websocket_cdp_runtime_evaluate_runs_while_parser_defer_source_is_blocked() {
async fn page() -> impl IntoResponse {
@@ -3579,6 +3888,205 @@ addEventListener('DOMContentLoaded', () => fetch('/stale-source-observed'));
drop(fixture_server);
}
+#[tokio::test]
+async fn websocket_cdp_replacement_cancels_source_document_xhrs() {
+ const XHR_COUNT: usize = 4;
+ const SOURCE_DOCUMENT_COUNT: usize = 2;
+
+ async fn source_page() -> impl IntoResponse {
+ (
+ [(axum::http::header::CONTENT_TYPE.as_str(), "text/html")],
+ r#"<!doctype html>
+<html>
+<body>
+<main>source</main>
+<script>
+const generation = new URL(location.href).searchParams.get('generation');
+for (let index = 0; index < 4; index += 1) {
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', `/held-xhr?generation=${generation}&index=${index}`);
+ xhr.send();
+}
+</script>
+</body>
+</html>"#,
+ )
+ }
+
+ let (xhr_requested_tx, mut xhr_requested_rx) = tokio::sync::mpsc::unbounded_channel();
+ let release_xhrs = Arc::new(tokio::sync::Notify::new());
+ let release_xhrs_for_route = Arc::clone(&release_xhrs);
+ let fixture_app = Router::new().route("/source", get(source_page)).route(
+ "/held-xhr",
+ get(move || {
+ let xhr_requested_tx = xhr_requested_tx.clone();
+ let release_xhrs = Arc::clone(&release_xhrs_for_route);
+ async move {
+ xhr_requested_tx
+ .send(())
+ .expect("held XHR request observer should remain live");
+ release_xhrs.notified().await;
+ "late XHR response"
+ }
+ }),
+ );
+ let (fixture_addr, fixture_server) =
+ spawn_dedicated_fixture_server(fixture_app, "xhr-document-replacement");
+
+ let (cdp_addr, protocol_server) = spawn_test_protocol_server().await;
+ let (mut socket, _) = connect_async(format!(
+ "ws://{cdp_addr}/devtools/browser/{DEFAULT_BROWSER_ID}"
+ ))
+ .await
+ .expect("connect to cdp websocket");
+
+ let browser_context_id = cdp_create_browser_context(&mut socket, 1).await;
+ let session = cdp_create_attached_target(&mut socket, 2, &browser_context_id).await;
+ for (id, method) in [(4_u64, "Page.enable"), (5_u64, "Network.enable")] {
+ let _ = send_cdp_command(
+ &mut socket,
+ id,
+ method,
+ Some(&session.session_id),
+ json!({}),
+ )
+ .await;
+ }
+
+ let mut messages = Vec::new();
+ for generation in 0..SOURCE_DOCUMENT_COUNT {
+ let source_url = format!("http://{fixture_addr}/source?generation={generation}");
+ messages.extend(
+ timeout(
+ Duration::from_secs(5),
+ cdp_navigate_and_wait_for_load(
+ &mut socket,
+ 6 + generation as u64,
+ &session.session_id,
+ &source_url,
+ ),
+ )
+ .await
+ .unwrap_or_else(|_| {
+ panic!(
+ "source document generation {generation} should load while its XHRs remain pending"
+ )
+ }),
+ );
+ for request_index in 0..XHR_COUNT {
+ timeout(Duration::from_secs(2), xhr_requested_rx.recv())
+ .await
+ .unwrap_or_else(|_| {
+ panic!("held XHR {generation}:{request_index} should reach the fixture server")
+ })
+ .unwrap_or_else(|| {
+ panic!("held XHR observer closed at request {generation}:{request_index}")
+ });
+ }
+ }
+
+ messages.extend(
+ send_cdp_command(
+ &mut socket,
+ 20,
+ "Runtime.evaluate",
+ Some(&session.session_id),
+ json!({ "expression": "document.querySelector('main').textContent" }),
+ )
+ .await,
+ );
+
+ let replacement_url =
+ "data:text/html;charset=utf-8,%3C!doctype%20html%3E%3Cmain%3Ereplacement%3C%2Fmain%3E";
+ messages.extend(
+ timeout(
+ Duration::from_secs(5),
+ cdp_navigate_and_wait_for_load(&mut socket, 21, &session.session_id, replacement_url),
+ )
+ .await
+ .expect("replacement document should not wait for source-document XHRs"),
+ );
+ messages.extend(
+ send_cdp_command(
+ &mut socket,
+ 22,
+ "Runtime.evaluate",
+ Some(&session.session_id),
+ json!({ "expression": "document.querySelector('main').textContent" }),
+ )
+ .await,
+ );
+ release_xhrs.notify_waiters();
+
+ let xhr_requests = messages
+ .iter()
+ .enumerate()
+ .filter_map(|(index, message)| {
+ let url = message["params"]["request"]["url"].as_str()?;
+ (message["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message["method"] == json!("Network.requestWillBeSent")
+ && url.contains("/held-xhr?generation="))
+ .then(|| {
+ let generation = usize::from(url.contains("generation=1"));
+ message["params"]["requestId"]
+ .as_str()
+ .map(|request_id| (request_id.to_owned(), generation, index))
+ })
+ .flatten()
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ xhr_requests.len(),
+ XHR_COUNT * SOURCE_DOCUMENT_COUNT,
+ "each source-document XHR should publish one request start: {messages:#?}"
+ );
+ let first_successor_xhr_index = xhr_requests
+ .iter()
+ .filter_map(|(_, generation, index)| (*generation == 1).then_some(*index))
+ .min()
+ .expect("second source Document should publish XHR starts");
+ let final_load_index = messages
+ .iter()
+ .rposition(|message| message["method"] == json!("Page.loadEventFired"))
+ .expect("final replacement should publish load");
+ for (request_id, generation, start_index) in xhr_requests {
+ let terminals = messages
+ .iter()
+ .enumerate()
+ .filter(|message| {
+ message.1["sessionId"].as_str() == Some(session.session_id.as_str())
+ && message.1["method"] == json!("Network.loadingFailed")
+ && message.1["params"]["requestId"] == json!(request_id)
+ })
+ .collect::<Vec<_>>();
+ assert_eq!(
+ terminals.len(),
+ 1,
+ "replacement must publish exactly one canceled terminal for old request {request_id}: {messages:#?}"
+ );
+ let (terminal_index, terminal) = terminals[0];
+ assert_eq!(terminal["params"]["errorText"], json!("net::ERR_ABORTED"));
+ assert_eq!(terminal["params"]["canceled"], json!(true));
+ assert!(
+ terminal_index > start_index,
+ "request terminal must follow its announced start"
+ );
+ let successor_boundary = if generation == 0 {
+ first_successor_xhr_index
+ } else {
+ final_load_index
+ };
+ assert!(
+ terminal_index < successor_boundary,
+ "old request {request_id} must terminate before its successor Document becomes observable: {messages:#?}"
+ );
+ }
+
+ let _ = socket.close(None).await;
+ abort_test_cdp_server(protocol_server).await;
+ drop(fixture_server);
+}
+
#[tokio::test]
async fn websocket_cdp_continue_response_ack_does_not_wait_for_document_body_tail() {
let release_tail = Arc::new(tokio::sync::Notify::new());