Title: [295088] trunk/Source
Revision
295088
Author
[email protected]
Date
2022-06-01 08:06:41 -0700 (Wed, 01 Jun 2022)

Log Message

Firing a fetch event should not be blocked on main thread
https://bugs.webkit.org/show_bug.cgi?id=241096

Patch by Youenn Fablet <[email protected]> on 2022-06-01
Reviewed by Chris Dumez.

The main thread might be blocked by work done by the web page, like executing _javascript_.
This might delay fetch events handling. This can cause PLT regressions when serving content through a service worker.
To limit the perf penalty, we are now hopping to a work queue to process all WebSWContextManagerConnection messages.
For fetch events and message events, we directly go from that thread to the service worker thread.
For install/activate/push/notification events, we keep going through the main thread as they are not as perf crtical.
Also install/activate should follow the same flow as other events like updatefound which are served through WebSWClientConnection.
We change skipWaiting accordingly to remove races in case the reply would go to main thread directly instead of going through the background work queue.

We do some refactoring to allow getting a ServiceWorkerThreadProxy from a background queue.

* Source/WebCore/workers/service/context/SWContextManager.cpp:
(WebCore::SWContextManager::didSaveScriptsToDisk): Deleted.
* Source/WebCore/workers/service/context/SWContextManager.h:
* Source/WebCore/workers/service/server/SWServerToContextConnection.cpp:
(WebCore::SWServerToContextConnection::skipWaiting): Deleted.
* Source/WebCore/workers/service/server/SWServerToContextConnection.h:
* Source/WebCore/workers/service/server/SWServerWorker.h:
* Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp:
(WebCore::ServiceWorkerThreadProxy::startFetch):
(WebCore::ServiceWorkerThreadProxy::convertFetchToDownload):
(WebCore::ServiceWorkerThreadProxy::continueDidReceiveFetchResponse):
(WebCore::ServiceWorkerThreadProxy::fireMessageEvent):
(WebCore::ServiceWorkerThreadProxy::didSaveScriptsToDisk):
(WebCore::ServiceWorkerThreadProxy::firePushEvent):
(WebCore::ServiceWorkerThreadProxy::firePushSubscriptionChangeEvent):
(WebCore::ServiceWorkerThreadProxy::fireNotificationEvent):
(WebCore::ServiceWorkerThreadProxy::willPostTaskToFireMessageEvent): Deleted.
* Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h:
* Source/WebKit/Shared/WebPreferencesStore.h
* Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp:
(WebKit::WebSWServerToContextConnection::skipWaiting):
* Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h:
* Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in:
* Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp:
(WebKit::WebSWContextManagerConnection::~WebSWContextManagerConnection):
(WebKit::WebSWContextManagerConnection::cancelFetch):
(WebKit::WebSWContextManagerConnection::continueDidReceiveFetchResponse):
(WebKit::WebSWContextManagerConnection::postMessageToServiceWorker):
(WebKit::WebSWContextManagerConnection::didSaveScriptsToDisk):
(WebKit::WebSWContextManagerConnection::convertFetchToDownload):
(WebKit::WebSWContextManagerConnection::skipWaiting):
(WebKit::WebSWContextManagerConnection::skipWaitingCompleted):
* Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h:
* Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in:

Canonical link: https://commits.webkit.org/251183@main

Modified Paths

Diff

Modified: trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp (295087 => 295088)


--- trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -51,7 +51,7 @@
 void ServiceWorkerInternals::setOnline(bool isOnline)
 {
     callOnMainThread([identifier = m_identifier, isOnline] () {
-        if (auto* proxy = SWContextManager::singleton().workerByID(identifier))
+        if (auto* proxy = SWContextManager::singleton().serviceWorkerThreadProxy(identifier))
             proxy->notifyNetworkStateChange(isOnline);
     });
 }
@@ -75,7 +75,7 @@
     }
     callOnMainThread([identifier = m_identifier, data = "" weakThis = WeakPtr { *this }, counter]() mutable {
         SWContextManager::singleton().firePushEvent(identifier, WTFMove(data), [identifier, weakThis = WTFMove(weakThis), counter](bool result) mutable {
-            if (auto* proxy = SWContextManager::singleton().workerByID(identifier)) {
+            if (auto* proxy = SWContextManager::singleton().serviceWorkerThreadProxy(identifier)) {
                 proxy->thread().runLoop().postTaskForMode([weakThis = WTFMove(weakThis), counter, result](auto&) {
                     if (!weakThis)
                         return;
@@ -169,7 +169,7 @@
     ASSERT(!m_lastNavigationWasAppInitiatedPromise);
     m_lastNavigationWasAppInitiatedPromise = WTFMove(promise);
     callOnMainThread([identifier = m_identifier, weakThis = WeakPtr { *this }]() mutable {
-        if (auto* proxy = SWContextManager::singleton().workerByID(identifier)) {
+        if (auto* proxy = SWContextManager::singleton().serviceWorkerThreadProxy(identifier)) {
             proxy->thread().runLoop().postTaskForMode([weakThis = WTFMove(weakThis), appInitiated = proxy->lastNavigationWasAppInitiated()](auto&) {
                 if (!weakThis || !weakThis->m_lastNavigationWasAppInitiatedPromise)
                     return;

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -57,8 +57,8 @@
     uint64_t focusOrder { 0 };
     Vector<String> ancestorOrigins;
 
-    ServiceWorkerClientData isolatedCopy() const &;
-    ServiceWorkerClientData isolatedCopy() &&;
+    WEBCORE_EXPORT ServiceWorkerClientData isolatedCopy() const &;
+    WEBCORE_EXPORT ServiceWorkerClientData isolatedCopy() &&;
 
     WEBCORE_EXPORT static ServiceWorkerClientData from(ScriptExecutionContext&);
 

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -102,8 +102,8 @@
     template<class Encoder> void encode(Encoder&) const;
     template<class Decoder> static std::optional<ServiceWorkerContextData> decode(Decoder&);
 
-    ServiceWorkerContextData isolatedCopy() const &;
-    ServiceWorkerContextData isolatedCopy() &&;
+    WEBCORE_EXPORT ServiceWorkerContextData isolatedCopy() const &;
+    WEBCORE_EXPORT ServiceWorkerContextData isolatedCopy() &&;
 };
 
 template<class Encoder>

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerData.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/ServiceWorkerData.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerData.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -41,8 +41,8 @@
     WorkerType type;
     ServiceWorkerRegistrationIdentifier registrationIdentifier;
 
-    ServiceWorkerData isolatedCopy() const &;
-    ServiceWorkerData isolatedCopy() &&;
+    WEBCORE_EXPORT ServiceWorkerData isolatedCopy() const &;
+    WEBCORE_EXPORT ServiceWorkerData isolatedCopy() &&;
 
     template<class Encoder> void encode(Encoder&) const;
     template<class Decoder> static std::optional<ServiceWorkerData> decode(Decoder&);

Modified: trunk/Source/WebCore/workers/service/context/SWContextManager.cpp (295087 => 295088)


--- trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -40,9 +40,11 @@
     return *sharedManager;
 }
 
-void SWContextManager::setConnection(std::unique_ptr<Connection>&& connection)
+void SWContextManager::setConnection(Ref<Connection>&& connection)
 {
     ASSERT(!m_connection || m_connection->isClosed());
+    if (m_connection)
+        m_connection->stop();
     m_connection = WTFMove(connection);
 }
 
@@ -53,12 +55,18 @@
 
 void SWContextManager::registerServiceWorkerThreadForInstall(Ref<ServiceWorkerThreadProxy>&& serviceWorkerThreadProxy)
 {
+    ASSERT(isMainThread());
+
     auto serviceWorkerIdentifier = serviceWorkerThreadProxy->identifier();
     auto jobDataIdentifier = serviceWorkerThreadProxy->thread().jobDataIdentifier();
     auto* threadProxy = serviceWorkerThreadProxy.ptr();
-    auto result = m_workerMap.add(serviceWorkerIdentifier, WTFMove(serviceWorkerThreadProxy));
-    ASSERT_UNUSED(result, result.isNewEntry);
-    
+
+    {
+        Locker locker { m_workerMapLock };
+        auto result = m_workerMap.add(serviceWorkerIdentifier, WTFMove(serviceWorkerThreadProxy));
+        ASSERT_UNUSED(result, result.isNewEntry);
+    }
+
     threadProxy->thread().start([jobDataIdentifier, serviceWorkerIdentifier](const String& exceptionMessage, bool doesHandleFetch) {
         SWContextManager::singleton().startedServiceWorker(jobDataIdentifier, serviceWorkerIdentifier, exceptionMessage, doesHandleFetch);
     });
@@ -77,22 +85,21 @@
 
 ServiceWorkerThreadProxy* SWContextManager::serviceWorkerThreadProxy(ServiceWorkerIdentifier identifier) const
 {
+    ASSERT(isMainThread());
+    Locker locker { m_workerMapLock };
     return m_workerMap.get(identifier);
 }
 
-void SWContextManager::postMessageToServiceWorker(ServiceWorkerIdentifier destination, MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
+RefPtr<ServiceWorkerThreadProxy> SWContextManager::serviceWorkerThreadProxyFromBackgroundThread(ServiceWorkerIdentifier identifier) const
 {
-    auto* serviceWorker = m_workerMap.get(destination);
-    if (!serviceWorker)
-        return;
-
-    // FIXME: We should pass valid MessagePortChannels.
-    serviceWorker->postMessageToServiceWorker(WTFMove(message), WTFMove(sourceData));
+    Locker locker { m_workerMapLock };
+    RefPtr result = m_workerMap.get(identifier);
+    return result;
 }
 
 void SWContextManager::fireInstallEvent(ServiceWorkerIdentifier identifier)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker)
         return;
 
@@ -101,7 +108,7 @@
 
 void SWContextManager::fireActivateEvent(ServiceWorkerIdentifier identifier)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker)
         return;
 
@@ -110,7 +117,7 @@
 
 void SWContextManager::firePushEvent(ServiceWorkerIdentifier identifier, std::optional<Vector<uint8_t>>&& data, CompletionHandler<void(bool)>&& callback)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker) {
         callback(false);
         return;
@@ -121,7 +128,7 @@
 
 void SWContextManager::firePushSubscriptionChangeEvent(ServiceWorkerIdentifier identifier, std::optional<PushSubscriptionData>&& newSubscriptionData, std::optional<PushSubscriptionData>&& oldSubscriptionData)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker)
         return;
 
@@ -130,7 +137,7 @@
 
 void SWContextManager::fireNotificationEvent(ServiceWorkerIdentifier identifier, NotificationData&& data, NotificationEventType eventType, CompletionHandler<void(bool)>&& callback)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker)
         return;
 
@@ -139,7 +146,14 @@
 
 void SWContextManager::terminateWorker(ServiceWorkerIdentifier identifier, Seconds timeout, Function<void()>&& completionHandler)
 {
-    auto serviceWorker = m_workerMap.take(identifier);
+    RELEASE_LOG(ServiceWorker, "SWContextManager::terminateWorker");
+
+    RefPtr<ServiceWorkerThreadProxy> serviceWorker;
+    {
+        Locker locker { m_workerMapLock };
+        serviceWorker = m_workerMap.take(identifier);
+    }
+
     if (!serviceWorker) {
         if (completionHandler)
             completionHandler();
@@ -148,12 +162,6 @@
     stopWorker(*serviceWorker, timeout, WTFMove(completionHandler));
 }
 
-void SWContextManager::didSaveScriptsToDisk(ServiceWorkerIdentifier identifier, ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
-{
-    if (auto serviceWorker = m_workerMap.get(identifier))
-        serviceWorker->didSaveScriptsToDisk(WTFMove(script), WTFMove(importedScripts));
-}
-
 void SWContextManager::stopWorker(ServiceWorkerThreadProxy& serviceWorker, Seconds timeout, Function<void()>&& completionHandler)
 {
     auto identifier = serviceWorker.identifier();
@@ -179,6 +187,7 @@
 
 void SWContextManager::forEachServiceWorker(const Function<Function<void(ScriptExecutionContext&)>()>& createTask)
 {
+    Locker locker { m_workerMapLock };
     for (auto& worker : m_workerMap.values())
         worker->thread().runLoop().postTask(createTask());
 }
@@ -185,7 +194,7 @@
 
 bool SWContextManager::postTaskToServiceWorker(ServiceWorkerIdentifier identifier, Function<void(ServiceWorkerGlobalScope&)>&& task)
 {
-    auto* serviceWorker = m_workerMap.get(identifier);
+    auto* serviceWorker = serviceWorkerThreadProxy(identifier);
     if (!serviceWorker)
         return false;
 
@@ -211,8 +220,12 @@
 
 void SWContextManager::stopAllServiceWorkers()
 {
-    auto serviceWorkers = WTFMove(m_workerMap);
-    for (auto& serviceWorker : serviceWorkers.values())
+    HashMap<ServiceWorkerIdentifier, Ref<ServiceWorkerThreadProxy>> workerMap;
+    {
+        Locker locker { m_workerMapLock };
+        workerMap = WTFMove(m_workerMap);
+    }
+    for (auto& serviceWorker : workerMap.values())
         stopWorker(serviceWorker, workerTerminationTimeout, [] { });
 }
 

Modified: trunk/Source/WebCore/workers/service/context/SWContextManager.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/context/SWContextManager.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -36,6 +36,7 @@
 #include "ServiceWorkerThreadProxy.h"
 #include <wtf/CompletionHandler.h>
 #include <wtf/HashMap.h>
+#include <wtf/Lock.h>
 #include <wtf/URLHash.h>
 
 namespace WebCore {
@@ -48,7 +49,6 @@
     WEBCORE_EXPORT static SWContextManager& singleton();
 
     class Connection {
-        WTF_MAKE_FAST_ALLOCATED;
     public:
         virtual ~Connection() { }
 
@@ -81,6 +81,10 @@
         virtual bool isThrottleable() const = 0;
         virtual PageIdentifier pageIdentifier() const = 0;
 
+        virtual void ref() const = 0;
+        virtual void deref() const = 0;
+        virtual void stop() = 0;
+
         bool isClosed() const { return m_isClosed; }
 
     protected:
@@ -90,12 +94,12 @@
         bool m_isClosed { false };
     };
 
-    WEBCORE_EXPORT void setConnection(std::unique_ptr<Connection>&&);
+    WEBCORE_EXPORT void setConnection(Ref<Connection>&&);
     WEBCORE_EXPORT Connection* connection() const;
 
     WEBCORE_EXPORT void registerServiceWorkerThreadForInstall(Ref<ServiceWorkerThreadProxy>&&);
     WEBCORE_EXPORT ServiceWorkerThreadProxy* serviceWorkerThreadProxy(ServiceWorkerIdentifier) const;
-    WEBCORE_EXPORT void postMessageToServiceWorker(ServiceWorkerIdentifier destination, MessageWithMessagePorts&&, ServiceWorkerOrClientData&& sourceData);
+    WEBCORE_EXPORT RefPtr<ServiceWorkerThreadProxy> serviceWorkerThreadProxyFromBackgroundThread(ServiceWorkerIdentifier) const;
     WEBCORE_EXPORT void fireInstallEvent(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void fireActivateEvent(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void firePushEvent(ServiceWorkerIdentifier, std::optional<Vector<uint8_t>>&&, CompletionHandler<void(bool)>&&);
@@ -103,7 +107,6 @@
     WEBCORE_EXPORT void fireNotificationEvent(ServiceWorkerIdentifier, NotificationData&&, NotificationEventType, CompletionHandler<void(bool)>&&);
 
     WEBCORE_EXPORT void terminateWorker(ServiceWorkerIdentifier, Seconds timeout, Function<void()>&&);
-    WEBCORE_EXPORT void didSaveScriptsToDisk(ServiceWorkerIdentifier, ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     void forEachServiceWorker(const Function<Function<void(ScriptExecutionContext&)>()>&);
 
@@ -112,8 +115,6 @@
     using ServiceWorkerCreationCallback = void(uint64_t);
     void setServiceWorkerCreationCallback(ServiceWorkerCreationCallback* callback) { m_serviceWorkerCreationCallback = callback; }
 
-    ServiceWorkerThreadProxy* workerByID(ServiceWorkerIdentifier identifier) { return m_workerMap.get(identifier); }
-
     WEBCORE_EXPORT void stopAllServiceWorkers();
 
     static constexpr Seconds workerTerminationTimeout { 10_s };
@@ -129,8 +130,9 @@
 
     void stopWorker(ServiceWorkerThreadProxy&, Seconds, Function<void()>&&);
 
-    HashMap<ServiceWorkerIdentifier, Ref<ServiceWorkerThreadProxy>> m_workerMap;
-    std::unique_ptr<Connection> m_connection;
+    HashMap<ServiceWorkerIdentifier, Ref<ServiceWorkerThreadProxy>> m_workerMap WTF_GUARDED_BY_LOCK(m_workerMapLock);
+    mutable Lock m_workerMapLock;
+    RefPtr<Connection> m_connection;
     ServiceWorkerCreationCallback* m_serviceWorkerCreationCallback { nullptr };
 
     class ServiceWorkerTerminationRequest {

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp (295087 => 295088)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -184,18 +184,53 @@
     }, WorkerRunLoop::defaultMode());
 }
 
+static inline bool isValidFetch(const ResourceRequest& request, const FetchOptions& options, const URL& serviceWorkerURL, const String& referrer)
+{
+    // For exotic service workers, do not enforce checks.
+    if (!serviceWorkerURL.protocolIsInHTTPFamily())
+        return true;
+
+    if (options.mode == FetchOptions::Mode::Navigate) {
+        if (!protocolHostAndPortAreEqual(request.url(), serviceWorkerURL)) {
+            RELEASE_LOG_ERROR(ServiceWorker, "Should not intercept a navigation load that is not same-origin as the service worker URL");
+            RELEASE_ASSERT_WITH_MESSAGE(request.url().host() == serviceWorkerURL.host(), "Hosts do not match");
+            RELEASE_ASSERT_WITH_MESSAGE(request.url().protocol() == serviceWorkerURL.protocol(), "Protocols do not match");
+            RELEASE_ASSERT_WITH_MESSAGE(request.url().port() == serviceWorkerURL.port(), "Ports do not match");
+            return false;
+        }
+        return true;
+    }
+
+    String origin = request.httpOrigin();
+    URL url { origin.isEmpty() ? referrer : origin };
+    if (url.protocolIsInHTTPFamily() && !protocolHostAndPortAreEqual(url, serviceWorkerURL)) {
+        RELEASE_LOG_ERROR(ServiceWorker, "Should not intercept a non navigation load that is not originating from a same-origin context as the service worker URL");
+        ASSERT(url.host() == serviceWorkerURL.host());
+        ASSERT(url.protocol() == serviceWorkerURL.protocol());
+        ASSERT(url.port() == serviceWorkerURL.port());
+        return false;
+    }
+    return true;
+}
+
 void ServiceWorkerThreadProxy::startFetch(SWServerConnectionIdentifier connectionIdentifier, FetchIdentifier fetchIdentifier, Ref<ServiceWorkerFetch::Client>&& client, ResourceRequest&& request, String&& referrer, FetchOptions&& options, bool isServiceWorkerNavigationPreloadEnabled, String&& clientIdentifier, String&& resultingClientIdentifier)
 {
-    RELEASE_LOG(ServiceWorker, "ServiceWorkerThreadProxy::startFetch %llu", fetchIdentifier.toUInt64());
+    ASSERT(!isMainThread());
 
-    auto key = std::make_pair(connectionIdentifier, fetchIdentifier);
+    callOnMainRunLoop([protectedThis = Ref { *this }] {
+        protectedThis->thread().startFetchEventMonitoring();
+    });
 
-    if (m_ongoingFetchTasks.isEmpty())
-        thread().startFetchEventMonitoring();
+    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, connectionIdentifier, client = WTFMove(client), request = request.isolatedCopy(), referrer = WTFMove(referrer).isolatedCopy(), options = WTFMove(options).isolatedCopy(), fetchIdentifier, isServiceWorkerNavigationPreloadEnabled, clientIdentifier = WTFMove(clientIdentifier).isolatedCopy(), resultingClientIdentifier = WTFMove(resultingClientIdentifier).isolatedCopy()] (auto& context) mutable {
+        if (!isValidFetch(request, options, downcast<ServiceWorkerGlobalScope>(context).contextData().scriptURL, referrer)) {
+            client->didNotHandle();
+            return;
+        }
 
-    ASSERT(!m_ongoingFetchTasks.contains(key));
-    m_ongoingFetchTasks.add(key, client.copyRef());
-    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, client = WTFMove(client), request = request.isolatedCopy(), referrer = WTFMove(referrer).isolatedCopy(), options = WTFMove(options).isolatedCopy(), fetchIdentifier, isServiceWorkerNavigationPreloadEnabled, clientIdentifier = WTFMove(clientIdentifier).isolatedCopy(), resultingClientIdentifier = WTFMove(resultingClientIdentifier).isolatedCopy()](auto&) mutable {
+        std::pair key { connectionIdentifier, fetchIdentifier };
+        ASSERT(!m_ongoingFetchTasks.contains(key));
+        m_ongoingFetchTasks.add(key, Ref { client });
+
         thread().queueTaskToFireFetchEvent(WTFMove(client), WTFMove(request), WTFMove(referrer), WTFMove(options), fetchIdentifier, isServiceWorkerNavigationPreloadEnabled, WTFMove(clientIdentifier), WTFMove(resultingClientIdentifier));
     }, WorkerRunLoop::defaultMode());
 }
@@ -204,14 +239,17 @@
 {
     RELEASE_LOG(ServiceWorker, "ServiceWorkerThreadProxy::cancelFetch %llu", fetchIdentifier.toUInt64());
 
-    auto client = m_ongoingFetchTasks.take(std::make_pair(connectionIdentifier, fetchIdentifier));
-    if (!client)
-        return;
+    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, connectionIdentifier, fetchIdentifier] (auto&) {
+        auto client = m_ongoingFetchTasks.take({ connectionIdentifier, fetchIdentifier });
+        if (!client)
+            return;
 
-    if (m_ongoingFetchTasks.isEmpty())
-        thread().stopFetchEventMonitoring();
+        if (m_ongoingFetchTasks.isEmpty()) {
+            callOnMainRunLoop([protectedThis] {
+                protectedThis->thread().stopFetchEventMonitoring();
+            });
+        }
 
-    postTaskForModeToWorkerOrWorkletGlobalScope([client = client.releaseNonNull()] (ScriptExecutionContext&) {
         client->cancel();
     }, WorkerRunLoop::defaultMode());
 }
@@ -220,12 +258,13 @@
 void ServiceWorkerThreadProxy::convertFetchToDownload(SWServerConnectionIdentifier connectionIdentifier, FetchIdentifier fetchIdentifier)
 {
     RELEASE_LOG(ServiceWorker, "ServiceWorkerThreadProxy::convertFetchToDownload %llu", fetchIdentifier.toUInt64());
+    ASSERT(!isMainThread());
 
-    auto client = m_ongoingFetchTasks.take(std::make_pair(connectionIdentifier, fetchIdentifier));
-    if (!client)
-        return;
+    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, connectionIdentifier, fetchIdentifier] (auto&) {
+        auto client = m_ongoingFetchTasks.take({ connectionIdentifier, fetchIdentifier });
+        if (!client)
+            return;
 
-    postTaskForModeToWorkerOrWorkletGlobalScope([client = Ref { *client }] (auto&) {
         client->convertFetchToDownload();
     }, WorkerRunLoop::defaultMode());
 }
@@ -232,11 +271,13 @@
 
 void ServiceWorkerThreadProxy::continueDidReceiveFetchResponse(SWServerConnectionIdentifier connectionIdentifier, FetchIdentifier fetchIdentifier)
 {
-    auto client = m_ongoingFetchTasks.get(std::make_pair(connectionIdentifier, fetchIdentifier));
-    if (!client)
-        return;
+    ASSERT(!isMainThread());
 
-    postTaskForModeToWorkerOrWorkletGlobalScope([client = Ref { *client }] (ScriptExecutionContext&) {
+    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, connectionIdentifier, fetchIdentifier] (auto&) {
+        auto client = m_ongoingFetchTasks.get({ connectionIdentifier, fetchIdentifier });
+        if (!client)
+            return;
+
         client->continueDidReceiveResponse();
     }, WorkerRunLoop::defaultMode());
 }
@@ -245,15 +286,24 @@
 {
     RELEASE_LOG(ServiceWorker, "ServiceWorkerThreadProxy::removeFetch %llu", fetchIdentifier.toUInt64());
 
-    m_ongoingFetchTasks.remove(std::make_pair(connectionIdentifier, fetchIdentifier));
+    postTaskForModeToWorkerOrWorkletGlobalScope([this, protectedThis = Ref { *this }, connectionIdentifier, fetchIdentifier] (auto&) {    m_ongoingFetchTasks.remove(std::make_pair(connectionIdentifier, fetchIdentifier));
 
-    if (m_ongoingFetchTasks.isEmpty())
-        thread().stopFetchEventMonitoring();
+        if (m_ongoingFetchTasks.isEmpty()) {
+            callOnMainRunLoop([protectedThis] {
+                protectedThis->thread().stopFetchEventMonitoring();
+            });
+        }
+    }, WorkerRunLoop::defaultMode());
 }
 
-void ServiceWorkerThreadProxy::postMessageToServiceWorker(MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
+void ServiceWorkerThreadProxy::fireMessageEvent(MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
 {
-    thread().willPostTaskToFireMessageEvent();
+    ASSERT(!isMainThread());
+
+    callOnMainRunLoop([protectedThis = Ref { *this }] {
+        protectedThis->thread().willPostTaskToFireMessageEvent();
+    });
+
     thread().runLoop().postTask([this, protectedThis = Ref { *this }, message = WTFMove(message), sourceData = WTFMove(sourceData)](auto&) mutable {
         thread().queueTaskToPostMessage(WTFMove(message), WTFMove(sourceData));
     });
@@ -261,6 +311,7 @@
 
 void ServiceWorkerThreadProxy::fireInstallEvent()
 {
+    ASSERT(isMainThread());
     thread().willPostTaskToFireInstallEvent();
     thread().runLoop().postTask([this, protectedThis = Ref { *this }](auto&) mutable {
         thread().queueTaskToFireInstallEvent();
@@ -269,6 +320,7 @@
 
 void ServiceWorkerThreadProxy::fireActivateEvent()
 {
+    ASSERT(isMainThread());
     thread().willPostTaskToFireActivateEvent();
     thread().runLoop().postTask([this, protectedThis = Ref { *this }](auto&) mutable {
         thread().queueTaskToFireActivateEvent();
@@ -277,6 +329,8 @@
 
 void ServiceWorkerThreadProxy::didSaveScriptsToDisk(ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
+    ASSERT(!isMainThread());
+
     thread().runLoop().postTask([script = WTFMove(script), importedScripts = WTFMove(importedScripts)](auto& context) mutable {
         downcast<ServiceWorkerGlobalScope>(context).didSaveScriptsToDisk(WTFMove(script), WTFMove(importedScripts));
     });
@@ -284,6 +338,8 @@
 
 void ServiceWorkerThreadProxy::firePushEvent(std::optional<Vector<uint8_t>>&& data, CompletionHandler<void(bool)>&& callback)
 {
+    ASSERT(isMainThread());
+
     if (m_ongoingFunctionalEventTasks.isEmpty())
         thread().startFunctionalEventMonitoring();
 
@@ -306,6 +362,8 @@
 
 void ServiceWorkerThreadProxy::firePushSubscriptionChangeEvent(std::optional<PushSubscriptionData>&& newSubscriptionData, std::optional<PushSubscriptionData>&& oldSubscriptionData)
 {
+    ASSERT(isMainThread());
+
     thread().willPostTaskToFirePushSubscriptionChangeEvent();
     thread().runLoop().postTask([this, protectedThis = Ref { *this }, newSubscriptionData = crossThreadCopy(WTFMove(newSubscriptionData)), oldSubscriptionData = crossThreadCopy(WTFMove(oldSubscriptionData))](auto&) mutable {
         thread().queueTaskToFirePushSubscriptionChangeEvent(WTFMove(newSubscriptionData), WTFMove(oldSubscriptionData));
@@ -314,6 +372,8 @@
 
 void ServiceWorkerThreadProxy::fireNotificationEvent(NotificationData&& data, NotificationEventType eventType, CompletionHandler<void(bool)>&& callback)
 {
+    ASSERT(isMainThread());
+
 #if ENABLE(NOTIFICATION_EVENT)
     if (m_ongoingFunctionalEventTasks.isEmpty())
         thread().startFunctionalEventMonitoring();

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -80,7 +80,8 @@
     WEBCORE_EXPORT void continueDidReceiveFetchResponse(SWServerConnectionIdentifier, FetchIdentifier);
     WEBCORE_EXPORT void removeFetch(SWServerConnectionIdentifier, FetchIdentifier);
 
-    void postMessageToServiceWorker(MessageWithMessagePorts&&, ServiceWorkerOrClientData&&);
+    WEBCORE_EXPORT void fireMessageEvent(MessageWithMessagePorts&&, ServiceWorkerOrClientData&&);
+
     void fireInstallEvent();
     void fireActivateEvent();
     void firePushEvent(std::optional<Vector<uint8_t>>&&, CompletionHandler<void(bool)>&&);
@@ -87,7 +88,7 @@
     void firePushSubscriptionChangeEvent(std::optional<PushSubscriptionData>&& newSubscriptionData, std::optional<PushSubscriptionData>&& oldSubscriptionData);
     void fireNotificationEvent(NotificationData&&, NotificationEventType, CompletionHandler<void(bool)>&&);
 
-    void didSaveScriptsToDisk(ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
+    WEBCORE_EXPORT void didSaveScriptsToDisk(ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     WEBCORE_EXPORT void setLastNavigationWasAppInitiated(bool);
     WEBCORE_EXPORT bool lastNavigationWasAppInitiated();
@@ -118,9 +119,11 @@
     bool m_isTerminatingOrTerminated { false };
 
     ServiceWorkerInspectorProxy m_inspectorProxy;
-    HashMap<std::pair<SWServerConnectionIdentifier, FetchIdentifier>, Ref<ServiceWorkerFetch::Client>> m_ongoingFetchTasks;
     uint64_t m_functionalEventTasksCounter { 0 };
     HashMap<uint64_t, CompletionHandler<void(bool)>> m_ongoingFunctionalEventTasks;
+
+    // Accessed in worker thread.
+    HashMap<std::pair<SWServerConnectionIdentifier, FetchIdentifier>, Ref<ServiceWorkerFetch::Client>> m_ongoingFetchTasks;
 };
 
 } // namespace WebKit

Modified: trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.cpp (295087 => 295088)


--- trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -117,14 +117,6 @@
     callback(server ? server->claim(*worker) : std::nullopt);
 }
 
-void SWServerToContextConnection::skipWaiting(ServiceWorkerIdentifier serviceWorkerIdentifier, CompletionHandler<void()>&& completionHandler)
-{
-    if (auto* worker = SWServerWorker::existingWorkerForIdentifier(serviceWorkerIdentifier))
-        worker->skipWaiting();
-
-    completionHandler();
-}
-
 void SWServerToContextConnection::setScriptResource(ServiceWorkerIdentifier serviceWorkerIdentifier, URL&& scriptURL, ServiceWorkerContextData::ImportedScript&& script)
 {
     if (auto* worker = SWServerWorker::existingWorkerForIdentifier(serviceWorkerIdentifier))

Modified: trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -77,7 +77,6 @@
     WEBCORE_EXPORT void didFinishInstall(const std::optional<ServiceWorkerJobDataIdentifier>&, ServiceWorkerIdentifier, bool wasSuccessful);
     WEBCORE_EXPORT void didFinishActivation(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void setServiceWorkerHasPendingEvents(ServiceWorkerIdentifier, bool hasPendingEvents);
-    WEBCORE_EXPORT void skipWaiting(ServiceWorkerIdentifier, CompletionHandler<void()>&&);
     WEBCORE_EXPORT void workerTerminated(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void matchAll(uint64_t requestIdentifier, ServiceWorkerIdentifier, const ServiceWorkerClientQueryOptions&);
     WEBCORE_EXPORT void claim(ServiceWorkerIdentifier, CompletionHandler<void(std::optional<ExceptionData>&&)>&&);

Modified: trunk/Source/WebCore/workers/service/server/SWServerWorker.h (295087 => 295088)


--- trunk/Source/WebCore/workers/service/server/SWServerWorker.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebCore/workers/service/server/SWServerWorker.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -109,7 +109,7 @@
     void setScriptResource(URL&&, ServiceWorkerContextData::ImportedScript&&);
     void didSaveScriptsToDisk(ScriptBuffer&& mainScript, MemoryCompactRobinHoodHashMap<URL, ScriptBuffer>&& importedScripts);
 
-    void skipWaiting();
+    WEBCORE_EXPORT void skipWaiting();
     bool isSkipWaitingFlagSet() const { return m_isSkipWaitingFlagSet; }
 
     WEBCORE_EXPORT static SWServerWorker* existingWorkerForIdentifier(ServiceWorkerIdentifier);

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp (295087 => 295088)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -89,6 +89,14 @@
         connection->postMessageToServiceWorkerClient(destinationIdentifier, message, sourceIdentifier, sourceOrigin);
 }
 
+void WebSWServerToContextConnection::skipWaiting(uint64_t requestIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier)
+{
+    if (auto* worker = SWServerWorker::existingWorkerForIdentifier(serviceWorkerIdentifier))
+        worker->skipWaiting();
+
+    send(Messages::WebSWContextManagerConnection::SkipWaitingCompleted { requestIdentifier });
+}
+
 void WebSWServerToContextConnection::close()
 {
     send(Messages::WebSWContextManagerConnection::Close { });

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h (295087 => 295088)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -87,6 +87,7 @@
     uint64_t messageSenderDestinationID() const final;
 
     void postMessageToServiceWorkerClient(const WebCore::ScriptExecutionContextIdentifier& destinationIdentifier, const WebCore::MessageWithMessagePorts&, WebCore::ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin);
+    void skipWaiting(uint64_t requestIdentifier, WebCore::ServiceWorkerIdentifier);
 
     // Messages to the SW host WebProcess
     void installServiceWorkerContext(const WebCore::ServiceWorkerContextData&, const WebCore::ServiceWorkerData&, const String& userAgent, WebCore::WorkerThreadMode) final;

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in (295087 => 295088)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in	2022-06-01 15:06:41 UTC (rev 295088)
@@ -30,7 +30,7 @@
     DidFinishInstall(std::optional<WebCore::ServiceWorkerJobDataIdentifier> jobDataIdentifier, WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, bool wasSuccessful)
     DidFinishActivation(WebCore::ServiceWorkerIdentifier identifier)
     SetServiceWorkerHasPendingEvents(WebCore::ServiceWorkerIdentifier identifier, bool hasPendingEvents)
-    SkipWaiting(WebCore::ServiceWorkerIdentifier identifier) -> ()
+    SkipWaiting(uint64_t matchAllRequestIdentifier, WebCore::ServiceWorkerIdentifier identifier)
     WorkerTerminated(WebCore::ServiceWorkerIdentifier identifier)
     FindClientByVisibleIdentifier(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, String clientIdentifier) -> (std::optional<WebCore::ServiceWorkerClientData> data)
     MatchAll(uint64_t matchAllRequestIdentifier, WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, struct WebCore::ServiceWorkerClientQueryOptions options);

Modified: trunk/Source/WebKit/Shared/WebPreferencesStore.h (295087 => 295088)


--- trunk/Source/WebKit/Shared/WebPreferencesStore.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/Shared/WebPreferencesStore.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -27,6 +27,7 @@
 
 #include "Decoder.h"
 #include "Encoder.h"
+#include <wtf/CrossThreadCopier.h>
 #include <wtf/RobinHoodHashMap.h>
 #include <wtf/text/StringHash.h>
 #include <wtf/text/WTFString.h>
@@ -36,6 +37,14 @@
 struct WebPreferencesStore {
     WebPreferencesStore();
 
+    using Value = std::variant<String, bool, uint32_t, double>;
+    using ValueMap = MemoryCompactRobinHoodHashMap<String, Value>;
+    WebPreferencesStore(ValueMap&& values, ValueMap&& overriddenDefaults)
+        : m_values(WTFMove(values))
+        , m_overriddenDefaults(WTFMove(overriddenDefaults))
+    {
+    }
+
     void encode(IPC::Encoder&) const;
     static WARN_UNUSED_RETURN bool decode(IPC::Decoder&, WebPreferencesStore&);
 
@@ -64,12 +73,12 @@
     static void overrideBoolValueForKey(const String& key, bool value);
     static void removeTestRunnerOverrides();
 
-    using Value = std::variant<String, bool, uint32_t, double>;
-
-    using ValueMap = MemoryCompactRobinHoodHashMap<String, Value>;
     ValueMap m_values;
     ValueMap m_overriddenDefaults;
 
+    WebPreferencesStore isolatedCopy() const & { return { crossThreadCopy(m_values), crossThreadCopy(m_overriddenDefaults) }; }
+    WebPreferencesStore isolatedCopy() && { return { crossThreadCopy(WTFMove(m_values)), crossThreadCopy(WTFMove(m_overriddenDefaults)) }; }
+
     static ValueMap& defaults();
 };
 

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp (295087 => 295088)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -90,30 +90,55 @@
     , m_userAgent(standardUserAgent())
 #endif
     , m_userContentController(WebUserContentController::getOrCreate(initializationData.userContentControllerIdentifier))
+    , m_queue(WorkQueue::create("WebSWContextManagerConnection queue", WorkQueue::QOS::UserInitiated))
 {
 #if ENABLE(CONTENT_EXTENSIONS)
     m_userContentController->addContentRuleLists(WTFMove(initializationData.contentRuleLists));
 #endif
 
-    updatePreferencesStore(store);
+    WebPage::updatePreferencesGenerated(store);
+    m_preferencesStore = store;
+
     WebProcess::singleton().disableTermination();
 }
 
-WebSWContextManagerConnection::~WebSWContextManagerConnection() = default;
+WebSWContextManagerConnection::~WebSWContextManagerConnection()
+{
+    auto callbacks = WTFMove(m_skipWaitingCallbacks);
+    for (auto& callback : callbacks.values())
+        callback();
+}
 
 void WebSWContextManagerConnection::establishConnection(CompletionHandler<void()>&& completionHandler)
 {
+    m_connectionToNetworkProcess->addWorkQueueMessageReceiver(Messages::WebSWContextManagerConnection::messageReceiverName(), m_queue.get(), *this);
     m_connectionToNetworkProcess->sendWithAsyncReply(Messages::NetworkConnectionToWebProcess::EstablishSWContextConnection { m_webPageProxyID, m_registrableDomain, m_serviceWorkerPageIdentifier }, WTFMove(completionHandler), 0);
 }
 
-void WebSWContextManagerConnection::updatePreferencesStore(const WebPreferencesStore& store)
+void WebSWContextManagerConnection::stop()
 {
+    ASSERT(isMainRunLoop());
+
+    m_connectionToNetworkProcess->removeWorkQueueMessageReceiver(Messages::WebSWContextManagerConnection::messageReceiverName());
+}
+
+void WebSWContextManagerConnection::updatePreferencesStore(WebPreferencesStore&& store)
+{
+    if (!isMainRunLoop()) {
+        callOnMainRunLoop([protectedThis = Ref { *this }, store = WTFMove(store).isolatedCopy()]() mutable {
+            protectedThis->updatePreferencesStore(WTFMove(store));
+        });
+        return;
+    }
+
     WebPage::updatePreferencesGenerated(store);
-    m_preferencesStore = store;
+    m_preferencesStore = WTFMove(store);
 }
 
 void WebSWContextManagerConnection::updateAppInitiatedValue(ServiceWorkerIdentifier serviceWorkerIdentifier, WebCore::LastNavigationWasAppInitiated lastNavigationWasAppInitiated)
 {
+    ASSERT(isMainRunLoop());
+
     if (auto* serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxy(serviceWorkerIdentifier))
         serviceWorkerThreadProxy->setLastNavigationWasAppInitiated(lastNavigationWasAppInitiated == WebCore::LastNavigationWasAppInitiated::Yes);
 }
@@ -120,51 +145,60 @@
 
 void WebSWContextManagerConnection::installServiceWorker(ServiceWorkerContextData&& contextData, ServiceWorkerData&& workerData, String&& userAgent, WorkerThreadMode workerThreadMode)
 {
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoopAndWait([this, protectedThis = Ref { *this }, contextData = WTFMove(contextData).isolatedCopy(), workerData = WTFMove(workerData).isolatedCopy(), userAgent = WTFMove(userAgent).isolatedCopy(), workerThreadMode]() mutable {
     auto pageConfiguration = pageConfigurationWithEmptyClients(WebProcess::singleton().sessionID());
-
-    pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroupID);
-    pageConfiguration.socketProvider = WebSocketProvider::create(m_webPageProxyID);
-    pageConfiguration.broadcastChannelRegistry = WebProcess::singleton().broadcastChannelRegistry();
-    pageConfiguration.userContentProvider = m_userContentController;
+        pageConfiguration.databaseProvider = WebDatabaseProvider::getOrCreate(m_pageGroupID);
+        pageConfiguration.socketProvider = WebSocketProvider::create(m_webPageProxyID);
+        pageConfiguration.broadcastChannelRegistry = WebProcess::singleton().broadcastChannelRegistry();
+        pageConfiguration.userContentProvider = m_userContentController;
 #if ENABLE(WEB_RTC)
-    pageConfiguration.libWebRTCProvider = makeUniqueRef<RemoteWorkerLibWebRTCProvider>();
+        pageConfiguration.libWebRTCProvider = makeUniqueRef<RemoteWorkerLibWebRTCProvider>();
 #endif
 
-    auto effectiveUserAgent =  WTFMove(userAgent);
-    if (effectiveUserAgent.isNull())
-        effectiveUserAgent = m_userAgent;
+        auto effectiveUserAgent =  WTFMove(userAgent);
+        if (effectiveUserAgent.isNull())
+            effectiveUserAgent = m_userAgent;
 
-    pageConfiguration.loaderClientForMainFrame = makeUniqueRef<RemoteWorkerFrameLoaderClient>(m_webPageProxyID, m_pageID, FrameIdentifier::generate(), effectiveUserAgent);
+        pageConfiguration.loaderClientForMainFrame = makeUniqueRef<RemoteWorkerFrameLoaderClient>(m_webPageProxyID, m_pageID, FrameIdentifier::generate(), effectiveUserAgent);
 
 #if !RELEASE_LOG_DISABLED
-    auto serviceWorkerIdentifier = contextData.serviceWorkerIdentifier;
+        auto serviceWorkerIdentifier = contextData.serviceWorkerIdentifier;
 #endif
-    
-    auto lastNavigationWasAppInitiated = contextData.lastNavigationWasAppInitiated;
-    auto page = makeUniqueRef<Page>(WTFMove(pageConfiguration));
-    if (m_preferencesStore) {
-        WebPage::updateSettingsGenerated(*m_preferencesStore, page->settings());
-        page->settings().setStorageBlockingPolicy(static_cast<StorageBlockingPolicy>(m_preferencesStore->getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
-    }
-    page->setupForRemoteWorker(contextData.scriptURL, contextData.registration.key.topOrigin(), contextData.referrerPolicy);
 
-    std::unique_ptr<WebCore::NotificationClient> notificationClient;
+        auto lastNavigationWasAppInitiated = contextData.lastNavigationWasAppInitiated;
+        auto page = makeUniqueRef<Page>(WTFMove(pageConfiguration));
+        if (m_preferencesStore) {
+            WebPage::updateSettingsGenerated(*m_preferencesStore, page->settings());
+            page->settings().setStorageBlockingPolicy(static_cast<StorageBlockingPolicy>(m_preferencesStore->getUInt32ValueForKey(WebPreferencesKey::storageBlockingPolicyKey())));
+        }
+        page->setupForRemoteWorker(contextData.scriptURL, contextData.registration.key.topOrigin(), contextData.referrerPolicy);
+
+        std::unique_ptr<WebCore::NotificationClient> notificationClient;
 #if ENABLE(NOTIFICATIONS)
-    notificationClient = makeUnique<WebNotificationClient>(nullptr);
+        notificationClient = makeUnique<WebNotificationClient>(nullptr);
 #endif
 
-    auto serviceWorkerThreadProxy = ServiceWorkerThreadProxy::create(WTFMove(page), WTFMove(contextData), WTFMove(workerData), WTFMove(effectiveUserAgent), workerThreadMode, WebProcess::singleton().cacheStorageProvider(), WTFMove(notificationClient));
+        auto serviceWorkerThreadProxy = ServiceWorkerThreadProxy::create(WTFMove(page), WTFMove(contextData), WTFMove(workerData), WTFMove(effectiveUserAgent), workerThreadMode, WebProcess::singleton().cacheStorageProvider(), WTFMove(notificationClient));
 
-    if (lastNavigationWasAppInitiated)
-        serviceWorkerThreadProxy->setLastNavigationWasAppInitiated(lastNavigationWasAppInitiated == WebCore::LastNavigationWasAppInitiated::Yes);
+        if (lastNavigationWasAppInitiated)
+            serviceWorkerThreadProxy->setLastNavigationWasAppInitiated(lastNavigationWasAppInitiated == WebCore::LastNavigationWasAppInitiated::Yes);
 
-    SWContextManager::singleton().registerServiceWorkerThreadForInstall(WTFMove(serviceWorkerThreadProxy));
+        SWContextManager::singleton().registerServiceWorkerThreadForInstall(WTFMove(serviceWorkerThreadProxy));
 
-    RELEASE_LOG(ServiceWorker, "Created service worker %" PRIu64 " in process PID %i", serviceWorkerIdentifier.toUInt64(), getCurrentProcessID());
+        RELEASE_LOG(ServiceWorker, "Created service worker %" PRIu64 " in process PID %i", serviceWorkerIdentifier.toUInt64(), getCurrentProcessID());
+    });
 }
 
 void WebSWContextManagerConnection::setUserAgent(String&& userAgent)
 {
+    if (!isMainThread()) {
+        callOnMainRunLoop([protectedThis = Ref { *this }, userAgent = WTFMove(userAgent).isolatedCopy()]() mutable {
+            protectedThis->setUserAgent(WTFMove(userAgent));
+        });
+        return;
+    }
     m_userAgent = WTFMove(userAgent);
 }
 
@@ -178,65 +212,36 @@
     m_connectionToNetworkProcess->send(Messages::WebSWServerToContextConnection::ScriptContextFailedToStart { jobDataIdentifier, serviceWorkerIdentifier, exceptionMessage }, 0);
 }
 
-static inline bool isValidFetch(const ResourceRequest& request, const FetchOptions& options, const URL& serviceWorkerURL, const String& referrer)
+void WebSWContextManagerConnection::cancelFetch(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier)
 {
-    // For exotic service workers, do not enforce checks.
-    if (!serviceWorkerURL.protocolIsInHTTPFamily())
-        return true;
+    assertIsCurrent(m_queue.get());
 
-    if (options.mode == FetchOptions::Mode::Navigate) {
-        if (!protocolHostAndPortAreEqual(request.url(), serviceWorkerURL)) {
-            RELEASE_LOG_ERROR(ServiceWorker, "Should not intercept a navigation load that is not same-origin as the service worker URL");
-            RELEASE_ASSERT_WITH_MESSAGE(request.url().host() == serviceWorkerURL.host(), "Hosts do not match");
-            RELEASE_ASSERT_WITH_MESSAGE(request.url().protocol() == serviceWorkerURL.protocol(), "Protocols do not match");
-            RELEASE_ASSERT_WITH_MESSAGE(request.url().port() == serviceWorkerURL.port(), "Ports do not match");
-            return false;
-        }
-        return true;
-    }
-
-    String origin = request.httpOrigin();
-    URL url { origin.isEmpty() ? referrer : origin };
-    if (url.protocolIsInHTTPFamily() && !protocolHostAndPortAreEqual(url, serviceWorkerURL)) {
-        RELEASE_LOG_ERROR(ServiceWorker, "Should not intercept a non navigation load that is not originating from a same-origin context as the service worker URL");
-        ASSERT(url.host() == serviceWorkerURL.host());
-        ASSERT(url.protocol() == serviceWorkerURL.protocol());
-        ASSERT(url.port() == serviceWorkerURL.port());
-        return false;
-    }
-    return true;
-}
-
-void WebSWContextManagerConnection::cancelFetch(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier)
-{
-    if (auto* serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxy(serviceWorkerIdentifier))
+    if (auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier))
         serviceWorkerThreadProxy->cancelFetch(serverConnectionIdentifier, fetchIdentifier);
 }
 
 void WebSWContextManagerConnection::continueDidReceiveFetchResponse(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier)
 {
-    auto* serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxy(serviceWorkerIdentifier);
-    RELEASE_LOG(ServiceWorker, "WebSWContextManagerConnection::continueDidReceiveFetchResponse for service worker %llu, fetch identifier %llu, has service worker %d", serviceWorkerIdentifier.toUInt64(), fetchIdentifier.toUInt64(), !!serviceWorkerThreadProxy);
+    assertIsCurrent(m_queue.get());
 
-    if (serviceWorkerThreadProxy)
+    if (auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier))
         serviceWorkerThreadProxy->continueDidReceiveFetchResponse(serverConnectionIdentifier, fetchIdentifier);
 }
 
 void WebSWContextManagerConnection::startFetch(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier, ResourceRequest&& request, FetchOptions&& options, IPC::FormDataReference&& formData, String&& referrer, bool isServiceWorkerNavigationPreloadEnabled, String&& clientIdentifier, String&& resultingClientIdentifier)
 {
-    auto* serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxy(serviceWorkerIdentifier);
+    assertIsCurrent(m_queue.get());
+
+    auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier);
     if (!serviceWorkerThreadProxy) {
         m_connectionToNetworkProcess->send(Messages::ServiceWorkerFetchTask::DidNotHandle { }, fetchIdentifier);
         return;
     }
 
-    serviceWorkerThreadProxy->setLastNavigationWasAppInitiated(request.isAppInitiated());
+    callOnMainRunLoop([serviceWorkerThreadProxy, isAppInitiated = request.isAppInitiated()]() mutable {
+        serviceWorkerThreadProxy->setLastNavigationWasAppInitiated(isAppInitiated);
+    });
 
-    if (!isValidFetch(request, options, serviceWorkerThreadProxy->scriptURL(), referrer)) {
-        m_connectionToNetworkProcess->send(Messages::ServiceWorkerFetchTask::DidNotHandle { }, fetchIdentifier);
-        return;
-    }
-
     auto client = WebServiceWorkerFetchTaskClient::create(m_connectionToNetworkProcess.copyRef(), serviceWorkerIdentifier, serverConnectionIdentifier, fetchIdentifier, request.requester() == ResourceRequest::Requester::Main);
 
     request.setHTTPBody(formData.takeData());
@@ -243,46 +248,92 @@
     serviceWorkerThreadProxy->startFetch(serverConnectionIdentifier, fetchIdentifier, WTFMove(client), WTFMove(request), WTFMove(referrer), WTFMove(options), isServiceWorkerNavigationPreloadEnabled, WTFMove(clientIdentifier), WTFMove(resultingClientIdentifier));
 }
 
-void WebSWContextManagerConnection::postMessageToServiceWorker(ServiceWorkerIdentifier destinationIdentifier, MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
+void WebSWContextManagerConnection::postMessageToServiceWorker(ServiceWorkerIdentifier serviceWorkerIdentifier, MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
 {
-    SWContextManager::singleton().postMessageToServiceWorker(destinationIdentifier, WTFMove(message), WTFMove(sourceData));
+    assertIsCurrent(m_queue.get());
+
+    if (auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier))
+        serviceWorkerThreadProxy->fireMessageEvent(WTFMove(message), WTFMove(sourceData));
 }
 
 void WebSWContextManagerConnection::fireInstallEvent(ServiceWorkerIdentifier identifier)
 {
-    SWContextManager::singleton().fireInstallEvent(identifier);
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([identifier] {
+        SWContextManager::singleton().fireInstallEvent(identifier);
+    });
 }
 
 void WebSWContextManagerConnection::fireActivateEvent(ServiceWorkerIdentifier identifier)
 {
-    SWContextManager::singleton().fireActivateEvent(identifier);
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([identifier] {
+        SWContextManager::singleton().fireActivateEvent(identifier);
+    });
 }
 
 void WebSWContextManagerConnection::firePushEvent(ServiceWorkerIdentifier identifier, const std::optional<IPC::DataReference>& ipcData, CompletionHandler<void(bool)>&& callback)
 {
+    assertIsCurrent(m_queue.get());
+
     std::optional<Vector<uint8_t>> data;
     if (ipcData)
         data = "" { ipcData->data(), ipcData->size() };
-    SWContextManager::singleton().firePushEvent(identifier, WTFMove(data), WTFMove(callback));
+
+    auto inQueueCallback = [queue = m_queue, callback = WTFMove(callback)](bool result) mutable {
+        queue->dispatch([result, callback = WTFMove(callback)]() mutable {
+            callback(result);
+        });
+    };
+
+    callOnMainRunLoop([identifier, data = "" callback = WTFMove(inQueueCallback)]() mutable {
+        SWContextManager::singleton().firePushEvent(identifier, WTFMove(data), WTFMove(callback));
+    });
 }
 
 void WebSWContextManagerConnection::fireNotificationEvent(ServiceWorkerIdentifier identifier, NotificationData&& data, NotificationEventType eventType, CompletionHandler<void(bool)>&& callback)
 {
-    SWContextManager::singleton().fireNotificationEvent(identifier, WTFMove(data), eventType, WTFMove(callback));
+    assertIsCurrent(m_queue.get());
+
+    auto inQueueCallback = [queue = m_queue, callback = WTFMove(callback)](bool result) mutable {
+        queue->dispatch([result, callback = WTFMove(callback)]() mutable {
+            callback(result);
+        });
+    };
+    callOnMainRunLoop([identifier, data = "" eventType, callback = WTFMove(inQueueCallback)]() mutable {
+        SWContextManager::singleton().fireNotificationEvent(identifier, WTFMove(data), eventType, WTFMove(callback));
+    });
 }
 
 void WebSWContextManagerConnection::terminateWorker(ServiceWorkerIdentifier identifier)
 {
-    SWContextManager::singleton().terminateWorker(identifier, SWContextManager::workerTerminationTimeout, nullptr);
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([identifier] {
+        SWContextManager::singleton().terminateWorker(identifier, SWContextManager::workerTerminationTimeout, nullptr);
+    });
 }
 
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-void WebSWContextManagerConnection::didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier identifier, ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
+void WebSWContextManagerConnection::didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
-    SWContextManager::singleton().didSaveScriptsToDisk(identifier, WTFMove(script), WTFMove(importedScripts));
+    assertIsCurrent(m_queue.get());
+
+    if (auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier))
+        serviceWorkerThreadProxy->didSaveScriptsToDisk(WTFMove(script), WTFMove(importedScripts));
 }
 #endif
 
+void WebSWContextManagerConnection::convertFetchToDownload(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier)
+{
+    assertIsCurrent(m_queue.get());
+
+    if (auto serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxyFromBackgroundThread(serviceWorkerIdentifier))
+        serviceWorkerThreadProxy->convertFetchToDownload(serverConnectionIdentifier, fetchIdentifier);
+}
+
 void WebSWContextManagerConnection::postMessageToServiceWorkerClient(const ScriptExecutionContextIdentifier& destinationIdentifier, const MessageWithMessagePorts& message, ServiceWorkerIdentifier sourceIdentifier, const String& sourceOrigin)
 {
     m_connectionToNetworkProcess->send(Messages::WebSWServerToContextConnection::PostMessageToServiceWorkerClient(destinationIdentifier, message, sourceIdentifier, sourceOrigin), 0);
@@ -305,9 +356,21 @@
 
 void WebSWContextManagerConnection::skipWaiting(ServiceWorkerIdentifier serviceWorkerIdentifier, CompletionHandler<void()>&& callback)
 {
-    m_connectionToNetworkProcess->sendWithAsyncReply(Messages::WebSWServerToContextConnection::SkipWaiting(serviceWorkerIdentifier), WTFMove(callback));
+    auto requestIdentifier = ++m_previousRequestIdentifier;
+    m_skipWaitingCallbacks.add(requestIdentifier, WTFMove(callback));
+    m_connectionToNetworkProcess->send(Messages::WebSWServerToContextConnection::SkipWaiting(requestIdentifier, serviceWorkerIdentifier), 0);
 }
 
+void WebSWContextManagerConnection::skipWaitingCompleted(uint64_t requestIdentifier)
+{
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([protectedThis = Ref { *this }, requestIdentifier]() mutable {
+        if (auto callback = protectedThis->m_skipWaitingCallbacks.take(requestIdentifier))
+            callback();
+    });
+}
+
 void WebSWContextManagerConnection::setScriptResource(ServiceWorkerIdentifier serviceWorkerIdentifier, const URL& url, const ServiceWorkerContextData::ImportedScript& script)
 {
     m_connectionToNetworkProcess->send(Messages::WebSWServerToContextConnection::SetScriptResource { serviceWorkerIdentifier, url, script }, 0);
@@ -332,8 +395,12 @@
 
 void WebSWContextManagerConnection::matchAllCompleted(uint64_t requestIdentifier, Vector<ServiceWorkerClientData>&& clientsData)
 {
-    if (auto callback = m_matchAllRequests.take(requestIdentifier))
-        callback(WTFMove(clientsData));
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([protectedThis = Ref { *this }, requestIdentifier, clientsData = crossThreadCopy(WTFMove(clientsData))]() mutable {
+        if (auto callback = protectedThis->m_matchAllRequests.take(requestIdentifier))
+            callback(WTFMove(clientsData));
+    });
 }
 
 void WebSWContextManagerConnection::openWindow(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, const URL& url, OpenWindowCallback&& callback)
@@ -372,6 +439,13 @@
 
 void WebSWContextManagerConnection::close()
 {
+    if (!isMainRunLoop()) {
+        callOnMainRunLoop([protectedThis = Ref { *this }] {
+            protectedThis->close();
+        });
+        return;
+    }
+
     RELEASE_LOG(ServiceWorker, "Service worker process is requested to stop all service workers (already stopped = %d)", isClosed());
     if (isClosed())
         return;
@@ -385,9 +459,13 @@
 
 void WebSWContextManagerConnection::setThrottleState(bool isThrottleable)
 {
-    RELEASE_LOG(ServiceWorker, "Service worker throttleable state is set to %d", isThrottleable);
-    m_isThrottleable = isThrottleable;
-    WebProcess::singleton().setProcessSuppressionEnabled(isThrottleable);
+    assertIsCurrent(m_queue.get());
+
+    callOnMainRunLoop([protectedThis = Ref { *this }, isThrottleable] {
+        RELEASE_LOG(ServiceWorker, "Service worker throttleable state is set to %d", isThrottleable);
+        protectedThis->m_isThrottleable = isThrottleable;
+        WebProcess::singleton().setProcessSuppressionEnabled(isThrottleable);
+    });
 }
 
 bool WebSWContextManagerConnection::isThrottleable() const
@@ -395,12 +473,6 @@
     return m_isThrottleable;
 }
 
-void WebSWContextManagerConnection::convertFetchToDownload(SWServerConnectionIdentifier serverConnectionIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier, FetchIdentifier fetchIdentifier)
-{
-    if (auto* serviceWorkerThreadProxy = SWContextManager::singleton().serviceWorkerThreadProxy(serviceWorkerIdentifier))
-        serviceWorkerThreadProxy->convertFetchToDownload(serverConnectionIdentifier, fetchIdentifier);
-}
-
 void WebSWContextManagerConnection::didFailHeartBeatCheck(ServiceWorkerIdentifier serviceWorkerIdentifier)
 {
     m_connectionToNetworkProcess->send(Messages::WebSWServerToContextConnection::DidFailHeartBeatCheck { serviceWorkerIdentifier }, 0);

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h (295087 => 295088)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2022-06-01 15:06:41 UTC (rev 295088)
@@ -59,9 +59,9 @@
 class WebUserContentController;
 struct RemoteWorkerInitializationData;
 
-class WebSWContextManagerConnection final : public WebCore::SWContextManager::Connection, public IPC::MessageReceiver {
+class WebSWContextManagerConnection final : public WebCore::SWContextManager::Connection, public IPC::Connection::WorkQueueMessageReceiver {
 public:
-    WebSWContextManagerConnection(Ref<IPC::Connection>&&, WebCore::RegistrableDomain&&, std::optional<WebCore::ScriptExecutionContextIdentifier> serviceWorkerPageIdentifier, PageGroupIdentifier, WebPageProxyIdentifier, WebCore::PageIdentifier, const WebPreferencesStore&, RemoteWorkerInitializationData&&);
+    static Ref<WebSWContextManagerConnection> create(Ref<IPC::Connection>&& connection, WebCore::RegistrableDomain&& registrableDomain, std::optional<WebCore::ScriptExecutionContextIdentifier> serviceWorkerPageIdentifier, PageGroupIdentifier pageGroupID, WebPageProxyIdentifier webPageProxyID, WebCore::PageIdentifier pageID, const WebPreferencesStore& store, RemoteWorkerInitializationData&& initializationData) { return adoptRef(*new WebSWContextManagerConnection(WTFMove(connection), WTFMove(registrableDomain), serviceWorkerPageIdentifier, pageGroupID, webPageProxyID, pageID, store, WTFMove(initializationData))); }
     ~WebSWContextManagerConnection();
 
     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) final;
@@ -68,8 +68,11 @@
 
     WebCore::PageIdentifier pageIdentifier() const final { return m_pageID; }
 
+    void ref() const final { IPC::Connection::WorkQueueMessageReceiver::ref(); }
+    void deref() const final { IPC::Connection::WorkQueueMessageReceiver::deref(); }
+
 private:
-    void updatePreferencesStore(const WebPreferencesStore&);
+    WebSWContextManagerConnection(Ref<IPC::Connection>&&, WebCore::RegistrableDomain&&, std::optional<WebCore::ScriptExecutionContextIdentifier> serviceWorkerPageIdentifier, PageGroupIdentifier, WebPageProxyIdentifier, WebCore::PageIdentifier, const WebPreferencesStore&, RemoteWorkerInitializationData&&);
 
     // WebCore::SWContextManager::Connection.
     void establishConnection(CompletionHandler<void()>&&) final;
@@ -89,8 +92,10 @@
     void didFailHeartBeatCheck(WebCore::ServiceWorkerIdentifier) final;
     void setAsInspected(WebCore::ServiceWorkerIdentifier, bool) final;
     void openWindow(WebCore::ServiceWorkerIdentifier, const URL&, OpenWindowCallback&&) final;
+    void stop() final;
 
     // IPC messages.
+    void updatePreferencesStore(WebPreferencesStore&&);
     void serviceWorkerStarted(std::optional<WebCore::ServiceWorkerJobDataIdentifier>, WebCore::ServiceWorkerIdentifier, bool doesHandleFetch) final;
     void serviceWorkerFailedToStart(std::optional<WebCore::ServiceWorkerJobDataIdentifier>, WebCore::ServiceWorkerIdentifier, const String& exceptionMessage) final;
     void installServiceWorker(WebCore::ServiceWorkerContextData&&, WebCore::ServiceWorkerData&&, String&& userAgent, WebCore::WorkerThreadMode);
@@ -108,6 +113,7 @@
     void didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier, WebCore::ScriptBuffer&&, HashMap<URL, WebCore::ScriptBuffer>&& importedScripts);
 #endif
     void matchAllCompleted(uint64_t matchAllRequestIdentifier, Vector<WebCore::ServiceWorkerClientData>&&);
+    void skipWaitingCompleted(uint64_t matchAllRequestIdentifier);
     void setUserAgent(String&& userAgent);
     void close();
     void setThrottleState(bool isThrottleable);
@@ -123,11 +129,13 @@
 
     HashSet<std::unique_ptr<RemoteWorkerFrameLoaderClient>> m_loaders;
     HashMap<uint64_t, WebCore::ServiceWorkerClientsMatchAllCallback> m_matchAllRequests;
+    HashMap<uint64_t, Function<void()>> m_skipWaitingCallbacks;
     uint64_t m_previousRequestIdentifier { 0 };
     String m_userAgent;
     bool m_isThrottleable { true };
     Ref<WebUserContentController> m_userContentController;
     std::optional<WebPreferencesStore> m_preferencesStore;
+    Ref<WorkQueue> m_queue;
 };
 
 } // namespace WebKit

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in (295087 => 295088)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in	2022-06-01 15:06:41 UTC (rev 295088)
@@ -22,7 +22,7 @@
 
 #if ENABLE(SERVICE_WORKER)
 
-messages -> WebSWContextManagerConnection NotRefCounted {
+messages -> WebSWContextManagerConnection {
     InstallServiceWorker(struct WebCore::ServiceWorkerContextData contextData, struct WebCore::ServiceWorkerData workerData, String userAgent, enum:bool WebCore::WorkerThreadMode workerThreadMode)
     UpdateAppInitiatedValue(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, enum:bool WebCore::LastNavigationWasAppInitiated lastNavigationWasAppInitiated)
     StartFetch(WebCore::SWServerConnectionIdentifier serverConnectionIdentifier, WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, WebCore::FetchIdentifier fetchIdentifier, WebCore::ResourceRequest request, struct WebCore::FetchOptions options, IPC::FormDataReference requestBody, String referrer, bool isServiceWorkerNavigationPreloadEnabled, String clientIdentifer, String resutlingClientIdentifier)
@@ -39,6 +39,7 @@
     DidSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, WebCore::ScriptBuffer script, HashMap<URL, WebCore::ScriptBuffer> importedScripts);
 #endif
     MatchAllCompleted(uint64_t matchAllRequestIdentifier, Vector<WebCore::ServiceWorkerClientData> clientsData)
+    SkipWaitingCompleted(uint64_t matchAllRequestIdentifier)
     SetUserAgent(String userAgent)
     UpdatePreferencesStore(struct WebKit::WebPreferencesStore store)
     Close()

Modified: trunk/Source/WebKit/WebProcess/WebProcess.cpp (295087 => 295088)


--- trunk/Source/WebKit/WebProcess/WebProcess.cpp	2022-06-01 15:04:44 UTC (rev 295087)
+++ trunk/Source/WebKit/WebProcess/WebProcess.cpp	2022-06-01 15:06:41 UTC (rev 295088)
@@ -1873,7 +1873,7 @@
     switch (workerType) {
     case RemoteWorkerType::ServiceWorker:
 #if ENABLE(SERVICE_WORKER)
-        SWContextManager::singleton().setConnection(makeUnique<WebSWContextManagerConnection>(ipcConnection, WTFMove(registrableDomain), serviceWorkerPageIdentifier, pageGroupID, webPageProxyID, pageID, store, WTFMove(initializationData)));
+        SWContextManager::singleton().setConnection(WebSWContextManagerConnection::create(ipcConnection, WTFMove(registrableDomain), serviceWorkerPageIdentifier, pageGroupID, webPageProxyID, pageID, store, WTFMove(initializationData)));
         SWContextManager::singleton().connection()->establishConnection(WTFMove(completionHandler));
 #endif
         break;
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to