mirror of
https://github.com/lexmount/moli.git
synced 2026-11-21 08:02:59 +00:00
fix(service-worker): preserve unregistered registration lifetimes
Remove unregistered storage-key/scope entries from lookup and persistence while existing clients and events retain their old registration. Start later jobs with fresh registrations and keep deferred cleanup from deleting replacement resources. Apply worker-state and registration-slot changes in separate lifecycle tasks, retain watchers for both old and new objects, and stop synthesizing clearing during unregister promise settlement. Clean failed initial registrations before advancing their queued jobs and publish failure slot updates by registration identity, preserving other retired objects at the same scope. Cover controlled clients, failed replacements, cached failed registrations, identity, persistent removal, queued jobs and callback/microtask slot ordering. Replace legacy resurrection and synchronous-clearing expectations with current Service Worker semantics.
This commit is contained in:
@@ -534,8 +534,6 @@ fn refresh_service_worker_container_registration_for_scope(
|
||||
service_worker_registration_snapshot_script_url(&snapshot),
|
||||
ServiceWorkerRegistrationPhase::Snapshot(&snapshot),
|
||||
);
|
||||
} else {
|
||||
service_worker_registration_clear_workers(scope, registration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1279,39 +1277,20 @@ fn navigator_service_worker_unregister_callback<'s>(
|
||||
};
|
||||
let promise = resolver.get_promise(scope);
|
||||
let scope_url = service_worker_registration_scope_from_this(scope, args.this());
|
||||
let active_worker = service_worker_registration_active_worker(scope, args.this());
|
||||
let Some(host_ptr) = context_host_ptr_from_global_bridge(scope) else {
|
||||
settle_service_worker_unregister_completion(
|
||||
scope,
|
||||
resolver,
|
||||
Some(args.this()),
|
||||
active_worker,
|
||||
false,
|
||||
);
|
||||
settle_service_worker_unregister_completion(scope, resolver, false);
|
||||
rv.set(promise.into());
|
||||
return;
|
||||
};
|
||||
let host = unsafe { &mut *host_ptr };
|
||||
let owner = service_worker_owner_scope_from_object(scope, args.this());
|
||||
let Some(request_context) = host.service_worker_window_request_context(owner) else {
|
||||
settle_service_worker_unregister_completion(
|
||||
scope,
|
||||
resolver,
|
||||
Some(args.this()),
|
||||
active_worker,
|
||||
false,
|
||||
);
|
||||
settle_service_worker_unregister_completion(scope, resolver, false);
|
||||
rv.set(promise.into());
|
||||
return;
|
||||
};
|
||||
let (request_id, document_owner, completion_tx) = host
|
||||
.register_pending_service_worker_unregister(
|
||||
scope,
|
||||
resolver,
|
||||
args.this(),
|
||||
active_worker,
|
||||
request_context.owner(),
|
||||
);
|
||||
let (request_id, document_owner, completion_tx) =
|
||||
host.register_pending_service_worker_unregister(scope, resolver, request_context.owner());
|
||||
let start = match scope_url.as_ref() {
|
||||
Some(scope_url) => host.unregister_service_worker_scope(
|
||||
&request_context,
|
||||
@@ -1329,13 +1308,7 @@ fn navigator_service_worker_unregister_callback<'s>(
|
||||
};
|
||||
if let crate::service_worker_runtime::ServiceWorkerUnregisterStart::Completed(removed) = start {
|
||||
let _ = host.take_pending_service_worker_unregister(request_id);
|
||||
settle_service_worker_unregister_completion(
|
||||
scope,
|
||||
resolver,
|
||||
Some(args.this()),
|
||||
active_worker,
|
||||
removed,
|
||||
);
|
||||
settle_service_worker_unregister_completion(scope, resolver, removed);
|
||||
}
|
||||
rv.set(promise.into());
|
||||
}
|
||||
@@ -2061,32 +2034,8 @@ fn service_worker_push_permission_state(scope: &mut v8::PinScope<'_, '_>) -> Str
|
||||
pub(crate) fn settle_service_worker_unregister_completion<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
resolver: v8::Local<'s, v8::PromiseResolver>,
|
||||
registration: Option<v8::Local<'s, v8::Object>>,
|
||||
active_worker: Option<v8::Local<'s, v8::Object>>,
|
||||
removed: bool,
|
||||
) {
|
||||
let retained_controller =
|
||||
registration
|
||||
.zip(active_worker)
|
||||
.is_some_and(|(registration, active_worker)| {
|
||||
let owner = service_worker_owner_scope_from_object(scope, registration);
|
||||
let active_version_id =
|
||||
service_worker_worker_version_id_value(scope, active_worker);
|
||||
context_host_ptr_from_global_bridge(scope)
|
||||
.and_then(|host_ptr| {
|
||||
unsafe { &*host_ptr }.service_worker_control_state_for_window_owner(owner)
|
||||
})
|
||||
.is_some_and(|state| state.active_version_id() == active_version_id)
|
||||
});
|
||||
if removed && !retained_controller {
|
||||
if let Some(registration) = registration {
|
||||
service_worker_registration_clear_workers(scope, registration);
|
||||
}
|
||||
if let Some(active_worker) = active_worker {
|
||||
service_worker_worker_set_state(scope, active_worker, "redundant");
|
||||
dispatch_service_worker_simple_event(scope, active_worker, "statechange");
|
||||
}
|
||||
}
|
||||
let _ = resolver.resolve(scope, v8::Boolean::new(scope, removed).into());
|
||||
}
|
||||
|
||||
@@ -2979,15 +2928,6 @@ fn remember_service_worker_registration_worker<'s>(
|
||||
array_push_value(scope, cache, worker.into());
|
||||
}
|
||||
|
||||
fn service_worker_registration_active_worker<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
registration: v8::Local<'s, v8::Object>,
|
||||
) -> Option<v8::Local<'s, v8::Object>> {
|
||||
registration
|
||||
.get(scope, v8str(scope, "active").into())
|
||||
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
|
||||
}
|
||||
|
||||
fn service_worker_registration_hidden_worker<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
registration: v8::Local<'s, v8::Object>,
|
||||
@@ -2996,20 +2936,6 @@ fn service_worker_registration_hidden_worker<'s>(
|
||||
.and_then(|value| v8::Local::<v8::Object>::try_from(value).ok())
|
||||
}
|
||||
|
||||
fn service_worker_registration_clear_workers<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
registration: v8::Local<'s, v8::Object>,
|
||||
) {
|
||||
let null_value: v8::Local<'_, v8::Value> = v8::null(scope).into();
|
||||
set_service_worker_registration_worker_values(
|
||||
scope,
|
||||
registration,
|
||||
null_value,
|
||||
null_value,
|
||||
null_value,
|
||||
);
|
||||
}
|
||||
|
||||
fn set_service_worker_registration_worker_values<'s>(
|
||||
scope: &mut v8::PinScope<'s, '_>,
|
||||
registration: v8::Local<'s, v8::Object>,
|
||||
|
||||
@@ -92,8 +92,6 @@ pub(crate) struct PendingServiceWorkerUnregister {
|
||||
pub(crate) owner: ServiceWorkerWindowOwner,
|
||||
pub(crate) context: v8::Global<v8::Context>,
|
||||
pub(crate) resolver: v8::Global<v8::PromiseResolver>,
|
||||
pub(crate) registration: v8::Global<v8::Object>,
|
||||
pub(crate) active_worker: Option<v8::Global<v8::Object>>,
|
||||
}
|
||||
|
||||
pub(crate) struct ServiceWorkerRegistrationWatcher {
|
||||
@@ -579,8 +577,6 @@ impl PageScriptHost {
|
||||
&mut self,
|
||||
scope: &mut v8::PinScope<'_, '_>,
|
||||
resolver: v8::Local<'_, v8::PromiseResolver>,
|
||||
registration: v8::Local<'_, v8::Object>,
|
||||
active_worker: Option<v8::Local<'_, v8::Object>>,
|
||||
owner: ServiceWorkerWindowOwner,
|
||||
) -> (
|
||||
u64,
|
||||
@@ -594,8 +590,6 @@ impl PageScriptHost {
|
||||
owner,
|
||||
context: v8::Global::new(scope, scope.get_current_context()),
|
||||
resolver: v8::Global::new(scope, resolver),
|
||||
registration: v8::Global::new(scope, registration),
|
||||
active_worker: active_worker.map(|worker| v8::Global::new(scope, worker)),
|
||||
},
|
||||
);
|
||||
tracing::debug!(
|
||||
@@ -960,7 +954,10 @@ impl PageScriptHost {
|
||||
watcher.owner == owner
|
||||
&& watcher.scope_url == scope_url
|
||||
&& watcher.storage_key == storage_key
|
||||
&& !watcher.registration.is_empty()
|
||||
&& watcher
|
||||
.registration
|
||||
.to_local(scope)
|
||||
.is_some_and(|existing| existing.strict_equals(registration.into()))
|
||||
})
|
||||
{
|
||||
watcher.registration = v8::Weak::new(scope, registration);
|
||||
|
||||
@@ -142,22 +142,12 @@ impl ScriptVm {
|
||||
|
||||
let context = pending.context;
|
||||
let resolver = pending.resolver;
|
||||
let registration = pending.registration;
|
||||
let active_worker = pending.active_worker;
|
||||
let removed = completion.result;
|
||||
let context_ptr: *const v8::Global<v8::Context> = &context;
|
||||
self.with_context_scope_by_ptr(context_ptr, move |scope, _host_ptr| {
|
||||
let resolver = v8::Local::new(scope, &resolver);
|
||||
let registration = v8::Local::new(scope, ®istration);
|
||||
let active_worker = active_worker
|
||||
.as_ref()
|
||||
.map(|worker| v8::Local::new(scope, worker));
|
||||
crate::context_bootstrap::settle_service_worker_unregister_completion(
|
||||
scope,
|
||||
resolver,
|
||||
Some(registration),
|
||||
active_worker,
|
||||
removed,
|
||||
scope, resolver, removed,
|
||||
);
|
||||
Ok(())
|
||||
})?;
|
||||
|
||||
+94
-4
@@ -491,6 +491,7 @@ async fn navigator_service_worker_registration_lifecycle_attributes_reflect_acti
|
||||
scope: "./"
|
||||
});
|
||||
const registration = await sw.ready;
|
||||
globalThis.__serviceWorkerLifecycleRegistration = registration;
|
||||
const newest = registration.active;
|
||||
const log = [
|
||||
[
|
||||
@@ -513,7 +514,7 @@ async fn navigator_service_worker_registration_lifecycle_attributes_reflect_acti
|
||||
active.state,
|
||||
registration.installing === null,
|
||||
registration.waiting === null,
|
||||
registration.active === null
|
||||
registration.active === active
|
||||
].join(":"));
|
||||
if (active.state === "redundant") {
|
||||
resolve();
|
||||
@@ -526,7 +527,7 @@ async fn navigator_service_worker_registration_lifecycle_attributes_reflect_acti
|
||||
"after-unregister",
|
||||
registration.installing === null,
|
||||
registration.waiting === null,
|
||||
registration.active === null
|
||||
registration.active === active
|
||||
].join(":"));
|
||||
globalThis.__serviceWorkerLifecycleProbe = log.join("|");
|
||||
})().catch((error) => {
|
||||
@@ -553,6 +554,16 @@ async fn navigator_service_worker_registration_lifecycle_attributes_reflect_acti
|
||||
result,
|
||||
r#""active:true:activated:true:true:true:function:function|redundant:redundant:true:true:true|after-unregister:true:true:true""#
|
||||
);
|
||||
drain_service_worker_test_until_eval_equals(
|
||||
&mut vm,
|
||||
&browser_context_runtime,
|
||||
&loader,
|
||||
"String(__serviceWorkerLifecycleRegistration.installing === null && \
|
||||
__serviceWorkerLifecycleRegistration.waiting === null && \
|
||||
__serviceWorkerLifecycleRegistration.active === null)",
|
||||
"true",
|
||||
)
|
||||
.await;
|
||||
server
|
||||
.await
|
||||
.expect("service worker lifecycle script server should finish");
|
||||
@@ -1420,10 +1431,11 @@ async fn navigator_service_worker_register_validates_urls_and_refreshes_cached_w
|
||||
const first = await sw.register("././worker.js", { scope: "./scope/" });
|
||||
const firstScriptURL = newest(first) && newest(first).scriptURL;
|
||||
const unregistered = await first.unregister();
|
||||
const cleared =
|
||||
first.installing === null && first.waiting === null && first.active === null;
|
||||
const second = await sw.register("../app/worker.js", { scope: "./scope/" });
|
||||
const secondScriptURL = newest(second) && newest(second).scriptURL;
|
||||
// Clear Registration updates worker slots in later tasks.
|
||||
const cleared =
|
||||
first.installing === null && first.waiting === null && first.active === null;
|
||||
|
||||
globalThis.__serviceWorkerRegistrationUrlProbe = JSON.stringify({
|
||||
encodedSlash,
|
||||
@@ -1716,3 +1728,81 @@ async fn navigator_service_worker_update_in_worker_preserves_events_and_install_
|
||||
.await;
|
||||
server.await.expect("worker update server");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn navigator_service_worker_unregister_keeps_old_clients_and_clears_old_objects_in_tasks() {
|
||||
let worker = r#"
|
||||
self.addEventListener('fetch', event => {
|
||||
const isClient = new URL(event.request.url).pathname.endsWith('/client.html');
|
||||
event.respondWith(new Response(isClient
|
||||
? "<script>parent.postMessage('controlled-ready', '*')</script>"
|
||||
: 'controlled-fetch',
|
||||
{headers: {'Content-Type': isClient ? 'text/html' : 'text/plain'}}));
|
||||
});
|
||||
"#;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let base_url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
for (path, status, content_type, body) in [
|
||||
("/controlled/sw.js", "200 OK", "text/javascript", worker),
|
||||
(
|
||||
"/controlled/invalid.js",
|
||||
"404 Not Found",
|
||||
"text/html",
|
||||
"not found",
|
||||
),
|
||||
("/controlled/sw.js", "200 OK", "text/javascript", worker),
|
||||
] {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let request = read_storage_bucket_partition_request_head(&mut stream)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
request.lines().next().unwrap(),
|
||||
format!("GET {path} HTTP/1.1")
|
||||
);
|
||||
let response = format!(
|
||||
"HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nCache-Control: no-store\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
stream.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
});
|
||||
let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
|
||||
let (mut vm, runtime) = new_service_worker_page_test_vm_with_loader_and_browser_context_runtime(
|
||||
&format!("{base_url}/app/page.html"),
|
||||
&loader,
|
||||
);
|
||||
vm.eval(include_str!("../../../service_worker_unregister.js"))
|
||||
.unwrap();
|
||||
drain_service_worker_test_until_eval_equals(
|
||||
&mut vm,
|
||||
&runtime,
|
||||
&loader,
|
||||
"String(unregisteredReplacementProbe.phase === 'error' || \
|
||||
(unregisteredReplacementProbe.phase === 'registered' && \
|
||||
unregisteredReplacementProbe.oldRegistration.active === null && \
|
||||
unregisteredReplacementProbe.events.length === 2))",
|
||||
"true",
|
||||
)
|
||||
.await;
|
||||
let observed = vm.eval(r#"
|
||||
JSON.stringify({
|
||||
error: unregisteredReplacementProbe.error || null,
|
||||
flags: Object.values(unregisteredReplacementProbe.result),
|
||||
events: unregisteredReplacementProbe.events,
|
||||
oldSlotsCleared: unregisteredReplacementProbe.oldRegistration.installing === null &&
|
||||
unregisteredReplacementProbe.oldRegistration.waiting === null &&
|
||||
unregisteredReplacementProbe.oldRegistration.active === null,
|
||||
oldWorkerState: unregisteredReplacementProbe.oldWorker.state,
|
||||
replacementActivated: unregisteredReplacementProbe.replacement.active.state === 'activated'
|
||||
})
|
||||
"#).unwrap();
|
||||
assert_eq!(
|
||||
observed,
|
||||
r#"{"error":null,"flags":[true,true,true,true,true,true,true,true,true,true,true,true,true,true,true,true],"events":["event:true","microtask:true"],"oldSlotsCleared":true,"oldWorkerState":"redundant","replacementActivated":true}"#
|
||||
);
|
||||
server
|
||||
.await
|
||||
.expect("both registrations must fetch a worker script");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
globalThis.unregisteredReplacementProbe = {phase: 'running', events: [], result: {}};
|
||||
(async () => {
|
||||
const probe = globalThis.unregisteredReplacementProbe;
|
||||
const sw = navigator.serviceWorker;
|
||||
const activated = async registration => {
|
||||
const worker = registration.installing || registration.waiting || registration.active;
|
||||
if (!worker) throw new Error('registration has no worker');
|
||||
if (worker.state !== 'activated') await new Promise((resolve, reject) => {
|
||||
worker.addEventListener('statechange', () => {
|
||||
if (worker.state === 'activated') resolve();
|
||||
if (worker.state === 'redundant') reject(new Error('worker became redundant'));
|
||||
});
|
||||
});
|
||||
return worker;
|
||||
};
|
||||
const oldRegistration = await sw.register('/controlled/sw.js', {scope: '/controlled/'});
|
||||
const oldWorker = await activated(oldRegistration);
|
||||
probe.oldRegistration = oldRegistration;
|
||||
probe.oldWorker = oldWorker;
|
||||
const frame = document.createElement('iframe');
|
||||
const ready = new Promise(resolve => {
|
||||
const listener = event => {
|
||||
if (event.source === frame.contentWindow && event.data === 'controlled-ready') {
|
||||
removeEventListener('message', listener);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
addEventListener('message', listener);
|
||||
});
|
||||
frame.src = '/controlled/client.html';
|
||||
document.body.appendChild(frame);
|
||||
await ready;
|
||||
const controller = frame.contentWindow.navigator.serviceWorker.controller;
|
||||
if (!controller || controller.state !== 'activated') throw new Error('initial iframe is not controlled');
|
||||
let oldUpdateFound = 0;
|
||||
oldRegistration.addEventListener('updatefound', () => oldUpdateFound++);
|
||||
oldWorker.addEventListener('statechange', () => {
|
||||
if (oldWorker.state === 'redundant') {
|
||||
probe.events.push('event:' + (oldRegistration.active === oldWorker));
|
||||
Promise.resolve().then(() => {
|
||||
probe.events.push('microtask:' + (oldRegistration.active === oldWorker));
|
||||
});
|
||||
}
|
||||
});
|
||||
const result = probe.result;
|
||||
result.unregistered = await oldRegistration.unregister();
|
||||
result.oldWorkerRetained = oldRegistration.active === oldWorker && oldWorker.state === 'activated';
|
||||
result.oldControllerRetained = frame.contentWindow.navigator.serviceWorker.controller === controller;
|
||||
result.lookupAbsent = await sw.getRegistration('/controlled/client.html') === undefined;
|
||||
let rejected = false;
|
||||
try {
|
||||
await sw.register('/controlled/invalid.js', {scope: '/controlled/'});
|
||||
} catch (error) {
|
||||
rejected = error instanceof TypeError;
|
||||
}
|
||||
result.failedReplacementRejected = rejected;
|
||||
result.failedReplacementKeepsOldWorker = oldRegistration.active === oldWorker && oldWorker.state === 'activated';
|
||||
result.failedReplacementStaysUnregistered = await sw.getRegistration('/controlled/client.html') === undefined;
|
||||
const replacement = await sw.register('/controlled/sw.js', {scope: '/controlled/'});
|
||||
probe.replacement = replacement;
|
||||
const replacementWorker = replacement.installing || replacement.waiting || replacement.active;
|
||||
result.newRegistration = replacement !== oldRegistration;
|
||||
result.newWorker = !!replacementWorker && replacementWorker !== oldWorker;
|
||||
await activated(replacement);
|
||||
result.oldWorkerStillActive = oldRegistration.active === oldWorker && oldWorker.state === 'activated';
|
||||
result.oldRegistrationHasNoInstallingWorker = oldRegistration.installing === null;
|
||||
result.oldRegistrationHasNoWaitingWorker = oldRegistration.waiting === null;
|
||||
result.oldRegistrationReceivedNoUpdateFound = oldUpdateFound === 0;
|
||||
result.controllerRetainedAfterReplacement = frame.contentWindow.navigator.serviceWorker.controller === controller;
|
||||
result.oldControllerStillHandlesFetch = await frame.contentWindow.fetch('/controlled/echo').then(response => response.text()) === 'controlled-fetch';
|
||||
frame.remove();
|
||||
result.replacementSurvivesOldClientRemoval = await sw.getRegistration('/controlled/client.html') === replacement;
|
||||
probe.phase = 'registered';
|
||||
})().catch(error => {
|
||||
unregisteredReplacementProbe.error = String(error);
|
||||
unregisteredReplacementProbe.phase = 'error';
|
||||
});
|
||||
@@ -660,6 +660,17 @@ pub(crate) enum ServiceWorkerUnregisterStart {
|
||||
Queued,
|
||||
}
|
||||
|
||||
impl ServiceWorkerUnregisterStart {
|
||||
pub(super) fn complete(job: Option<ServiceWorkerUnregisterJob>, removed: bool) -> Self {
|
||||
if let Some(job) = job {
|
||||
job.send(removed);
|
||||
Self::Queued
|
||||
} else {
|
||||
Self::Completed(removed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct ServiceWorkerVersionLaunchConfig {
|
||||
pub(super) document_url: Url,
|
||||
|
||||
@@ -28,12 +28,6 @@ impl ServiceWorkerPendingClearPhase {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) enum ServiceWorkerPendingClearAction {
|
||||
DeleteRegistration,
|
||||
KeepRegistrationForQueuedJob,
|
||||
}
|
||||
|
||||
pub(super) fn registration_ready_to_delete_locked(
|
||||
state: &ServiceWorkerRuntimeState,
|
||||
registration: &ServiceWorkerRegistration,
|
||||
@@ -70,31 +64,12 @@ pub(super) fn pending_clear_phase_for_registration_locked(
|
||||
pub(super) fn execute_pending_clear_locked(
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
registration_id: ServiceWorkerRegistrationId,
|
||||
action: ServiceWorkerPendingClearAction,
|
||||
) -> Vec<LifecycleProgress> {
|
||||
match action {
|
||||
ServiceWorkerPendingClearAction::DeleteRegistration => {
|
||||
if state.registrations.remove(®istration_id).is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
ServiceWorkerPendingClearAction::KeepRegistrationForQueuedJob => {
|
||||
if !state.registrations.contains_key(®istration_id) {
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
if state.registrations.remove(®istration_id).is_none() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut progress = clear_registration_owner_state_locked(state, registration_id);
|
||||
progress.extend(clear_registration_versions_locked(state, registration_id));
|
||||
if action == ServiceWorkerPendingClearAction::KeepRegistrationForQueuedJob
|
||||
&& let Some(registration) = state.registrations.get_mut(®istration_id)
|
||||
{
|
||||
registration.installing_version_id = None;
|
||||
registration.waiting_version_id = None;
|
||||
registration.active_version_id = None;
|
||||
registration.pending_register_jobs.clear();
|
||||
registration.controlled_client_ids.clear();
|
||||
}
|
||||
progress
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ pub(super) struct ServiceWorkerRegistration {
|
||||
pub(super) installing_version_id: Option<ServiceWorkerVersionId>,
|
||||
pub(super) waiting_version_id: Option<ServiceWorkerVersionId>,
|
||||
pub(super) active_version_id: Option<ServiceWorkerVersionId>,
|
||||
/// Removed from the registration map; existing clients/events may still use it.
|
||||
pub(super) pending_unregistration: bool,
|
||||
pub(super) update_via_cache: ServiceWorkerUpdateViaCache,
|
||||
pub(super) navigation_preload_state: ServiceWorkerNavigationPreloadState,
|
||||
|
||||
@@ -89,7 +89,7 @@ use super::jobs::{
|
||||
use super::matching::service_worker_scope_matches_url;
|
||||
use super::owner_wake::{ServiceWorkerRuntimeOwnerWake, ServiceWorkerRuntimeOwnerWakeSender};
|
||||
use super::pending_clear::{
|
||||
ServiceWorkerPendingClearAction, execute_pending_clear_locked,
|
||||
execute_pending_clear_locked,
|
||||
pending_clear_phase_for_registration_locked, registration_ready_to_delete_locked,
|
||||
};
|
||||
use super::registration::{
|
||||
@@ -596,6 +596,14 @@ fn lifecycle_notifications_for_registration_locked(
|
||||
if events.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
registration_notifications_locked(state, registration_id, events)
|
||||
}
|
||||
|
||||
fn registration_notifications_locked(
|
||||
state: &ServiceWorkerRuntimeState,
|
||||
registration_id: ServiceWorkerRegistrationId,
|
||||
events: Vec<ServiceWorkerLifecycleClientEvent>,
|
||||
) -> Vec<ServiceWorkerLifecycleNotificationDelivery> {
|
||||
let Some(registration) = state.registrations.get(®istration_id) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
@@ -276,7 +276,9 @@ impl ServiceWorkerRuntimeService {
|
||||
let Some(registration_id) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
.find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == registration_key
|
||||
})
|
||||
.map(|registration| registration.id)
|
||||
else {
|
||||
return Ok(false);
|
||||
@@ -373,7 +375,9 @@ impl ServiceWorkerRuntimeService {
|
||||
let Some(registration_id) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
.find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == registration_key
|
||||
})
|
||||
.map(|registration| registration.id)
|
||||
else {
|
||||
return Ok(false);
|
||||
@@ -433,7 +437,9 @@ impl ServiceWorkerRuntimeService {
|
||||
let Some(registration_id) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
.find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == registration_key
|
||||
})
|
||||
.map(|registration| registration.id)
|
||||
else {
|
||||
return Ok(false);
|
||||
|
||||
@@ -204,24 +204,67 @@ impl ServiceWorkerRuntimeService {
|
||||
if !registration_ready_to_delete_locked(state, registration) {
|
||||
return Vec::new();
|
||||
}
|
||||
let registration_key = registration.key();
|
||||
let has_queued_jobs = state.job_coordinator.has_jobs(®istration_key);
|
||||
if has_queued_jobs {
|
||||
self.delete_registration_resources_for_key_locked(®istration_key);
|
||||
let mut progress = execute_pending_clear_locked(
|
||||
state,
|
||||
registration_id,
|
||||
ServiceWorkerPendingClearAction::KeepRegistrationForQueuedJob,
|
||||
// The persistent registration-map entry was removed by Unregister.
|
||||
// Clearing this retired registration must not delete a replacement
|
||||
// that has since been registered at the same storage key and scope.
|
||||
self.clear_registration_locked(state, registration_id)
|
||||
}
|
||||
|
||||
pub(super) fn clear_registration_locked(
|
||||
&self,
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
registration_id: ServiceWorkerRegistrationId,
|
||||
) -> Vec<LifecycleProgress> {
|
||||
let Some(registration) = state.registrations.get(®istration_id) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let versions = [
|
||||
registration.installing_version_id,
|
||||
registration.waiting_version_id,
|
||||
registration.active_version_id,
|
||||
];
|
||||
let mut progress = Vec::new();
|
||||
for version_id in versions.into_iter().flatten() {
|
||||
if let Some(version) = state.versions.get_mut(&version_id) {
|
||||
version.lifecycle_state = ServiceWorkerVersionLifecycleState::Redundant;
|
||||
}
|
||||
progress.extend(
|
||||
lifecycle_notifications_for_registration_locked(
|
||||
state,
|
||||
registration_id,
|
||||
vec![ServiceWorkerLifecycleClientEvent::WorkerStateChanged {
|
||||
version_id,
|
||||
state: "redundant",
|
||||
}],
|
||||
)
|
||||
.into_iter()
|
||||
.map(|notification| LifecycleProgress::NotifyLifecycle(Box::new(notification))),
|
||||
);
|
||||
|
||||
// Update Worker State and Update Registration State enqueue separate
|
||||
// tasks. A statechange callback and its microtasks still see the
|
||||
// worker in its registration slot before the following task clears it.
|
||||
let registration = state
|
||||
.registrations
|
||||
.get_mut(®istration_id)
|
||||
.expect("registration being cleared");
|
||||
if registration.installing_version_id == Some(version_id) {
|
||||
registration.installing_version_id = None;
|
||||
}
|
||||
if registration.waiting_version_id == Some(version_id) {
|
||||
registration.waiting_version_id = None;
|
||||
}
|
||||
if registration.active_version_id == Some(version_id) {
|
||||
registration.active_version_id = None;
|
||||
}
|
||||
progress.extend(
|
||||
registration_notifications_locked(state, registration_id, Vec::new())
|
||||
.into_iter()
|
||||
.map(|notification| LifecycleProgress::NotifyLifecycle(Box::new(notification))),
|
||||
);
|
||||
progress.extend(self.advance_registration_job_queue_locked(state, registration_id));
|
||||
return progress;
|
||||
}
|
||||
self.delete_registration_resources_for_key_locked(®istration_key);
|
||||
execute_pending_clear_locked(
|
||||
state,
|
||||
registration_id,
|
||||
ServiceWorkerPendingClearAction::DeleteRegistration,
|
||||
)
|
||||
progress.extend(execute_pending_clear_locked(state, registration_id));
|
||||
progress
|
||||
}
|
||||
|
||||
pub(super) fn unregistration_progress_for_version_if_ready_locked(
|
||||
|
||||
@@ -484,8 +484,8 @@ impl ServiceWorkerRuntimeService {
|
||||
let _ = waiter.send(());
|
||||
}
|
||||
}
|
||||
LifecycleProgress::UnregisterCompleted(job) => {
|
||||
job.send_all(true);
|
||||
LifecycleProgress::UnregisterCompleted(job, removed) => {
|
||||
job.send_all(removed);
|
||||
}
|
||||
LifecycleProgress::FetchFailed(progress) => {
|
||||
let (job, message) = *progress;
|
||||
|
||||
@@ -89,6 +89,41 @@ impl ServiceWorkerRuntimeService {
|
||||
.is_some_and(|version| version.should_pause_on_start_for_devtools)
|
||||
}
|
||||
|
||||
fn registration_for_register_job_locked(
|
||||
&self,
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
job: &ServiceWorkerQueuedRegisterJob,
|
||||
) -> ServiceWorkerRegistrationId {
|
||||
let key = job.registration_key();
|
||||
if let Some(registration) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| !registration.pending_unregistration && registration.key() == key)
|
||||
{
|
||||
return registration.id;
|
||||
}
|
||||
let id = self.next_unused_registration_id_locked(state);
|
||||
state.registrations.insert(
|
||||
id,
|
||||
ServiceWorkerRegistration {
|
||||
id,
|
||||
storage_key: key.storage_key,
|
||||
scope_url: job.scope_url.clone(),
|
||||
script_url: job.script_url.clone(),
|
||||
installing_version_id: None,
|
||||
waiting_version_id: None,
|
||||
active_version_id: None,
|
||||
pending_unregistration: false,
|
||||
update_via_cache: job.update_via_cache,
|
||||
navigation_preload_state: ServiceWorkerNavigationPreloadState::default(),
|
||||
last_update_check_time_ms: None,
|
||||
pending_register_jobs: HashMap::new(),
|
||||
controlled_client_ids: HashSet::new(),
|
||||
},
|
||||
);
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn start_registration_update(&self, request: ServiceWorkerRegistrationUpdate) {
|
||||
let newest = {
|
||||
let state = self.inner.state.lock();
|
||||
@@ -277,57 +312,24 @@ impl ServiceWorkerRuntimeService {
|
||||
return;
|
||||
}
|
||||
self.restore_stored_registration_for_queued_job_locked(&mut state, &queued_job);
|
||||
let registration_id = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
.map(|registration| registration.id)
|
||||
.unwrap_or_else(|| {
|
||||
ServiceWorkerRegistrationId(
|
||||
self.inner
|
||||
.next_registration_id
|
||||
.fetch_add(1, Ordering::Relaxed),
|
||||
)
|
||||
});
|
||||
state
|
||||
.registrations
|
||||
.entry(registration_id)
|
||||
.or_insert_with(|| ServiceWorkerRegistration {
|
||||
id: registration_id,
|
||||
storage_key: registration_key.storage_key.clone(),
|
||||
scope_url: queued_job.scope_url.clone(),
|
||||
script_url: queued_job.script_url.clone(),
|
||||
installing_version_id: None,
|
||||
waiting_version_id: None,
|
||||
active_version_id: None,
|
||||
pending_unregistration: false,
|
||||
update_via_cache: queued_job.update_via_cache,
|
||||
navigation_preload_state: ServiceWorkerNavigationPreloadState::default(),
|
||||
last_update_check_time_ms: None,
|
||||
pending_register_jobs: HashMap::new(),
|
||||
controlled_client_ids: HashSet::new(),
|
||||
});
|
||||
let (
|
||||
installing_version_id,
|
||||
pending_unregistration,
|
||||
registration_scope_url,
|
||||
registration_update_via_cache,
|
||||
) = {
|
||||
if state.job_coordinator.has_jobs(®istration_key) {
|
||||
state
|
||||
.job_coordinator
|
||||
.enqueue_register(registration_key, queued_job);
|
||||
return;
|
||||
}
|
||||
let registration_id =
|
||||
self.registration_for_register_job_locked(&mut state, &queued_job);
|
||||
let (installing_version_id, registration_scope_url, registration_update_via_cache) = {
|
||||
let Some(registration) = state.registrations.get(®istration_id) else {
|
||||
return;
|
||||
};
|
||||
(
|
||||
registration.installing_version_id,
|
||||
registration.pending_unregistration,
|
||||
registration.scope_url.clone(),
|
||||
registration.update_via_cache,
|
||||
)
|
||||
};
|
||||
if pending_unregistration
|
||||
&& let Some(registration) = state.registrations.get_mut(®istration_id)
|
||||
{
|
||||
registration.pending_unregistration = false;
|
||||
}
|
||||
let can_coalesce_with_installing = queued_job.update_registration_id.is_none()
|
||||
&& installing_version_id
|
||||
.and_then(|version_id| state.versions.get(&version_id))
|
||||
@@ -515,22 +517,23 @@ impl ServiceWorkerRuntimeService {
|
||||
let Some(registration_id) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
.find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == registration_key
|
||||
})
|
||||
.map(|registration| registration.id)
|
||||
else {
|
||||
return ServiceWorkerUnregisterStart::Completed(false);
|
||||
return ServiceWorkerUnregisterStart::complete(job, false);
|
||||
};
|
||||
let Some(registration) = state.registrations.get(®istration_id) else {
|
||||
return ServiceWorkerUnregisterStart::Completed(false);
|
||||
return ServiceWorkerUnregisterStart::complete(job, false);
|
||||
};
|
||||
let register_job_in_progress = registration.installing_version_id.is_some()
|
||||
|| state
|
||||
.pending_main_script_update_checks
|
||||
.contains_key(®istration_id);
|
||||
if registration.pending_unregistration
|
||||
|| state
|
||||
.job_coordinator
|
||||
.has_queued_unregistration(®istration_key)
|
||||
if state
|
||||
.job_coordinator
|
||||
.has_queued_unregistration(®istration_key)
|
||||
{
|
||||
if register_job_in_progress && job.is_some() {
|
||||
state
|
||||
@@ -538,7 +541,7 @@ impl ServiceWorkerRuntimeService {
|
||||
.enqueue_unregister(registration_key, job);
|
||||
return ServiceWorkerUnregisterStart::Queued;
|
||||
}
|
||||
return ServiceWorkerUnregisterStart::Completed(false);
|
||||
return ServiceWorkerUnregisterStart::complete(job, false);
|
||||
}
|
||||
if register_job_in_progress {
|
||||
state
|
||||
@@ -547,14 +550,18 @@ impl ServiceWorkerRuntimeService {
|
||||
(ServiceWorkerUnregisterStart::Queued, Vec::new())
|
||||
} else {
|
||||
let Some(registration) = state.registrations.get_mut(®istration_id) else {
|
||||
return ServiceWorkerUnregisterStart::Completed(false);
|
||||
return ServiceWorkerUnregisterStart::complete(job, false);
|
||||
};
|
||||
registration.pending_unregistration = true;
|
||||
// Unregister removes the registration-map entry immediately;
|
||||
// controlled clients retain only the in-memory registration.
|
||||
self.delete_registration_resources_for_key_locked(®istration_key);
|
||||
let start = ServiceWorkerUnregisterStart::complete(job, true);
|
||||
let progress = self.unregistration_progress_for_registration_if_ready_locked(
|
||||
&mut state,
|
||||
registration_id,
|
||||
);
|
||||
(ServiceWorkerUnregisterStart::Completed(true), progress)
|
||||
(start, progress)
|
||||
}
|
||||
};
|
||||
for progress in progress {
|
||||
@@ -584,21 +591,10 @@ impl ServiceWorkerRuntimeService {
|
||||
};
|
||||
|
||||
self.delete_registration_resources_for_key_locked(®istration_key);
|
||||
if state.job_coordinator.has_jobs(®istration_key) {
|
||||
let mut progress = execute_pending_clear_locked(
|
||||
state,
|
||||
registration_id,
|
||||
ServiceWorkerPendingClearAction::KeepRegistrationForQueuedJob,
|
||||
);
|
||||
progress.extend(self.advance_registration_job_queue_locked(state, registration_id));
|
||||
return progress;
|
||||
}
|
||||
|
||||
execute_pending_clear_locked(
|
||||
state,
|
||||
registration_id,
|
||||
ServiceWorkerPendingClearAction::DeleteRegistration,
|
||||
)
|
||||
let mut progress = self.clear_registration_locked(state, registration_id);
|
||||
progress
|
||||
.extend(self.advance_registration_job_queue_for_key_locked(state, ®istration_key));
|
||||
progress
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -879,7 +875,6 @@ impl ServiceWorkerRuntimeService {
|
||||
registration.scope_url = queued_job.scope_url.clone();
|
||||
registration.update_via_cache = queued_job.update_via_cache;
|
||||
registration.installing_version_id = Some(version_id);
|
||||
registration.pending_unregistration = false;
|
||||
let launch_config = ServiceWorkerVersionLaunchConfig::from_queued_register_job(queued_job);
|
||||
let host = RendererServiceWorkerHost::new_loading(&owner);
|
||||
let should_pause_on_start_for_devtools = self
|
||||
@@ -949,23 +944,37 @@ impl ServiceWorkerRuntimeService {
|
||||
&self,
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
registration_id: ServiceWorkerRegistrationId,
|
||||
) -> Vec<LifecycleProgress> {
|
||||
let Some(key) = state
|
||||
.registrations
|
||||
.get(®istration_id)
|
||||
.map(ServiceWorkerRegistration::key)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
self.advance_registration_job_queue_for_key_locked(state, &key)
|
||||
}
|
||||
|
||||
fn advance_registration_job_queue_for_key_locked(
|
||||
&self,
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
registration_key: &ServiceWorkerRegistrationKey,
|
||||
) -> Vec<LifecycleProgress> {
|
||||
let mut progress = Vec::new();
|
||||
loop {
|
||||
let registration_key = {
|
||||
let Some(registration) = state.registrations.get(®istration_id) else {
|
||||
return progress;
|
||||
};
|
||||
if registration.installing_version_id.is_some()
|
||||
let current = state.registrations.values().find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == *registration_key
|
||||
});
|
||||
if current.is_some_and(|registration| {
|
||||
registration.installing_version_id.is_some()
|
||||
|| state
|
||||
.pending_main_script_update_checks
|
||||
.contains_key(®istration_id)
|
||||
{
|
||||
return progress;
|
||||
}
|
||||
registration.key()
|
||||
};
|
||||
let Some(queued_job) = state.job_coordinator.pop_next(®istration_key) else {
|
||||
.contains_key(®istration.id)
|
||||
}) {
|
||||
return progress;
|
||||
}
|
||||
let current_id = current.map(|registration| registration.id);
|
||||
let Some(queued_job) = state.job_coordinator.pop_next(registration_key) else {
|
||||
return progress;
|
||||
};
|
||||
match queued_job {
|
||||
@@ -978,6 +987,8 @@ impl ServiceWorkerRuntimeService {
|
||||
)));
|
||||
continue;
|
||||
}
|
||||
let registration_id =
|
||||
self.registration_for_register_job_locked(state, &queued_job);
|
||||
// A register queued behind update must wait for that job,
|
||||
// then reuse the matching registration without another fetch.
|
||||
if queued_job.update_registration_id.is_none()
|
||||
@@ -1023,24 +1034,24 @@ impl ServiceWorkerRuntimeService {
|
||||
return progress;
|
||||
}
|
||||
ServiceWorkerQueuedJob::Unregister(mut queued_job) => {
|
||||
let Some(registration) = state.registrations.get_mut(®istration_id) else {
|
||||
return progress;
|
||||
};
|
||||
queued_job.mark_pending();
|
||||
registration.pending_unregistration = true;
|
||||
progress.push(LifecycleProgress::UnregisterCompleted(queued_job));
|
||||
progress.extend(
|
||||
self.unregistration_progress_for_registration_if_ready_locked(
|
||||
state,
|
||||
registration_id,
|
||||
),
|
||||
);
|
||||
if state
|
||||
.registrations
|
||||
.get(®istration_id)
|
||||
.is_some_and(|registration| registration.pending_unregistration)
|
||||
{
|
||||
return progress;
|
||||
progress.push(LifecycleProgress::UnregisterCompleted(
|
||||
queued_job,
|
||||
current_id.is_some(),
|
||||
));
|
||||
if let Some(registration_id) = current_id {
|
||||
state
|
||||
.registrations
|
||||
.get_mut(®istration_id)
|
||||
.expect("current registration")
|
||||
.pending_unregistration = true;
|
||||
self.delete_registration_resources_for_key_locked(registration_key);
|
||||
progress.extend(
|
||||
self.unregistration_progress_for_registration_if_ready_locked(
|
||||
state,
|
||||
registration_id,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,11 +127,9 @@ impl ServiceWorkerRuntimeService {
|
||||
scope_url: stored.scope_url.clone(),
|
||||
storage_key: stored.storage_key.clone(),
|
||||
};
|
||||
if let Some(registration) = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| registration.key() == registration_key)
|
||||
{
|
||||
if let Some(registration) = state.registrations.values().find(|registration| {
|
||||
!registration.pending_unregistration && registration.key() == registration_key
|
||||
}) {
|
||||
return Some(registration.id);
|
||||
}
|
||||
if !matches!(
|
||||
@@ -204,7 +202,7 @@ impl ServiceWorkerRuntimeService {
|
||||
Some(registration_id)
|
||||
}
|
||||
|
||||
fn next_unused_registration_id_locked(
|
||||
pub(super) fn next_unused_registration_id_locked(
|
||||
&self,
|
||||
state: &ServiceWorkerRuntimeState,
|
||||
) -> ServiceWorkerRegistrationId {
|
||||
|
||||
+27
-20
@@ -842,7 +842,7 @@ fn pending_unregistration_waits_for_active_fetch_to_complete_before_delete() {
|
||||
assert_eq!(completion.result.err().as_deref(), Some("done"));
|
||||
}
|
||||
#[test]
|
||||
fn register_aborts_pending_unregistration_and_starts_update() {
|
||||
fn register_after_unregistration_starts_a_distinct_registration() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let registration_id = ServiceWorkerRegistrationId(1);
|
||||
let active_version_id = ServiceWorkerVersionId(1);
|
||||
@@ -884,20 +884,27 @@ fn register_aborts_pending_unregistration_and_starts_update() {
|
||||
);
|
||||
|
||||
let diagnostics = service.diagnostics_snapshot();
|
||||
assert_eq!(diagnostics.registration_count, 1);
|
||||
assert_eq!(diagnostics.registration_count, 2);
|
||||
assert_eq!(diagnostics.version_count, 2);
|
||||
assert_eq!(diagnostics.pending_unregistration_count, 0);
|
||||
assert_eq!(diagnostics.pending_unregistration_count, 1);
|
||||
assert_eq!(diagnostics.queued_register_job_count, 0);
|
||||
assert_eq!(diagnostics.starting_version_count, 1);
|
||||
assert_eq!(
|
||||
service
|
||||
.matching_registration_for_client(&document_url)
|
||||
.expect("register should abort pending unregister and restore visibility")
|
||||
.expect("register should create a visible replacement")
|
||||
.installing()
|
||||
.expect("different script should start installing immediately")
|
||||
.script_url(),
|
||||
&second_script_url
|
||||
);
|
||||
assert_ne!(
|
||||
service
|
||||
.matching_registration_for_client(&document_url)
|
||||
.unwrap()
|
||||
.registration_id(),
|
||||
registration_id,
|
||||
);
|
||||
assert_eq!(
|
||||
service.matching_controller_for_fetch(
|
||||
&document_url,
|
||||
@@ -910,14 +917,14 @@ fn register_aborts_pending_unregistration_and_starts_update() {
|
||||
service.unregister_client(client_id);
|
||||
let diagnostics = service.diagnostics_snapshot();
|
||||
assert_eq!(diagnostics.registration_count, 1);
|
||||
assert_eq!(diagnostics.version_count, 2);
|
||||
assert_eq!(diagnostics.version_count, 1);
|
||||
assert_eq!(diagnostics.pending_unregistration_count, 0);
|
||||
assert_eq!(diagnostics.starting_version_count, 1);
|
||||
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
#[test]
|
||||
fn same_options_register_aborts_pending_unregistration_fast_path() {
|
||||
fn same_options_register_after_unregistration_installs_a_new_worker() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let registration_id = ServiceWorkerRegistrationId(1);
|
||||
let active_version_id = ServiceWorkerVersionId(1);
|
||||
@@ -952,31 +959,31 @@ fn same_options_register_aborts_pending_unregistration_fast_path() {
|
||||
1,
|
||||
completion_queue.sender(),
|
||||
);
|
||||
let completion = pop_register_completion(&mut completion_queue);
|
||||
assert_eq!(completion.request_id, 33);
|
||||
let snapshot = completion
|
||||
.result
|
||||
.expect("same-options register should resolve restored registration");
|
||||
assert_eq!(snapshot.registration_id(), registration_id);
|
||||
assert!(snapshot.installing().is_none());
|
||||
assert_eq!(
|
||||
assert!(!completion_queue.has_ready_task());
|
||||
let snapshot = service
|
||||
.matching_registration_for_client(&document_url)
|
||||
.expect("same-options register should create a replacement");
|
||||
assert_ne!(snapshot.registration_id(), registration_id);
|
||||
assert!(snapshot.active().is_none());
|
||||
assert_ne!(
|
||||
snapshot
|
||||
.active()
|
||||
.expect("active version should remain visible")
|
||||
.installing()
|
||||
.expect("a fresh worker starts installing")
|
||||
.version_id(),
|
||||
active_version_id
|
||||
);
|
||||
let diagnostics = service.diagnostics_snapshot();
|
||||
assert_eq!(diagnostics.registration_count, 1);
|
||||
assert_eq!(diagnostics.version_count, 1);
|
||||
assert_eq!(diagnostics.pending_unregistration_count, 0);
|
||||
assert_eq!(diagnostics.registration_count, 2);
|
||||
assert_eq!(diagnostics.version_count, 2);
|
||||
assert_eq!(diagnostics.pending_unregistration_count, 1);
|
||||
assert_eq!(diagnostics.queued_register_job_count, 0);
|
||||
assert_eq!(diagnostics.starting_version_count, 0);
|
||||
assert_eq!(diagnostics.starting_version_count, 1);
|
||||
assert!(
|
||||
service
|
||||
.matching_registration_for_client(&document_url)
|
||||
.is_some()
|
||||
);
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
#[test]
|
||||
fn resource_store_restores_no_fetch_handler_metadata_for_controlled_fetch() {
|
||||
|
||||
+364
@@ -1,5 +1,369 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn failed_replacement_updates_only_its_registration_object() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let old_id = ServiceWorkerRegistrationId(10);
|
||||
let old_version = ServiceWorkerVersionId(10);
|
||||
let failed_id = ServiceWorkerRegistrationId(20);
|
||||
let failed_version = ServiceWorkerVersionId(20);
|
||||
let scope = url("https://example.test/app/");
|
||||
let document = scope.join("page.html").unwrap();
|
||||
let old_controller = insert_registered_version(
|
||||
&service,
|
||||
old_id,
|
||||
old_version,
|
||||
scope.join("old.js").unwrap(),
|
||||
scope.clone(),
|
||||
[document.clone()],
|
||||
);
|
||||
assert!(service.mark_registration_unregistered(&scope));
|
||||
let mut register_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
let mut lifecycle_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
insert_starting_version_with_register_job(
|
||||
&service,
|
||||
failed_id,
|
||||
failed_version,
|
||||
scope.join("missing.js").unwrap(),
|
||||
scope.clone(),
|
||||
11,
|
||||
register_queue.sender(),
|
||||
);
|
||||
service.watch_registration_lifecycle(
|
||||
scope.clone(),
|
||||
ServiceWorkerRegistrationKey::storage_key_for_scope_url(&scope),
|
||||
crate::window_document_identity::WindowDocumentOwner::for_test(1),
|
||||
lifecycle_queue.sender(),
|
||||
);
|
||||
|
||||
service.finish_worker_start_failed(
|
||||
failed_version,
|
||||
exact_version_run(&service, failed_version),
|
||||
ServiceWorkerVersionStartFailure::ScriptLoad {
|
||||
message: "script was not found".to_owned(),
|
||||
},
|
||||
);
|
||||
assert!(pop_register_completion(&mut register_queue).result.is_err());
|
||||
let Some(crate::page_task_queue::RendererServiceWorkerInternalTask::Lifecycle(notification)) =
|
||||
lifecycle_queue.pop_internal()
|
||||
else {
|
||||
panic!("failed registration objects must receive a slot update");
|
||||
};
|
||||
assert_eq!(notification.registration.registration_id(), failed_id);
|
||||
assert!(notification.registration.installing().is_none());
|
||||
assert!(notification.registration.waiting().is_none());
|
||||
assert!(notification.registration.active().is_none());
|
||||
assert!(notification.events.is_empty());
|
||||
assert!(!lifecycle_queue.has_ready_task());
|
||||
assert_eq!(
|
||||
service.matching_controller_for_document(&document),
|
||||
Some(old_controller)
|
||||
);
|
||||
let state = service.inner.state.lock();
|
||||
assert_eq!(
|
||||
state.registrations[&old_id].active_version_id,
|
||||
Some(old_version)
|
||||
);
|
||||
assert!(state.registrations[&old_id].pending_unregistration);
|
||||
assert!(!state.registrations.contains_key(&failed_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queued_unregistration_after_initial_script_failure_resolves_false() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let registration_id = ServiceWorkerRegistrationId(10);
|
||||
let version_id = ServiceWorkerVersionId(10);
|
||||
let scope_url = url("https://example.test/app/");
|
||||
let mut register_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
let mut unregister_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
insert_starting_version_with_register_job(
|
||||
&service,
|
||||
registration_id,
|
||||
version_id,
|
||||
url("https://example.test/app/missing.js"),
|
||||
scope_url.clone(),
|
||||
11,
|
||||
register_queue.sender(),
|
||||
);
|
||||
assert_eq!(
|
||||
service.start_unregistration(&scope_url, 21, 1, unregister_queue.sender()),
|
||||
ServiceWorkerUnregisterStart::Queued
|
||||
);
|
||||
service.finish_worker_start_failed(
|
||||
version_id,
|
||||
exact_version_run(&service, version_id),
|
||||
ServiceWorkerVersionStartFailure::ScriptLoad {
|
||||
message: "script was not found".to_owned(),
|
||||
},
|
||||
);
|
||||
assert!(pop_register_completion(&mut register_queue).result.is_err());
|
||||
assert!(!pop_unregister_completion(&mut unregister_queue).result);
|
||||
assert_eq!(service.diagnostics_snapshot().registration_count, 0);
|
||||
assert_eq!(service.diagnostics_snapshot().version_count, 0);
|
||||
assert_eq!(
|
||||
service
|
||||
.diagnostics_snapshot()
|
||||
.queued_unregistration_job_count,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_registration_is_removed_from_persistent_map_before_clients_unload() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let registration_id = ServiceWorkerRegistrationId(10);
|
||||
let version_id = ServiceWorkerVersionId(10);
|
||||
let script_url = url("https://example.test/app/worker.js");
|
||||
let scope_url = url("https://example.test/app/");
|
||||
let document_url = url("https://example.test/app/page.html");
|
||||
let old_control = insert_registered_version(
|
||||
&service,
|
||||
registration_id,
|
||||
version_id,
|
||||
script_url.clone(),
|
||||
scope_url.clone(),
|
||||
[document_url.clone()],
|
||||
);
|
||||
service
|
||||
.inner
|
||||
.state
|
||||
.lock()
|
||||
.versions
|
||||
.get_mut(&version_id)
|
||||
.unwrap()
|
||||
.main_script_resource = Some(test_script_resource(&script_url));
|
||||
assert!(
|
||||
service
|
||||
.store_registration_resources_for_test(registration_id, version_id)
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(service.inner.resource_store.lock().registrations().len(), 1);
|
||||
|
||||
assert!(service.mark_registration_unregistered(&scope_url));
|
||||
assert!(
|
||||
service
|
||||
.inner
|
||||
.resource_store
|
||||
.lock()
|
||||
.registrations()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(service.restore_all_stored_registrations().is_empty());
|
||||
assert!(service.inner.state.lock().registrations[®istration_id].pending_unregistration);
|
||||
assert_eq!(
|
||||
service.matching_controller_for_document(&document_url),
|
||||
Some(old_control)
|
||||
);
|
||||
assert!(!service.mark_registration_unregistered(&scope_url));
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_registration_queue_creates_replacement_before_old_client_unloads() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let registration_id = ServiceWorkerRegistrationId(10);
|
||||
let version_id = ServiceWorkerVersionId(10);
|
||||
let script_url = url("https://example.test/app/worker.js");
|
||||
let scope_url = url("https://example.test/app/");
|
||||
let document_url = url("https://example.test/app/page.html");
|
||||
let old_control = insert_registered_version(
|
||||
&service,
|
||||
registration_id,
|
||||
version_id,
|
||||
script_url.clone(),
|
||||
scope_url.clone(),
|
||||
[document_url.clone()],
|
||||
);
|
||||
let installing_id = {
|
||||
let mut state = service.inner.state.lock();
|
||||
let update = test_queued_register_job(&service, script_url.clone(), scope_url.clone());
|
||||
service
|
||||
.create_installing_version_locked(&mut state, registration_id, &update, false)
|
||||
.unwrap()
|
||||
.0
|
||||
};
|
||||
let mut unregister_queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
assert_eq!(
|
||||
service.start_unregistration(&scope_url, 21, 1, unregister_queue.sender()),
|
||||
ServiceWorkerUnregisterStart::Queued
|
||||
);
|
||||
service.start_queued_register_job(test_queued_register_job(
|
||||
&service,
|
||||
script_url.clone(),
|
||||
scope_url.clone(),
|
||||
));
|
||||
assert_eq!(
|
||||
service.diagnostics_snapshot().queued_register_job_count,
|
||||
1,
|
||||
"same-script register must not coalesce across a queued unregister"
|
||||
);
|
||||
|
||||
let progress = {
|
||||
let mut state = service.inner.state.lock();
|
||||
let registration = state.registrations.get_mut(®istration_id).unwrap();
|
||||
registration.installing_version_id = None;
|
||||
registration.waiting_version_id = Some(installing_id);
|
||||
state
|
||||
.versions
|
||||
.get_mut(&installing_id)
|
||||
.unwrap()
|
||||
.lifecycle_state = ServiceWorkerVersionLifecycleState::Installed;
|
||||
service.advance_registration_job_queue_locked(&mut state, registration_id)
|
||||
};
|
||||
let mut launch = None;
|
||||
for action in progress {
|
||||
if let LifecycleProgress::StartWorker(worker) = action {
|
||||
launch = Some(worker);
|
||||
} else {
|
||||
service.run_lifecycle_progress(action);
|
||||
}
|
||||
}
|
||||
assert!(pop_unregister_completion(&mut unregister_queue).result);
|
||||
let launch = launch.expect("a queued replacement starts without waiting for old clients");
|
||||
assert_ne!(launch.params.registration_id, registration_id);
|
||||
assert_eq!(service.diagnostics_snapshot().queued_register_job_count, 0);
|
||||
assert_eq!(
|
||||
service.matching_controller_for_document(&document_url),
|
||||
Some(old_control)
|
||||
);
|
||||
assert!(service.inner.state.lock().registrations[®istration_id].pending_unregistration);
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_registration_is_not_revived_when_a_client_still_uses_it() {
|
||||
for same_script in [true, false] {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let old_id = ServiceWorkerRegistrationId(10);
|
||||
let old_version = ServiceWorkerVersionId(10);
|
||||
let document_url = url("https://example.test/app/page.html");
|
||||
let scope_url = url("https://example.test/app/");
|
||||
let script_url = url("https://example.test/app/worker.js");
|
||||
let old_control = insert_registered_version(
|
||||
&service,
|
||||
old_id,
|
||||
old_version,
|
||||
script_url.clone(),
|
||||
scope_url.clone(),
|
||||
[document_url.clone()],
|
||||
);
|
||||
let client_id = client_id_for_document(&service, &document_url);
|
||||
assert!(service.mark_registration_unregistered(&scope_url));
|
||||
assert_eq!(
|
||||
service.matching_registration_for_client(&document_url),
|
||||
None
|
||||
);
|
||||
|
||||
let queue = crate::page_task_queue::RendererPageServiceWorkerTestHarness::new();
|
||||
service.start_registration(
|
||||
if same_script {
|
||||
script_url
|
||||
} else {
|
||||
url("https://example.test/app/replacement.js")
|
||||
},
|
||||
scope_url.clone(),
|
||||
document_url.clone(),
|
||||
WorkerScriptKind::Classic,
|
||||
test_request_client(&service),
|
||||
WorkerNetworkPolicy::default(),
|
||||
service.browser_context_runtime(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
ServiceWorkerUpdateViaCache::Imports,
|
||||
42,
|
||||
1,
|
||||
queue.sender(),
|
||||
);
|
||||
|
||||
let new_id = {
|
||||
let state = service.inner.state.lock();
|
||||
let current = state
|
||||
.registrations
|
||||
.values()
|
||||
.find(|registration| {
|
||||
registration.scope_url == scope_url && !registration.pending_unregistration
|
||||
})
|
||||
.expect("register should create a current registration");
|
||||
assert_ne!(current.id, old_id, "same_script={same_script}");
|
||||
assert!(current.installing_version_id.is_some());
|
||||
assert_eq!(current.active_version_id, None);
|
||||
assert!(state.registrations[&old_id].pending_unregistration);
|
||||
current.id
|
||||
};
|
||||
assert_eq!(
|
||||
service.matching_controller_for_document(&document_url),
|
||||
Some(old_control),
|
||||
"the existing client keeps its old registration until it unloads"
|
||||
);
|
||||
service.unregister_client(client_id);
|
||||
{
|
||||
let state = service.inner.state.lock();
|
||||
assert!(!state.registrations.contains_key(&old_id));
|
||||
assert!(state.registrations.contains_key(&new_id));
|
||||
}
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unregistered_registration_cleanup_preserves_replacement_resources() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
let scope_url = url("https://example.test/app/");
|
||||
let document_url = url("https://example.test/app/page.html");
|
||||
insert_registered_version(
|
||||
&service,
|
||||
ServiceWorkerRegistrationId(10),
|
||||
ServiceWorkerVersionId(10),
|
||||
url("https://example.test/app/old.js"),
|
||||
scope_url.clone(),
|
||||
[document_url.clone()],
|
||||
);
|
||||
let client_id = client_id_for_document(&service, &document_url);
|
||||
assert!(service.mark_registration_unregistered(&scope_url));
|
||||
let new_id = ServiceWorkerRegistrationId(11);
|
||||
let new_version = ServiceWorkerVersionId(11);
|
||||
let new_script_url = url("https://example.test/app/new.js");
|
||||
insert_registered_version(
|
||||
&service,
|
||||
new_id,
|
||||
new_version,
|
||||
new_script_url.clone(),
|
||||
scope_url,
|
||||
[],
|
||||
);
|
||||
service
|
||||
.inner
|
||||
.state
|
||||
.lock()
|
||||
.versions
|
||||
.get_mut(&new_version)
|
||||
.expect("replacement version")
|
||||
.main_script_resource = Some(test_script_resource(&new_script_url));
|
||||
assert!(
|
||||
service
|
||||
.store_registration_resources_for_test(new_id, new_version)
|
||||
.expect("replacement resources should persist")
|
||||
);
|
||||
service.unregister_client(client_id);
|
||||
assert!(
|
||||
service
|
||||
.inner
|
||||
.state
|
||||
.lock()
|
||||
.registrations
|
||||
.contains_key(&new_id)
|
||||
);
|
||||
let stored = service.inner.resource_store.lock().registrations();
|
||||
assert_eq!(
|
||||
stored.len(),
|
||||
1,
|
||||
"clearing the retired registration must keep the replacement"
|
||||
);
|
||||
assert_eq!(stored[0].script_url, new_script_url);
|
||||
service.terminate_all_for_context_shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registration_lifecycle_watchers_are_partitioned_by_storage_key() {
|
||||
let service = new_service_worker_runtime_service();
|
||||
|
||||
@@ -966,17 +966,32 @@ impl ServiceWorkerRuntimeService {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// A Window may already hold this registration from getRegistration()
|
||||
// while its script loads. Update that exact object before deleting
|
||||
// the map entry; a different retired registration can share its scope.
|
||||
let mut queue_progress = if failed_installing_version {
|
||||
registration_notifications_locked(&state, registration_id, Vec::new())
|
||||
.into_iter()
|
||||
.map(|notification| LifecycleProgress::NotifyLifecycle(Box::new(notification)))
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if failed_installing_version {
|
||||
state.record_target_destroyed(version_id);
|
||||
state.versions.remove(&version_id);
|
||||
} else if let Some(run) = target_run {
|
||||
state.record_target_stopped(version_id, run, "start_failed");
|
||||
}
|
||||
let queue_progress =
|
||||
self.advance_registration_job_queue_locked(&mut state, registration_id);
|
||||
if failed_installing_version {
|
||||
prune_empty_registration_after_start_failure_locked(&mut state, registration_id);
|
||||
queue_progress.extend(self.cleanup_failed_install_version_locked(
|
||||
&mut state,
|
||||
registration_id,
|
||||
version_id,
|
||||
));
|
||||
}
|
||||
queue_progress
|
||||
.extend(self.advance_registration_job_queue_locked(&mut state, registration_id));
|
||||
(
|
||||
completion,
|
||||
queue_progress,
|
||||
@@ -1119,35 +1134,3 @@ fn registration_error_for_start_failure(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn prune_empty_registration_after_start_failure_locked(
|
||||
state: &mut ServiceWorkerRuntimeState,
|
||||
registration_id: ServiceWorkerRegistrationId,
|
||||
) {
|
||||
let should_remove = state
|
||||
.registrations
|
||||
.get(®istration_id)
|
||||
.is_some_and(|registration| {
|
||||
if registration.installing_version_id.is_some()
|
||||
|| registration.waiting_version_id.is_some()
|
||||
|| registration.active_version_id.is_some()
|
||||
|| registration.pending_unregistration
|
||||
|| !registration.pending_register_jobs.is_empty()
|
||||
|| !registration.controlled_client_ids.is_empty()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let registration_key = registration.key();
|
||||
state
|
||||
.job_coordinator
|
||||
.queued_register_job_count(®istration_key)
|
||||
== 0
|
||||
&& state
|
||||
.job_coordinator
|
||||
.queued_unregistration_job_count(®istration_key)
|
||||
== 0
|
||||
});
|
||||
if should_remove {
|
||||
state.registrations.remove(®istration_id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -720,7 +720,7 @@ pub(super) enum LifecycleProgress {
|
||||
),
|
||||
),
|
||||
ForceUpdatePageLoadCompleted(Vec<tokio::sync::oneshot::Sender<()>>),
|
||||
UnregisterCompleted(ServiceWorkerQueuedUnregisterJob),
|
||||
UnregisterCompleted(ServiceWorkerQueuedUnregisterJob, bool),
|
||||
FetchFailed(Box<(ServiceWorkerFetchJob, String)>),
|
||||
StartWorker(Box<ServiceWorkerQueuedLaunch>),
|
||||
StartMainScriptUpdateCheck(
|
||||
|
||||
Reference in New Issue
Block a user