Close service worker database on network process suspension
[WebKit-https.git] / Source / WebCore / workers / service / server / SWServer.h
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 #pragma once
27
28 #if ENABLE(SERVICE_WORKER)
29
30 #include "ClientOrigin.h"
31 #include "DocumentIdentifier.h"
32 #include "SWServerWorker.h"
33 #include "SecurityOriginData.h"
34 #include "ServiceWorkerClientData.h"
35 #include "ServiceWorkerIdentifier.h"
36 #include "ServiceWorkerJob.h"
37 #include "ServiceWorkerRegistrationData.h"
38 #include "ServiceWorkerRegistrationKey.h"
39 #include "ServiceWorkerTypes.h"
40 #include <wtf/HashMap.h>
41 #include <wtf/HashSet.h>
42 #include <wtf/ObjectIdentifier.h>
43 #include <wtf/RunLoop.h>
44 #include <wtf/ThreadSafeRefCounted.h>
45 #include <wtf/Threading.h>
46 #include <wtf/UniqueRef.h>
47 #include <wtf/WeakPtr.h>
48
49 namespace WebCore {
50
51 class RegistrationStore;
52 class SWOriginStore;
53 class SWServerJobQueue;
54 class SWServerRegistration;
55 class SWServerToContextConnection;
56 enum class ServiceWorkerRegistrationState : uint8_t;
57 enum class ServiceWorkerState : uint8_t;
58 struct ExceptionData;
59 struct ServiceWorkerClientQueryOptions;
60 struct ServiceWorkerContextData;
61 struct ServiceWorkerFetchResult;
62 struct ServiceWorkerRegistrationData;
63 class Timer;
64
65 class SWServer {
66     WTF_MAKE_FAST_ALLOCATED;
67 public:
68     class Connection : public CanMakeWeakPtr<Connection> {
69         WTF_MAKE_FAST_ALLOCATED;
70         friend class SWServer;
71     public:
72         virtual ~Connection() = default;
73
74         using Identifier = SWServerConnectionIdentifier;
75         Identifier identifier() const { return m_identifier; }
76
77         WEBCORE_EXPORT void didResolveRegistrationPromise(const ServiceWorkerRegistrationKey&);
78         SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL) { return m_server.doRegistrationMatching(topOrigin, clientURL); }
79         void resolveRegistrationReadyRequests(SWServerRegistration&);
80
81         // Messages to the client WebProcess
82         virtual void updateRegistrationStateInClient(ServiceWorkerRegistrationIdentifier, ServiceWorkerRegistrationState, const Optional<ServiceWorkerData>&) = 0;
83         virtual void updateWorkerStateInClient(ServiceWorkerIdentifier, ServiceWorkerState) = 0;
84         virtual void fireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier) = 0;
85         virtual void setRegistrationLastUpdateTime(ServiceWorkerRegistrationIdentifier, WallTime) = 0;
86         virtual void setRegistrationUpdateViaCache(ServiceWorkerRegistrationIdentifier, ServiceWorkerUpdateViaCache) = 0;
87         virtual void notifyClientsOfControllerChange(const HashSet<DocumentIdentifier>& contextIdentifiers, const ServiceWorkerData& newController) = 0;
88         virtual void registrationReady(uint64_t registrationReadyRequestIdentifier, ServiceWorkerRegistrationData&&) = 0;
89
90         SWServer& server() { return m_server; }
91
92     protected:
93         WEBCORE_EXPORT explicit Connection(SWServer&);
94
95         WEBCORE_EXPORT void finishFetchingScriptInServer(const ServiceWorkerFetchResult&);
96         WEBCORE_EXPORT void addServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier);
97         WEBCORE_EXPORT void removeServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier);
98         WEBCORE_EXPORT void syncTerminateWorker(ServiceWorkerIdentifier);
99         WEBCORE_EXPORT void whenRegistrationReady(uint64_t registrationReadyRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL);
100
101     private:
102         // Messages to the client WebProcess
103         virtual void rejectJobInClient(ServiceWorkerJobIdentifier, const ExceptionData&) = 0;
104         virtual void resolveRegistrationJobInClient(ServiceWorkerJobIdentifier, const ServiceWorkerRegistrationData&, ShouldNotifyWhenResolved) = 0;
105         virtual void resolveUnregistrationJobInClient(ServiceWorkerJobIdentifier, const ServiceWorkerRegistrationKey&, bool registrationResult) = 0;
106         virtual void startScriptFetchInClient(ServiceWorkerJobIdentifier, const ServiceWorkerRegistrationKey&, FetchOptions::Cache) = 0;
107
108         struct RegistrationReadyRequest {
109             SecurityOriginData topOrigin;
110             URL clientURL;
111             uint64_t identifier;
112         };
113
114         SWServer& m_server;
115         Identifier m_identifier;
116         Vector<RegistrationReadyRequest> m_registrationReadyRequests;
117     };
118
119     WEBCORE_EXPORT SWServer(UniqueRef<SWOriginStore>&&, String&& registrationDatabaseDirectory, PAL::SessionID);
120     WEBCORE_EXPORT ~SWServer();
121
122     WEBCORE_EXPORT void clearAll(WTF::CompletionHandler<void()>&&);
123     WEBCORE_EXPORT void clear(const SecurityOriginData&, WTF::CompletionHandler<void()>&&);
124
125     WEBCORE_EXPORT void startSuspension(CompletionHandler<void()>&&);
126     WEBCORE_EXPORT void endSuspension();
127
128     SWServerRegistration* getRegistration(const ServiceWorkerRegistrationKey&);
129     void addRegistration(std::unique_ptr<SWServerRegistration>&&);
130     void removeRegistration(const ServiceWorkerRegistrationKey&);
131     WEBCORE_EXPORT Vector<ServiceWorkerRegistrationData> getRegistrations(const SecurityOriginData& topOrigin, const URL& clientURL);
132
133     WEBCORE_EXPORT void scheduleJob(ServiceWorkerJobData&&);
134     void rejectJob(const ServiceWorkerJobData&, const ExceptionData&);
135     void resolveRegistrationJob(const ServiceWorkerJobData&, const ServiceWorkerRegistrationData&, ShouldNotifyWhenResolved);
136     void resolveUnregistrationJob(const ServiceWorkerJobData&, const ServiceWorkerRegistrationKey&, bool unregistrationResult);
137     void startScriptFetch(const ServiceWorkerJobData&, FetchOptions::Cache);
138
139     void updateWorker(Connection&, const ServiceWorkerJobDataIdentifier&, SWServerRegistration&, const URL&, const String& script, const ContentSecurityPolicyResponseHeaders&, const String& referrerPolicy, WorkerType, HashMap<URL, ServiceWorkerContextData::ImportedScript>&&);
140     void terminateWorker(SWServerWorker&);
141     void syncTerminateWorker(SWServerWorker&);
142     void fireInstallEvent(SWServerWorker&);
143     void fireActivateEvent(SWServerWorker&);
144
145     WEBCORE_EXPORT SWServerWorker* workerByID(ServiceWorkerIdentifier) const;
146     Optional<ServiceWorkerClientData> serviceWorkerClientWithOriginByID(const ClientOrigin&, const ServiceWorkerClientIdentifier&) const;
147     String serviceWorkerClientUserAgent(const ClientOrigin&) const;
148     WEBCORE_EXPORT SWServerWorker* activeWorkerFromRegistrationID(ServiceWorkerRegistrationIdentifier);
149
150     WEBCORE_EXPORT void markAllWorkersForRegistrableDomainAsTerminated(const RegistrableDomain&);
151     
152     WEBCORE_EXPORT void addConnection(std::unique_ptr<Connection>&&);
153     WEBCORE_EXPORT void removeConnection(SWServerConnectionIdentifier);
154     Connection* connection(SWServerConnectionIdentifier identifier) const { return m_connections.get(identifier); }
155
156     SWOriginStore& originStore() { return m_originStore; }
157
158     void scriptContextFailedToStart(const Optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&, const String& message);
159     void scriptContextStarted(const Optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&);
160     void didFinishInstall(const Optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&, bool wasSuccessful);
161     void didFinishActivation(SWServerWorker&);
162     void workerContextTerminated(SWServerWorker&);
163     void matchAll(SWServerWorker&, const ServiceWorkerClientQueryOptions&, ServiceWorkerClientsMatchAllCallback&&);
164     void claim(SWServerWorker&);
165
166     WEBCORE_EXPORT void serverToContextConnectionCreated(SWServerToContextConnection&);
167     
168     WEBCORE_EXPORT static HashSet<SWServer*>& allServers();
169
170     WEBCORE_EXPORT void registerServiceWorkerClient(ClientOrigin&&, ServiceWorkerClientData&&, const Optional<ServiceWorkerRegistrationIdentifier>&, String&& userAgent);
171     WEBCORE_EXPORT void unregisterServiceWorkerClient(const ClientOrigin&, ServiceWorkerClientIdentifier);
172
173     using RunServiceWorkerCallback = WTF::Function<void(SWServerToContextConnection*)>;
174     WEBCORE_EXPORT void runServiceWorkerIfNecessary(ServiceWorkerIdentifier, RunServiceWorkerCallback&&);
175
176     void resolveRegistrationReadyRequests(SWServerRegistration&);
177
178     void addRegistrationFromStore(ServiceWorkerContextData&&);
179     void registrationStoreImportComplete();
180     void registrationStoreDatabaseFailedToOpen();
181
182     WEBCORE_EXPORT void getOriginsWithRegistrations(Function<void(const HashSet<SecurityOriginData>&)>&&);
183
184     PAL::SessionID sessionID() const { return m_sessionID; }
185     WEBCORE_EXPORT bool needsServerToContextConnectionForRegistrableDomain(const RegistrableDomain&) const;
186
187     void disableServiceWorkerProcessTerminationDelay() { m_shouldDisableServiceWorkerProcessTerminationDelay = true; }
188
189 private:
190     void scriptFetchFinished(Connection&, const ServiceWorkerFetchResult&);
191
192     void didResolveRegistrationPromise(Connection&, const ServiceWorkerRegistrationKey&);
193
194     void addClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
195     void removeClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
196
197     void terminatePreinstallationWorker(SWServerWorker&);
198
199     WEBCORE_EXPORT SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL);
200     bool runServiceWorker(ServiceWorkerIdentifier);
201
202     void tryInstallContextData(ServiceWorkerContextData&&);
203     void installContextData(const ServiceWorkerContextData&);
204
205     SWServerRegistration* registrationFromServiceWorkerIdentifier(ServiceWorkerIdentifier);
206     void forEachClientForOrigin(const ClientOrigin&, const WTF::Function<void(ServiceWorkerClientData&)>&);
207
208     void performGetOriginsWithRegistrationsCallbacks();
209
210     enum TerminationMode {
211         Synchronous,
212         Asynchronous,
213     };
214     void terminateWorkerInternal(SWServerWorker&, TerminationMode);
215
216     HashMap<SWServerConnectionIdentifier, std::unique_ptr<Connection>> m_connections;
217     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerRegistration>> m_registrations;
218     HashMap<ServiceWorkerRegistrationIdentifier, SWServerRegistration*> m_registrationsByID;
219     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerJobQueue>> m_jobQueues;
220
221     HashMap<ServiceWorkerIdentifier, Ref<SWServerWorker>> m_runningOrTerminatingWorkers;
222
223     HashMap<RegistrableDomain, HashSet<ServiceWorkerClientIdentifier>> m_clientsByRegistrableDomain;
224     struct Clients {
225         Vector<ServiceWorkerClientIdentifier> identifiers;
226         std::unique_ptr<Timer> terminateServiceWorkersTimer;
227         String userAgent;
228     };
229     HashMap<ClientOrigin, Clients> m_clientIdentifiersPerOrigin;
230     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerClientData> m_clientsById;
231     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerRegistrationIdentifier> m_clientToControllingRegistration;
232
233     UniqueRef<SWOriginStore> m_originStore;
234     std::unique_ptr<RegistrationStore> m_registrationStore;
235     HashMap<RegistrableDomain, Vector<ServiceWorkerContextData>> m_pendingContextDatas;
236     HashMap<RegistrableDomain, HashMap<ServiceWorkerIdentifier, Vector<RunServiceWorkerCallback>>> m_serviceWorkerRunRequests;
237     PAL::SessionID m_sessionID;
238     bool m_importCompleted { false };
239     bool m_shouldDisableServiceWorkerProcessTerminationDelay { false };
240     Vector<CompletionHandler<void()>> m_clearCompletionCallbacks;
241     Vector<Function<void(const HashSet<SecurityOriginData>&)>> m_getOriginsWithRegistrationsCallbacks;
242 };
243
244 } // namespace WebCore
245
246 #endif // ENABLE(SERVICE_WORKER)