We no longer need to queue service worker jobs until the connection to the service...
[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 scheduleJobInServer(ServiceWorkerJobData&&);
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     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 markAllWorkersAsTerminated();
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&, ServiceWorkerClientsMatchAllCallback&&);
159     void claim(SWServerWorker&);
160
161     WEBCORE_EXPORT void serverToContextConnectionCreated();
162     
163     WEBCORE_EXPORT static HashSet<SWServer*>& allServers();
164
165     WEBCORE_EXPORT void registerServiceWorkerClient(ClientOrigin&&, ServiceWorkerClientData&&, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier);
166     WEBCORE_EXPORT void unregisterServiceWorkerClient(const ClientOrigin&, ServiceWorkerClientIdentifier);
167
168     using RunServiceWorkerCallback = WTF::Function<void(bool, SWServerToContextConnection&)>;
169     WEBCORE_EXPORT void runServiceWorkerIfNecessary(ServiceWorkerIdentifier, RunServiceWorkerCallback&&);
170
171     void setClientActiveWorker(ServiceWorkerClientIdentifier, ServiceWorkerIdentifier);
172     void resolveRegistrationReadyRequests(SWServerRegistration&);
173
174     void addRegistrationFromStore(ServiceWorkerContextData&&);
175     void registrationStoreImportComplete();
176     void registrationStoreDatabaseFailedToOpen();
177
178     WEBCORE_EXPORT void getOriginsWithRegistrations(WTF::Function<void(const HashSet<SecurityOriginData>&)>);
179
180 private:
181     void registerConnection(Connection&);
182     void unregisterConnection(Connection&);
183
184     void scriptFetchFinished(Connection&, const ServiceWorkerFetchResult&);
185
186     void didResolveRegistrationPromise(Connection&, const ServiceWorkerRegistrationKey&);
187
188     void addClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
189     void removeClientServiceWorkerRegistration(Connection&, ServiceWorkerRegistrationIdentifier);
190
191     WEBCORE_EXPORT SWServerRegistration* doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL);
192     bool runServiceWorker(ServiceWorkerIdentifier);
193
194     void tryInstallContextData(ServiceWorkerContextData&&);
195     void installContextData(const ServiceWorkerContextData&);
196
197     SWServerRegistration* registrationFromServiceWorkerIdentifier(ServiceWorkerIdentifier);
198     void forEachClientForOrigin(const ClientOrigin&, const WTF::Function<void(ServiceWorkerClientData&)>&);
199
200     void performGetOriginsWithRegistrationsCallbacks();
201
202     enum TerminationMode {
203         Synchronous,
204         Asynchronous,
205     };
206     void terminateWorkerInternal(SWServerWorker&, TerminationMode);
207
208     HashMap<SWServerConnectionIdentifier, Connection*> m_connections;
209     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerRegistration>> m_registrations;
210     HashMap<ServiceWorkerRegistrationIdentifier, SWServerRegistration*> m_registrationsByID;
211     HashMap<ServiceWorkerRegistrationKey, std::unique_ptr<SWServerJobQueue>> m_jobQueues;
212
213     HashMap<ServiceWorkerIdentifier, Ref<SWServerWorker>> m_runningOrTerminatingWorkers;
214
215     struct Clients {
216         Vector<ServiceWorkerClientIdentifier> identifiers;
217         std::unique_ptr<Timer> terminateServiceWorkersTimer;
218     };
219     HashMap<ClientOrigin, Clients> m_clientIdentifiersPerOrigin;
220     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerClientData> m_clientsById;
221     HashMap<ServiceWorkerClientIdentifier, ServiceWorkerIdentifier> m_clientToControllingWorker;
222
223     UniqueRef<SWOriginStore> m_originStore;
224     RegistrationStore m_registrationStore;
225     Vector<ServiceWorkerContextData> m_pendingContextDatas;
226     HashMap<ServiceWorkerIdentifier, Vector<RunServiceWorkerCallback>> m_serviceWorkerRunRequests;
227     PAL::SessionID m_sessionID;
228     bool m_importCompleted { false };
229     Vector<WTF::Function<void(const HashSet<SecurityOriginData>&)>> m_getOriginsWithRegistrationsCallbacks;
230 };
231
232 } // namespace WebCore
233
234 #endif // ENABLE(SERVICE_WORKER)