mirror of
https://github.com/lexmount/moli.git
synced 2026-11-20 08:03:30 +00:00
fix(fetch): preserve navigation interception on worker fallback
This commit is contained in:
@@ -707,6 +707,16 @@ class FixtureServer:
|
||||
self._send_html("<!doctype html><main>plain ok</main>")
|
||||
elif route == "/fetch-dispatch/page":
|
||||
self._send_html("<!doctype html><main>resource dispatch</main>")
|
||||
elif route in {"/navigation-sw-fallback-start", "/fetch-dispatch/nav-fallback/middle"}:
|
||||
outer._record_resource_request(self.path, self.headers)
|
||||
destination = ("middle" if route == "/navigation-sw-fallback-start" else "final")
|
||||
self._send_common(
|
||||
HTTPStatus.FOUND, "text/plain", b"",
|
||||
{"Location": f"/fetch-dispatch/nav-fallback/{destination}?{parsed.query}"},
|
||||
)
|
||||
elif route == "/fetch-dispatch/nav-fallback/final":
|
||||
outer._record_resource_request(self.path, self.headers)
|
||||
self._send_html("<!doctype html><main>network fallback</main>")
|
||||
elif route == "/fetch-dispatch/sw.js":
|
||||
resources = {
|
||||
"font.woff2": ("font/woff2", (REPO_ROOT / "moli-layout/tests/fixtures/moli-ahem.woff2").read_bytes()),
|
||||
|
||||
@@ -48,6 +48,7 @@ async def run_navigation_outcomes_group(state: SmokeState) -> None:
|
||||
"Page.navigate",
|
||||
"Runtime.evaluate",
|
||||
"Fetch.enable",
|
||||
"Fetch.continueRequest",
|
||||
"Fetch.failRequest",
|
||||
"Fetch.continueResponse",
|
||||
"Fetch.fulfillRequest",
|
||||
@@ -195,6 +196,15 @@ def _contracts() -> tuple[NavigationOutcomeContract, ...]:
|
||||
)
|
||||
for action in ("fail", "continue")
|
||||
),
|
||||
*(
|
||||
NavigationOutcomeContract(
|
||||
f"navigate_service_worker_fallback_preserves_redirect_pause_{action}",
|
||||
"A network redirect into an unhandled Service Worker scope keeps "
|
||||
"later Document requests paused before they reach the server.",
|
||||
partial(_service_worker_redirect_fallback, action=action),
|
||||
)
|
||||
for action in ("continue", "fail", "fulfill")
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -771,6 +781,98 @@ async def _mixed_redirect_request_metadata(
|
||||
return {"action": action, "attachment": attachment, "requests": observed, "finalUrl": urls[-1]}
|
||||
|
||||
|
||||
async def _service_worker_redirect_fallback(
|
||||
state: SmokeState, *, action: str
|
||||
) -> dict[str, Any]:
|
||||
async with _new_probe(state) as probe:
|
||||
await probe.page.goto(f"{state.fixture}/fetch-dispatch/page", wait_until="load")
|
||||
await _evaluate_value(probe.cdp, """
|
||||
globalThis.__navigationFallbackReady = false;
|
||||
navigator.serviceWorker.register('/fetch-dispatch/sw.js', {scope:'/fetch-dispatch/'})
|
||||
.then(() => navigator.serviceWorker.ready)
|
||||
.then(() => { globalThis.__navigationFallbackReady = true; });
|
||||
true;
|
||||
""")
|
||||
await wait_until(
|
||||
lambda: probe.page.evaluate(
|
||||
"__navigationFallbackReady && !!navigator.serviceWorker.controller"
|
||||
),
|
||||
"navigation fallback controlling service worker",
|
||||
)
|
||||
paths = [
|
||||
f"{path}?case=navigation-sw-fallback-{action}"
|
||||
for path in (
|
||||
"/navigation-sw-fallback-start",
|
||||
"/fetch-dispatch/nav-fallback/middle",
|
||||
"/fetch-dispatch/nav-fallback/final",
|
||||
)
|
||||
]
|
||||
urls = [f"{state.fixture}{path}" for path in paths]
|
||||
for path in paths:
|
||||
state.fixture_server.reset_request_count(path)
|
||||
paused: asyncio.Queue[dict[str, Any]] = asyncio.Queue()
|
||||
probe.cdp.on("Fetch.requestPaused", paused.put_nowait)
|
||||
await probe.cdp.send("Fetch.enable", {"patterns": [{
|
||||
"urlPattern": "*", "resourceType": "Document", "requestStage": "Request",
|
||||
}]})
|
||||
probe.events.clear()
|
||||
navigation = asyncio.create_task(probe.cdp.send("Page.navigate", {"url": urls[0]}))
|
||||
try:
|
||||
for index, url in enumerate(urls):
|
||||
await wait_until(
|
||||
lambda: not paused.empty() or state.fixture_server.request_count(paths[-1]) > 0,
|
||||
f"service worker fallback pause before {url}",
|
||||
)
|
||||
if paused.empty():
|
||||
raise SmokeError(
|
||||
f"final request reached the server without Fetch.requestPaused: {url}"
|
||||
)
|
||||
request = paused.get_nowait()
|
||||
assert_equal(request["request"]["url"], url, "fallback paused redirect URL")
|
||||
assert_equal("responseStatusCode" in request, False, "fallback Request-stage pause")
|
||||
for pending_path in paths[index:]:
|
||||
assert_equal(state.fixture_server.request_count(pending_path), 0,
|
||||
f"server request count before releasing {pending_path}")
|
||||
params = {"requestId": request["requestId"]}
|
||||
if index < 2 or action == "continue":
|
||||
await probe.cdp.send("Fetch.continueRequest", params)
|
||||
elif action == "fail":
|
||||
await probe.cdp.send("Fetch.failRequest", {
|
||||
**params, "errorReason": "BlockedByClient",
|
||||
})
|
||||
else:
|
||||
await probe.cdp.send("Fetch.fulfillRequest", {
|
||||
**params,
|
||||
"responseCode": 200,
|
||||
"responseHeaders": [{"name": "Content-Type", "value": "text/html"}],
|
||||
"body": base64.b64encode(b"<main>fulfilled fallback</main>").decode(),
|
||||
})
|
||||
result = await navigation
|
||||
assert_equal(result.get("errorText"),
|
||||
"net::ERR_BLOCKED_BY_CLIENT" if action == "fail" else None,
|
||||
"fallback navigation error")
|
||||
await wait_until(
|
||||
lambda: any(event["method"] == "Page.loadEventFired" for event in probe.events),
|
||||
"fallback navigation Document load",
|
||||
)
|
||||
counts = [state.fixture_server.request_count(path) for path in paths]
|
||||
assert_equal(counts, [1, 1, 1 if action == "continue" else 0],
|
||||
"fallback server requests after final action")
|
||||
if action != "fail":
|
||||
assert_equal(await _evaluate_value(probe.cdp, "location.href"), urls[-1],
|
||||
"fallback final Document URL")
|
||||
assert_equal(await _evaluate_value(probe.cdp, "document.body.textContent"),
|
||||
"network fallback" if action == "continue" else "fulfilled fallback",
|
||||
"fallback final Document body")
|
||||
return {"action": action, "requestUrls": urls, "serverRequests": counts}
|
||||
finally:
|
||||
await probe.cdp.send("Fetch.disable")
|
||||
if not navigation.done():
|
||||
navigation.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await navigation
|
||||
|
||||
|
||||
async def _wait_for_document_response(
|
||||
probe: NavigationProbe,
|
||||
url: str,
|
||||
|
||||
@@ -903,6 +903,7 @@ mod tests {
|
||||
cancel_handle: moli_fetch::FetchCancelHandle,
|
||||
) -> ServiceWorkerFetchJob {
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
|
||||
@@ -276,8 +276,10 @@ impl ServiceWorkerRuntimeService {
|
||||
let native_request = dispatch
|
||||
.request_client
|
||||
.bind_browser_site_context(native_request);
|
||||
let initial_redirect_count = native_request.redirect_count();
|
||||
let fetch_job = ServiceWorkerFetchJob {
|
||||
request: native_request,
|
||||
initial_redirect_count,
|
||||
internal_id: dispatch.internal_id,
|
||||
owner: None,
|
||||
cors_preflight_request_headers: dispatch.cors_preflight_request_headers,
|
||||
|
||||
@@ -269,7 +269,7 @@ impl ServiceWorkerRuntimeService {
|
||||
pub(super) fn dispatch_fetch_fallback(&self, mut job: ServiceWorkerFetchJob) {
|
||||
job.cancel_pending_navigation_preload();
|
||||
if let Some(completion_tx) = job.direct_completion_tx.take() {
|
||||
if job.request.redirect_count() != 0 {
|
||||
if job.request.redirect_count() > job.initial_redirect_count {
|
||||
self.dispatch_direct_fetch_network_fallback(job, completion_tx);
|
||||
return;
|
||||
}
|
||||
@@ -1170,6 +1170,7 @@ mod tests {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
@@ -2043,6 +2044,7 @@ mod tests {
|
||||
let completion_queue = crate::page_task_queue::RendererResourceCompletionTestHarness::new();
|
||||
let request_url = url("https://example.test/app/post");
|
||||
let mut job = ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&request_url);
|
||||
let initiator = request_url.clone();
|
||||
|
||||
@@ -736,6 +736,7 @@ fn pending_unregistration_waits_for_active_fetch_to_complete_before_delete() {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
@@ -1203,6 +1204,7 @@ fn restart_start_failure_rejects_pending_fetch_job() {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = document_url.clone();
|
||||
@@ -2292,6 +2294,7 @@ fn empty_fetch_handler_pending_start_fetch_falls_back_after_worker_start() {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
@@ -2420,6 +2423,7 @@ fn fetch_completion_schedules_idle_timeout_for_running_active_worker() {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
@@ -2650,6 +2654,7 @@ fn active_fetch_completion_queues_waiting_activation_after_controllees_are_gone(
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = (document_url).clone();
|
||||
@@ -2843,6 +2848,7 @@ fn activating_new_worker_fails_replaced_active_fetch_and_pending_start_events()
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&document_url);
|
||||
let initiator = document_url.clone();
|
||||
|
||||
+1
@@ -227,6 +227,7 @@ fn pending_unregistration_deletion_clears_owner_state() {
|
||||
state.pending_fetch_jobs.insert(
|
||||
event_id,
|
||||
ServiceWorkerFetchJob {
|
||||
initial_redirect_count: 0,
|
||||
request: {
|
||||
let origin = moli_url::WebOrigin::from_url(&request_url);
|
||||
let initiator = request_url.clone();
|
||||
|
||||
@@ -770,6 +770,8 @@ pub(super) enum ServiceWorkerPeriodicSyncStart {
|
||||
|
||||
pub(super) struct ServiceWorkerFetchJob {
|
||||
pub(super) request: moli_fetch::Request,
|
||||
// Only redirects followed during this job transfer network fallback to it.
|
||||
pub(super) initial_redirect_count: usize,
|
||||
pub(super) internal_id: u64,
|
||||
pub(super) owner: Option<ServiceWorkerRunOwner>,
|
||||
pub(super) cors_preflight_request_headers: Vec<(String, String)>,
|
||||
|
||||
Reference in New Issue
Block a user