Layout Test imported/w3c/web-platform-tests/service-workers/service-worker/register...
[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 "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 SWOriginStore;
52 class SWServerJobQueue;
53 class SWServerRegistration;
54 class SWServerToContextConnection;
55 enum class ServiceWorkerRegistrationState;
56 enum class ServiceWorkerState;
57 struct ExceptionData;
58 struct ServiceWorkerClientQueryOptions;
59 struct ServiceWorkerContextData;
60 struct ServiceWorkerFetchResult;
61 struct ServiceWorkerRegistrationData;
62 class Timer;
63
64 class SWServer {
65     WTF_MAKE_FAST_ALLOCATED;
66 public:
67     class Connection {
68         WTF_MAKE_FAST_ALLOCATED;
69         friend class SWServer;
70     public:
71         WEBCORE_EXPORT virtual ~Connection();
72
73         using Identifier = SWServerConnectionIdentifier;
74         Identifier identifier() const { return m_identifier; }
75
76         auto& weakPtrFactory() { return m_weakFactory; }
77
78         WEBCORE_EXPORT void didResolveRegistrationPromise(const ServiceWorkerRegistrationKey&);
79         SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL) { return m_server.doRegistrationMatching(topOrigin, clientURL); }
80         void resolveRegistrationReadyRequests(SWServerRegistration&);
81
82         // Messages to the client WebProcess
83         virtual void updateRegistrationStateInClient(ServiceWorkerRegistrationIdentifier, ServiceWorkerRegistrationState, const std::optional<ServiceWorkerData>&) = 0;
84         virtual void updateWorkerStateInClient(ServiceWorkerIdentifier, ServiceWorkerState) = 0;
85         virtual void fireUpdateFoundEvent(ServiceWorkerRegistrationIdentifier) = 0;
86         virtual void setRegistrationLastUpdateTime(ServiceWorkerRegistrationIdentifier, WallTime) = 0;
87         virtual void setRegistrationUpdateViaCache(ServiceWorkerRegistrationIdentifier, ServiceWorkerUpdateViaCache) = 0;
88         virtual void notifyClientsOfControllerChange(const HashSet<DocumentIdentifier>& contextIdentifiers, const ServiceWorkerData& newController) = 0;
89         virtual void registrationReady(uint64_t registrationReadyRequestIdentifier, ServiceWorkerRegistrationData&&) = 0;
90
91     protected:
92         WEBCORE_EXPORT explicit Connection(SWServer&);
93         SWServer& server() { return m_server; }
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         WeakPtrFactory<Connection> m_weakFactory;
117         Vector<RegistrationReadyRequest> m_registrationReadyRequests;
118     };
119
120     WEBCORE_EXPORT SWServer(UniqueRef<SWOriginStore>&&, String&& registrationDatabaseDirectory, PAL::SessionID);
121     WEBCORE_EXPORT ~SWServer();
122
123     WEBCORE_EXPORT void clearAll(WTF::CompletionHandler<void()>&&);
124     WEBCORE_EXPORT void clear(const SecurityOrigin&, WTF::CompletionHandler<void()>&&);
125
126     SWServerRegistration* getRegistration(const ServiceWorkerRegistrationKey&);
127     void addRegistration(std::unique_ptr<SWServerRegistration>&&);
128     void removeRegistration(const ServiceWorkerRegistrationKey&);
129     WEBCORE_EXPORT Vector<ServiceWorkerRegistrationData> getRegistrations(const SecurityOriginData& topOrigin, const URL& clientURL);
130
131     WEBCORE_EXPORT void scheduleJob(ServiceWorkerJobData&&);
132     void rejectJob(const ServiceWorkerJobData&, const ExceptionData&);
133     void resolveRegistrationJob(const ServiceWorkerJobData&, const ServiceWorkerRegistrationData&, ShouldNotifyWhenResolved);
134     void resolveUnregistrationJob(const ServiceWorkerJobData&, const ServiceWorkerRegistrationKey&, bool unregistrationResult);
135     void startScriptFetch(const ServiceWorkerJobData&, FetchOptions::Cache);
136
137     void updateWorker(Connection&, const ServiceWorkerJobDataIdentifier&, SWServerRegistration&, const URL&, const String& script, const ContentSecurityPolicyResponseHeaders&, WorkerType);
138     void terminateWorker(SWServerWorker&);
139     void syncTerminateWorker(SWServerWorker&);
140     void fireInstallEvent(SWServerWorker&);
141     void fireActivateEvent(SWServerWorker&);
142
143     WEBCORE_EXPORT SWServerWorker* workerByID(ServiceWorkerIdentifier) const;
144     std::optional<ServiceWorkerClientData> serviceWorkerClientWithOriginByID(const ClientOrigin&, const ServiceWorkerClientIdentifier&) const;
145     WEBCORE_EXPORT SWServerWorker* activeWorkerFromRegistrationID(ServiceWorkerRegistrationIdentifier);
146
147     WEBCORE_EXPORT void markAllWorkersAsTerminated();
148     
149     Connection* getConnection(SWServerConnectionIdentifier identifier) { return m_connections.get(identifier); }
150     SWOriginStore& originStore() { return m_originStore; }
151
152     void scriptContextFailedToStart(const std::optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&, const String& message);
153     void scriptContextStarted(const std::optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&);
154     void didFinishInstall(const std::optional<ServiceWorkerJobDataIdentifier>&, SWServerWorker&, bool wasSuccessful);
155     void didFinishActivation(SWServerWorker&);
156     void workerContextTerminated(SWServerWorker&);
157     void matchAll(SWServerWorker&, const ServiceWorkerClientQueryOptions&, ServiceWorkerClientsMatchAllCallback&&);
158     void claim(SWServerWorker&);
159
160     WEBCORE_EXPORT void serverToContextConnectionCreated();
161     
162     WEBCORE_EXPORT static HashSet<SWServer*>& allServers();
163
164     WEBCORE_EXPORT void registerServiceWorkerClient(ClientOrigin&&, ServiceWorkerClientData&&, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier);
165     WEBCORE_EXPORT void unregisterServiceWorkerClient(const ClientOrigin&, ServiceWorkerClientIdentifier);
166
167     using RunServiceWorkerCallback = WTF::Function<void(bool, SWServerToContextConnection&)>;
168     WEBCORE_EXPORT void runServiceWorkerIfNecessary(ServiceWorkerIdentifier, RunServiceWorkerCallback&&);
169
170     void setClientActiveWorker(ServiceWorkerClientIdentifier, ServiceWorkerIdentifier);
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
181 private:
182     void registerConnection(Connection&);
183     void unregisterConnection(Connection&);
184
185     void scriptFetchFinished(Connection&, const ServiceWorkerFetchResult&);
186
187     void didResolveRegistrationPromise(Connection&, const ServiceWorkerRegistrationKey&);
188
189     void addClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
190     void removeClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
191
192     void terminatePreinstallationWorker(SWServerWorker&);
193
194     WEBCORE_EXPORT SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL);
195     bool runServiceWorker(ServiceWorkerIdentifier);
196
197     void tryInstallContextData(ServiceWorkerContextData&&);
198     void installContextData(const ServiceWorkerContextData&);
199
200     SWServerRegistration* registrationFromServiceWorkerIdentifier(ServiceWorkerIdentifier);
201     void forEachClientForOrigin(const ClientOrigin&, const WTF::Function<void(ServiceWorkerClientData&)>&);
202
203     void performGetOriginsWithRegistrationsCallbacks();
204
205     enum TerminationMode {
206         Synchronous,
207         Asynchronous,
208     };
209     void terminateWorkerInternal(SWServerWorker&, TerminationMode);
210
211     HashMap<SWServerConnectionIdentifier, Connection*> m_connections;
212     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerRegistration>> m_registrations;
213     HashMap<ServiceWorkerRegistrationIdentifier, SWServerRegistration*> m_registrationsByID;
214     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerJobQueue>> m_jobQueues;
215
216     HashMap<ServiceWorkerIdentifier, Ref<SWServerWorker>> m_runningOrTerminatingWorkers;
217
218     struct Clients {
219         Vector<ServiceWorkerClientIdentifier> identifiers;
220         std::unique_ptr<Timer> terminateServiceWorkersTimer;
221     };
222     HashMap<ClientOrigin, Clients> m_clientIdentifiersPerOrigin;
223     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerClientData> m_clientsById;
224     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerIdentifier> m_clientToControllingWorker;
225
226     UniqueRef<SWOriginStore> m_originStore;
227     RegistrationStore m_registrationStore;
228     Vector<ServiceWorkerContextData> m_pendingContextDatas;
229     HashMap<ServiceWorkerIdentifier, Vector<RunServiceWorkerCallback>> m_serviceWorkerRunRequests;
230     PAL::SessionID m_sessionID;
231     bool m_importCompleted { false };
232     Vector<CompletionHandler<void()>> m_clearCompletionCallbacks;
233     Vector<Function<void(const HashSet<SecurityOriginData>&)>> m_getOriginsWithRegistrationsCallbacks;
234 };
235
236 } // namespace WebCore
237
238 #endif // ENABLE(SERVICE_WORKER)