Service Workers restored from persistent storage have 'redundant' state
[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(const 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(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(const ServiceWorkerJobData& jobData)
260 {
261     ASSERT(m_connections.contains(jobData.connectionIdentifier()));
262
263     // FIXME: Per the spec, check if this job is equivalent to the last job on the queue.
264     // If it is, stack it along with that job.
265
266     auto& jobQueue = *m_jobQueues.ensure(jobData.registrationKey(), [this, &jobData] {
267         return std::make_unique<SWServerJobQueue>(*this, jobData.registrationKey());
268     }).iterator->value;
269
270     jobQueue.enqueueJob(jobData);
271     if (jobQueue.size() == 1)
272         jobQueue.runNextJob();
273 }
274
275 void SWServer::rejectJob(const ServiceWorkerJobData& jobData, const ExceptionData& exceptionData)
276 {
277     LOG(ServiceWorker, "Rejected ServiceWorker job %s in server", jobData.identifier().loggingString().utf8().data());
278     auto* connection = m_connections.get(jobData.connectionIdentifier());
279     if (!connection)
280         return;
281
282     connection->rejectJobInClient(jobData.identifier().jobIdentifier, exceptionData);
283 }
284
285 void SWServer::resolveRegistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationData& registrationData, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
286 {
287     LOG(ServiceWorker, "Resolved ServiceWorker job %s in server with registration %s", jobData.identifier().loggingString().utf8().data(), registrationData.identifier.loggingString().utf8().data());
288     auto* connection = m_connections.get(jobData.connectionIdentifier());
289     if (!connection)
290         return;
291
292     connection->resolveRegistrationJobInClient(jobData.identifier().jobIdentifier, registrationData, shouldNotifyWhenResolved);
293 }
294
295 void SWServer::resolveUnregistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationKey& registrationKey, bool unregistrationResult)
296 {
297     auto* connection = m_connections.get(jobData.connectionIdentifier());
298     if (!connection)
299         return;
300
301     connection->resolveUnregistrationJobInClient(jobData.identifier().jobIdentifier, registrationKey, unregistrationResult);
302 }
303
304 void SWServer::startScriptFetch(const ServiceWorkerJobData& jobData, FetchOptions::Cache cachePolicy)
305 {
306     LOG(ServiceWorker, "Server issuing startScriptFetch for current job %s in client", jobData.identifier().loggingString().utf8().data());
307     auto* connection = m_connections.get(jobData.connectionIdentifier());
308     if (!connection)
309         return;
310
311     connection->startScriptFetchInClient(jobData.identifier().jobIdentifier, jobData.registrationKey(), cachePolicy);
312 }
313
314 void SWServer::scriptFetchFinished(Connection& connection, const ServiceWorkerFetchResult& result)
315 {
316     LOG(ServiceWorker, "Server handling scriptFetchFinished for current job %s in client", result.jobDataIdentifier.loggingString().utf8().data());
317
318     ASSERT(m_connections.contains(result.jobDataIdentifier.connectionIdentifier));
319
320     auto jobQueue = m_jobQueues.get(result.registrationKey);
321     if (!jobQueue)
322         return;
323
324     jobQueue->scriptFetchFinished(connection, result);
325 }
326
327 void SWServer::scriptContextFailedToStart(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, const String& message)
328 {
329     if (!jobDataIdentifier)
330         return;
331
332     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
333         jobQueue->scriptContextFailedToStart(*jobDataIdentifier, worker.identifier(), message);
334 }
335
336 void SWServer::scriptContextStarted(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker)
337 {
338     if (!jobDataIdentifier)
339         return;
340
341     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
342         jobQueue->scriptContextStarted(*jobDataIdentifier, worker.identifier());
343 }
344
345 void SWServer::didFinishInstall(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, bool wasSuccessful)
346 {
347     if (!jobDataIdentifier)
348         return;
349
350     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
351         jobQueue->didFinishInstall(*jobDataIdentifier, worker.identifier(), wasSuccessful);
352 }
353
354 void SWServer::didFinishActivation(SWServerWorker& worker)
355 {
356     if (auto* registration = getRegistration(worker.registrationKey()))
357         registration->didFinishActivation(worker.identifier());
358 }
359
360 // https://w3c.github.io/ServiceWorker/#clients-getall
361 void SWServer::matchAll(SWServerWorker& worker, const ServiceWorkerClientQueryOptions& options, ServiceWorkerClientsMatchAllCallback&& callback)
362 {
363     // FIXME: Support reserved client filtering.
364     // FIXME: Support WindowClient additional properties.
365
366     Vector<ServiceWorkerClientData> matchingClients;
367     forEachClientForOrigin(worker.origin(), [&](auto& clientData) {
368         if (!options.includeUncontrolled && worker.identifier() != m_clientToControllingWorker.get(clientData.identifier))
369             return;
370         if (options.type != ServiceWorkerClientType::All && options.type != clientData.type)
371             return;
372         matchingClients.append(clientData);
373     });
374     callback(WTFMove(matchingClients));
375 }
376
377 void SWServer::forEachClientForOrigin(const ClientOrigin& origin, const WTF::Function<void(ServiceWorkerClientData&)>& apply)
378 {
379     auto iterator = m_clientIdentifiersPerOrigin.find(origin);
380     if (iterator == m_clientIdentifiersPerOrigin.end())
381         return;
382
383     for (auto& clientIdentifier : iterator->value.identifiers) {
384         auto clientIterator = m_clientsById.find(clientIdentifier);
385         ASSERT(clientIterator != m_clientsById.end());
386         apply(clientIterator->value);
387     }
388 }
389
390 void SWServer::claim(SWServerWorker& worker)
391 {
392     auto& origin = worker.origin();
393     forEachClientForOrigin(origin, [&](auto& clientData) {
394         auto* registration = doRegistrationMatching(origin.topOrigin, clientData.url);
395         if (!(registration && registration->key() == worker.registrationKey()))
396             return;
397
398         auto result = m_clientToControllingWorker.add(clientData.identifier, worker.identifier());
399         if (!result.isNewEntry) {
400             if (result.iterator->value == worker.identifier())
401                 return;
402             if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(result.iterator->value))
403                 controllingRegistration->removeClientUsingRegistration(clientData.identifier);
404             result.iterator->value = worker.identifier();
405         }
406         registration->controlClient(clientData.identifier);
407     });
408 }
409
410 void SWServer::didResolveRegistrationPromise(Connection& connection, const ServiceWorkerRegistrationKey& registrationKey)
411 {
412     ASSERT_UNUSED(connection, m_connections.contains(connection.identifier()));
413
414     if (auto* jobQueue = m_jobQueues.get(registrationKey))
415         jobQueue->didResolveRegistrationPromise();
416 }
417
418 void SWServer::addClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
419 {
420     auto* registration = m_registrationsByID.get(identifier);
421     if (!registration) {
422         LOG_ERROR("Request to add client-side ServiceWorkerRegistration to non-existent server-side registration");
423         return;
424     }
425     
426     registration->addClientServiceWorkerRegistration(connection.identifier());
427 }
428
429 void SWServer::removeClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
430 {
431     auto* registration = m_registrationsByID.get(identifier);
432     if (!registration) {
433         LOG_ERROR("Request to remove client-side ServiceWorkerRegistration from non-existent server-side registration");
434         return;
435     }
436     
437     registration->removeClientServiceWorkerRegistration(connection.identifier());
438 }
439
440 void SWServer::updateWorker(Connection&, const ServiceWorkerJobDataIdentifier& jobDataIdentifier, SWServerRegistration& registration, const URL& url, const String& script, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, WorkerType type)
441 {
442     registration.setLastUpdateTime(WallTime::now());
443     tryInstallContextData({ jobDataIdentifier, registration.data(), generateObjectIdentifier<ServiceWorkerIdentifierType>(), script, contentSecurityPolicy, url, type, false });
444 }
445
446 void SWServer::tryInstallContextData(ServiceWorkerContextData&& data)
447 {
448     // Right now we only ever keep up to one connection to one SW context process.
449     // And it should always exist if we're trying to install context data.
450     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
451     if (!connection) {
452         m_pendingContextDatas.append(WTFMove(data));
453         return;
454     }
455     
456     installContextData(data);
457 }
458
459 void SWServer::serverToContextConnectionCreated()
460 {
461     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
462     ASSERT(connection);
463
464     auto pendingContextDatas = WTFMove(m_pendingContextDatas);
465     for (auto& data : pendingContextDatas)
466         installContextData(data);
467
468     auto serviceWorkerRunRequests = WTFMove(m_serviceWorkerRunRequests);
469     for (auto& item : serviceWorkerRunRequests) {
470         bool success = runServiceWorker(item.key);
471         for (auto& callback : item.value)
472             callback(success, *connection);
473     }
474 }
475
476 void SWServer::installContextData(const ServiceWorkerContextData& data)
477 {
478     if (!data.loadedFromDisk)
479         m_registrationStore.updateRegistration(data);
480
481     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
482     ASSERT(connection);
483
484     auto* registration = m_registrations.get(data.registration.key);
485     RELEASE_ASSERT(registration);
486
487     auto worker = SWServerWorker::create(*this, *registration, connection->identifier(), data.scriptURL, data.script, data.contentSecurityPolicy, data.workerType, data.serviceWorkerIdentifier);
488
489     // We don't immediately launch all workers that were just read in from disk,
490     // as it is unlikely they will be needed immediately.
491     if (data.loadedFromDisk) {
492         registration->updateRegistrationState(ServiceWorkerRegistrationState::Active, worker.ptr());
493         worker->setState(ServiceWorkerState::Activated);
494         return;
495     }
496
497     worker->setState(SWServerWorker::State::Running);
498     auto result = m_runningOrTerminatingWorkers.add(data.serviceWorkerIdentifier, WTFMove(worker));
499     ASSERT_UNUSED(result, result.isNewEntry);
500
501     connection->installServiceWorkerContext(data, m_sessionID);
502 }
503
504 void SWServer::runServiceWorkerIfNecessary(ServiceWorkerIdentifier identifier, RunServiceWorkerCallback&& callback)
505 {
506     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
507     if (auto* worker = m_runningOrTerminatingWorkers.get(identifier)) {
508         if (worker->isRunning()) {
509             ASSERT(connection);
510             callback(true, *connection);
511             return;
512         }
513     }
514
515     if (!connection) {
516         m_serviceWorkerRunRequests.ensure(identifier, [&] {
517             return Vector<RunServiceWorkerCallback> { };
518         }).iterator->value.append(WTFMove(callback));
519         return;
520     }
521
522     callback(runServiceWorker(identifier), *connection);
523 }
524
525 bool SWServer::runServiceWorker(ServiceWorkerIdentifier identifier)
526 {
527     auto* worker = workerByID(identifier);
528     if (!worker)
529         return false;
530
531     // If the registration for a working has been removed then the request to run
532     // the worker is moot.
533     if (!getRegistration(worker->registrationKey()))
534         return false;
535
536     auto addResult = m_runningOrTerminatingWorkers.add(identifier, *worker);
537     ASSERT_UNUSED(addResult, addResult.isNewEntry || worker->isTerminating());
538
539     worker->setState(SWServerWorker::State::Running);
540
541     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
542     ASSERT(connection);
543
544     // When re-running a service worker after a context process crash, the connection identifier may have changed
545     // so we update it here.
546     worker->setContextConnectionIdentifier(connection->identifier());
547
548     connection->installServiceWorkerContext(worker->contextData(), m_sessionID);
549
550     return true;
551 }
552
553 void SWServer::terminateWorker(SWServerWorker& worker)
554 {
555     terminateWorkerInternal(worker, Asynchronous);
556 }
557
558 void SWServer::syncTerminateWorker(SWServerWorker& worker)
559 {
560     terminateWorkerInternal(worker, Synchronous);
561 }
562
563 void SWServer::terminateWorkerInternal(SWServerWorker& worker, TerminationMode mode)
564 {
565     ASSERT(m_runningOrTerminatingWorkers.get(worker.identifier()) == &worker);
566     ASSERT(worker.isRunning());
567
568     worker.setState(SWServerWorker::State::Terminating);
569
570     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
571     ASSERT(connection);
572     if (!connection) {
573         LOG_ERROR("Request to terminate a worker whose context connection does not exist");
574         workerContextTerminated(worker);
575         return;
576     }
577
578     switch (mode) {
579     case Asynchronous:
580         connection->terminateWorker(worker.identifier());
581         break;
582     case Synchronous:
583         connection->syncTerminateWorker(worker.identifier());
584         break;
585     };
586 }
587
588 void SWServer::markAllWorkersAsTerminated()
589 {
590     while (!m_runningOrTerminatingWorkers.isEmpty())
591         workerContextTerminated(m_runningOrTerminatingWorkers.begin()->value);
592 }
593
594 void SWServer::workerContextTerminated(SWServerWorker& worker)
595 {
596     worker.setState(SWServerWorker::State::NotRunning);
597
598     // At this point if no registrations are referencing the worker then it will be destroyed,
599     // removing itself from the m_workersByID map.
600     auto result = m_runningOrTerminatingWorkers.take(worker.identifier());
601     ASSERT_UNUSED(result, result && result->ptr() == &worker);
602 }
603
604 void SWServer::fireInstallEvent(SWServerWorker& worker)
605 {
606     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
607     if (!connection) {
608         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
609         return;
610     }
611
612     connection->fireInstallEvent(worker.identifier());
613 }
614
615 void SWServer::fireActivateEvent(SWServerWorker& worker)
616 {
617     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
618     if (!connection) {
619         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
620         return;
621     }
622
623     connection->fireActivateEvent(worker.identifier());
624 }
625
626 void SWServer::taskThreadEntryPoint()
627 {
628     ASSERT(!isMainThread());
629
630     while (!m_taskQueue.isKilled())
631         m_taskQueue.waitForMessage().performTask();
632
633     Locker<Lock> locker(m_taskThreadLock);
634     m_taskThread = nullptr;
635 }
636
637 void SWServer::postTask(CrossThreadTask&& task)
638 {
639     m_taskQueue.append(WTFMove(task));
640 }
641
642 void SWServer::postTaskReply(CrossThreadTask&& task)
643 {
644     m_taskReplyQueue.append(WTFMove(task));
645
646     Locker<Lock> locker(m_mainThreadReplyLock);
647     if (m_mainThreadReplyScheduled)
648         return;
649
650     m_mainThreadReplyScheduled = true;
651     callOnMainThread([this] {
652         handleTaskRepliesOnMainThread();
653     });
654 }
655
656 void SWServer::handleTaskRepliesOnMainThread()
657 {
658     {
659         Locker<Lock> locker(m_mainThreadReplyLock);
660         m_mainThreadReplyScheduled = false;
661     }
662
663     while (auto task = m_taskReplyQueue.tryGetMessage())
664         task->performTask();
665 }
666
667 void SWServer::registerConnection(Connection& connection)
668 {
669     auto result = m_connections.add(connection.identifier(), nullptr);
670     ASSERT(result.isNewEntry);
671     result.iterator->value = &connection;
672 }
673
674 void SWServer::unregisterConnection(Connection& connection)
675 {
676     ASSERT(m_connections.get(connection.identifier()) == &connection);
677     m_connections.remove(connection.identifier());
678
679     for (auto& registration : m_registrations.values())
680         registration->unregisterServerConnection(connection.identifier());
681 }
682
683 SWServerRegistration* SWServer::doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL)
684 {
685     SWServerRegistration* selectedRegistration = nullptr;
686     for (auto& registration : m_registrations.values()) {
687         if (!registration->key().isMatching(topOrigin, clientURL))
688             continue;
689         if (!selectedRegistration || selectedRegistration->key().scopeLength() < registration->key().scopeLength())
690             selectedRegistration = registration.get();
691     }
692
693     return (selectedRegistration && !selectedRegistration->isUninstalling()) ? selectedRegistration : nullptr;
694 }
695
696 void SWServer::setClientActiveWorker(ServiceWorkerClientIdentifier clientIdentifier, ServiceWorkerIdentifier serviceWorkerIdentifier)
697 {
698     m_clientToControllingWorker.set(clientIdentifier, serviceWorkerIdentifier);
699 }
700
701 SWServerRegistration* SWServer::registrationFromServiceWorkerIdentifier(ServiceWorkerIdentifier identifier)
702 {
703     auto iterator = m_runningOrTerminatingWorkers.find(identifier);
704     if (iterator == m_runningOrTerminatingWorkers.end())
705         return nullptr;
706
707     return m_registrations.get(iterator->value->registrationKey());
708 }
709
710 void SWServer::registerServiceWorkerClient(ClientOrigin&& clientOrigin, ServiceWorkerClientData&& data, const std::optional<ServiceWorkerIdentifier>& controllingServiceWorkerIdentifier)
711 {
712     auto clientIdentifier = data.identifier;
713     auto addResult = m_clientsById.add(clientIdentifier, WTFMove(data));
714     ASSERT_UNUSED(addResult, addResult.isNewEntry);
715
716     auto& clientIdentifiersForOrigin = m_clientIdentifiersPerOrigin.ensure(WTFMove(clientOrigin), [] {
717         return Clients { };
718     }).iterator->value;
719     clientIdentifiersForOrigin.identifiers.append(clientIdentifier);
720     clientIdentifiersForOrigin.terminateServiceWorkersTimer = nullptr;
721
722     if (!controllingServiceWorkerIdentifier)
723         return;
724
725     if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(*controllingServiceWorkerIdentifier)) {
726         controllingRegistration->addClientUsingRegistration(clientIdentifier);
727         auto result = m_clientToControllingWorker.add(clientIdentifier, *controllingServiceWorkerIdentifier);
728         ASSERT_UNUSED(result, result.isNewEntry);
729     }
730 }
731
732 void SWServer::unregisterServiceWorkerClient(const ClientOrigin& clientOrigin, ServiceWorkerClientIdentifier clientIdentifier)
733 {
734     bool wasRemoved = m_clientsById.remove(clientIdentifier);
735     ASSERT_UNUSED(wasRemoved, wasRemoved);
736
737     auto iterator = m_clientIdentifiersPerOrigin.find(clientOrigin);
738     ASSERT(iterator != m_clientIdentifiersPerOrigin.end());
739
740     auto& clientIdentifiers = iterator->value.identifiers;
741     clientIdentifiers.removeFirstMatching([&] (const auto& identifier) {
742         return clientIdentifier == identifier;
743     });
744     if (clientIdentifiers.isEmpty()) {
745         ASSERT(!iterator->value.terminateServiceWorkersTimer);
746         iterator->value.terminateServiceWorkersTimer = std::make_unique<Timer>([clientOrigin, this] {
747             for (auto& worker : m_runningOrTerminatingWorkers.values()) {
748                 if (worker->isRunning() && worker->origin() == clientOrigin)
749                     terminateWorker(worker);
750             }
751             m_clientIdentifiersPerOrigin.remove(clientOrigin);
752         });
753         iterator->value.terminateServiceWorkersTimer->startOneShot(terminationDelay);
754     }
755
756     auto workerIterator = m_clientToControllingWorker.find(clientIdentifier);
757     if (workerIterator == m_clientToControllingWorker.end())
758         return;
759
760     if (auto* controllingRegistration = registrationFromServiceWorkerIdentifier(workerIterator->value))
761         controllingRegistration->removeClientUsingRegistration(clientIdentifier);
762
763     m_clientToControllingWorker.remove(workerIterator);
764 }
765
766 void SWServer::resolveRegistrationReadyRequests(SWServerRegistration& registration)
767 {
768     for (auto* connection : m_connections.values())
769         connection->resolveRegistrationReadyRequests(registration);
770 }
771
772 void SWServer::Connection::whenRegistrationReady(uint64_t registrationReadyRequestIdentifier, const SecurityOriginData& topOrigin, const URL& clientURL)
773 {
774     if (auto* registration = doRegistrationMatching(topOrigin, clientURL)) {
775         if (registration->activeWorker()) {
776             registrationReady(registrationReadyRequestIdentifier, registration->data());
777             return;
778         }
779     }
780     m_registrationReadyRequests.append({ topOrigin, clientURL, registrationReadyRequestIdentifier });
781 }
782
783 void SWServer::Connection::resolveRegistrationReadyRequests(SWServerRegistration& registration)
784 {
785     m_registrationReadyRequests.removeAllMatching([&](auto& request) {
786         if (!registration.key().isMatching(request.topOrigin, request.clientURL))
787             return false;
788
789         registrationReady(request.identifier, registration.data());
790         return true;
791     });
792 }
793
794 void SWServer::getOriginsWithRegistrations(WTF::Function<void(const HashSet<SecurityOriginData>&)> callback)
795 {
796     m_getOriginsWithRegistrationsCallbacks.append(WTFMove(callback));
797
798     if (m_importCompleted)
799         performGetOriginsWithRegistrationsCallbacks();
800 }
801
802 void SWServer::performGetOriginsWithRegistrationsCallbacks()
803 {
804     ASSERT(isMainThread());
805     ASSERT(m_importCompleted);
806
807     if (m_getOriginsWithRegistrationsCallbacks.isEmpty())
808         return;
809
810     HashSet<SecurityOriginData> originsWithRegistrations;
811     for (auto& key : m_registrations.keys()) {
812         originsWithRegistrations.add(key.topOrigin());
813         originsWithRegistrations.add(SecurityOriginData { key.scope().protocol().toString(), key.scope().host(), key.scope().port() });
814     }
815
816     auto callbacks = WTFMove(m_getOriginsWithRegistrationsCallbacks);
817     for (auto& callback : callbacks)
818         callback(originsWithRegistrations);
819 }
820
821 } // namespace WebCore
822
823 #endif // ENABLE(SERVICE_WORKER)