Title: [292861] trunk
Revision
292861
Author
[email protected]
Date
2022-04-14 01:48:21 -0700 (Thu, 14 Apr 2022)

Log Message

Expose workers as service worker clients and implement registration matching for dedicated workers
https://bugs.webkit.org/show_bug.cgi?id=239066

Reviewed by Chris Dumez.

LayoutTests/imported/w3c:

* web-platform-tests/service-workers/service-worker/local-url-inherit-controller.https-expected.txt:
* web-platform-tests/service-workers/service-worker/worker-client-id.https-expected.txt:
* web-platform-tests/service-workers/service-worker/worker-interception-redirect.https-expected.txt:
* web-platform-tests/service-workers/service-worker/worker-interception.https-expected.txt:

Source/WebCore:

Add support for exposing workers (dedicated and shared) as service worker clients.
Add support for setting the controlling registration for dedicated workers
(a follow-up patch should handle shared workers).
To properly handle loads coming from a worker, we properly set clientIdentifier and registration identifier
from the worker context, instead of from the worker's document.

Small refactoring to pass additional data to worker through WorkerInitializationData.
This is used to set the context ID and context controlling service worker.

Adding a specific check in CachedResourceLoader to not reuse the cache in case the service worker modes are different.
A potential issue is that the service workers are the same (0) as one request is the main request
and the second request is the request triggered by service worker to answer the first request.

Properly support blob URL matching directly in WorkerScriptLoader for workers.

Test: http/wpt/service-workers/controlled-dedicatedworker.https.html

* WebCore.xcodeproj/project.pbxproj:
* dom/Document.h:
* dom/ScriptExecutionContext.h:
* loader/DocumentLoader.cpp:
* loader/FetchOptions.h:
* loader/ThreadableLoader.cpp:
* loader/WorkerThreadableLoader.cpp:
* loader/cache/CachedResourceLoader.cpp:
* workers/DedicatedWorkerThread.cpp:
* workers/Worker.cpp:
* workers/Worker.h:
* workers/WorkerGlobalScope.cpp:
* workers/WorkerGlobalScope.h:
* workers/WorkerGlobalScopeProxy.h:
* workers/WorkerInitializationData.h: Added.
* workers/WorkerMessagingProxy.cpp:
* workers/WorkerMessagingProxy.h:
* workers/WorkerOrWorkletGlobalScope.cpp:
* workers/WorkerOrWorkletGlobalScope.h:
* workers/WorkerScriptLoader.cpp:
* workers/WorkerScriptLoader.h:
* workers/WorkerThread.cpp:
* workers/WorkerThread.h:
* workers/service/SWClientConnection.cpp:
* workers/service/ServiceWorker.h:
* workers/service/ServiceWorkerClientData.cpp:
* workers/service/ServiceWorkerClientType.h:
* workers/service/ServiceWorkerContainer.cpp:
* workers/service/context/ServiceWorkerThread.cpp:
* workers/shared/SharedWorkerScriptLoader.h:
* workers/shared/context/SharedWorkerThreadProxy.cpp:

Source/WebKit:

Reuse the same strategy for DedicatedWorkers as for Documents to match registrations and control then:
- Do matching in network process
- If matching, send a message to WebProcess to set the matching registration data.
Add specific handling for worker registration rematching in case of redirections:
- If redirection comes from service worker (via respondWith), do rematching.
- If redirection comes from network, do not do rematching.

* NetworkProcess/NetworkResourceLoader.cpp:
* NetworkProcess/ServiceWorker/ServiceWorkerFetchTask.cpp:
* NetworkProcess/ServiceWorker/WebSWServerConnection.cpp:
* WebProcess/Network/WebLoaderStrategy.cpp:
* WebProcess/Storage/WebSWClientConnection.cpp:
* WebProcess/Storage/WebSWClientConnection.h:
* WebProcess/Storage/WebSWClientConnection.messages.in:

LayoutTests:

* TestExpectations:
* http/wpt/service-workers/controlled-dedicatedworker.https-expected.txt: Added.
* http/wpt/service-workers/controlled-dedicatedworker.https.html: Added.
* http/wpt/service-workers/resources/controlled-worker.js: Added.

Modified Paths

Added Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (292860 => 292861)


--- trunk/LayoutTests/ChangeLog	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/ChangeLog	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,5 +1,17 @@
 2022-04-14  Youenn Fablet  <[email protected]>
 
+        Expose workers as service worker clients and implement registration matching for dedicated workers
+        https://bugs.webkit.org/show_bug.cgi?id=239066
+
+        Reviewed by Chris Dumez.
+
+        * TestExpectations:
+        * http/wpt/service-workers/controlled-dedicatedworker.https-expected.txt: Added.
+        * http/wpt/service-workers/controlled-dedicatedworker.https.html: Added.
+        * http/wpt/service-workers/resources/controlled-worker.js: Added.
+
+2022-04-14  Youenn Fablet  <[email protected]>
+
         A shared worker in a cached page should not allow the remote shared worker to continue executing
         https://bugs.webkit.org/show_bug.cgi?id=239286
 

Modified: trunk/LayoutTests/TestExpectations (292860 => 292861)


--- trunk/LayoutTests/TestExpectations	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/TestExpectations	2022-04-14 08:48:21 UTC (rev 292861)
@@ -369,7 +369,6 @@
 webkit.org/b/201666 imported/w3c/web-platform-tests/service-workers/service-worker/fetch-canvas-tainting-video-with-range-request.https.html [ Skip ]
 
 # Newly imported service worker tests that are flaky.
-imported/w3c/web-platform-tests/service-workers/service-worker/worker-client-id.https.html [ Pass Failure ]
 imported/w3c/web-platform-tests/service-workers/service-worker/update-not-allowed.https.html [ Pass Failure ]
 imported/w3c/web-platform-tests/service-workers/service-worker/performance-timeline.https.html [ Pass Failure ]
 

Added: trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https-expected.txt (0 => 292861)


--- trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https-expected.txt	                        (rev 0)
+++ trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https-expected.txt	2022-04-14 08:48:21 UTC (rev 292861)
@@ -0,0 +1,4 @@
+
+PASS Register service worker
+PASS Verify dedicated worker is controlled
+

Added: trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https.html (0 => 292861)


--- trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https.html	                        (rev 0)
+++ trunk/LayoutTests/http/wpt/service-workers/controlled-dedicatedworker.https.html	2022-04-14 08:48:21 UTC (rev 292861)
@@ -0,0 +1,31 @@
+<html>
+<head>
+<script src=""
+<script src=""
+<script src=""
+</head>
+<body>
+<script>
+promise_test(async (test) => {
+    const registration = await navigator.serviceWorker.register("skipFetchEvent-worker.js", { scope : 'resources' });
+    activeWorker = registration.active;
+    if (activeWorker)
+        return;
+
+    activeWorker = registration.installing;
+    await new Promise(resolve => {
+        activeWorker.addEventListener('statechange', () => {
+            if (activeWorker.state === "activated")
+                resolve();
+        });
+    });
+}, "Register service worker");
+
+promise_test(async (test) => {
+    worker = new Worker('resources/controlled-worker.js');
+    const event = await new Promise(resolve => worker._onmessage_ = resolve);
+    assert_true(event.data.isControlled);
+}, "Verify dedicated worker is controlled");
+</script>
+</body>
+</html>

Added: trunk/LayoutTests/http/wpt/service-workers/resources/controlled-worker.js (0 => 292861)


--- trunk/LayoutTests/http/wpt/service-workers/resources/controlled-worker.js	                        (rev 0)
+++ trunk/LayoutTests/http/wpt/service-workers/resources/controlled-worker.js	2022-04-14 08:48:21 UTC (rev 292861)
@@ -0,0 +1 @@
+self.postMessage({ isControlled : !!navigator.serviceWorker.controller });

Modified: trunk/LayoutTests/imported/w3c/ChangeLog (292860 => 292861)


--- trunk/LayoutTests/imported/w3c/ChangeLog	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/imported/w3c/ChangeLog	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,3 +1,15 @@
+2022-04-14  Youenn Fablet  <[email protected]>
+
+        Expose workers as service worker clients and implement registration matching for dedicated workers
+        https://bugs.webkit.org/show_bug.cgi?id=239066
+
+        Reviewed by Chris Dumez.
+
+        * web-platform-tests/service-workers/service-worker/local-url-inherit-controller.https-expected.txt:
+        * web-platform-tests/service-workers/service-worker/worker-client-id.https-expected.txt:
+        * web-platform-tests/service-workers/service-worker/worker-interception-redirect.https-expected.txt:
+        * web-platform-tests/service-workers/service-worker/worker-interception.https-expected.txt:
+
 2022-04-13  Chris Dumez  <[email protected]>
 
         imported/w3c/web-platform-tests/webaudio/the-audio-api/the-biquadfilternode-interface/no-dezippering.html

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/local-url-inherit-controller.https-expected.txt (292860 => 292861)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/local-url-inherit-controller.https-expected.txt	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/local-url-inherit-controller.https-expected.txt	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,9 +1,9 @@
 
 PASS Same-origin blob URL iframe should inherit service worker controller.
 PASS Same-origin blob URL iframe should intercept fetch().
-FAIL Same-origin blob URL worker should inherit service worker controller. assert_equals: blob URL worker should inherit controller expected (string) "https://localhost:9443/service-workers/service-worker/resources/local-url-inherit-controller-worker.js" but got (object) null
+PASS Same-origin blob URL worker should inherit service worker controller.
 PASS Same-origin blob URL worker should intercept fetch().
 PASS Data URL iframe should not intercept fetch().
 FAIL Data URL worker should not inherit service worker controller. promise_test: Unhandled rejection with value: "TypeError: undefined is not an object (evaluating 'navigator.serviceWorker.controller')"
-FAIL Data URL worker should not intercept fetch(). assert_equals: data URL worker should not intercept fetch expected "" but got "intercepted"
+PASS Data URL worker should not intercept fetch().
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-client-id.https-expected.txt (292860 => 292861)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-client-id.https-expected.txt	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-client-id.https-expected.txt	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,3 +1,3 @@
 
-FAIL Verify workers have a unique client id separate from their owning documents window assert_not_equals: frame and worker client ids should be different got disallowed value "2c4f7936-9c76-4ed4-b8e5-0b10ec2bea42"
+PASS Verify workers have a unique client id separate from their owning documents window
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception-redirect.https-expected.txt (292860 => 292861)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception-redirect.https-expected.txt	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception-redirect.https-expected.txt	2022-04-14 08:48:21 UTC (rev 292861)
@@ -8,20 +8,20 @@
 PASS Case #2: network scope1->out-scope (module DedicatedWorker)
 PASS Case #2: network scope1->out-scope (classic SharedWorker)
 PASS Case #2: network scope1->out-scope (module SharedWorker)
-FAIL Case #3: sw scope1->scope2 (classic DedicatedWorker) assert_unreached: Worker error Reached unreachable code
-FAIL Case #3: sw scope1->scope2 (module DedicatedWorker) assert_unreached: Worker error Reached unreachable code
+PASS Case #3: sw scope1->scope2 (classic DedicatedWorker)
+PASS Case #3: sw scope1->scope2 (module DedicatedWorker)
 FAIL Case #3: sw scope1->scope2 (classic SharedWorker) assert_unreached: Worker error Reached unreachable code
 FAIL Case #3: sw scope1->scope2 (module SharedWorker) assert_unreached: Worker error Reached unreachable code
-FAIL Case #4: sw scope1->out-scope (classic DedicatedWorker) assert_unreached: Worker error Reached unreachable code
-FAIL Case #4: sw scope1->out-scope (module DedicatedWorker) assert_unreached: Worker error Reached unreachable code
+PASS Case #4: sw scope1->out-scope (classic DedicatedWorker)
+PASS Case #4: sw scope1->out-scope (module DedicatedWorker)
 FAIL Case #4: sw scope1->out-scope (classic SharedWorker) assert_unreached: Worker error Reached unreachable code
 FAIL Case #4: sw scope1->out-scope (module SharedWorker) assert_unreached: Worker error Reached unreachable code
 PASS cleanup global state
-FAIL Case #1: network scope1->scope2 (classic DedicatedWorker, importScripts()) assert_equals: expected "sw1 saw importScripts from the worker: /service-workers/service-worker/resources/scope2/import-scripts-echo.py" but got "importScripts: served from network (scope2/)"
-FAIL Case #1: network scope1->scope2 (classic DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt" but got "fetch(): a simple text file (scope2/)\n"
+PASS Case #1: network scope1->scope2 (classic DedicatedWorker, importScripts())
+PASS Case #1: network scope1->scope2 (classic DedicatedWorker, fetch())
 PASS Case #1: network scope1->scope2 (classic DedicatedWorker, location.href)
 PASS Case #1: network scope1->scope2 (module DedicatedWorker, importScripts())
-FAIL Case #1: network scope1->scope2 (module DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt" but got "fetch(): a simple text file (scope2/)\n"
+PASS Case #1: network scope1->scope2 (module DedicatedWorker, fetch())
 PASS Case #1: network scope1->scope2 (module DedicatedWorker, location.href)
 FAIL Case #1: network scope1->scope2 (classic SharedWorker, importScripts()) assert_equals: expected "sw1 saw importScripts from the worker: /service-workers/service-worker/resources/scope2/import-scripts-echo.py" but got "importScripts: served from network (scope2/)"
 FAIL Case #1: network scope1->scope2 (classic SharedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt" but got "fetch(): a simple text file (scope2/)\n"
@@ -29,11 +29,11 @@
 PASS Case #1: network scope1->scope2 (module SharedWorker, importScripts())
 FAIL Case #1: network scope1->scope2 (module SharedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt" but got "fetch(): a simple text file (scope2/)\n"
 PASS Case #1: network scope1->scope2 (module SharedWorker, location.href)
-FAIL Case #2: network scope1->out-scope (classic DedicatedWorker, importScripts()) assert_equals: expected "sw1 saw importScripts from the worker: /service-workers/service-worker/resources/import-scripts-echo.py" but got "importScripts: served from network"
-FAIL Case #2: network scope1->out-scope (classic DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/simple.txt" but got "fetch(): a simple text file\n"
+PASS Case #2: network scope1->out-scope (classic DedicatedWorker, importScripts())
+PASS Case #2: network scope1->out-scope (classic DedicatedWorker, fetch())
 PASS Case #2: network scope1->out-scope (classic DedicatedWorker, location.href)
 PASS Case #2: network scope1->out-scope (module DedicatedWorker, importScripts())
-FAIL Case #2: network scope1->out-scope (module DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/simple.txt" but got "fetch(): a simple text file\n"
+PASS Case #2: network scope1->out-scope (module DedicatedWorker, fetch())
 PASS Case #2: network scope1->out-scope (module DedicatedWorker, location.href)
 FAIL Case #2: network scope1->out-scope (classic SharedWorker, importScripts()) assert_equals: expected "sw1 saw importScripts from the worker: /service-workers/service-worker/resources/import-scripts-echo.py" but got "importScripts: served from network"
 FAIL Case #2: network scope1->out-scope (classic SharedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/simple.txt" but got "fetch(): a simple text file\n"
@@ -41,4 +41,16 @@
 PASS Case #2: network scope1->out-scope (module SharedWorker, importScripts())
 FAIL Case #2: network scope1->out-scope (module SharedWorker, fetch()) assert_equals: expected "fetch(): sw1 saw the fetch from the worker: /service-workers/service-worker/resources/simple.txt" but got "fetch(): a simple text file\n"
 PASS Case #2: network scope1->out-scope (module SharedWorker, location.href)
+FAIL Case #3: sw scope1->scope2 (classic DedicatedWorker, importScripts()) assert_equals: expected "sw2 saw importScripts from the worker: /service-workers/service-worker/resources/subdir/import-scripts-echo.py" but got "sw2 saw importScripts from the worker: /service-workers/service-worker/resources/scope2/import-scripts-echo.py"
+FAIL Case #3: sw scope1->scope2 (classic DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw2 saw the fetch from the worker: /service-workers/service-worker/resources/subdir/simple.txt" but got "fetch(): sw2 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt"
+FAIL Case #3: sw scope1->scope2 (classic DedicatedWorker, location.href) assert_equals: location.href expected "https://localhost:9443/service-workers/service-worker/resources/subdir/worker_interception_redirect_webworker.py?greeting=sw2%20saw%20the%20request%20for%20the%20worker%20script" but got "https://localhost:9443/service-workers/service-worker/resources/scope2/worker_interception_redirect_webworker.py"
+PASS Case #3: sw scope1->scope2 (module DedicatedWorker, importScripts())
+FAIL Case #3: sw scope1->scope2 (module DedicatedWorker, fetch()) assert_equals: expected "fetch(): sw2 saw the fetch from the worker: /service-workers/service-worker/resources/subdir/simple.txt" but got "fetch(): sw2 saw the fetch from the worker: /service-workers/service-worker/resources/scope2/simple.txt"
+FAIL Case #3: sw scope1->scope2 (module DedicatedWorker, location.href) assert_equals: location.href expected "https://localhost:9443/service-workers/service-worker/resources/subdir/worker_interception_redirect_webworker.py?greeting=sw2%20saw%20the%20request%20for%20the%20worker%20script" but got "https://localhost:9443/service-workers/service-worker/resources/scope2/worker_interception_redirect_webworker.py"
+PASS Case #4: sw scope1->out-scope (classic DedicatedWorker, importScripts())
+PASS Case #4: sw scope1->out-scope (classic DedicatedWorker, fetch())
+PASS Case #4: sw scope1->out-scope (classic DedicatedWorker, location.href)
+PASS Case #4: sw scope1->out-scope (module DedicatedWorker, importScripts())
+PASS Case #4: sw scope1->out-scope (module DedicatedWorker, fetch())
+PASS Case #4: sw scope1->out-scope (module DedicatedWorker, location.href)
 

Modified: trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception.https-expected.txt (292860 => 292861)


--- trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception.https-expected.txt	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/worker-interception.https-expected.txt	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,8 +1,8 @@
 
-FAIL Verify a dedicated worker script request issued from a uncontrolled document is intercepted by worker's own service worker. promise_test: Unhandled rejection with value: undefined
-FAIL Verify an out-of-scope dedicated worker script request issued from a controlled document should not be intercepted by document's service worker. assert_equals: expected "worker loading was not intercepted by service worker" but got "worker loading intercepted by service worker"
+PASS Verify a dedicated worker script request issued from a uncontrolled document is intercepted by worker's own service worker.
+PASS Verify an out-of-scope dedicated worker script request issued from a controlled document should not be intercepted by document's service worker.
 FAIL Verify a shared worker script request issued from a uncontrolled document is intercepted by worker's own service worker. promise_test: Unhandled rejection with value: undefined
-FAIL Verify a same-origin worker script served by a service worker succeeds in starting a dedicated worker. promise_test: Unhandled rejection with value: undefined
+PASS Verify a same-origin worker script served by a service worker succeeds in starting a dedicated worker.
 FAIL Verify a same-origin worker script served by a service worker succeeds in starting a shared worker. promise_test: Unhandled rejection with value: undefined
 PASS Verify a cors worker script served by a service worker fails dedicated worker start.
 PASS Verify a cors worker script served by a service worker fails shared worker start.
@@ -9,7 +9,7 @@
 PASS Verify a no-cors cross-origin worker script served by a service worker fails dedicated worker start.
 PASS Verify a no-cors cross-origin worker script served by a service worker fails shared worker start.
 PASS Register a service worker for worker subresource interception tests.
-FAIL Requests on a dedicated worker controlled by a service worker. assert_equals: expected "This load was successfully intercepted." but got "{\"error\": {\"code\": 404, \"message\": \"404\"}}"
+PASS Requests on a dedicated worker controlled by a service worker.
 FAIL Requests on a shared worker controlled by a service worker. assert_equals: expected "This load was successfully intercepted." but got "{\"error\": {\"code\": 404, \"message\": \"404\"}}"
 FAIL Requests on a dedicated worker nested in a dedicated worker and controlled by a service worker assert_equals: expected "This load was successfully intercepted." but got "Unexpected error! Can't find variable: Worker"
 FAIL Requests on a dedicated worker nested in a shared worker and controlled by a service worker assert_equals: expected "This load was successfully intercepted." but got "Unexpected error! Can't find variable: Worker"

Modified: trunk/Source/WebCore/ChangeLog (292860 => 292861)


--- trunk/Source/WebCore/ChangeLog	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/ChangeLog	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,5 +1,61 @@
 2022-04-14  Youenn Fablet  <[email protected]>
 
+        Expose workers as service worker clients and implement registration matching for dedicated workers
+        https://bugs.webkit.org/show_bug.cgi?id=239066
+
+        Reviewed by Chris Dumez.
+
+        Add support for exposing workers (dedicated and shared) as service worker clients.
+        Add support for setting the controlling registration for dedicated workers
+        (a follow-up patch should handle shared workers).
+        To properly handle loads coming from a worker, we properly set clientIdentifier and registration identifier
+        from the worker context, instead of from the worker's document.
+
+        Small refactoring to pass additional data to worker through WorkerInitializationData.
+        This is used to set the context ID and context controlling service worker.
+
+        Adding a specific check in CachedResourceLoader to not reuse the cache in case the service worker modes are different.
+        A potential issue is that the service workers are the same (0) as one request is the main request
+        and the second request is the request triggered by service worker to answer the first request.
+
+        Properly support blob URL matching directly in WorkerScriptLoader for workers.
+
+        Test: http/wpt/service-workers/controlled-dedicatedworker.https.html
+
+        * WebCore.xcodeproj/project.pbxproj:
+        * dom/Document.h:
+        * dom/ScriptExecutionContext.h:
+        * loader/DocumentLoader.cpp:
+        * loader/FetchOptions.h:
+        * loader/ThreadableLoader.cpp:
+        * loader/WorkerThreadableLoader.cpp:
+        * loader/cache/CachedResourceLoader.cpp:
+        * workers/DedicatedWorkerThread.cpp:
+        * workers/Worker.cpp:
+        * workers/Worker.h:
+        * workers/WorkerGlobalScope.cpp:
+        * workers/WorkerGlobalScope.h:
+        * workers/WorkerGlobalScopeProxy.h:
+        * workers/WorkerInitializationData.h: Added.
+        * workers/WorkerMessagingProxy.cpp:
+        * workers/WorkerMessagingProxy.h:
+        * workers/WorkerOrWorkletGlobalScope.cpp:
+        * workers/WorkerOrWorkletGlobalScope.h:
+        * workers/WorkerScriptLoader.cpp:
+        * workers/WorkerScriptLoader.h:
+        * workers/WorkerThread.cpp:
+        * workers/WorkerThread.h:
+        * workers/service/SWClientConnection.cpp:
+        * workers/service/ServiceWorker.h:
+        * workers/service/ServiceWorkerClientData.cpp:
+        * workers/service/ServiceWorkerClientType.h:
+        * workers/service/ServiceWorkerContainer.cpp:
+        * workers/service/context/ServiceWorkerThread.cpp:
+        * workers/shared/SharedWorkerScriptLoader.h:
+        * workers/shared/context/SharedWorkerThreadProxy.cpp:
+
+2022-04-14  Youenn Fablet  <[email protected]>
+
         A shared worker in a cached page should not allow the remote shared worker to continue executing
         https://bugs.webkit.org/show_bug.cgi?id=239286
 

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (292860 => 292861)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1065,6 +1065,7 @@
 		3FF813A71DBA8640009BF001 /* PointerLockController.h in Headers */ = {isa = PBXBuildFile; fileRef = 5CFC434F192406A900A0D3B5 /* PointerLockController.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		4107908C1FC3F0330061B27A /* ClientOrigin.h in Headers */ = {isa = PBXBuildFile; fileRef = 4107908A1FC3E4F20061B27A /* ClientOrigin.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		410BCF5626F0CD8C0040B124 /* RTCLocalSessionDescriptionInit.h in Headers */ = {isa = PBXBuildFile; fileRef = 410BCF5326F0CD8B0040B124 /* RTCLocalSessionDescriptionInit.h */; };
+		410C48A7280420F80084D104 /* WorkerInitializationData.h in Headers */ = {isa = PBXBuildFile; fileRef = 410C48A6280420F20084D104 /* WorkerInitializationData.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		410E4461234373E9000173D4 /* LibWebRTCSocketIdentifier.h in Headers */ = {isa = PBXBuildFile; fileRef = 410E445F234373AD000173D4 /* LibWebRTCSocketIdentifier.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		41100C8023F74583001BC33B /* WebSocketChannelInspector.h in Headers */ = {isa = PBXBuildFile; fileRef = 41100C7E23F73982001BC33B /* WebSocketChannelInspector.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		41103AAC1E39791000769F03 /* RealtimeOutgoingAudioSource.h in Headers */ = {isa = PBXBuildFile; fileRef = 41103AA81E39790A00769F03 /* RealtimeOutgoingAudioSource.h */; };
@@ -1353,7 +1354,7 @@
 		4672AA9926B0943F00E6EC38 /* CrossOriginOpenerPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 4672AA9726B0942100E6EC38 /* CrossOriginOpenerPolicy.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		467302021C4EFE7800BCB357 /* IgnoreOpensDuringUnloadCountIncrementer.h in Headers */ = {isa = PBXBuildFile; fileRef = 467302011C4EFE6600BCB357 /* IgnoreOpensDuringUnloadCountIncrementer.h */; };
 		467A68D7275EA991009B31C5 /* SharedWorkerThread.h in Headers */ = {isa = PBXBuildFile; fileRef = 467A68D4275EA98B009B31C5 /* SharedWorkerThread.h */; settings = {ATTRIBUTES = (Private, ); }; };
-		467A68D8275EA995009B31C5 /* SharedWorkerScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = 467A68D5275EA98C009B31C5 /* SharedWorkerScriptLoader.h */; };
+		467A68D8275EA995009B31C5 /* SharedWorkerScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = 467A68D5275EA98C009B31C5 /* SharedWorkerScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		467A68D9275EA998009B31C5 /* SharedWorkerThreadProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 467A68D6275EA98C009B31C5 /* SharedWorkerThreadProxy.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		4682D2001F79783000C863DB /* StoredCredentialsPolicy.h in Headers */ = {isa = PBXBuildFile; fileRef = 4682D1FF1F79782300C863DB /* StoredCredentialsPolicy.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		468344E01EDDFAAA00B7795B /* DOMRectList.h in Headers */ = {isa = PBXBuildFile; fileRef = 468344DE1EDDFA5F00B7795B /* DOMRectList.h */; settings = {ATTRIBUTES = (Private, ); }; };
@@ -8567,6 +8568,7 @@
 		410BA1312570FE57002E2F8A /* LibWebRTCRtpTransformableFrame.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = LibWebRTCRtpTransformableFrame.cpp; path = libwebrtc/LibWebRTCRtpTransformableFrame.cpp; sourceTree = "<group>"; };
 		410BCF5326F0CD8B0040B124 /* RTCLocalSessionDescriptionInit.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RTCLocalSessionDescriptionInit.h; sourceTree = "<group>"; };
 		410BCF5526F0CD8C0040B124 /* RTCLocalSessionDescriptionInit.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = RTCLocalSessionDescriptionInit.idl; sourceTree = "<group>"; };
+		410C48A6280420F20084D104 /* WorkerInitializationData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerInitializationData.h; sourceTree = "<group>"; };
 		410E445F234373AD000173D4 /* LibWebRTCSocketIdentifier.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LibWebRTCSocketIdentifier.h; path = libwebrtc/LibWebRTCSocketIdentifier.h; sourceTree = "<group>"; };
 		410F565524FCF70500A2E50C /* RTCSessionDescriptionInit.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = RTCSessionDescriptionInit.idl; sourceTree = "<group>"; };
 		410F565724FCF7C700A2E50C /* RTCIceCandidateInit.idl */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = RTCIceCandidateInit.idl; sourceTree = "<group>"; };
@@ -20950,6 +20952,7 @@
 				2E4346370F546A8200B0F1BA /* WorkerGlobalScope.h */,
 				2E4346380F546A8200B0F1BA /* WorkerGlobalScope.idl */,
 				2E4346390F546A8200B0F1BA /* WorkerGlobalScopeProxy.h */,
+				410C48A6280420F20084D104 /* WorkerInitializationData.h */,
 				A54A0C691DB831F10017A90B /* WorkerInspectorProxy.cpp */,
 				A54A0C6A1DB831F20017A90B /* WorkerInspectorProxy.h */,
 				18F831B70FD48C7800D8C56B /* WorkerLoaderProxy.h */,
@@ -38351,6 +38354,7 @@
 				A7D6B3490F61104500FF9FD1 /* WorkerFontLoadRequest.h in Headers */,
 				2E4346490F546A8200B0F1BA /* WorkerGlobalScope.h in Headers */,
 				2E43464B0F546A8200B0F1BA /* WorkerGlobalScopeProxy.h in Headers */,
+				410C48A7280420F80084D104 /* WorkerInitializationData.h in Headers */,
 				A54A0C621DB7F8C10017A90B /* WorkerInspectorController.h in Headers */,
 				A54A0C6C1DB831F90017A90B /* WorkerInspectorProxy.h in Headers */,
 				18F831B80FD48C7800D8C56B /* WorkerLoaderProxy.h in Headers */,

Modified: trunk/Source/WebCore/dom/Document.h (292860 => 292861)


--- trunk/Source/WebCore/dom/Document.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/dom/Document.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1568,7 +1568,7 @@
 
 #if ENABLE(SERVICE_WORKER)
     void setServiceWorkerConnection(SWClientConnection*);
-    void updateServiceWorkerClientData();
+    void updateServiceWorkerClientData() final;
     WEBCORE_EXPORT void navigateFromServiceWorker(const URL&, CompletionHandler<void(bool)>&&);
 #endif
 

Modified: trunk/Source/WebCore/dom/ScriptExecutionContext.h (292860 => 292861)


--- trunk/Source/WebCore/dom/ScriptExecutionContext.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/dom/ScriptExecutionContext.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -289,6 +289,7 @@
 
     ServiceWorkerContainer* serviceWorkerContainer();
     ServiceWorkerContainer* ensureServiceWorkerContainer();
+    virtual void updateServiceWorkerClientData() { ASSERT_NOT_REACHED(); }
 #endif
     WEBCORE_EXPORT static bool postTaskTo(ScriptExecutionContextIdentifier, Task&&);
     WEBCORE_EXPORT static bool ensureOnContextThread(ScriptExecutionContextIdentifier, Task&&);

Modified: trunk/Source/WebCore/loader/DocumentLoader.cpp (292860 => 292861)


--- trunk/Source/WebCore/loader/DocumentLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/loader/DocumentLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -2140,6 +2140,7 @@
         m_resultingClientId = ScriptExecutionContextIdentifier::generate();
         ASSERT(!scriptExecutionContextIdentifierToLoaderMap().contains(m_resultingClientId));
         scriptExecutionContextIdentifierToLoaderMap().add(m_resultingClientId, this);
+        mainResourceLoadOptions.clientIdentifier = m_resultingClientId;
     }
 #endif
 

Modified: trunk/Source/WebCore/loader/FetchOptions.h (292860 => 292861)


--- trunk/Source/WebCore/loader/FetchOptions.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/loader/FetchOptions.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -44,9 +44,9 @@
     enum class Redirect : uint8_t { Follow, Error, Manual };
 
     FetchOptions() = default;
-    FetchOptions(Destination, Mode, Credentials, Cache, Redirect, ReferrerPolicy, String&&, bool);
-    FetchOptions isolatedCopy() const & { return { destination, mode, credentials, cache, redirect, referrerPolicy, integrity.isolatedCopy(), keepAlive }; }
-    FetchOptions isolatedCopy() && { return { destination, mode, credentials, cache, redirect, referrerPolicy, WTFMove(integrity).isolatedCopy(), keepAlive }; }
+    FetchOptions(Destination, Mode, Credentials, Cache, Redirect, ReferrerPolicy, String&&, bool, std::optional<ScriptExecutionContextIdentifier>);
+    FetchOptions isolatedCopy() const & { return { destination, mode, credentials, cache, redirect, referrerPolicy, integrity.isolatedCopy(), keepAlive, clientIdentifier }; }
+    FetchOptions isolatedCopy() && { return { destination, mode, credentials, cache, redirect, referrerPolicy, WTFMove(integrity).isolatedCopy(), keepAlive, clientIdentifier }; }
 
     template<class Encoder> void encodePersistent(Encoder&) const;
     template<class Decoder> static WARN_UNUSED_RETURN bool decodePersistent(Decoder&, FetchOptions&);
@@ -59,12 +59,12 @@
     Cache cache { Cache::Default };
     Redirect redirect { Redirect::Follow };
     ReferrerPolicy referrerPolicy { ReferrerPolicy::EmptyString };
+    String integrity;
     bool keepAlive { false };
-    String integrity;
     std::optional<ScriptExecutionContextIdentifier> clientIdentifier;
 };
 
-inline FetchOptions::FetchOptions(Destination destination, Mode mode, Credentials credentials, Cache cache, Redirect redirect, ReferrerPolicy referrerPolicy, String&& integrity, bool keepAlive)
+inline FetchOptions::FetchOptions(Destination destination, Mode mode, Credentials credentials, Cache cache, Redirect redirect, ReferrerPolicy referrerPolicy, String&& integrity, bool keepAlive, std::optional<ScriptExecutionContextIdentifier> clientIdentifier)
     : destination(destination)
     , mode(mode)
     , credentials(credentials)
@@ -71,8 +71,9 @@
     , cache(cache)
     , redirect(redirect)
     , referrerPolicy(referrerPolicy)
+    , integrity(WTFMove(integrity))
     , keepAlive(keepAlive)
-    , integrity(WTFMove(integrity))
+    , clientIdentifier(clientIdentifier)
 {
 }
 

Modified: trunk/Source/WebCore/loader/ThreadableLoader.cpp (292860 => 292861)


--- trunk/Source/WebCore/loader/ThreadableLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/loader/ThreadableLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -77,6 +77,8 @@
     copy.redirect = this->redirect;
     copy.referrerPolicy = this->referrerPolicy;
     copy.integrity = this->integrity.isolatedCopy();
+    copy.keepAlive = this->keepAlive;
+    copy.clientIdentifier = this->clientIdentifier;
 
     // ResourceLoaderOptions
     copy.sendLoadCallbacks = this->sendLoadCallbacks;

Modified: trunk/Source/WebCore/loader/WorkerThreadableLoader.cpp (292860 => 292861)


--- trunk/Source/WebCore/loader/WorkerThreadableLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/loader/WorkerThreadableLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -33,6 +33,7 @@
 #include "WorkerThreadableLoader.h"
 
 #include "ContentSecurityPolicy.h"
+#include "DedicatedWorkerGlobalScope.h"
 #include "Document.h"
 #include "DocumentThreadableLoader.h"
 #include "InspectorInstrumentation.h"
@@ -133,10 +134,20 @@
     optionsCopy->options.initiatorContext = InitiatorContext::Worker;
 
 #if ENABLE(SERVICE_WORKER)
-    optionsCopy->options.serviceWorkersMode = is<ServiceWorkerGlobalScope>(globalScope) ? ServiceWorkersMode::None : ServiceWorkersMode::All;
-    if (auto* activeServiceWorker = globalScope.activeServiceWorker())
-        optionsCopy->options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
+    if (optionsCopy->options.serviceWorkersMode == ServiceWorkersMode::All) {
+        if (is<ServiceWorkerGlobalScope>(globalScope))
+            optionsCopy->options.serviceWorkersMode = ServiceWorkersMode::None;
+        else if (auto* activeServiceWorker = globalScope.activeServiceWorker()) {
+            optionsCopy->options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
+            optionsCopy->options.serviceWorkersMode = ServiceWorkersMode::All;
+        } else if (is<DedicatedWorkerGlobalScope>(globalScope))
+            optionsCopy->options.serviceWorkersMode = ServiceWorkersMode::None;
+        else
+            optionsCopy->options.serviceWorkersMode = ServiceWorkersMode::All;
+    }
 #endif
+    if (!optionsCopy->options.clientIdentifier)
+        optionsCopy->options.clientIdentifier = globalScope.identifier();
 
     if (is<WorkerGlobalScope>(globalScope))
         InspectorInstrumentation::willSendRequest(downcast<WorkerGlobalScope>(globalScope), m_workerRequestIdentifier, request);

Modified: trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp (292860 => 292861)


--- trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/loader/cache/CachedResourceLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1202,8 +1202,8 @@
 
 #if ENABLE(SERVICE_WORKER)
     // FIXME: We should validate/specify this behavior.
-    if (cachedResourceRequest.options().serviceWorkerRegistrationIdentifier != existingResource->options().serviceWorkerRegistrationIdentifier) {
-        LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading because selected service worker differs");
+    if (cachedResourceRequest.options().serviceWorkerRegistrationIdentifier != existingResource->options().serviceWorkerRegistrationIdentifier || cachedResourceRequest.options().serviceWorkersMode != existingResource->options().serviceWorkersMode) {
+        LOG(ResourceLoading, "CachedResourceLoader::determineRevalidationPolicy reloading because selected service worker may differ");
         return Reload;
     }
 #endif

Modified: trunk/Source/WebCore/workers/DedicatedWorkerThread.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/DedicatedWorkerThread.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/DedicatedWorkerThread.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -48,7 +48,12 @@
 
 Ref<WorkerGlobalScope> DedicatedWorkerThread::createWorkerGlobalScope(const WorkerParameters& params, Ref<SecurityOrigin>&& origin, Ref<SecurityOrigin>&& topOrigin)
 {
-    return DedicatedWorkerGlobalScope::create(params, WTFMove(origin), *this, WTFMove(topOrigin), idbConnectionProxy(), socketProvider());
+    auto scope = DedicatedWorkerGlobalScope::create(params, WTFMove(origin), *this, WTFMove(topOrigin), idbConnectionProxy(), socketProvider());
+#if ENABLE(SERVICE_WORKER)
+    if (params.serviceWorkerData)
+        scope->setActiveServiceWorker(ServiceWorker::getOrCreate(scope.get(), ServiceWorkerData { *params.serviceWorkerData }));
+#endif
+    return scope;
 }
 
 void DedicatedWorkerThread::runEventLoop()

Modified: trunk/Source/WebCore/workers/Worker.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/Worker.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/Worker.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -43,6 +43,7 @@
 #include "SecurityOrigin.h"
 #include "StructuredSerializeOptions.h"
 #include "WorkerGlobalScopeProxy.h"
+#include "WorkerInitializationData.h"
 #include "WorkerScriptLoader.h"
 #include "WorkerThread.h"
 #include <_javascript_Core/IdentifiersFactory.h>
@@ -57,15 +58,15 @@
 
 WTF_MAKE_ISO_ALLOCATED_IMPL(Worker);
 
-static HashSet<Worker*>& allWorkers()
+static HashMap<ScriptExecutionContextIdentifier, Worker*>& allWorkers()
 {
-    static NeverDestroyed<HashSet<Worker*>> set;
-    return set;
+    static NeverDestroyed<HashMap<ScriptExecutionContextIdentifier, Worker*>> map;
+    return map;
 }
 
 void Worker::networkStateChanged(bool isOnLine)
 {
-    for (auto* worker : allWorkers())
+    for (auto* worker : allWorkers().values())
         worker->notifyNetworkStateChange(isOnLine);
 }
 
@@ -75,6 +76,7 @@
     , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
     , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
     , m_runtimeFlags(runtimeFlags)
+    , m_clientIdentifier(ScriptExecutionContextIdentifier::generate())
 {
     static bool addedListener;
     if (!addedListener) {
@@ -82,7 +84,7 @@
         addedListener = true;
     }
 
-    auto addResult = allWorkers().add(this);
+    auto addResult = allWorkers().add(m_clientIdentifier, this);
     ASSERT_UNUSED(addResult, addResult.isNewEntry);
 }
 
@@ -114,7 +116,7 @@
     request.setInitiatorIdentifier(worker->m_identifier);
 
     auto source = options.type == WorkerType::Module ? WorkerScriptLoader::Source::ModuleScript : WorkerScriptLoader::Source::ClassicWorkerScript;
-    worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), source, workerFetchOptions(worker->m_options, FetchOptions::Destination::Worker), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get(), WorkerRunLoop::defaultMode());
+    worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), source, workerFetchOptions(worker->m_options, FetchOptions::Destination::Worker), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get(), WorkerRunLoop::defaultMode(), worker->m_clientIdentifier);
 
     return worker;
 }
@@ -123,7 +125,7 @@
 {
     ASSERT(isMainThread());
     ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
-    allWorkers().remove(this);
+    allWorkers().remove(m_clientIdentifier);
     m_contextProxy.workerObjectDestroyed();
 }
 
@@ -208,13 +210,19 @@
         return;
     }
 
-    bool isOnline = platformStrategies()->loaderStrategy()->isOnLine();
     const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders = m_contentSecurityPolicyResponseHeaders ? m_contentSecurityPolicyResponseHeaders.value() : context->contentSecurityPolicy()->responseHeaders();
     ReferrerPolicy referrerPolicy = ReferrerPolicy::EmptyString;
     if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
         referrerPolicy = *policy;
 
-    m_contextProxy.startWorkerGlobalScope(m_scriptLoader->lastRequestURL(), m_options.name, context->userAgent(m_scriptLoader->lastRequestURL()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_scriptLoader->crossOriginEmbedderPolicy(), m_workerCreationTime, referrerPolicy, m_options.type, m_options.credentials, m_runtimeFlags);
+    WorkerInitializationData initializationData {
+#if ENABLE(SERVICE_WORKER)
+        m_scriptLoader->takeServiceWorkerData(),
+#endif
+        m_clientIdentifier,
+        context->userAgent(m_scriptLoader->lastRequestURL())
+    };
+    m_contextProxy.startWorkerGlobalScope(m_scriptLoader->lastRequestURL(), m_options.name, WTFMove(initializationData), m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_scriptLoader->crossOriginEmbedderPolicy(), m_workerCreationTime, referrerPolicy, m_options.type, m_options.credentials, m_runtimeFlags);
     InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script().toString());
 }
 
@@ -251,8 +259,13 @@
 
 void Worker::forEachWorker(const Function<Function<void(ScriptExecutionContext&)>()>& callback)
 {
-    for (auto* worker : allWorkers())
+    for (auto* worker : allWorkers().values())
         worker->postTaskToWorkerGlobalScope(callback());
 }
 
+Worker* Worker::workerByIdentifier(ScriptExecutionContextIdentifier identifier)
+{
+    return allWorkers().get(identifier);
+}
+
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/Worker.h (292860 => 292861)


--- trunk/Source/WebCore/workers/Worker.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/Worker.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -81,10 +81,12 @@
     WorkerType type() const { return m_options.type; }
 
     void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&);
+
     static void forEachWorker(const Function<Function<void(ScriptExecutionContext&)>()>&);
+    static Worker* workerByIdentifier(ScriptExecutionContextIdentifier);
 
 private:
-    explicit Worker(ScriptExecutionContext&, JSC::RuntimeFlags, WorkerOptions&&);
+    Worker(ScriptExecutionContext&, JSC::RuntimeFlags, WorkerOptions&&);
 
     EventTargetInterface eventTargetInterface() const final { return WorkerEventTargetInterfaceType; }
 
@@ -116,6 +118,7 @@
 #if ENABLE(WEB_RTC)
     HashSet<String> m_transformers;
 #endif
+    ScriptExecutionContextIdentifier m_clientIdentifier;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerGlobalScope.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerGlobalScope.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerGlobalScope.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -48,6 +48,7 @@
 #include "ScriptSourceCode.h"
 #include "SecurityOrigin.h"
 #include "SecurityOriginPolicy.h"
+#include "ServiceWorkerClientData.h"
 #include "ServiceWorkerGlobalScope.h"
 #include "SocketProvider.h"
 #include "WorkerCacheStorageConnection.h"
@@ -91,7 +92,7 @@
 WTF_MAKE_ISO_ALLOCATED_IMPL(WorkerGlobalScope);
 
 WorkerGlobalScope::WorkerGlobalScope(WorkerThreadType type, const WorkerParameters& params, Ref<SecurityOrigin>&& origin, WorkerThread& thread, Ref<SecurityOrigin>&& topOrigin, IDBClient::IDBConnectionProxy* connectionProxy, SocketProvider* socketProvider)
-    : WorkerOrWorkletGlobalScope(type, isMainThread() ? Ref { commonVM() } : JSC::VM::create(), &thread)
+    : WorkerOrWorkletGlobalScope(type, isMainThread() ? Ref { commonVM() } : JSC::VM::create(), &thread, params.clientIdentifier)
     , m_url(params.scriptURL)
     , m_inspectorIdentifier(params.inspectorIdentifier)
     , m_userAgent(params.userAgent)
@@ -653,4 +654,14 @@
     }
 }
 
+#if ENABLE(SERVICE_WORKER)
+void WorkerGlobalScope::updateServiceWorkerClientData()
+{
+    ASSERT(type() == WebCore::WorkerGlobalScope::Type::DedicatedWorker);
+    auto controllingServiceWorkerRegistrationIdentifier = activeServiceWorker() ? std::make_optional<ServiceWorkerRegistrationIdentifier>(activeServiceWorker()->registrationIdentifier()) : std::nullopt;
+    SWClientConnection& connection = swClientConnection();
+    connection.registerServiceWorkerClient(topOrigin(), ServiceWorkerClientData::from(*this), controllingServiceWorkerRegistrationIdentifier, String { m_userAgent });
+}
+#endif
+
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerGlobalScope.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerGlobalScope.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerGlobalScope.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -192,6 +192,9 @@
     bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) final;
     bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) final;
 #endif
+#if ENABLE(SERVICE_WORKER)
+    void updateServiceWorkerClientData() final;
+#endif
 
     void stopIndexedDatabase();
 

Modified: trunk/Source/WebCore/workers/WorkerGlobalScopeProxy.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerGlobalScopeProxy.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerGlobalScopeProxy.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -43,6 +43,7 @@
 class ScriptBuffer;
 class ScriptExecutionContext;
 class Worker;
+struct WorkerInitializationData;
 enum class ReferrerPolicy : uint8_t;
 enum class WorkerType : bool;
 
@@ -51,7 +52,7 @@
 public:
     static WorkerGlobalScopeProxy& create(Worker&);
 
-    virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy&, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) = 0;
+    virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, WorkerInitializationData&&, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy&, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) = 0;
     virtual void terminateWorkerGlobalScope() = 0;
     virtual void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) = 0;
     virtual void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&) = 0;

Added: trunk/Source/WebCore/workers/WorkerInitializationData.h (0 => 292861)


--- trunk/Source/WebCore/workers/WorkerInitializationData.h	                        (rev 0)
+++ trunk/Source/WebCore/workers/WorkerInitializationData.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2022 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include "ScriptExecutionContextIdentifier.h"
+#include "ServiceWorkerData.h"
+#include <wtf/text/WTFString.h>
+
+namespace WebCore {
+
+struct WorkerInitializationData {
+#if ENABLE(SERVICE_WORKER)
+    std::optional<ServiceWorkerData> serviceWorkerData;
+#endif
+    std::optional<ScriptExecutionContextIdentifier> clientIdentifier;
+    String userAgent;
+};
+
+} // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerMessagingProxy.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerMessagingProxy.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerMessagingProxy.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -38,11 +38,14 @@
 #include "EventNames.h"
 #include "FetchRequestCredentials.h"
 #include "LibWebRTCProvider.h"
+#include "LoaderStrategy.h"
 #include "MessageEvent.h"
 #include "Page.h"
+#include "PlatformStrategies.h"
 #include "ScriptExecutionContext.h"
 #include "Settings.h"
 #include "Worker.h"
+#include "WorkerInitializationData.h"
 #include "WorkerInspectorProxy.h"
 #include <_javascript_Core/ConsoleTypes.h>
 #include <_javascript_Core/ScriptCallStack.h>
@@ -75,7 +78,7 @@
         || (is<WorkerGlobalScope>(*m_scriptExecutionContext) && downcast<WorkerGlobalScope>(*m_scriptExecutionContext).thread().thread() == &Thread::current()));
 }
 
-void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy& crossOriginEmbedderPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags runtimeFlags)
+void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, WorkerInitializationData&& initializationData, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy& crossOriginEmbedderPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags runtimeFlags)
 {
     // FIXME: This need to be revisited when we support nested worker one day
     ASSERT(m_scriptExecutionContext);
@@ -87,7 +90,12 @@
 
     SocketProvider* socketProvider = document.socketProvider();
 
-    WorkerParameters params = { scriptURL, name, identifier, userAgent, isOnline, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, crossOriginEmbedderPolicy, timeOrigin, referrerPolicy, workerType, credentials, document.settingsValues() };
+    WorkerParameters params { scriptURL, name, identifier, WTFMove(initializationData.userAgent), platformStrategies()->loaderStrategy()->isOnLine(), contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, crossOriginEmbedderPolicy, timeOrigin, referrerPolicy, workerType, credentials, document.settingsValues(), WorkerThreadMode::CreateNewThread, { },
+#if ENABLE(SERVICE_WORKER)
+        WTFMove(initializationData.serviceWorkerData),
+#endif
+        initializationData.clientIdentifier.value_or(ScriptExecutionContextIdentifier { })
+    };
     auto thread = DedicatedWorkerThread::create(params, sourceCode, *this, *this, *this, startMode, document.topOrigin(), proxy, socketProvider, runtimeFlags);
 
     workerThreadCreated(thread.get());

Modified: trunk/Source/WebCore/workers/WorkerMessagingProxy.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerMessagingProxy.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerMessagingProxy.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -50,7 +50,7 @@
 private:
     // Implementations of WorkerGlobalScopeProxy.
     // (Only use these functions in the worker object thread.)
-    void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy&, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) final;
+    void startWorkerGlobalScope(const URL& scriptURL, const String& name, WorkerInitializationData&&, const ScriptBuffer& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, const CrossOriginEmbedderPolicy&, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) final;
     void terminateWorkerGlobalScope() final;
     void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) final;
     void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&) final;

Modified: trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -40,8 +40,9 @@
 
 WTF_MAKE_ISO_ALLOCATED_IMPL(WorkerOrWorkletGlobalScope);
 
-WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(WorkerThreadType type, Ref<JSC::VM>&& vm, WorkerOrWorkletThread* thread)
-    : m_script(makeUnique<WorkerOrWorkletScriptController>(type, WTFMove(vm), this))
+WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(WorkerThreadType type, Ref<JSC::VM>&& vm, WorkerOrWorkletThread* thread, ScriptExecutionContextIdentifier contextIdentifier)
+    : ScriptExecutionContext(contextIdentifier)
+    , m_script(makeUnique<WorkerOrWorkletScriptController>(type, WTFMove(vm), this))
     , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this, ScriptModuleLoader::OwnerType::WorkerOrWorklet))
     , m_thread(thread)
     , m_inspectorController(makeUnique<WorkerInspectorController>(*this))

Modified: trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -80,7 +80,7 @@
     virtual FetchOptions::Destination destination() const = 0;
 
 protected:
-    WorkerOrWorkletGlobalScope(WorkerThreadType, Ref<JSC::VM>&&, WorkerOrWorkletThread*);
+    WorkerOrWorkletGlobalScope(WorkerThreadType, Ref<JSC::VM>&&, WorkerOrWorkletThread*, ScriptExecutionContextIdentifier = { });
 
     // ScriptExecutionContext.
     bool isJSExecutionForbidden() const final;

Modified: trunk/Source/WebCore/workers/WorkerScriptLoader.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerScriptLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerScriptLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -45,12 +45,22 @@
 
 namespace WebCore {
 
+static HashMap<ScriptExecutionContextIdentifier, WorkerScriptLoader*>& scriptExecutionContextIdentifierToWorkerScriptLoaderMap()
+{
+    static MainThreadNeverDestroyed<HashMap<ScriptExecutionContextIdentifier, WorkerScriptLoader*>> map;
+    return map.get();
+}
+
 WorkerScriptLoader::WorkerScriptLoader()
     : m_script(ScriptBuffer::empty())
 {
 }
 
-WorkerScriptLoader::~WorkerScriptLoader() = default;
+WorkerScriptLoader::~WorkerScriptLoader()
+{
+    if (m_clientIdentifier)
+        scriptExecutionContextIdentifierToWorkerScriptLoaderMap().remove(m_clientIdentifier);
+}
 
 std::optional<Exception> WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecutionContext, const URL& url, Source source, FetchOptions::Mode mode, FetchOptions::Cache cachePolicy, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, const String& initiatorIdentifier)
 {
@@ -93,11 +103,7 @@
     options.sendLoadCallbacks = SendCallbackPolicy::SendCallbacks;
     options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
     options.destination = m_destination;
-#if ENABLE(SERVICE_WORKER)
-    options.serviceWorkersMode = isServiceWorkerGlobalScope ? ServiceWorkersMode::None : ServiceWorkersMode::All;
-    if (auto* activeServiceWorker = workerGlobalScope.activeServiceWorker())
-        options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
-#endif
+
     WorkerThreadableLoader::loadResourceSynchronously(workerGlobalScope, WTFMove(*request), *this, options);
 
     // If the fetching attempt failed, throw a NetworkError exception and abort all these steps.
@@ -115,7 +121,7 @@
     return std::nullopt;
 }
 
-void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, Source source, FetchOptions&& fetchOptions, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, ServiceWorkersMode serviceWorkerMode, WorkerScriptLoaderClient& client, String&& taskMode)
+void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, Source source, FetchOptions&& fetchOptions, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, ServiceWorkersMode serviceWorkerMode, WorkerScriptLoaderClient& client, String&& taskMode, ScriptExecutionContextIdentifier clientIdentifier)
 {
     m_client = &client;
     m_url = scriptRequest.url();
@@ -142,7 +148,17 @@
     // A service worker job can be executed from a worker context or a document context.
     options.serviceWorkersMode = serviceWorkerMode;
 #if ENABLE(SERVICE_WORKER)
-    if (auto* activeServiceWorker = scriptExecutionContext.activeServiceWorker())
+    // FIXME: Add support for shared worker.
+    if (m_destination == FetchOptions::Destination::Worker && is<Document>(scriptExecutionContext)) {
+        ASSERT(clientIdentifier);
+        // In case of blob URLs, we reuse the document controlling service worker.
+        if (request->url().protocolIsBlob() && scriptExecutionContext.activeServiceWorker())
+            setControllingServiceWorker(ServiceWorkerData { scriptExecutionContext.activeServiceWorker()->data() });
+        else {
+            options.clientIdentifier = m_clientIdentifier = clientIdentifier;
+            scriptExecutionContextIdentifierToWorkerScriptLoaderMap().add(m_clientIdentifier, this);
+        }
+    } else if (auto* activeServiceWorker = scriptExecutionContext.activeServiceWorker())
         options.serviceWorkerRegistrationIdentifier = activeServiceWorker->registrationIdentifier();
 #endif
 
@@ -305,4 +321,20 @@
     return { script(), lastRequestURL(), certificateInfo(), contentSecurityPolicy(), crossOriginEmbedderPolicy(), referrerPolicy(), { } };
 }
 
+WorkerScriptLoader* WorkerScriptLoader::fromScriptExecutionContextIdentifier(ScriptExecutionContextIdentifier identifier)
+{
+    return scriptExecutionContextIdentifierToWorkerScriptLoaderMap().get(identifier);
+}
+
+#if ENABLE(SERVICE_WORKER)
+bool WorkerScriptLoader::setControllingServiceWorker(ServiceWorkerData&& activeServiceWorkerData)
+{
+    if (!m_client)
+        return false;
+
+    m_activeServiceWorkerData = WTFMove(activeServiceWorkerData);
+    return true;
+}
+#endif
+
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerScriptLoader.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerScriptLoader.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerScriptLoader.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -34,6 +34,8 @@
 #include "ResourceRequest.h"
 #include "ResourceResponse.h"
 #include "ScriptBuffer.h"
+#include "ScriptExecutionContextIdentifier.h"
+#include "ServiceWorkerRegistrationData.h"
 #include "ThreadableLoader.h"
 #include "ThreadableLoaderClient.h"
 #include <memory>
@@ -49,6 +51,7 @@
 class ScriptExecutionContext;
 class TextResourceDecoder;
 class WorkerScriptLoaderClient;
+struct ServiceWorkerRegistrationData;
 struct WorkerFetchResult;
 enum class CertificateInfoPolicy : uint8_t;
 
@@ -63,7 +66,7 @@
     enum class Source : uint8_t { ClassicWorkerScript, ClassicWorkerImport, ModuleScript };
 
     std::optional<Exception> loadSynchronously(ScriptExecutionContext*, const URL&, Source, FetchOptions::Mode, FetchOptions::Cache, ContentSecurityPolicyEnforcement, const String& initiatorIdentifier);
-    void loadAsynchronously(ScriptExecutionContext&, ResourceRequest&&, Source, FetchOptions&&, ContentSecurityPolicyEnforcement, ServiceWorkersMode, WorkerScriptLoaderClient&, String&& taskMode);
+    void loadAsynchronously(ScriptExecutionContext&, ResourceRequest&&, Source, FetchOptions&&, ContentSecurityPolicyEnforcement, ServiceWorkersMode, WorkerScriptLoaderClient&, String&& taskMode, ScriptExecutionContextIdentifier clientIdentifier = { });
 
     void notifyError();
 
@@ -94,6 +97,13 @@
 
     WEBCORE_EXPORT static ResourceError validateWorkerResponse(const ResourceResponse&, Source, FetchOptions::Destination);
 
+    WEBCORE_EXPORT static WorkerScriptLoader* fromScriptExecutionContextIdentifier(ScriptExecutionContextIdentifier);
+
+#if ENABLE(SERVICE_WORKER)
+    WEBCORE_EXPORT bool setControllingServiceWorker(ServiceWorkerData&&);
+    std::optional<ServiceWorkerData> takeServiceWorkerData() { return std::exchange(m_activeServiceWorkerData, { }); }
+#endif
+
 private:
     friend class RefCounted<WorkerScriptLoader>;
     friend struct std::default_delete<WorkerScriptLoader>;
@@ -125,6 +135,10 @@
     bool m_isCOEPEnabled { false };
     ResourceResponse::Source m_responseSource { ResourceResponse::Source::Unknown };
     ResourceError m_error;
+    ScriptExecutionContextIdentifier m_clientIdentifier;
+#if ENABLE(SERVICE_WORKER)
+    std::optional<ServiceWorkerData> m_activeServiceWorkerData;
+#endif
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerThread.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerThread.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerThread.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -64,6 +64,10 @@
         settingsValues.isolatedCopy(),
         workerThreadMode,
         sessionID,
+#if ENABLE(SERVICE_WORKER)
+        crossThreadCopy(serviceWorkerData),
+#endif
+        clientIdentifier
     };
 }
 

Modified: trunk/Source/WebCore/workers/WorkerThread.h (292860 => 292861)


--- trunk/Source/WebCore/workers/WorkerThread.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/WorkerThread.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -29,6 +29,8 @@
 #include "CrossOriginEmbedderPolicy.h"
 #include "FetchRequestCredentials.h"
 #include "NotificationPermission.h"
+#include "ScriptExecutionContextIdentifier.h"
+#include "ServiceWorkerRegistrationData.h"
 #include "WorkerOrWorkletThread.h"
 #include "WorkerRunLoop.h"
 #include "WorkerType.h"
@@ -76,6 +78,10 @@
     Settings::Values settingsValues;
     WorkerThreadMode workerThreadMode { WorkerThreadMode::CreateNewThread };
     std::optional<PAL::SessionID> sessionID { std::nullopt };
+#if ENABLE(SERVICE_WORKER)
+    std::optional<ServiceWorkerData> serviceWorkerData;
+#endif
+    ScriptExecutionContextIdentifier clientIdentifier;
 
     WorkerParameters isolatedCopy() const;
 };

Modified: trunk/Source/WebCore/workers/service/SWClientConnection.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/service/SWClientConnection.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/SWClientConnection.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -227,6 +227,13 @@
     });
 }
 
+static void updateController(ScriptExecutionContext& context, ServiceWorkerData&& newController)
+{
+    context.setActiveServiceWorker(ServiceWorker::getOrCreate(context, WTFMove(newController)));
+    if (auto* container = context.serviceWorkerContainer())
+        container->queueTaskToDispatchControllerChangeEvent();
+}
+
 void SWClientConnection::notifyClientsOfControllerChange(const HashSet<ScriptExecutionContextIdentifier>& contextIdentifiers, ServiceWorkerData&& newController)
 {
     ASSERT(isMainThread());
@@ -233,14 +240,17 @@
     ASSERT(!contextIdentifiers.isEmpty());
 
     for (auto& clientIdentifier : contextIdentifiers) {
-        // FIXME: Support worker contexts.
-        auto* client = Document::allDocumentsMap().get(clientIdentifier);
-        if (!client)
+        if (auto* document = Document::allDocumentsMap().get(clientIdentifier)) {
+            updateController(*document, ServiceWorkerData { newController });
             continue;
-
-        client->setActiveServiceWorker(ServiceWorker::getOrCreate(*client, WTFMove(newController)));
-        if (auto* container = client->serviceWorkerContainer())
-            container->queueTaskToDispatchControllerChangeEvent();
+        }
+        if (auto* worker = Worker::workerByIdentifier(clientIdentifier)) {
+            worker->postTaskToWorkerGlobalScope([newController = newController.isolatedCopy()] (auto& context) mutable {
+                updateController(context, WTFMove(newController));
+            });
+            continue;
+        }
+        // FIXME: Support shared workers.
     }
 }
 
@@ -261,10 +271,11 @@
 
 void SWClientConnection::registerServiceWorkerClients()
 {
-    for (auto* document : Document::allDocuments()) {
-        auto controllingServiceWorkerRegistrationIdentifier = document->activeServiceWorker() ? std::make_optional<ServiceWorkerRegistrationIdentifier>(document->activeServiceWorker()->registrationIdentifier()) : std::nullopt;
-        registerServiceWorkerClient(document->topOrigin(), ServiceWorkerClientData::from(*document), controllingServiceWorkerRegistrationIdentifier, document->userAgent(document->url()));
-    }
+    for (auto* document : Document::allDocuments())
+        document->updateServiceWorkerClientData();
+
+    SharedWorkerContextManager::singleton().forEachSharedWorker([] { return [] (auto& context) { context.updateServiceWorkerClientData(); }; });
+    Worker::forEachWorker([] { return [] (auto& context) { context.updateServiceWorkerClientData(); }; });
 }
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/service/ServiceWorker.h (292860 => 292861)


--- trunk/Source/WebCore/workers/service/ServiceWorker.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/ServiceWorker.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -70,6 +70,8 @@
     using RefCounted::ref;
     using RefCounted::deref;
 
+    const ServiceWorkerData& data() const { return m_data; }
+
 private:
     ServiceWorker(ScriptExecutionContext&, ServiceWorkerData&&);
     void updatePendingActivityForEventDispatch();

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClientData.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClientData.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClientData.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -69,30 +69,44 @@
 
 ServiceWorkerClientData ServiceWorkerClientData::from(ScriptExecutionContext& context)
 {
-    bool isDocument = is<Document>(context);
-    RELEASE_ASSERT(isDocument); // We do not support dedicated workers as clients yet.
+    if (auto* document = dynamicDowncast<Document>(context)) {
+        auto lastNavigationWasAppInitiated = document->loader() && document->loader()->lastNavigationWasAppInitiated() ? LastNavigationWasAppInitiated::Yes : LastNavigationWasAppInitiated::No;
 
-    auto& document = downcast<Document>(context);
-    auto lastNavigationWasAppInitiated = document.loader() && document.loader()->lastNavigationWasAppInitiated() ? LastNavigationWasAppInitiated::Yes : LastNavigationWasAppInitiated::No;
+        Vector<String> ancestorOrigins;
+        if (auto* frame = document->frame()) {
+            for (auto* ancestor = frame->tree().parent(); ancestor; ancestor = ancestor->tree().parent())
+                ancestorOrigins.append(ancestor->document()->securityOrigin().toString());
+        }
 
-    Vector<String> ancestorOrigins;
-    if (auto* frame = document.frame()) {
-        for (auto* ancestor = frame->tree().parent(); ancestor; ancestor = ancestor->tree().parent())
-            ancestorOrigins.append(ancestor->document()->securityOrigin().toString());
+        return {
+            context.identifier(),
+            ServiceWorkerClientType::Window,
+            toServiceWorkerClientFrameType(context),
+            document->creationURL(),
+            document->pageID(),
+            document->frameID(),
+            lastNavigationWasAppInitiated,
+            !document->hidden(),
+            document->hasFocus(),
+            0,
+            WTFMove(ancestorOrigins)
+        };
     }
 
+    RELEASE_ASSERT(is<WorkerGlobalScope>(context));
+    auto& scope = downcast<WorkerGlobalScope>(context);
     return {
-        context.identifier(),
-        isDocument ? ServiceWorkerClientType::Window : ServiceWorkerClientType::Worker,
-        toServiceWorkerClientFrameType(context),
-        document.creationURL(),
-        document.pageID(),
-        document.frameID(),
-        lastNavigationWasAppInitiated,
-        !document.hidden(),
-        document.hasFocus(),
+        scope.identifier(),
+        scope.type() == WebCore::WorkerGlobalScope::Type::SharedWorker ? ServiceWorkerClientType::Sharedworker : ServiceWorkerClientType::Worker,
+        ServiceWorkerClientFrameType::None,
+        scope.url(),
+        { },
+        { },
+        LastNavigationWasAppInitiated::No,
+        false,
+        false,
         0,
-        WTFMove(ancestorOrigins)
+        { }
     };
 }
 

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClientType.h (292860 => 292861)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClientType.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClientType.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -31,7 +31,7 @@
 
 namespace WebCore {
 
-enum class ServiceWorkerClientType {
+enum class ServiceWorkerClientType : uint8_t {
     Window,
     Worker,
     Sharedworker,

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContainer.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -30,6 +30,7 @@
 
 #include "ContentSecurityPolicy.h"
 #include "DOMPromiseProxy.h"
+#include "DedicatedWorkerGlobalScope.h"
 #include "Document.h"
 #include "Event.h"
 #include "EventLoop.h"
@@ -132,7 +133,7 @@
 ServiceWorker* ServiceWorkerContainer::controller() const
 {
     auto* context = scriptExecutionContext();
-    ASSERT_WITH_MESSAGE(!context || is<Document>(*context) || !context->activeServiceWorker(), "Only documents can have a controller at the moment.");
+    ASSERT_WITH_MESSAGE(!context || is<Document>(*context) || is<DedicatedWorkerGlobalScope>(*context) || !context->activeServiceWorker(), "Only documents and dedicated workers can have a controller at the moment.");
     return context ? context->activeServiceWorker() : nullptr;
 }
 

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


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -95,7 +95,9 @@
         FetchRequestCredentials::Omit,
         settingsValues,
         workerThreadMode,
-        sessionID
+        sessionID,
+        { },
+        { }
     };
 }
 

Modified: trunk/Source/WebCore/workers/shared/SharedWorkerScriptLoader.h (292860 => 292861)


--- trunk/Source/WebCore/workers/shared/SharedWorkerScriptLoader.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/shared/SharedWorkerScriptLoader.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -36,6 +36,7 @@
 
 namespace WebCore {
 
+struct ServiceWorkerRegistrationData;
 class SharedWorker;
 class WorkerScriptLoader;
 struct WorkerFetchResult;

Modified: trunk/Source/WebCore/workers/shared/context/SharedWorkerThreadProxy.cpp (292860 => 292861)


--- trunk/Source/WebCore/workers/shared/context/SharedWorkerThreadProxy.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebCore/workers/shared/context/SharedWorkerThreadProxy.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -57,7 +57,7 @@
 
 static WorkerParameters generateWorkerParameters(const WorkerFetchResult& workerFetchResult, WorkerOptions&& workerOptions, const String& userAgent, Document& document)
 {
-    return WorkerParameters {
+    return {
         workerFetchResult.lastRequestURL,
         workerOptions.name,
         "sharedworker:" + Inspector::IdentifiersFactory::createIdentifier(),
@@ -70,7 +70,13 @@
         parseReferrerPolicy(workerFetchResult.referrerPolicy, ReferrerPolicySource::HTTPHeader).value_or(ReferrerPolicy::EmptyString),
         workerOptions.type,
         workerOptions.credentials,
-        document.settingsValues()
+        document.settingsValues(),
+        WorkerThreadMode::CreateNewThread,
+        { },
+#if ENABLE(SERVICE_WORKER)
+        { },
+#endif
+        { }
     };
 }
 

Modified: trunk/Source/WebKit/ChangeLog (292860 => 292861)


--- trunk/Source/WebKit/ChangeLog	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/ChangeLog	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,5 +1,27 @@
 2022-04-14  Youenn Fablet  <[email protected]>
 
+        Expose workers as service worker clients and implement registration matching for dedicated workers
+        https://bugs.webkit.org/show_bug.cgi?id=239066
+
+        Reviewed by Chris Dumez.
+
+        Reuse the same strategy for DedicatedWorkers as for Documents to match registrations and control then:
+        - Do matching in network process
+        - If matching, send a message to WebProcess to set the matching registration data.
+        Add specific handling for worker registration rematching in case of redirections:
+        - If redirection comes from service worker (via respondWith), do rematching.
+        - If redirection comes from network, do not do rematching.
+
+        * NetworkProcess/NetworkResourceLoader.cpp:
+        * NetworkProcess/ServiceWorker/ServiceWorkerFetchTask.cpp:
+        * NetworkProcess/ServiceWorker/WebSWServerConnection.cpp:
+        * WebProcess/Network/WebLoaderStrategy.cpp:
+        * WebProcess/Storage/WebSWClientConnection.cpp:
+        * WebProcess/Storage/WebSWClientConnection.h:
+        * WebProcess/Storage/WebSWClientConnection.messages.in:
+
+2022-04-14  Youenn Fablet  <[email protected]>
+
         A shared worker in a cached page should not allow the remote shared worker to continue executing
         https://bugs.webkit.org/show_bug.cgi?id=239286
 

Modified: trunk/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp (292860 => 292861)


--- trunk/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1220,7 +1220,7 @@
     LOADER_RELEASE_LOG("continueWillSendRequest: (isAllowedToAskUserForCredentials=%d)", isAllowedToAskUserForCredentials);
 
 #if ENABLE(SERVICE_WORKER)
-    if (parameters().options.mode == FetchOptions::Mode::Navigate) {
+    if (parameters().options.mode == FetchOptions::Mode::Navigate || (parameters().options.destination == FetchOptions::Destination::Worker && m_serviceWorkerFetchTask)) {
         m_serviceWorkerRegistration = { };
         if (auto serviceWorkerFetchTask = m_connection->createFetchTask(*this, newRequest)) {
             LOADER_RELEASE_LOG("continueWillSendRequest: Created a ServiceWorkerFetchTask to handle the redirect (fetchIdentifier=%" PRIu64 ")", serviceWorkerFetchTask->fetchIdentifier().toUInt64());

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerFetchTask.cpp (292860 => 292861)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerFetchTask.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerFetchTask.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -153,7 +153,7 @@
     cleanHTTPRequestHeadersForAccessControl(request, m_loader.parameters().httpHeadersToKeep);
 
     String clientIdentifier;
-    if (m_loader.parameters().options.mode != FetchOptions::Mode::Navigate) {
+    if (m_loader.parameters().options.mode != FetchOptions::Mode::Navigate && m_loader.parameters().options.destination != FetchOptions::Destination::Worker) {
         if (auto identifier = m_loader.parameters().options.clientIdentifier)
             clientIdentifier = identifier->toString();
     }

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp (292860 => 292861)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -166,11 +166,17 @@
 
 void WebSWServerConnection::controlClient(const NetworkResourceLoadParameters& parameters, SWServerRegistration& registration, const ResourceRequest& request)
 {
+    ServiceWorkerClientType clientType;
+    if (parameters.options.destination  == FetchOptions::Destination::Worker)
+        clientType = ServiceWorkerClientType::Worker;
+    else
+        clientType = ServiceWorkerClientType::Window;
+
     auto clientIdentifier = *parameters.options.clientIdentifier;
     // As per step 12 of https://w3c.github.io/ServiceWorker/#on-fetch-request-algorithm, the active service worker should be controlling the document.
     // We register the service worker client using the identifier provided by DocumentLoader and notify DocumentLoader about it.
     // If notification is successful, DocumentLoader is responsible to unregister the service worker client as needed.
-    sendWithAsyncReply(Messages::WebSWClientConnection::SetDocumentIsControlled { clientIdentifier, registration.data() }, [weakThis = WeakPtr { *this }, this, clientIdentifier](bool isSuccess) {
+    sendWithAsyncReply(Messages::WebSWClientConnection::SetServiceWorkerClientIsControlled { clientIdentifier, registration.data() }, [weakThis = WeakPtr { *this }, this, clientIdentifier](bool isSuccess) {
         if (!weakThis || isSuccess)
             return;
         unregisterServiceWorkerClient(clientIdentifier);
@@ -177,7 +183,7 @@
     });
 
     auto ancestorOrigins = map(parameters.frameAncestorOrigins, [](auto& origin) { return origin->toString(); });
-    ServiceWorkerClientData data { clientIdentifier, ServiceWorkerClientType::Window, ServiceWorkerClientFrameType::None, request.url(), parameters.webPageID, parameters.webFrameID, request.isAppInitiated() ? WebCore::LastNavigationWasAppInitiated::Yes : WebCore::LastNavigationWasAppInitiated::No, false, false, 0, WTFMove(ancestorOrigins) };
+    ServiceWorkerClientData data { clientIdentifier, clientType, ServiceWorkerClientFrameType::None, request.url(), parameters.webPageID, parameters.webFrameID, request.isAppInitiated() ? WebCore::LastNavigationWasAppInitiated::Yes : WebCore::LastNavigationWasAppInitiated::No, false, false, 0, WTFMove(ancestorOrigins) };
     registerServiceWorkerClient(SecurityOriginData { registration.key().topOrigin() }, WTFMove(data), registration.identifier(), request.httpUserAgent());
 }
 
@@ -195,7 +201,7 @@
         return nullptr;
 
     std::optional<ServiceWorkerRegistrationIdentifier> serviceWorkerRegistrationIdentifier;
-    if (loader.parameters().options.mode == FetchOptions::Mode::Navigate) {
+    if (loader.parameters().options.mode == FetchOptions::Mode::Navigate || loader.parameters().options.destination == FetchOptions::Destination::Worker) {
         auto topOrigin = loader.parameters().isMainFrameNavigation ? SecurityOriginData::fromURL(request.url()) : loader.parameters().topOrigin->data();
         auto* registration = doRegistrationMatching(topOrigin, request.url());
         if (!registration)

Modified: trunk/Source/WebKit/WebProcess/Network/WebLoaderStrategy.cpp (292860 => 292861)


--- trunk/Source/WebKit/WebProcess/Network/WebLoaderStrategy.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/WebProcess/Network/WebLoaderStrategy.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -460,13 +460,6 @@
         for (auto* frame = resourceLoader.frame()->tree().parent(); frame; frame = frame->tree().parent())
             frameAncestorOrigins.append(&frame->document()->securityOrigin());
         loadParameters.frameAncestorOrigins = WTFMove(frameAncestorOrigins);
-
-#if ENABLE(SERVICE_WORKER)
-        if (auto* documentLoader = resourceLoader.documentLoader()) {
-            if (auto resultingClientId = static_cast<WebDocumentLoader&>(*documentLoader).resultingClientId())
-                loadParameters.options.clientIdentifier = resultingClientId;
-        }
-#endif
     }
 
     ASSERT((loadParameters.webPageID && loadParameters.webFrameID) || loadParameters.clientCredentialPolicy == ClientCredentialPolicy::CannotAskClientForCredentials);

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp (292860 => 292861)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp	2022-04-14 08:48:21 UTC (rev 292861)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 Apple Inc. All rights reserved.
+ * Copyright (C) 2017-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -53,6 +53,7 @@
 #include <WebCore/ServiceWorkerRegistrationData.h>
 #include <WebCore/ServiceWorkerRegistrationKey.h>
 #include <WebCore/WorkerFetchResult.h>
+#include <WebCore/WorkerScriptLoader.h>
 
 namespace WebKit {
 using namespace PAL;
@@ -180,11 +181,18 @@
     });
 }
 
-void WebSWClientConnection::setDocumentIsControlled(ScriptExecutionContextIdentifier documentIdentifier, ServiceWorkerRegistrationData&& data, CompletionHandler<void(bool)>&& completionHandler)
+void WebSWClientConnection::setServiceWorkerClientIsControlled(ScriptExecutionContextIdentifier identifier, ServiceWorkerRegistrationData&& data, CompletionHandler<void(bool)>&& completionHandler)
 {
-    auto* documentLoader = DocumentLoader::fromScriptExecutionContextIdentifier(documentIdentifier);
-    bool result = documentLoader ? documentLoader->setControllingServiceWorkerRegistration(WTFMove(data)) : false;
-    completionHandler(result);
+    if (auto* loader = DocumentLoader::fromScriptExecutionContextIdentifier(identifier)) {
+        completionHandler(loader->setControllingServiceWorkerRegistration(WTFMove(data)));
+        return;
+    }
+
+    if (auto* loader = WorkerScriptLoader::fromScriptExecutionContextIdentifier(identifier)) {
+        completionHandler(data.activeWorker ? loader->setControllingServiceWorker(WTFMove(*data.activeWorker)) : false);
+        return;
+    }
+    completionHandler(false);
 }
 
 void WebSWClientConnection::getRegistrations(SecurityOriginData&& topOrigin, const URL& clientURL, GetRegistrationsCallback&& callback)

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h (292860 => 292861)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h	2022-04-14 08:48:21 UTC (rev 292861)
@@ -82,7 +82,8 @@
     void didGetRegistrations(uint64_t matchRequestIdentifier, Vector<WebCore::ServiceWorkerRegistrationData>&&);
     void whenRegistrationReady(const WebCore::SecurityOriginData& topOrigin, const URL& clientURL, WhenRegistrationReadyCallback&&) final;
 
-    void setDocumentIsControlled(WebCore::ScriptExecutionContextIdentifier, WebCore::ServiceWorkerRegistrationData&&, CompletionHandler<void(bool)>&&);
+    void setServiceWorkerClientIsControlled(WebCore::ScriptExecutionContextIdentifier, WebCore::ServiceWorkerRegistrationData&&, CompletionHandler<void(bool)>&&);
+    void setWorkerIsControlled(WebCore::ScriptExecutionContextIdentifier, WebCore::ServiceWorkerRegistrationData&&, CompletionHandler<void(bool)>&&);
 
     void getRegistrations(WebCore::SecurityOriginData&& topOrigin, const URL& clientURL, GetRegistrationsCallback&&) final;
     void whenServiceWorkerIsTerminatedForTesting(WebCore::ServiceWorkerIdentifier, CompletionHandler<void()>&&) final;

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in (292860 => 292861)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in	2022-04-14 07:16:17 UTC (rev 292860)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in	2022-04-14 08:48:21 UTC (rev 292861)
@@ -38,7 +38,7 @@
     SetSWOriginTableSharedMemory(WebKit::SharedMemory::IPCHandle handle)
     PostMessageToServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier destinationContextIdentifier, struct WebCore::MessageWithMessagePorts message, struct WebCore::ServiceWorkerData source, String sourceOrigin)
 
-    SetDocumentIsControlled(WebCore::ScriptExecutionContextIdentifier temporaryDocumentIdentifier, struct WebCore::ServiceWorkerRegistrationData data) -> (bool isSuccess)
+    SetServiceWorkerClientIsControlled(WebCore::ScriptExecutionContextIdentifier workerIdentifier, struct WebCore::ServiceWorkerRegistrationData data) -> (bool isSuccess)
 
     FocusServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier clientIdentifier) -> (std::optional<WebCore::ServiceWorkerClientData> result)
 }
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to