161d15b061a5367be49488afbca324e83437c7fa
[WebKit-https.git] / Source / WebCore / workers / service / server / SWServer.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 "SWServer.h"
28
29 #if ENABLE(SERVICE_WORKER)
30
31 #include "ExceptionCode.h"
32 #include "ExceptionData.h"
33 #include "Logging.h"
34 #include "RegistrationStore.h"
35 #include "SWOriginStore.h"
36 #include "SWServerJobQueue.h"
37 #include "SWServerRegistration.h"
38 #include "SWServerToContextConnection.h"
39 #include "SWServerWorker.h"
40 #include "SecurityOrigin.h"
41 #include "ServiceWorkerClientType.h"
42 #include "ServiceWorkerContextData.h"
43 #include "ServiceWorkerFetchResult.h"
44 #include "ServiceWorkerJobData.h"
45 #include <wtf/CompletionHandler.h>
46 #include <wtf/NeverDestroyed.h>
47 #include <wtf/text/WTFString.h>
48
49 namespace WebCore {
50
51 static Seconds terminationDelay { 10_s };
52
53 SWServer::Connection::Connection(SWServer& server)
54     : m_server(server)
55     , m_identifier(generateObjectIdentifier<SWServerConnectionIdentifierType>())
56 {
57     m_server.registerConnection(*this);
58 }
59
60 SWServer::Connection::~Connection()
61 {
62     m_server.unregisterConnection(*this);
63 }
64
65 HashSet<SWServer*>& SWServer::allServers()
66 {
67     static NeverDestroyed<HashSet<SWServer*>> servers;
68     return servers;
69 }
70
71 SWServer::~SWServer()
72 {
73     RELEASE_ASSERT(m_connections.isEmpty());
74     RELEASE_ASSERT(m_registrations.isEmpty());
75     RELEASE_ASSERT(m_jobQueues.isEmpty());
76
77     ASSERT(m_taskQueue.isEmpty());
78     ASSERT(m_taskReplyQueue.isEmpty());
79
80     // For a SWServer to be cleanly shut down its thread must have finished and gone away.
81     // At this stage in development of the feature that actually never happens.
82     // But once it does start happening, this ASSERT will catch us doing it wrong.
83     Locker<Lock> locker(m_taskThreadLock);
84     ASSERT(!m_taskThread);
85     
86     allServers().remove(this);
87 }
88
89 SWServerWorker* SWServer::workerByID(ServiceWorkerIdentifier identifier) const
90 {
91     auto* worker = SWServerWorker::existingWorkerForIdentifier(identifier);
92     ASSERT(!worker || &worker->server() == this);
93     return worker;
94 }
95
96 std::optional<ServiceWorkerClientData> SWServer::serviceWorkerClientByID(const ServiceWorkerClientIdentifier& clientIdentifier) const
97 {
98     auto iterator = m_clientsById.find(clientIdentifier);
99     if (iterator == m_clientsById.end())
100         return std::nullopt;
101     return iterator->value;
102 }
103
104 SWServerWorker* SWServer::activeWorkerFromRegistrationID(ServiceWorkerRegistrationIdentifier identifier)
105 {
106     auto* registration = m_registrationsByID.get(identifier);
107     return registration ? registration->activeWorker() : nullptr;
108 }
109
110 SWServerRegistration* SWServer::getRegistration(const ServiceWorkerRegistrationKey& registrationKey)
111 {
112     return m_registrations.get(registrationKey);
113 }
114
115 void SWServer::registrationStoreImportComplete()
116 {
117     ASSERT(!m_importCompleted);
118     m_importCompleted = true;
119     m_originStore->importComplete();
120     performGetOriginsWithRegistrationsCallbacks();
121 }
122
123 void SWServer::registrationStoreDatabaseFailedToOpen()
124 {
125     if (!m_importCompleted)
126         registrationStoreImportComplete();
127 }
128
129 void SWServer::addRegistrationFromStore(ServiceWorkerContextData&& data)
130 {
131     // Pages should not have been able to make a new registration to this key while the import was still taking place.
132     ASSERT(!m_registrations.contains(data.registration.key));
133
134     auto registration = std::make_unique<SWServerRegistration>(*this, data.registration.key, data.registration.updateViaCache, data.registration.scopeURL, data.scriptURL);
135     registration->setLastUpdateTime(data.registration.lastUpdateTime);
136     addRegistration(WTFMove(registration));
137     tryInstallContextData(WTFMove(data));
138 }
139
140 void SWServer::addRegistration(std::unique_ptr<SWServerRegistration>&& registration)
141 {
142     auto key = registration->key();
143     auto* registrationPtr = registration.get();
144     auto addResult1 = m_registrations.add(key, WTFMove(registration));
145     ASSERT_UNUSED(addResult1, addResult1.isNewEntry);
146
147     auto addResult2 = m_registrationsByID.add(registrationPtr->identifier(), registrationPtr);
148     ASSERT_UNUSED(addResult2, addResult2.isNewEntry);
149
150     m_originStore->add(key.topOrigin().securityOrigin());
151 }
152
153 void SWServer::removeRegistration(const ServiceWorkerRegistrationKey& key)
154 {
155     auto topOrigin = key.topOrigin().securityOrigin();
156     auto registration = m_registrations.take(key);
157     ASSERT(registration);
158     bool wasRemoved = m_registrationsByID.remove(registration->identifier());
159     ASSERT_UNUSED(wasRemoved, wasRemoved);
160
161     m_originStore->remove(topOrigin);
162     m_registrationStore.removeRegistration(*registration);
163 }
164
165 Vector<ServiceWorkerRegistrationData> SWServer::getRegistrations(const SecurityOriginData& topOrigin, const URL& clientURL)
166 {
167     Vector<SWServerRegistration*> matchingRegistrations;
168     for (auto& item : m_registrations) {
169         if (!item.value->isUninstalling() && item.key.originIsMatching(topOrigin, clientURL))
170             matchingRegistrations.append(item.value.get());
171     }
172     // The specification mandates that registrations are returned in the insertion order.
173     std::sort(matchingRegistrations.begin(), matchingRegistrations.end(), [](auto& a, auto& b) {
174         return a->creationTime() < b->creationTime();
175     });
176     Vector<ServiceWorkerRegistrationData> matchingRegistrationDatas;
177     matchingRegistrationDatas.reserveInitialCapacity(matchingRegistrations.size());
178     for (auto* registration : matchingRegistrations)
179         matchingRegistrationDatas.uncheckedAppend(registration->data());
180     return matchingRegistrationDatas;
181 }
182
183 void SWServer::clearAll(WTF::CompletionHandler<void()>&& completionHandler)
184 {
185     m_jobQueues.clear();
186     while (!m_registrations.isEmpty())
187         m_registrations.begin()->value->clear();
188     ASSERT(m_registrationsByID.isEmpty());
189     m_originStore->clearAll();
190     m_registrationStore.clearAll(WTFMove(completionHandler));
191 }
192
193 void SWServer::clear(const SecurityOrigin& origin, WTF::CompletionHandler<void()>&& completionHandler)
194 {
195     m_jobQueues.removeIf([&](auto& keyAndValue) {
196         return keyAndValue.key.relatesToOrigin(origin);
197     });
198
199     Vector<SWServerRegistration*> registrationsToRemove;
200     for (auto& keyAndValue : m_registrations) {
201         if (keyAndValue.key.relatesToOrigin(origin))
202             registrationsToRemove.append(keyAndValue.value.get());
203     }
204
205     // Calling SWServerRegistration::clear() takes care of updating m_registrations, m_originStore and m_registrationStore.
206     for (auto* registration : registrationsToRemove)
207         registration->clear();
208
209     m_registrationStore.flushChanges(WTFMove(completionHandler));
210 }
211
212 void SWServer::Connection::scheduleJobInServer(ServiceWorkerJobData&& jobData)
213 {
214     LOG(ServiceWorker, "Scheduling ServiceWorker job %s in server", jobData.identifier().loggingString().utf8().data());
215     ASSERT(identifier() == jobData.connectionIdentifier());
216
217     m_server.scheduleJob(WTFMove(jobData));
218 }
219
220 void SWServer::Connection::finishFetchingScriptInServer(const ServiceWorkerFetchResult& result)
221 {
222     m_server.scriptFetchFinished(*this, result);
223 }
224
225 void SWServer::Connection::didResolveRegistrationPromise(const ServiceWorkerRegistrationKey& key)
226 {
227     m_server.didResolveRegistrationPromise(*this, key);
228 }
229
230 void SWServer::Connection::addServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
231 {
232     m_server.addClientServiceWorkerRegistration(*this, identifier);
233 }
234
235 void SWServer::Connection::removeServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
236 {
237     m_server.removeClientServiceWorkerRegistration(*this, identifier);
238 }
239
240 void SWServer::Connection::syncTerminateWorker(ServiceWorkerIdentifier identifier)
241 {
242     if (auto* worker = m_server.workerByID(identifier))
243         m_server.syncTerminateWorker(*worker);
244 }
245
246 SWServer::SWServer(UniqueRef<SWOriginStore>&& originStore, String&& registrationDatabaseDirectory, PAL::SessionID sessionID)
247     : m_originStore(WTFMove(originStore))
248     , m_registrationStore(*this, WTFMove(registrationDatabaseDirectory))
249     , m_sessionID(sessionID)
250 {
251     UNUSED_PARAM(registrationDatabaseDirectory);
252     allServers().add(this);
253     m_taskThread = Thread::create(ASCIILiteral("ServiceWorker Task Thread"), [this] {
254         taskThreadEntryPoint();
255     });
256 }
257
258 // https://w3c.github.io/ServiceWorker/#schedule-job-algorithm
259 void SWServer::scheduleJob(ServiceWorkerJobData&& jobData)
260 {
261     ASSERT(m_connections.contains(jobData.connectionIdentifier()));
262
263     if (!SWServerToContextConnection::globalServerToContextConnection()) {
264         m_pendingJobs.append(WTFMove(jobData));
265         return;
266     }
267
268     // FIXME: Per the spec, check if this job is equivalent to the last job on the queue.
269     // If it is, stack it along with that job.
270
271     auto& jobQueue = *m_jobQueues.ensure(jobData.registrationKey(), [this, &jobData] {
272         return std::make_unique<SWServerJobQueue>(*this, jobData.registrationKey());
273     }).iterator->value;
274
275     jobQueue.enqueueJob(jobData);
276     if (jobQueue.size() == 1)
277         jobQueue.runNextJob();
278 }
279
280 void SWServer::rejectJob(const ServiceWorkerJobData& jobData, const ExceptionData& exceptionData)
281 {
282     LOG(ServiceWorker, "Rejected ServiceWorker job %s in server", jobData.identifier().loggingString().utf8().data());
283     auto* connection = m_connections.get(jobData.connectionIdentifier());
284     if (!connection)
285         return;
286
287     connection->rejectJobInClient(jobData.identifier().jobIdentifier, exceptionData);
288 }
289
290 void SWServer::resolveRegistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationData& registrationData, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
291 {
292     LOG(ServiceWorker, "Resolved ServiceWorker job %s in server with registration %s", jobData.identifier().loggingString().utf8().data(), registrationData.identifier.loggingString().utf8().data());
293     auto* connection = m_connections.get(jobData.connectionIdentifier());
294     if (!connection)
295         return;
296
297     connection->resolveRegistrationJobInClient(jobData.identifier().jobIdentifier, registrationData, shouldNotifyWhenResolved);
298 }
299
300 void SWServer::resolveUnregistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationKey& registrationKey, bool unregistrationResult)
301 {
302     auto* connection = m_connections.get(jobData.connectionIdentifier());
303     if (!connection)
304         return;
305
306     connection->resolveUnregistrationJobInClient(jobData.identifier().jobIdentifier, registrationKey, unregistrationResult);
307 }
308
309 void SWServer::startScriptFetch(const ServiceWorkerJobData& jobData, FetchOptions::Cache cachePolicy)
310 {
311     LOG(ServiceWorker, "Server issuing startScriptFetch for current job %s in client", jobData.identifier().loggingString().utf8().data());
312     auto* connection = m_connections.get(jobData.connectionIdentifier());
313     if (!connection)
314         return;
315
316     connection->startScriptFetchInClient(jobData.identifier().jobIdentifier, jobData.registrationKey(), cachePolicy);
317 }
318
319 void SWServer::scriptFetchFinished(Connection& connection, const ServiceWorkerFetchResult& result)
320 {
321     LOG(ServiceWorker, "Server handling scriptFetchFinished for current job %s in client", result.jobDataIdentifier.loggingString().utf8().data());
322
323     ASSERT(m_connections.contains(result.jobDataIdentifier.connectionIdentifier));
324
325     auto jobQueue = m_jobQueues.get(result.registrationKey);
326     if (!jobQueue)
327         return;
328
329     jobQueue->scriptFetchFinished(connection, result);
330 }
331
332 void SWServer::scriptContextFailedToStart(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, const String& message)
333 {
334     if (!jobDataIdentifier)
335         return;
336
337     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
338         jobQueue->scriptContextFailedToStart(*jobDataIdentifier, worker.identifier(), message);
339 }
340
341 void SWServer::scriptContextStarted(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker)
342 {
343     if (!jobDataIdentifier)
344         return;
345
346     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
347         jobQueue->scriptContextStarted(*jobDataIdentifier, worker.identifier());
348 }
349
350 void SWServer::didFinishInstall(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, bool wasSuccessful)
351 {
352     if (!jobDataIdentifier)
353         return;
354
355     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
356         jobQueue->didFinishInstall(*jobDataIdentifier, worker.identifier(), wasSuccessful);
357 }
358
359 void SWServer::didFinishActivation(SWServerWorker& worker)
360 {
361     if (auto* registration = getRegistration(worker.registrationKey()))
362         registration->didFinishActivation(worker.identifier());
363 }
364
365 // https://w3c.github.io/ServiceWorker/#clients-getall
366 void SWServer::matchAll(SWServerWorker& worker, const ServiceWorkerClientQueryOptions& options, ServiceWorkerClientsMatchAllCallback&& callback)
367 {
368     // FIXME: Support reserved client filtering.
369     // FIXME: Support WindowClient additional properties.
370
371     Vector<ServiceWorkerClientData> matchingClients;
372     forEachClientForOrigin(worker.origin(), [&](auto& clientData) {
373         if (!options.includeUncontrolled && worker.identifier() != m_clientToControllingWorker.get(clientData.identifier))
374             return;
375         if (options.type != ServiceWorkerClientType::All && options.type != clientData.type)
376             return;
377         matchingClients.append(clientData);
378     });
379     callback(WTFMove(matchingClients));
380 }
381
382 void SWServer::forEachClientForOrigin(const ClientOrigin& origin, const WTF::Function<void(ServiceWorkerClientData&)>& apply)
383 {
384     auto iterator = m_clientIdentifiersPerOrigin.find(origin);
385     if (iterator == m_clientIdentifiersPerOrigin.end())
386         return;
387
388     for (auto& clientIdentifier : iterator->value.identifiers) {
389         auto clientIterator = m_clientsById.find(clientIdentifier);
390         ASSERT(clientIterator != m_clientsById.end());
391         apply(clientIterator->value);
392     }
393 }
394
395 void SWServer::claim(SWServerWorker& worker)
396 {
397     auto& origin = worker.origin();
398     forEachClientForOrigin(origin, [&](auto& clientData) {
399         auto* registration = doRegistrationMatching(origin.topOrigin, clientData.url);
400         if (!(registration && registration->key() == worker.registrationKey()))
401             return;
402
403         auto result = m_clientToControllingWorker.add(clientData.identifier, worker.identifier());
404         if (!result.isNewEntry) {
405             if (result.iterator->value == worker.identifier())
406                 return;
407             if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(result.iterator->value))
408                 controllingRegistration->removeClientUsingRegistration(clientData.identifier);
409             result.iterator->value = worker.identifier();
410         }
411         registration->controlClient(clientData.identifier);
412     });
413 }
414
415 void SWServer::didResolveRegistrationPromise(Connection& connection, const ServiceWorkerRegistrationKey& registrationKey)
416 {
417     ASSERT_UNUSED(connection, m_connections.contains(connection.identifier()));
418
419     if (auto* jobQueue = m_jobQueues.get(registrationKey))
420         jobQueue->didResolveRegistrationPromise();
421 }
422
423 void SWServer::addClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
424 {
425     auto* registration = m_registrationsByID.get(identifier);
426     if (!registration) {
427         LOG_ERROR("Request to add client-side ServiceWorkerRegistration to non-existent server-side registration");
428         return;
429     }
430     
431     registration->addClientServiceWorkerRegistration(connection.identifier());
432 }
433
434 void SWServer::removeClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
435 {
436     auto* registration = m_registrationsByID.get(identifier);
437     if (!registration) {
438         LOG_ERROR("Request to remove client-side ServiceWorkerRegistration from non-existent server-side registration");
439         return;
440     }
441     
442     registration->removeClientServiceWorkerRegistration(connection.identifier());
443 }
444
445 void SWServer::updateWorker(Connection&, const ServiceWorkerJobDataIdentifier& jobDataIdentifier, SWServerRegistration& registration, const URL& url, const String& script, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, WorkerType type)
446 {
447     registration.setLastUpdateTime(WallTime::now());
448     tryInstallContextData({ jobDataIdentifier, registration.data(), generateObjectIdentifier<ServiceWorkerIdentifierType>(), script, contentSecurityPolicy, url, type, false });
449 }
450
451 void SWServer::tryInstallContextData(ServiceWorkerContextData&& data)
452 {
453     // Right now we only ever keep up to one connection to one SW context process.
454     // And it should always exist if we're trying to install context data.
455     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
456     if (!connection) {
457         m_pendingContextDatas.append(WTFMove(data));
458         return;
459     }
460     
461     installContextData(data);
462 }
463
464 void SWServer::serverToContextConnectionCreated()
465 {
466     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
467     ASSERT(connection);
468
469     auto pendingContextDatas = WTFMove(m_pendingContextDatas);
470     for (auto& data : pendingContextDatas)
471         installContextData(data);
472
473     auto serviceWorkerRunRequests = WTFMove(m_serviceWorkerRunRequests);
474     for (auto& item : serviceWorkerRunRequests) {
475         bool success = runServiceWorker(item.key);
476         for (auto& callback : item.value)
477             callback(success, *connection);
478     }
479
480     auto pendingJobs = WTFMove(m_pendingJobs);
481     for (auto& jobData : pendingJobs)
482         scheduleJob(WTFMove(jobData));
483 }
484
485 void SWServer::installContextData(const ServiceWorkerContextData& data)
486 {
487     if (!data.loadedFromDisk)
488         m_registrationStore.updateRegistration(data);
489
490     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
491     ASSERT(connection);
492
493     auto* registration = m_registrations.get(data.registration.key);
494     RELEASE_ASSERT(registration);
495
496     auto worker = SWServerWorker::create(*this, *registration, connection->identifier(), data.scriptURL, data.script, data.contentSecurityPolicy, data.workerType, data.serviceWorkerIdentifier);
497
498     // We don't immediately launch all workers that were just read in from disk,
499     // as it is unlikely they will be needed immediately.
500     if (data.loadedFromDisk) {
501         registration->updateRegistrationState(ServiceWorkerRegistrationState::Active, worker.ptr());
502         worker->setState(ServiceWorkerState::Activated);
503         return;
504     }
505
506     registration->setPreInstallationWorker(worker.ptr());
507     worker->setState(SWServerWorker::State::Running);
508     auto result = m_runningOrTerminatingWorkers.add(data.serviceWorkerIdentifier, WTFMove(worker));
509     ASSERT_UNUSED(result, result.isNewEntry);
510
511     connection->installServiceWorkerContext(data, m_sessionID);
512 }
513
514 void SWServer::runServiceWorkerIfNecessary(ServiceWorkerIdentifier identifier, RunServiceWorkerCallback&& callback)
515 {
516     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
517     if (auto* worker = m_runningOrTerminatingWorkers.get(identifier)) {
518         if (worker->isRunning()) {
519             ASSERT(connection);
520             callback(true, *connection);
521             return;
522         }
523     }
524
525     if (!connection) {
526         m_serviceWorkerRunRequests.ensure(identifier, [&] {
527             return Vector<RunServiceWorkerCallback> { };
528         }).iterator->value.append(WTFMove(callback));
529         return;
530     }
531
532     callback(runServiceWorker(identifier), *connection);
533 }
534
535 bool SWServer::runServiceWorker(ServiceWorkerIdentifier identifier)
536 {
537     auto* worker = workerByID(identifier);
538     if (!worker)
539         return false;
540
541     // If the registration for a working has been removed then the request to run
542     // the worker is moot.
543     if (!getRegistration(worker->registrationKey()))
544         return false;
545
546     auto addResult = m_runningOrTerminatingWorkers.add(identifier, *worker);
547     ASSERT_UNUSED(addResult, addResult.isNewEntry || worker->isTerminating());
548
549     worker->setState(SWServerWorker::State::Running);
550
551     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
552     ASSERT(connection);
553
554     // When re-running a service worker after a context process crash, the connection identifier may have changed
555     // so we update it here.
556     worker->setContextConnectionIdentifier(connection->identifier());
557
558     connection->installServiceWorkerContext(worker->contextData(), m_sessionID);
559
560     return true;
561 }
562
563 void SWServer::terminateWorker(SWServerWorker& worker)
564 {
565     terminateWorkerInternal(worker, Asynchronous);
566 }
567
568 void SWServer::syncTerminateWorker(SWServerWorker& worker)
569 {
570     terminateWorkerInternal(worker, Synchronous);
571 }
572
573 void SWServer::terminateWorkerInternal(SWServerWorker& worker, TerminationMode mode)
574 {
575     ASSERT(m_runningOrTerminatingWorkers.get(worker.identifier()) == &worker);
576     ASSERT(worker.isRunning());
577
578     worker.setState(SWServerWorker::State::Terminating);
579
580     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
581     ASSERT(connection);
582     if (!connection) {
583         LOG_ERROR("Request to terminate a worker whose context connection does not exist");
584         workerContextTerminated(worker);
585         return;
586     }
587
588     switch (mode) {
589     case Asynchronous:
590         connection->terminateWorker(worker.identifier());
591         break;
592     case Synchronous:
593         connection->syncTerminateWorker(worker.identifier());
594         break;
595     };
596 }
597
598 void SWServer::markAllWorkersAsTerminated()
599 {
600     while (!m_runningOrTerminatingWorkers.isEmpty())
601         workerContextTerminated(m_runningOrTerminatingWorkers.begin()->value);
602 }
603
604 void SWServer::workerContextTerminated(SWServerWorker& worker)
605 {
606     worker.setState(SWServerWorker::State::NotRunning);
607
608     // At this point if no registrations are referencing the worker then it will be destroyed,
609     // removing itself from the m_workersByID map.
610     auto result = m_runningOrTerminatingWorkers.take(worker.identifier());
611     ASSERT_UNUSED(result, result && result->ptr() == &worker);
612 }
613
614 void SWServer::fireInstallEvent(SWServerWorker& worker)
615 {
616     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
617     if (!connection) {
618         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
619         return;
620     }
621
622     connection->fireInstallEvent(worker.identifier());
623 }
624
625 void SWServer::fireActivateEvent(SWServerWorker& worker)
626 {
627     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
628     if (!connection) {
629         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
630         return;
631     }
632
633     connection->fireActivateEvent(worker.identifier());
634 }
635
636 void SWServer::taskThreadEntryPoint()
637 {
638     ASSERT(!isMainThread());
639
640     while (!m_taskQueue.isKilled())
641         m_taskQueue.waitForMessage().performTask();
642
643     Locker<Lock> locker(m_taskThreadLock);
644     m_taskThread = nullptr;
645 }
646
647 void SWServer::postTask(CrossThreadTask&& task)
648 {
649     m_taskQueue.append(WTFMove(task));
650 }
651
652 void SWServer::postTaskReply(CrossThreadTask&& task)
653 {
654     m_taskReplyQueue.append(WTFMove(task));
655
656     Locker<Lock> locker(m_mainThreadReplyLock);
657     if (m_mainThreadReplyScheduled)
658         return;
659
660     m_mainThreadReplyScheduled = true;
661     callOnMainThread([this] {
662         handleTaskRepliesOnMainThread();
663     });
664 }
665
666 void SWServer::handleTaskRepliesOnMainThread()
667 {
668     {
669         Locker<Lock> locker(m_mainThreadReplyLock);
670         m_mainThreadReplyScheduled = false;
671     }
672
673     while (auto task = m_taskReplyQueue.tryGetMessage())
674         task->performTask();
675 }
676
677 void SWServer::registerConnection(Connection& connection)
678 {
679     auto result = m_connections.add(connection.identifier(), nullptr);
680     ASSERT(result.isNewEntry);
681     result.iterator->value = &connection;
682 }
683
684 void SWServer::unregisterConnection(Connection& connection)
685 {
686     ASSERT(m_connections.get(connection.identifier()) == &connection);
687     m_connections.remove(connection.identifier());
688
689     for (auto& registration : m_registrations.values())
690         registration->unregisterServerConnection(connection.identifier());
691 }
692
693 SWServerRegistration* SWServer::doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL)
694 {
695     SWServerRegistration* selectedRegistration = nullptr;
696     for (auto& registration : m_registrations.values()) {
697         if (!registration->key().isMatching(topOrigin, clientURL))
698             continue;
699         if (!selectedRegistration || selectedRegistration->key().scopeLength() < registration->key().scopeLength())
700             selectedRegistration = registration.get();
701     }
702
703     return (selectedRegistration && !selectedRegistration->isUninstalling()) ? selectedRegistration : nullptr;
704 }
705
706 void SWServer::setClientActiveWorker(ServiceWorkerClientIdentifier clientIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier)
707 {
708     m_clientToControllingWorker.set(clientIdentifier, serviceWorkerIdentifier);
709 }
710
711 SWServerRegistration* SWServer::registrationFromServiceWorkerIdentifier(ServiceWorkerIdentifier identifier)
712 {
713     auto iterator = m_runningOrTerminatingWorkers.find(identifier);
714     if (iterator == m_runningOrTerminatingWorkers.end())
715         return nullptr;
716
717     return m_registrations.get(iterator->value->registrationKey());
718 }
719
720 void SWServer::registerServiceWorkerClient(ClientOrigin&& clientOrigin, ServiceWorkerClientData&& data, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier)
721 {
722     auto clientIdentifier = data.identifier;
723     auto addResult = m_clientsById.add(clientIdentifier, WTFMove(data));
724     ASSERT_UNUSED(addResult, addResult.isNewEntry);
725
726     auto& clientIdentifiersForOrigin = m_clientIdentifiersPerOrigin.ensure(WTFMove(clientOrigin), [] {
727         return Clients { };
728     }).iterator->value;
729     clientIdentifiersForOrigin.identifiers.append(clientIdentifier);
730     clientIdentifiersForOrigin.terminateServiceWorkersTimer = nullptr;
731
732     if (!controllingServiceWorkerIdentifier)
733         return;
734
735     if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(*controllingServiceWorkerIdentifier)) {
736         controllingRegistration->addClientUsingRegistration(clientIdentifier);
737         auto result = m_clientToControllingWorker.add(clientIdentifier, *controllingServiceWorkerIdentifier);
738         ASSERT_UNUSED(result, result.isNewEntry);
739     }
740 }
741
742 void SWServer::unregisterServiceWorkerClient(const ClientOrigin& clientOrigin, ServiceWorkerClientIdentifier clientIdentifier)
743 {
744     bool wasRemoved = m_clientsById.remove(clientIdentifier);
745     ASSERT_UNUSED(wasRemoved, wasRemoved);
746
747     auto iterator = m_clientIdentifiersPerOrigin.find(clientOrigin);
748     ASSERT(iterator != m_clientIdentifiersPerOrigin.end());
749
750     auto& clientIdentifiers = iterator->value.identifiers;
751     clientIdentifiers.removeFirstMatching([&] (const auto& identifier) {
752         return clientIdentifier == identifier;
753     });
754     if (clientIdentifiers.isEmpty()) {
755         ASSERT(!iterator->value.terminateServiceWorkersTimer);
756         iterator->value.terminateServiceWorkersTimer = std::make_unique<Timer>([clientOrigin, this] {
757             for (auto& worker : m_runningOrTerminatingWorkers.values()) {
758                 if (worker->isRunning() && worker->origin() == clientOrigin)
759                     terminateWorker(worker);
760             }
761             m_clientIdentifiersPerOrigin.remove(clientOrigin);
762         });
763         iterator->value.terminateServiceWorkersTimer->startOneShot(terminationDelay);
764     }
765
766     auto workerIterator = m_clientToControllingWorker.find(clientIdentifier);
767     if (workerIterator == m_clientToControllingWorker.end())
768         return;
769
770     if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(workerIterator->value))
771         controllingRegistration->removeClientUsingRegistration(clientIdentifier);
772
773     m_clientToControllingWorker.remove(workerIterator);
774 }
775
776 void SWServer::resolveRegistrationReadyRequests(SWServerRegistration& registration)
777 {
778     for (auto* connection : m_connections.values())
779         connection->resolveRegistrationReadyRequests(registration);
780 }
781
782 void SWServer::Connection::whenRegistrationReady(uint64_t registrationReadyRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
783 {
784     if (auto* registration = doRegistrationMatching(topOrigin, clientURL)) {
785         if (registration->activeWorker()) {
786             registrationReady(registrationReadyRequestIdentifier, registration->data());
787             return;
788         }
789     }
790     m_registrationReadyRequests.append({ topOrigin, clientURL, registrationReadyRequestIdentifier });
791 }
792
793 void SWServer::Connection::resolveRegistrationReadyRequests(SWServerRegistration& registration)
794 {
795     m_registrationReadyRequests.removeAllMatching([&](auto& request) {
796         if (!registration.key().isMatching(request.topOrigin, request.clientURL))
797             return false;
798
799         registrationReady(request.identifier, registration.data());
800         return true;
801     });
802 }
803
804 void SWServer::getOriginsWithRegistrations(WTF::Function<void(const HashSet<SecurityOriginData>&)> callback)
805 {
806     m_getOriginsWithRegistrationsCallbacks.append(WTFMove(callback));
807
808     if (m_importCompleted)
809         performGetOriginsWithRegistrationsCallbacks();
810 }
811
812 void SWServer::performGetOriginsWithRegistrationsCallbacks()
813 {
814     ASSERT(isMainThread());
815     ASSERT(m_importCompleted);
816
817     if (m_getOriginsWithRegistrationsCallbacks.isEmpty())
818         return;
819
820     HashSet<SecurityOriginData> originsWithRegistrations;
821     for (auto& key : m_registrations.keys()) {
822         originsWithRegistrations.add(key.topOrigin());
823         originsWithRegistrations.add(SecurityOriginData { key.scope().protocol().toString(), key.scope().host(), key.scope().port() });
824     }
825
826     auto callbacks = WTFMove(m_getOriginsWithRegistrationsCallbacks);
827     for (auto& callback : callbacks)
828         callback(originsWithRegistrations);
829 }
830
831 } // namespace WebCore
832
833 #endif // ENABLE(SERVICE_WORKER)