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