Delay some service worker operations until after the database import completes.
[WebKit-https.git] / Source / WebKit / WebProcess / Storage / WebSWClientConnection.cpp
1 /*
2  * Copyright (C) 2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "WebSWClientConnection.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "DataReference.h"
32 #include "FormDataReference.h"
33 #include "Logging.h"
34 #include "ServiceWorkerClientFetch.h"
35 #include "StorageToWebProcessConnectionMessages.h"
36 #include "WebCoreArgumentCoders.h"
37 #include "WebSWOriginTable.h"
38 #include "WebSWServerConnectionMessages.h"
39 #include <WebCore/Document.h>
40 #include <WebCore/SerializedScriptValue.h>
41 #include <WebCore/ServiceWorkerClientData.h>
42 #include <WebCore/ServiceWorkerFetchResult.h>
43 #include <WebCore/ServiceWorkerJobData.h>
44 #include <WebCore/ServiceWorkerRegistrationData.h>
45
46 using namespace PAL;
47 using namespace WebCore;
48
49 namespace WebKit {
50
51 WebSWClientConnection::WebSWClientConnection(IPC::Connection& connection, SessionID sessionID)
52     : m_sessionID(sessionID)
53     , m_connection(connection)
54     , m_swOriginTable(makeUniqueRef<WebSWOriginTable>())
55 {
56     bool result = sendSync(Messages::StorageToWebProcessConnection::EstablishSWServerConnection(sessionID), Messages::StorageToWebProcessConnection::EstablishSWServerConnection::Reply(m_identifier));
57
58     ASSERT_UNUSED(result, result);
59 }
60
61 WebSWClientConnection::~WebSWClientConnection()
62 {
63 }
64
65 void WebSWClientConnection::scheduleJobInServer(const ServiceWorkerJobData& jobData)
66 {
67     send(Messages::WebSWServerConnection::ScheduleJobInServer(jobData));
68 }
69
70 void WebSWClientConnection::finishFetchingScriptInServer(const ServiceWorkerFetchResult& result)
71 {
72     send(Messages::WebSWServerConnection::FinishFetchingScriptInServer(result));
73 }
74
75 void WebSWClientConnection::addServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
76 {
77     send(Messages::WebSWServerConnection::AddServiceWorkerRegistrationInServer(identifier));
78 }
79
80 void WebSWClientConnection::removeServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
81 {
82     send(Messages::WebSWServerConnection::RemoveServiceWorkerRegistrationInServer(identifier));
83 }
84
85 void WebSWClientConnection::postMessageToServiceWorker(ServiceWorkerIdentifier destinationIdentifier, Ref<SerializedScriptValue>&& scriptValue, ServiceWorkerClientIdentifier sourceIdentifier, ServiceWorkerClientData&& source)
86 {
87     send(Messages::WebSWServerConnection::PostMessageToServiceWorkerFromClient(destinationIdentifier, IPC::DataReference { scriptValue->data() }, sourceIdentifier, WTFMove(source)));
88 }
89
90 void WebSWClientConnection::postMessageToServiceWorker(ServiceWorkerIdentifier destinationIdentifier, Ref<SerializedScriptValue>&& scriptValue, ServiceWorkerIdentifier sourceWorkerIdentifier)
91 {
92     send(Messages::WebSWServerConnection::PostMessageToServiceWorkerFromServiceWorker(destinationIdentifier, IPC::DataReference { scriptValue->data() }, sourceWorkerIdentifier));
93 }
94
95 void WebSWClientConnection::registerServiceWorkerClient(const SecurityOrigin& topOrigin, WebCore::DocumentIdentifier contextIdentifier, const WebCore::ServiceWorkerClientData& data, const std::optional<WebCore::ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier)
96 {
97     send(Messages::WebSWServerConnection::RegisterServiceWorkerClient { SecurityOriginData::fromSecurityOrigin(topOrigin), contextIdentifier, data, controllingServiceWorkerIdentifier });
98 }
99
100 void WebSWClientConnection::unregisterServiceWorkerClient(WebCore::DocumentIdentifier contextIdentifier)
101 {
102     send(Messages::WebSWServerConnection::UnregisterServiceWorkerClient { contextIdentifier });
103 }
104
105 void WebSWClientConnection::didResolveRegistrationPromise(const ServiceWorkerRegistrationKey& key)
106 {
107     send(Messages::WebSWServerConnection::DidResolveRegistrationPromise(key));
108 }
109
110 bool WebSWClientConnection::mayHaveServiceWorkerRegisteredForOrigin(const SecurityOrigin& origin) const
111 {
112     if (!m_swOriginTable->isImported())
113         return true;
114
115     return m_swOriginTable->contains(origin);
116 }
117
118 void WebSWClientConnection::setSWOriginTableSharedMemory(const SharedMemory::Handle& handle)
119 {
120     m_swOriginTable->setSharedMemory(handle);
121 }
122
123 void WebSWClientConnection::setSWOriginTableIsImported()
124 {
125     m_swOriginTable->setIsImported();
126     while (!m_tasksPendingOriginImport.isEmpty())
127         m_tasksPendingOriginImport.takeFirst()();
128 }
129
130 void WebSWClientConnection::didMatchRegistration(uint64_t matchingRequest, std::optional<ServiceWorkerRegistrationData>&& result)
131 {
132     ASSERT(isMainThread());
133
134     if (auto completionHandler = m_ongoingMatchRegistrationTasks.take(matchingRequest))
135         completionHandler(WTFMove(result));
136 }
137
138 void WebSWClientConnection::didGetRegistrations(uint64_t matchingRequest, Vector<ServiceWorkerRegistrationData>&& registrations)
139 {
140     ASSERT(isMainThread());
141
142     if (auto completionHandler = m_ongoingGetRegistrationsTasks.take(matchingRequest))
143         completionHandler(WTFMove(registrations));
144 }
145
146 void WebSWClientConnection::matchRegistration(const SecurityOrigin& topOrigin, const URL& clientURL, RegistrationCallback&& callback)
147 {
148     ASSERT(isMainThread());
149
150     if (!mayHaveServiceWorkerRegisteredForOrigin(topOrigin)) {
151         callback(std::nullopt);
152         return;
153     }
154
155     runOrDelayTaskForImport([this, callback = WTFMove(callback), topOrigin = SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL]() mutable {
156         uint64_t callbackID = ++m_previousCallbackIdentifier;
157         m_ongoingMatchRegistrationTasks.add(callbackID, WTFMove(callback));
158         send(Messages::WebSWServerConnection::MatchRegistration(callbackID, topOrigin, clientURL));
159     });
160 }
161
162 void WebSWClientConnection::runOrDelayTaskForImport(WTF::Function<void()>&& task)
163 {
164     if (m_swOriginTable->isImported())
165         task();
166     else
167         m_tasksPendingOriginImport.append(WTFMove(task));
168 }
169
170 void WebSWClientConnection::whenRegistrationReady(const SecurityOrigin& topOrigin, const URL& clientURL, WhenRegistrationReadyCallback&& callback)
171 {
172     uint64_t callbackID = ++m_previousCallbackIdentifier;
173     m_ongoingRegistrationReadyTasks.add(callbackID, WTFMove(callback));
174     send(Messages::WebSWServerConnection::WhenRegistrationReady(callbackID, SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL));
175 }
176
177 void WebSWClientConnection::registrationReady(uint64_t callbackID, WebCore::ServiceWorkerRegistrationData&& registrationData)
178 {
179     ASSERT(registrationData.activeWorker);
180     if (auto callback = m_ongoingRegistrationReadyTasks.take(callbackID))
181         callback(WTFMove(registrationData));
182 }
183
184 void WebSWClientConnection::getRegistrations(const SecurityOrigin& topOrigin, const URL& clientURL, GetRegistrationsCallback&& callback)
185 {
186     ASSERT(isMainThread());
187
188     if (!mayHaveServiceWorkerRegisteredForOrigin(topOrigin)) {
189         callback({ });
190         return;
191     }
192
193     runOrDelayTaskForImport([this, callback = WTFMove(callback), topOrigin = SecurityOriginData::fromSecurityOrigin(topOrigin), clientURL]() mutable {
194         uint64_t callbackID = ++m_previousCallbackIdentifier;
195         m_ongoingGetRegistrationsTasks.add(callbackID, WTFMove(callback));
196         send(Messages::WebSWServerConnection::GetRegistrations(callbackID, topOrigin, clientURL));
197     });
198 }
199
200 void WebSWClientConnection::startFetch(const ResourceLoader& loader, uint64_t identifier)
201 {
202     ASSERT(loader.options().serviceWorkersMode != ServiceWorkersMode::None && loader.options().serviceWorkerIdentifier);
203     send(Messages::WebSWServerConnection::StartFetch { identifier, loader.options().serviceWorkerIdentifier.value(), loader.request(), loader.options(), IPC::FormDataReference { loader.request().httpBody() } });
204 }
205
206 void WebSWClientConnection::postMessageToServiceWorkerClient(DocumentIdentifier destinationContextIdentifier, const IPC::DataReference& message, ServiceWorkerData&& source, const String& sourceOrigin)
207 {
208     SWClientConnection::postMessageToServiceWorkerClient(destinationContextIdentifier, SerializedScriptValue::adopt(message.vector()), WTFMove(source), sourceOrigin);
209 }
210
211 void WebSWClientConnection::connectionToServerLost()
212 {
213     auto registrationTasks = WTFMove(m_ongoingMatchRegistrationTasks);
214     for (auto& callback : registrationTasks.values())
215         callback(std::nullopt);
216
217     auto getRegistrationTasks = WTFMove(m_ongoingGetRegistrationsTasks);
218     for (auto& callback : getRegistrationTasks.values())
219         callback({ });
220
221     clearPendingJobs();
222 }
223
224 void WebSWClientConnection::syncTerminateWorker(ServiceWorkerIdentifier identifier)
225 {
226     sendSync(Messages::WebSWServerConnection::SyncTerminateWorker(identifier), Messages::WebSWServerConnection::SyncTerminateWorker::Reply());
227 }
228
229 } // namespace WebKit
230
231 #endif // ENABLE(SERVICE_WORKER)