Title: [253667] trunk
Revision
253667
Author
[email protected]
Date
2019-12-17 18:34:57 -0800 (Tue, 17 Dec 2019)

Log Message

Port service worker code to the HTML5 event loop
https://bugs.webkit.org/show_bug.cgi?id=205359

Reviewed by Ryosuke Niwa.

Source/WebCore:

Port service worker code to the HTML5 event loop. We were mixing using the HTML5 event loop and ScriptExecutionContext::postTask().
This would cause test flakiness because tasks posted via thsse 2 mechanisms could get processed out of order, even though the
service worker specification guarantees a specific ordering.

The new pattern is that we only use WorkerRunLoop::postTask() to hop to the worker thread from the main thread, and not for any work
specified in the service workers specification. Whenever the service workers specifications to "queue a task", we now queue a task
on the ScriptExecutionContext's event loop, with the specified TaskSource.

No new tests, updated existing test.

* dom/ScriptExecutionContext.cpp:
* dom/ScriptExecutionContext.h:
* workers/service/SWClientConnection.cpp:
(WebCore::dispatchToContextThreadIfNecessary):
(WebCore::SWClientConnection::postTaskForJob):
(WebCore::SWClientConnection::updateRegistrationState):
(WebCore::SWClientConnection::updateWorkerState):
(WebCore::SWClientConnection::fireUpdateFoundEvent):
(WebCore::SWClientConnection::notifyClientsOfControllerChange):
(WebCore::SWClientConnection::clearPendingJobs):
* workers/service/ServiceWorker.cpp:
(WebCore::ServiceWorker::updateState):
* workers/service/ServiceWorker.h:
* workers/service/ServiceWorkerContainer.cpp:
(WebCore::ServiceWorkerContainer::updateRegistrationState):
(WebCore::ServiceWorkerContainer::updateWorkerState):
(WebCore::ServiceWorkerContainer::queueTaskToFireUpdateFoundEvent):
(WebCore::ServiceWorkerContainer::queueTaskToDispatchControllerChangeEvent):
* workers/service/ServiceWorkerContainer.h:
* workers/service/ServiceWorkerRegistration.cpp:
(WebCore::ServiceWorkerRegistration::queueTaskToFireUpdateFoundEvent):
* workers/service/ServiceWorkerRegistration.h:
* workers/service/context/SWContextManager.cpp:
(WebCore::SWContextManager::postMessageToServiceWorker):
(WebCore::SWContextManager::fireInstallEvent):
(WebCore::SWContextManager::fireActivateEvent):
* workers/service/context/ServiceWorkerThread.cpp:
(WebCore::ServiceWorkerThread::queueTaskToFireFetchEvent):
(WebCore::ServiceWorkerThread::queueTaskToPostMessage):
(WebCore::ServiceWorkerThread::queueTaskToFireInstallEvent):
(WebCore::ServiceWorkerThread::queueTaskToFireActivateEvent):
* workers/service/context/ServiceWorkerThread.h:
* workers/service/context/ServiceWorkerThreadProxy.cpp:
(WebCore::ServiceWorkerThreadProxy::notifyNetworkStateChange):
(WebCore::ServiceWorkerThreadProxy::startFetch):

LayoutTests:

* http/wpt/service-workers/online-worker.js:
Drop process name check as it causes flakiness depending on whether or not the service worker runs in process.

* http/wpt/service-workers/ready.https.window-expected.txt:
* http/wpt/service-workers/ready.https.window.js:
Include all subtests from https://github.com/web-platform-tests/wpt/pull/20655 now that they are no longer
flaky.

Modified Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (253666 => 253667)


--- trunk/LayoutTests/ChangeLog	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/LayoutTests/ChangeLog	2019-12-18 02:34:57 UTC (rev 253667)
@@ -1,5 +1,20 @@
 2019-12-17  Chris Dumez  <[email protected]>
 
+        Port service worker code to the HTML5 event loop
+        https://bugs.webkit.org/show_bug.cgi?id=205359
+
+        Reviewed by Ryosuke Niwa.
+
+        * http/wpt/service-workers/online-worker.js:
+        Drop process name check as it causes flakiness depending on whether or not the service worker runs in process.
+
+        * http/wpt/service-workers/ready.https.window-expected.txt:
+        * http/wpt/service-workers/ready.https.window.js:
+        Include all subtests from https://github.com/web-platform-tests/wpt/pull/20655 now that they are no longer
+        flaky.
+
+2019-12-17  Chris Dumez  <[email protected]>
+
         Unreviewed, revert r253493 because it broke an Apple internal site
 
         * platform/mac/TestExpectations:

Modified: trunk/LayoutTests/http/wpt/service-workers/online-worker.js (253666 => 253667)


--- trunk/LayoutTests/http/wpt/service-workers/online-worker.js	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/LayoutTests/http/wpt/service-workers/online-worker.js	2019-12-18 02:34:57 UTC (rev 253667)
@@ -27,11 +27,6 @@
             return;
         }
 
-        if (self.internals.processName !== "none" && self.internals.processName !== "WebKitTestRunner Service Worker (localhost)") {
-            event.source.postMessage("FAIL: wrong service worker process name: " + self.internals.processName + "'");
-            return;
-        }
-
         internals.setOnline(true);
         var eventName = await waitForOnlineEvent();
         if (!navigator.onLine)

Modified: trunk/LayoutTests/http/wpt/service-workers/ready.https.window-expected.txt (253666 => 253667)


--- trunk/LayoutTests/http/wpt/service-workers/ready.https.window-expected.txt	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/LayoutTests/http/wpt/service-workers/ready.https.window-expected.txt	2019-12-18 02:34:57 UTC (rev 253667)
@@ -7,4 +7,5 @@
 PASS ready on an iframe that installs a new service worker 
 PASS ready after a longer matched registration registered 
 PASS access ready after it has been resolved 
+PASS resolve ready after unregistering 
 

Modified: trunk/LayoutTests/http/wpt/service-workers/ready.https.window.js (253666 => 253667)


--- trunk/LayoutTests/http/wpt/service-workers/ready.https.window.js	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/LayoutTests/http/wpt/service-workers/ready.https.window.js	2019-12-18 02:34:57 UTC (rev 253667)
@@ -193,3 +193,29 @@
   );
 }, 'access ready after it has been resolved');
 
+promise_test(async t => {
+  const url1 = 'resources/empty-worker.js';
+  const url2 = url1 + '?2';
+  const matchedScope = 'resources/blank.html?ready-after-unregister';
+  const reg1 = await service_worker_unregister_and_register(t, url1, matchedScope);
+  t.add_cleanup(() => reg1.unregister());
+
+  await wait_for_state(t, reg1.installing, 'activating');
+
+  const frame = await with_iframe(matchedScope);
+  t.add_cleanup(() => frame.remove());
+
+  await reg1.unregister();
+
+  // Ready promise should be pending, waiting for a new registration to arrive
+  const readyPromise = frame.contentWindow.navigator.serviceWorker.ready;
+
+  const reg2 = await navigator.serviceWorker.register(url2, { scope: matchedScope });
+  t.add_cleanup(() => reg2.unregister());
+
+  const readyReg = await readyPromise;
+
+  assert_not_equals(reg1, reg2, 'Registrations should be different');
+  assert_equals(readyReg.active.scriptURL, reg2.active.scriptURL, 'Resolves with the second registration');
+}, 'resolve ready after unregistering');
+

Modified: trunk/Source/WebCore/ChangeLog (253666 => 253667)


--- trunk/Source/WebCore/ChangeLog	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/ChangeLog	2019-12-18 02:34:57 UTC (rev 253667)
@@ -1,5 +1,58 @@
 2019-12-17  Chris Dumez  <[email protected]>
 
+        Port service worker code to the HTML5 event loop
+        https://bugs.webkit.org/show_bug.cgi?id=205359
+
+        Reviewed by Ryosuke Niwa.
+
+        Port service worker code to the HTML5 event loop. We were mixing using the HTML5 event loop and ScriptExecutionContext::postTask().
+        This would cause test flakiness because tasks posted via thsse 2 mechanisms could get processed out of order, even though the
+        service worker specification guarantees a specific ordering.
+
+        The new pattern is that we only use WorkerRunLoop::postTask() to hop to the worker thread from the main thread, and not for any work
+        specified in the service workers specification. Whenever the service workers specifications to "queue a task", we now queue a task
+        on the ScriptExecutionContext's event loop, with the specified TaskSource.
+
+        No new tests, updated existing test.
+
+        * dom/ScriptExecutionContext.cpp:
+        * dom/ScriptExecutionContext.h:
+        * workers/service/SWClientConnection.cpp:
+        (WebCore::dispatchToContextThreadIfNecessary):
+        (WebCore::SWClientConnection::postTaskForJob):
+        (WebCore::SWClientConnection::updateRegistrationState):
+        (WebCore::SWClientConnection::updateWorkerState):
+        (WebCore::SWClientConnection::fireUpdateFoundEvent):
+        (WebCore::SWClientConnection::notifyClientsOfControllerChange):
+        (WebCore::SWClientConnection::clearPendingJobs):
+        * workers/service/ServiceWorker.cpp:
+        (WebCore::ServiceWorker::updateState):
+        * workers/service/ServiceWorker.h:
+        * workers/service/ServiceWorkerContainer.cpp:
+        (WebCore::ServiceWorkerContainer::updateRegistrationState):
+        (WebCore::ServiceWorkerContainer::updateWorkerState):
+        (WebCore::ServiceWorkerContainer::queueTaskToFireUpdateFoundEvent):
+        (WebCore::ServiceWorkerContainer::queueTaskToDispatchControllerChangeEvent):
+        * workers/service/ServiceWorkerContainer.h:
+        * workers/service/ServiceWorkerRegistration.cpp:
+        (WebCore::ServiceWorkerRegistration::queueTaskToFireUpdateFoundEvent):
+        * workers/service/ServiceWorkerRegistration.h:
+        * workers/service/context/SWContextManager.cpp:
+        (WebCore::SWContextManager::postMessageToServiceWorker):
+        (WebCore::SWContextManager::fireInstallEvent):
+        (WebCore::SWContextManager::fireActivateEvent):
+        * workers/service/context/ServiceWorkerThread.cpp:
+        (WebCore::ServiceWorkerThread::queueTaskToFireFetchEvent):
+        (WebCore::ServiceWorkerThread::queueTaskToPostMessage):
+        (WebCore::ServiceWorkerThread::queueTaskToFireInstallEvent):
+        (WebCore::ServiceWorkerThread::queueTaskToFireActivateEvent):
+        * workers/service/context/ServiceWorkerThread.h:
+        * workers/service/context/ServiceWorkerThreadProxy.cpp:
+        (WebCore::ServiceWorkerThreadProxy::notifyNetworkStateChange):
+        (WebCore::ServiceWorkerThreadProxy::startFetch):
+
+2019-12-17  Chris Dumez  <[email protected]>
+
         Unreviewed, revert r253493 because it broke an Apple internal site
 
         * html/HTMLFormElement.cpp:

Modified: trunk/Source/WebCore/dom/ScriptExecutionContext.cpp (253666 => 253667)


--- trunk/Source/WebCore/dom/ScriptExecutionContext.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/dom/ScriptExecutionContext.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -598,27 +598,6 @@
     return navigator ? &navigator->serviceWorker() : nullptr;
 }
 
-bool ScriptExecutionContext::postTaskTo(const DocumentOrWorkerIdentifier& contextIdentifier, WTF::Function<void(ScriptExecutionContext&)>&& task)
-{
-    ASSERT(isMainThread());
-
-    bool wasPosted = false;
-    switchOn(contextIdentifier, [&] (DocumentIdentifier identifier) {
-        auto* document = Document::allDocumentsMap().get(identifier);
-        if (!document)
-            return;
-        document->postTask([task = WTFMove(task)](auto& scope) {
-            task(scope);
-        });
-        wasPosted= true;
-    }, [&](ServiceWorkerIdentifier identifier) {
-        wasPosted = SWContextManager::singleton().postTaskToServiceWorker(identifier, [task = WTFMove(task)](auto& scope) {
-            task(scope);
-        });
-    });
-    return wasPosted;
-}
-
 #endif
 
 bool ScriptExecutionContext::postTaskTo(ScriptExecutionContextIdentifier identifier, Task&& task)

Modified: trunk/Source/WebCore/dom/ScriptExecutionContext.h (253666 => 253667)


--- trunk/Source/WebCore/dom/ScriptExecutionContext.h	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/dom/ScriptExecutionContext.h	2019-12-18 02:34:57 UTC (rev 253667)
@@ -253,8 +253,6 @@
 
     ServiceWorkerContainer* serviceWorkerContainer();
     ServiceWorkerContainer* ensureServiceWorkerContainer();
-
-    WEBCORE_EXPORT static bool postTaskTo(const DocumentOrWorkerIdentifier&, WTF::Function<void(ScriptExecutionContext&)>&&);
 #endif
     WEBCORE_EXPORT static bool postTaskTo(ScriptExecutionContextIdentifier, Task&&);
 

Modified: trunk/Source/WebCore/workers/service/SWClientConnection.cpp (253666 => 253667)


--- trunk/Source/WebCore/workers/service/SWClientConnection.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/SWClientConnection.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -40,6 +40,24 @@
 
 namespace WebCore {
 
+static bool dispatchToContextThreadIfNecessary(const DocumentOrWorkerIdentifier& contextIdentifier, WTF::Function<void(ScriptExecutionContext&)>&& task)
+{
+    RELEASE_ASSERT(isMainThread());
+    bool wasPosted = false;
+    switchOn(contextIdentifier, [&] (DocumentIdentifier identifier) {
+        auto* document = Document::allDocumentsMap().get(identifier);
+        if (!document)
+            return;
+        task(*document);
+        wasPosted = true;
+    }, [&](ServiceWorkerIdentifier identifier) {
+        wasPosted = SWContextManager::singleton().postTaskToServiceWorker(identifier, [task = WTFMove(task)](auto& scope) mutable {
+            task(scope);
+        });
+    });
+    return wasPosted;
+}
+
 SWClientConnection::SWClientConnection() = default;
 
 SWClientConnection::~SWClientConnection() = default;
@@ -61,7 +79,7 @@
         LOG_ERROR("Job %s was not found", jobIdentifier.loggingString().utf8().data());
         return false;
     }
-    auto isPosted = ScriptExecutionContext::postTaskTo(iterator->value, [jobIdentifier, task = WTFMove(task)] (ScriptExecutionContext& context) mutable {
+    auto isPosted = dispatchToContextThreadIfNecessary(iterator->value, [jobIdentifier, task = WTFMove(task)] (ScriptExecutionContext& context) mutable {
         if (auto* container = context.serviceWorkerContainer()) {
             if (auto* job = container->job(jobIdentifier))
                 task(*job);
@@ -131,10 +149,8 @@
     });
 
     for (auto* document : Document::allDocuments()) {
-        document->postTask([identifier, state, serviceWorkerData, document](auto&) {
-            if (auto* container = document->serviceWorkerContainer())
-                container->updateRegistrationState(identifier, state, serviceWorkerData);
-        });
+        if (auto* container = document->serviceWorkerContainer())
+            container->updateRegistrationState(identifier, state, serviceWorkerData);
     }
 }
 
@@ -144,16 +160,14 @@
 
     SWContextManager::singleton().forEachServiceWorkerThread([identifier, state] (auto& workerThread) {
         workerThread.thread().runLoop().postTask([identifier, state](ScriptExecutionContext& context) {
-            if (auto* serviceWorker = context.serviceWorker(identifier))
-                serviceWorker->updateState(state);
+            if (auto* container = context.serviceWorkerContainer())
+                container->updateWorkerState(identifier, state);
         });
     });
 
     for (auto* document : Document::allDocuments()) {
-        document->postTask([identifier, document, state](auto&) {
-            if (auto* serviceWorker = document->serviceWorker(identifier))
-                serviceWorker->updateState(state);
-        });
+        if (auto* container = document->serviceWorkerContainer())
+            container->updateWorkerState(identifier, state);
     }
 }
 
@@ -164,15 +178,13 @@
     SWContextManager::singleton().forEachServiceWorkerThread([identifier] (auto& workerThread) {
         workerThread.thread().runLoop().postTask([identifier](ScriptExecutionContext& context) {
             if (auto* container = context.serviceWorkerContainer())
-                container->fireUpdateFoundEvent(identifier);
+                container->queueTaskToFireUpdateFoundEvent(identifier);
         });
     });
 
     for (auto* document : Document::allDocuments()) {
-        document->postTask([document, identifier](auto&) {
-            if (auto* container = document->serviceWorkerContainer())
-                container->fireUpdateFoundEvent(identifier);
-        });
+        if (auto* container = document->serviceWorkerContainer())
+            container->queueTaskToFireUpdateFoundEvent(identifier);
     }
 }
 
@@ -229,12 +241,9 @@
         if (!client)
             continue;
 
-        client->postTask([client, contextIdentifiers, newController](auto&) mutable {
-            ASSERT(!client->activeServiceWorker() || client->activeServiceWorker()->identifier() != newController.identifier);
-            client->setActiveServiceWorker(ServiceWorker::getOrCreate(*client, WTFMove(newController)));
-            if (auto* container = client->serviceWorkerContainer())
-                container->fireControllerChangeEvent();
-        });
+        client->setActiveServiceWorker(ServiceWorker::getOrCreate(*client, WTFMove(newController)));
+        if (auto* container = client->serviceWorkerContainer())
+            container->queueTaskToDispatchControllerChangeEvent();
     }
 }
 
@@ -244,7 +253,7 @@
 
     auto jobSources = WTFMove(m_scheduledJobSources);
     for (auto& keyValue : jobSources) {
-        ScriptExecutionContext::postTaskTo(keyValue.value, [identifier = keyValue.key] (auto& context) {
+        dispatchToContextThreadIfNecessary(keyValue.value, [identifier = keyValue.key] (auto& context) {
             if (auto* container = context.serviceWorkerContainer()) {
                 if (auto* job = container->job(identifier))
                     job->failedWithException(Exception { TypeError, "Internal error"_s });

Modified: trunk/Source/WebCore/workers/service/ServiceWorker.cpp (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorker.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorker.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -81,11 +81,6 @@
 
 void ServiceWorker::updateState(State state)
 {
-    if (m_isSuspended) {
-        m_pendingStateChanges.append(state);
-        return;
-    }
-
     WORKER_RELEASE_LOG_IF_ALLOWED("updateState: Updating service worker %llu state from %hhu to %hhu. Registration ID: %llu", identifier().toUInt64(), m_data.state, state, registrationIdentifier().toUInt64());
     m_data.state = state;
     if (state != State::Installing && !m_isStopped) {
@@ -150,22 +145,6 @@
     return "ServiceWorker";
 }
 
-void ServiceWorker::suspend(ReasonForSuspension)
-{
-    m_isSuspended = true;
-}
-
-void ServiceWorker::resume()
-{
-    m_isSuspended = false;
-    if (!m_pendingStateChanges.isEmpty()) {
-        scriptExecutionContext()->postTask([this, protectedThis = makeRef(*this)](auto&) {
-            for (auto pendingStateChange : std::exchange(m_pendingStateChanges, { }))
-                updateState(pendingStateChange);
-        });
-    }
-}
-
 void ServiceWorker::stop()
 {
     m_isStopped = true;

Modified: trunk/Source/WebCore/workers/service/ServiceWorker.h (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorker.h	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorker.h	2019-12-18 02:34:57 UTC (rev 253667)
@@ -78,8 +78,6 @@
 
     // ActiveDOMObject.
     const char* activeDOMObjectName() const final;
-    void suspend(ReasonForSuspension) final;
-    void resume() final;
     void stop() final;
 
     bool isAlwaysOnLoggingAllowed() const;
@@ -88,9 +86,7 @@
 
     ServiceWorkerData m_data;
     bool m_isStopped { false };
-    bool m_isSuspended { false };
     RefPtr<PendingActivity<ServiceWorker>> m_pendingActivityForEventDispatch;
-    Vector<State> m_pendingStateChanges;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -285,14 +285,27 @@
     if (m_isStopped)
         return;
 
-    RefPtr<ServiceWorker> serviceWorker;
-    if (serviceWorkerData)
-        serviceWorker = ServiceWorker::getOrCreate(*scriptExecutionContext(), ServiceWorkerData { *serviceWorkerData });
+    queueTaskKeepingObjectAlive(*this, TaskSource::DOMManipulation, [this, identifier, state, serviceWorkerData = Optional<ServiceWorkerData> { serviceWorkerData }]() mutable {
+        RefPtr<ServiceWorker> serviceWorker;
+        if (serviceWorkerData)
+            serviceWorker = ServiceWorker::getOrCreate(*scriptExecutionContext(), WTFMove(*serviceWorkerData));
 
-    if (auto* registration = m_registrations.get(identifier))
-        registration->updateStateFromServer(state, WTFMove(serviceWorker));
+        if (auto* registration = m_registrations.get(identifier))
+            registration->updateStateFromServer(state, WTFMove(serviceWorker));
+    });
 }
 
+void ServiceWorkerContainer::updateWorkerState(ServiceWorkerIdentifier identifier, ServiceWorkerState state)
+{
+    if (m_isStopped)
+        return;
+
+    queueTaskKeepingObjectAlive(*this, TaskSource::DOMManipulation, [this, identifier, state] {
+        if (auto* serviceWorker = scriptExecutionContext()->serviceWorker(identifier))
+            serviceWorker->updateState(state);
+    });
+}
+
 void ServiceWorkerContainer::getRegistrations(Ref<DeferredPromise>&& promise)
 {
     if (m_isStopped) {
@@ -342,7 +355,7 @@
     });
 }
 
-void ServiceWorkerContainer::fireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier identifier)
+void ServiceWorkerContainer::queueTaskToFireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier identifier)
 {
 #ifndef NDEBUG
     ASSERT(m_creationThread.ptr() == &Thread::current());
@@ -349,7 +362,7 @@
 #endif
 
     if (auto* registration = m_registrations.get(identifier))
-        registration->fireUpdateFoundEvent();
+        registration->queueTaskToFireUpdateFoundEvent();
 }
 
 void ServiceWorkerContainer::jobResolvedWithRegistration(ServiceWorkerJob& job, ServiceWorkerRegistrationData&& data, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
@@ -550,7 +563,7 @@
     m_registrations.remove(registration.identifier());
 }
 
-void ServiceWorkerContainer::fireControllerChangeEvent()
+void ServiceWorkerContainer::queueTaskToDispatchControllerChangeEvent()
 {
 #ifndef NDEBUG
     ASSERT(m_creationThread.ptr() == &Thread::current());

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContainer.h (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContainer.h	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContainer.h	2019-12-18 02:34:57 UTC (rev 253667)
@@ -68,8 +68,9 @@
 
     void getRegistration(const String& clientURL, Ref<DeferredPromise>&&);
     void updateRegistrationState(ServiceWorkerRegistrationIdentifier, ServiceWorkerRegistrationState, const Optional<ServiceWorkerData>&);
-    void fireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier);
-    void fireControllerChangeEvent();
+    void updateWorkerState(ServiceWorkerIdentifier, ServiceWorkerState);
+    void queueTaskToFireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier);
+    void queueTaskToDispatchControllerChangeEvent();
 
     void postMessage(MessageWithMessagePorts&&, ServiceWorkerData&& sourceData, String&& sourceOrigin);
 

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -182,20 +182,15 @@
     updatePendingActivityForEventDispatch();
 }
 
-void ServiceWorkerRegistration::fireUpdateFoundEvent()
+void ServiceWorkerRegistration::queueTaskToFireUpdateFoundEvent()
 {
     if (m_isStopped)
         return;
 
-    if (m_isSuspended) {
-        m_shouldFireUpdateFoundEventUponResuming = true;
-        return;
-    }
-
     REGISTRATION_RELEASE_LOG_IF_ALLOWED("fireUpdateFoundEvent: Firing updatefound event for registration %llu", identifier().toUInt64());
 
     ASSERT(m_pendingActivityForEventDispatch);
-    dispatchEvent(Event::create(eventNames().updatefoundEvent, Event::CanBubble::No, Event::IsCancelable::No));
+    queueTaskToDispatchEvent(*this, TaskSource::DOMManipulation, Event::create(eventNames().updatefoundEvent, Event::CanBubble::No, Event::IsCancelable::No));
 }
 
 EventTargetInterface ServiceWorkerRegistration::eventTargetInterface() const
@@ -213,22 +208,6 @@
     return "ServiceWorkerRegistration";
 }
 
-void ServiceWorkerRegistration::suspend(ReasonForSuspension)
-{
-    m_isSuspended = true;
-}
-
-void ServiceWorkerRegistration::resume()
-{
-    m_isSuspended = false;
-    if (m_shouldFireUpdateFoundEventUponResuming) {
-        m_shouldFireUpdateFoundEventUponResuming = false;
-        scriptExecutionContext()->postTask([this, protectedThis = makeRef(*this)](auto&) {
-            fireUpdateFoundEvent();
-        });
-    }
-}
-
 void ServiceWorkerRegistration::stop()
 {
     m_isStopped = true;

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.h (253666 => 253667)


--- trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.h	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerRegistration.h	2019-12-18 02:34:57 UTC (rev 253667)
@@ -74,7 +74,7 @@
     const ServiceWorkerRegistrationData& data() const { return m_registrationData; }
 
     void updateStateFromServer(ServiceWorkerRegistrationState, RefPtr<ServiceWorker>&&);
-    void fireUpdateFoundEvent();
+    void queueTaskToFireUpdateFoundEvent();
 
 private:
     ServiceWorkerRegistration(ScriptExecutionContext&, Ref<ServiceWorkerContainer>&&, ServiceWorkerRegistrationData&&);
@@ -87,8 +87,6 @@
 
     // ActiveDOMObject.
     const char* activeDOMObjectName() const final;
-    void suspend(ReasonForSuspension) final;
-    void resume() final;
     void stop() final;
 
     ServiceWorkerRegistrationData m_registrationData;
@@ -99,8 +97,6 @@
     RefPtr<ServiceWorker> m_activeWorker;
 
     bool m_isStopped { false };
-    bool m_isSuspended { false };
-    bool m_shouldFireUpdateFoundEventUponResuming { false };
     RefPtr<PendingActivity<ServiceWorkerRegistration>> m_pendingActivityForEventDispatch;
 };
 

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


--- trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -87,7 +87,9 @@
     ASSERT(!serviceWorker->isTerminatingOrTerminated());
 
     // FIXME: We should pass valid MessagePortChannels.
-    serviceWorker->thread().postMessageToServiceWorker(WTFMove(message), WTFMove(sourceData));
+    serviceWorker->thread().runLoop().postTask([serviceWorker = makeRef(*serviceWorker), message = WTFMove(message), sourceData = WTFMove(sourceData)](auto&) mutable {
+        serviceWorker->thread().queueTaskToPostMessage(WTFMove(message), WTFMove(sourceData));
+    });
 }
 
 void SWContextManager::fireInstallEvent(ServiceWorkerIdentifier identifier)
@@ -96,7 +98,9 @@
     if (!serviceWorker)
         return;
 
-    serviceWorker->thread().fireInstallEvent();
+    serviceWorker->thread().runLoop().postTask([serviceWorker = makeRef(*serviceWorker)](auto&) mutable {
+        serviceWorker->thread().queueTaskToFireInstallEvent();
+    });
 }
 
 void SWContextManager::fireActivateEvent(ServiceWorkerIdentifier identifier)
@@ -105,7 +109,9 @@
     if (!serviceWorker)
         return;
 
-    serviceWorker->thread().fireActivateEvent();
+    serviceWorker->thread().runLoop().postTask([serviceWorker = makeRef(*serviceWorker)](auto&) mutable {
+        serviceWorker->thread().queueTaskToFireActivateEvent();
+    });
 }
 
 void SWContextManager::terminateWorker(ServiceWorkerIdentifier identifier, Seconds timeout, Function<void()>&& completionHandler)

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp (253666 => 253667)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -30,6 +30,7 @@
 
 #include "CacheStorageProvider.h"
 #include "ContentSecurityPolicyResponseHeaders.h"
+#include "EventLoop.h"
 #include "EventNames.h"
 #include "ExtendableMessageEvent.h"
 #include "JSDOMPromise.h"
@@ -93,13 +94,12 @@
     WorkerThread::runEventLoop();
 }
 
-void ServiceWorkerThread::postFetchTask(Ref<ServiceWorkerFetch::Client>&& client, Optional<ServiceWorkerClientIdentifier>&& clientId, ResourceRequest&& request, String&& referrer, FetchOptions&& options)
+void ServiceWorkerThread::queueTaskToFireFetchEvent(Ref<ServiceWorkerFetch::Client>&& client, Optional<ServiceWorkerClientIdentifier>&& clientId, ResourceRequest&& request, String&& referrer, FetchOptions&& options)
 {
-    // FIXME: instead of directly using runLoop(), we should be using something like WorkerGlobalScopeProxy.
-    // FIXME: request and options come straigth from IPC so are already isolated. We should be able to take benefit of that.
-    runLoop().postTaskForMode([client = WTFMove(client), clientId, request = request.isolatedCopy(), referrer = referrer.isolatedCopy(), options = options.isolatedCopy()] (ScriptExecutionContext& context) mutable {
-        ServiceWorkerFetch::dispatchFetchEvent(WTFMove(client), downcast<ServiceWorkerGlobalScope>(context), clientId, WTFMove(request), WTFMove(referrer), WTFMove(options));
-    }, WorkerRunLoop::defaultMode());
+    auto serviceWorkerGlobalScope = makeRef(downcast<ServiceWorkerGlobalScope>(*workerGlobalScope()));
+    serviceWorkerGlobalScope->eventLoop().queueTask(TaskSource::DOMManipulation, [serviceWorkerGlobalScope = serviceWorkerGlobalScope.copyRef(), client = WTFMove(client), clientId, request = WTFMove(request), referrer = WTFMove(referrer), options = WTFMove(options)]() mutable {
+        ServiceWorkerFetch::dispatchFetchEvent(WTFMove(client), serviceWorkerGlobalScope, clientId, WTFMove(request), WTFMove(referrer), WTFMove(options));
+    });
 }
 
 static void fireMessageEvent(ServiceWorkerGlobalScope& scope, MessageWithMessagePorts&& message, ExtendableMessageEventSource&& source, const URL& sourceURL)
@@ -111,16 +111,16 @@
     scope.updateExtendedEventsSet(messageEvent.ptr());
 }
 
-void ServiceWorkerThread::postMessageToServiceWorker(MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
+void ServiceWorkerThread::queueTaskToPostMessage(MessageWithMessagePorts&& message, ServiceWorkerOrClientData&& sourceData)
 {
-    runLoop().postTask([message = WTFMove(message), sourceData = WTFMove(sourceData)] (auto& context) mutable {
-        auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
+    auto serviceWorkerGlobalScope = makeRef(downcast<ServiceWorkerGlobalScope>(*workerGlobalScope()));
+    serviceWorkerGlobalScope->eventLoop().queueTask(TaskSource::DOMManipulation, [serviceWorkerGlobalScope = serviceWorkerGlobalScope.copyRef(), message = WTFMove(message), sourceData = WTFMove(sourceData)]() mutable {
         URL sourceURL;
         ExtendableMessageEventSource source;
         if (WTF::holds_alternative<ServiceWorkerClientData>(sourceData)) {
             RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerClientData>(sourceData)));
 
-            RELEASE_ASSERT(!sourceClient->url().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope.url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope.url(), sourceClient->url()));
+            RELEASE_ASSERT(!sourceClient->url().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope->url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope->url(), sourceClient->url()));
 
             sourceURL = sourceClient->url();
             source = WTFMove(sourceClient);
@@ -127,7 +127,7 @@
         } else {
             RefPtr<ServiceWorker> sourceWorker = ServiceWorker::getOrCreate(serviceWorkerGlobalScope, WTFMove(WTF::get<ServiceWorkerData>(sourceData)));
 
-            RELEASE_ASSERT(!sourceWorker->scriptURL().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope.url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope.url(), sourceWorker->scriptURL()));
+            RELEASE_ASSERT(!sourceWorker->scriptURL().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope->url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope->url(), sourceWorker->scriptURL()));
 
             sourceURL = sourceWorker->scriptURL();
             source = WTFMove(sourceWorker);
@@ -136,12 +136,12 @@
     });
 }
 
-void ServiceWorkerThread::fireInstallEvent()
+void ServiceWorkerThread::queueTaskToFireInstallEvent()
 {
-    runLoop().postTask([jobDataIdentifier = m_data.jobDataIdentifier, serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
-        auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
+    auto serviceWorkerGlobalScope = makeRef(downcast<ServiceWorkerGlobalScope>(*workerGlobalScope()));
+    serviceWorkerGlobalScope->eventLoop().queueTask(TaskSource::DOMManipulation, [serviceWorkerGlobalScope = serviceWorkerGlobalScope.copyRef(), jobDataIdentifier = m_data.jobDataIdentifier, serviceWorkerIdentifier = this->identifier()] {
         auto installEvent = ExtendableEvent::create(eventNames().installEvent, { }, ExtendableEvent::IsTrusted::Yes);
-        serviceWorkerGlobalScope.dispatchEvent(installEvent);
+        serviceWorkerGlobalScope->dispatchEvent(installEvent);
 
         installEvent->whenAllExtendLifetimePromisesAreSettled([jobDataIdentifier, serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&& extendLifetimePromises) {
             bool hasRejectedAnyPromise = false;
@@ -159,12 +159,12 @@
     });
 }
 
-void ServiceWorkerThread::fireActivateEvent()
+void ServiceWorkerThread::queueTaskToFireActivateEvent()
 {
-    runLoop().postTask([serviceWorkerIdentifier = this->identifier()] (ScriptExecutionContext& context) mutable {
-        auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
+    auto serviceWorkerGlobalScope = makeRef(downcast<ServiceWorkerGlobalScope>(*workerGlobalScope()));
+    serviceWorkerGlobalScope->eventLoop().queueTask(TaskSource::DOMManipulation, [serviceWorkerGlobalScope = serviceWorkerGlobalScope.copyRef(), serviceWorkerIdentifier = this->identifier()]() mutable {
         auto activateEvent = ExtendableEvent::create(eventNames().activateEvent, { }, ExtendableEvent::IsTrusted::Yes);
-        serviceWorkerGlobalScope.dispatchEvent(activateEvent);
+        serviceWorkerGlobalScope->dispatchEvent(activateEvent);
 
         activateEvent->whenAllExtendLifetimePromisesAreSettled([serviceWorkerIdentifier](HashSet<Ref<DOMPromise>>&&) {
             callOnMainThread([serviceWorkerIdentifier] () mutable {

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.h (253666 => 253667)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.h	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.h	2019-12-18 02:34:57 UTC (rev 253667)
@@ -56,11 +56,11 @@
     WorkerObjectProxy& workerObjectProxy() const { return m_workerObjectProxy; }
 
     void start(Function<void(const String&, bool)>&&);
-    WEBCORE_EXPORT void postFetchTask(Ref<ServiceWorkerFetch::Client>&&, Optional<ServiceWorkerClientIdentifier>&&, ResourceRequest&&, String&& referrer, FetchOptions&&);
-    WEBCORE_EXPORT void postMessageToServiceWorker(MessageWithMessagePorts&&, ServiceWorkerOrClientData&& sourceData);
+    WEBCORE_EXPORT void queueTaskToFireFetchEvent(Ref<ServiceWorkerFetch::Client>&&, Optional<ServiceWorkerClientIdentifier>&&, ResourceRequest&&, String&& referrer, FetchOptions&&);
+    WEBCORE_EXPORT void queueTaskToPostMessage(MessageWithMessagePorts&&, ServiceWorkerOrClientData&& sourceData);
 
-    void fireInstallEvent();
-    void fireActivateEvent();
+    void queueTaskToFireInstallEvent();
+    void queueTaskToFireActivateEvent();
 
     const ServiceWorkerContextData& contextData() const { return m_data; }
 

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


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2019-12-18 02:32:05 UTC (rev 253666)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2019-12-18 02:34:57 UTC (rev 253667)
@@ -186,7 +186,9 @@
     postTaskForModeToWorkerGlobalScope([isOnline] (ScriptExecutionContext& context) {
         auto& globalScope = downcast<WorkerGlobalScope>(context);
         globalScope.setIsOnline(isOnline);
-        globalScope.dispatchEvent(Event::create(isOnline ? eventNames().onlineEvent : eventNames().offlineEvent, Event::CanBubble::No, Event::IsCancelable::No));
+        globalScope.eventLoop().queueTask(TaskSource::DOMManipulation, [globalScope = makeRef(globalScope), isOnline] {
+            globalScope->dispatchEvent(Event::create(isOnline ? eventNames().onlineEvent : eventNames().offlineEvent, Event::CanBubble::No, Event::IsCancelable::No));
+        });
     }, WorkerRunLoop::defaultMode());
 }
 
@@ -196,7 +198,9 @@
 
     ASSERT(!m_ongoingFetchTasks.contains(key));
     m_ongoingFetchTasks.add(key, client.copyRef());
-    thread().postFetchTask(WTFMove(client), WTFMove(clientId), WTFMove(request), WTFMove(referrer), WTFMove(options));
+    postTaskForModeToWorkerGlobalScope([this, protectedThis = makeRef(*this), client = WTFMove(client), clientId, request = request.isolatedCopy(), referrer = referrer.isolatedCopy(), options = options.isolatedCopy()](auto&) mutable {
+        thread().queueTaskToFireFetchEvent(WTFMove(client), WTFMove(clientId), WTFMove(request), WTFMove(referrer), WTFMove(options));
+    }, WorkerRunLoop::defaultMode());
 }
 
 void ServiceWorkerThreadProxy::cancelFetch(SWServerConnectionIdentifier connectionIdentifier, FetchIdentifier fetchIdentifier)
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to