Get a directory path to SWServers for storing ServiceWorker registrations.
[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 "SWOriginStore.h"
35 #include "SWServerJobQueue.h"
36 #include "SWServerRegistration.h"
37 #include "SWServerToContextConnection.h"
38 #include "SWServerWorker.h"
39 #include "SecurityOrigin.h"
40 #include "ServiceWorkerClientType.h"
41 #include "ServiceWorkerContextData.h"
42 #include "ServiceWorkerFetchResult.h"
43 #include "ServiceWorkerJobData.h"
44 #include <wtf/CompletionHandler.h>
45 #include <wtf/NeverDestroyed.h>
46 #include <wtf/text/WTFString.h>
47
48 namespace WebCore {
49
50 static ServiceWorkerIdentifier generateServiceWorkerIdentifier()
51 {
52     return generateObjectIdentifier<ServiceWorkerIdentifierType>();
53 }
54
55 static Seconds terminationDelay { 60_s };
56
57 SWServer::Connection::Connection(SWServer& server)
58     : m_server(server)
59     , m_identifier(generateObjectIdentifier<SWServerConnectionIdentifierType>())
60 {
61     m_server.registerConnection(*this);
62 }
63
64 SWServer::Connection::~Connection()
65 {
66     m_server.unregisterConnection(*this);
67 }
68
69 HashSet<SWServer*>& SWServer::allServers()
70 {
71     static NeverDestroyed<HashSet<SWServer*>> servers;
72     return servers;
73 }
74
75 SWServer::~SWServer()
76 {
77     RELEASE_ASSERT(m_connections.isEmpty());
78     RELEASE_ASSERT(m_registrations.isEmpty());
79     RELEASE_ASSERT(m_jobQueues.isEmpty());
80
81     ASSERT(m_taskQueue.isEmpty());
82     ASSERT(m_taskReplyQueue.isEmpty());
83
84     // For a SWServer to be cleanly shut down its thread must have finished and gone away.
85     // At this stage in development of the feature that actually never happens.
86     // But once it does start happening, this ASSERT will catch us doing it wrong.
87     Locker<Lock> locker(m_taskThreadLock);
88     ASSERT(!m_taskThread);
89     
90     allServers().remove(this);
91 }
92
93 SWServerWorker* SWServer::workerByID(ServiceWorkerIdentifier identifier) const
94 {
95     auto* worker = SWServerWorker::existingWorkerForIdentifier(identifier);
96     ASSERT(!worker || &worker->server() == this);
97     return worker;
98 }
99
100 SWServerRegistration* SWServer::getRegistration(const ServiceWorkerRegistrationKey& registrationKey)
101 {
102     return m_registrations.get(registrationKey);
103 }
104
105 void SWServer::addRegistration(std::unique_ptr<SWServerRegistration>&& registration)
106 {
107     auto key = registration->key();
108     auto* registrationPtr = registration.get();
109     auto addResult1 = m_registrations.add(key, WTFMove(registration));
110     ASSERT_UNUSED(addResult1, addResult1.isNewEntry);
111
112     auto addResult2 = m_registrationsByID.add(registrationPtr->identifier(), registrationPtr);
113     ASSERT_UNUSED(addResult2, addResult2.isNewEntry);
114
115     m_originStore->add(key.topOrigin().securityOrigin());
116 }
117
118 void SWServer::removeRegistration(const ServiceWorkerRegistrationKey& key)
119 {
120     auto topOrigin = key.topOrigin().securityOrigin();
121     auto registration = m_registrations.take(key);
122     ASSERT(registration);
123     bool wasRemoved = m_registrationsByID.remove(registration->identifier());
124     ASSERT_UNUSED(wasRemoved, wasRemoved);
125
126     m_originStore->remove(topOrigin);
127 }
128
129 Vector<ServiceWorkerRegistrationData> SWServer::getRegistrations(const SecurityOriginData& topOrigin, const URL& clientURL)
130 {
131     Vector<SWServerRegistration*> matchingRegistrations;
132     for (auto& item : m_registrations) {
133         if (!item.value->isUninstalling() && item.key.originIsMatching(topOrigin, clientURL))
134             matchingRegistrations.append(item.value.get());
135     }
136     // The specification mandates that registrations are returned in the insertion order.
137     std::sort(matchingRegistrations.begin(), matchingRegistrations.end(), [](auto& a, auto& b) {
138         return a->creationTime() < b->creationTime();
139     });
140     Vector<ServiceWorkerRegistrationData> matchingRegistrationDatas;
141     matchingRegistrationDatas.reserveInitialCapacity(matchingRegistrations.size());
142     for (auto* registration : matchingRegistrations)
143         matchingRegistrationDatas.uncheckedAppend(registration->data());
144     return matchingRegistrationDatas;
145 }
146
147 void SWServer::clearAll()
148 {
149     m_jobQueues.clear();
150     while (!m_registrations.isEmpty())
151         m_registrations.begin()->value->clear();
152     ASSERT(m_registrationsByID.isEmpty());
153     m_originStore->clearAll();
154 }
155
156 void SWServer::clear(const SecurityOrigin& origin)
157 {
158     m_originStore->clear(origin);
159
160     // FIXME: We should clear entries in m_registrations, m_jobQueues and m_workersByID.
161 }
162
163 void SWServer::Connection::scheduleJobInServer(const ServiceWorkerJobData& jobData)
164 {
165     LOG(ServiceWorker, "Scheduling ServiceWorker job %s in server", jobData.identifier().loggingString().utf8().data());
166     ASSERT(identifier() == jobData.connectionIdentifier());
167
168     m_server.scheduleJob(jobData);
169 }
170
171 void SWServer::Connection::finishFetchingScriptInServer(const ServiceWorkerFetchResult& result)
172 {
173     m_server.scriptFetchFinished(*this, result);
174 }
175
176 void SWServer::Connection::didResolveRegistrationPromise(const ServiceWorkerRegistrationKey& key)
177 {
178     m_server.didResolveRegistrationPromise(*this, key);
179 }
180
181 void SWServer::Connection::addServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
182 {
183     m_server.addClientServiceWorkerRegistration(*this, identifier);
184 }
185
186 void SWServer::Connection::removeServiceWorkerRegistrationInServer(ServiceWorkerRegistrationIdentifier identifier)
187 {
188     m_server.removeClientServiceWorkerRegistration(*this, identifier);
189 }
190
191 void SWServer::Connection::serviceWorkerStartedControllingClient(ServiceWorkerIdentifier serviceWorkerIdentifier, ServiceWorkerRegistrationIdentifier registrationIdentifier, DocumentIdentifier contextIdentifier)
192 {
193     m_server.serviceWorkerStartedControllingClient(*this, serviceWorkerIdentifier, registrationIdentifier, contextIdentifier);
194 }
195
196 void SWServer::Connection::serviceWorkerStoppedControllingClient(ServiceWorkerIdentifier serviceWorkerIdentifier, ServiceWorkerRegistrationIdentifier registrationIdentifier, DocumentIdentifier contextIdentifier)
197 {
198     m_server.serviceWorkerStoppedControllingClient(*this, serviceWorkerIdentifier, registrationIdentifier, contextIdentifier);
199 }
200
201 void SWServer::Connection::syncTerminateWorker(ServiceWorkerIdentifier identifier)
202 {
203     if (auto* worker = m_server.workerByID(identifier))
204         m_server.syncTerminateWorker(*worker);
205 }
206
207 SWServer::SWServer(UniqueRef<SWOriginStore>&& originStore, const String& registrationDatabaseDirectory)
208     : m_originStore(WTFMove(originStore))
209 {
210     UNUSED_PARAM(registrationDatabaseDirectory);
211     allServers().add(this);
212     m_taskThread = Thread::create(ASCIILiteral("ServiceWorker Task Thread"), [this] {
213         taskThreadEntryPoint();
214     });
215 }
216
217 // https://w3c.github.io/ServiceWorker/#schedule-job-algorithm
218 void SWServer::scheduleJob(const ServiceWorkerJobData& jobData)
219 {
220     ASSERT(m_connections.contains(jobData.connectionIdentifier()));
221
222     // FIXME: Per the spec, check if this job is equivalent to the last job on the queue.
223     // If it is, stack it along with that job.
224
225     auto& jobQueue = *m_jobQueues.ensure(jobData.registrationKey(), [this, &jobData] {
226         return std::make_unique<SWServerJobQueue>(*this, jobData.registrationKey());
227     }).iterator->value;
228
229     jobQueue.enqueueJob(jobData);
230     if (jobQueue.size() == 1)
231         jobQueue.runNextJob();
232 }
233
234 void SWServer::rejectJob(const ServiceWorkerJobData& jobData, const ExceptionData& exceptionData)
235 {
236     LOG(ServiceWorker, "Rejected ServiceWorker job %s in server", jobData.identifier().loggingString().utf8().data());
237     auto* connection = m_connections.get(jobData.connectionIdentifier());
238     if (!connection)
239         return;
240
241     connection->rejectJobInClient(jobData.identifier(), exceptionData);
242 }
243
244 void SWServer::resolveRegistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationData& registrationData, ShouldNotifyWhenResolved shouldNotifyWhenResolved)
245 {
246     LOG(ServiceWorker, "Resolved ServiceWorker job %s in server with registration %s", jobData.identifier().loggingString().utf8().data(), registrationData.identifier.loggingString().utf8().data());
247     auto* connection = m_connections.get(jobData.connectionIdentifier());
248     if (!connection)
249         return;
250
251     connection->resolveRegistrationJobInClient(jobData.identifier(), registrationData, shouldNotifyWhenResolved);
252 }
253
254 void SWServer::resolveUnregistrationJob(const ServiceWorkerJobData& jobData, const ServiceWorkerRegistrationKey& registrationKey, bool unregistrationResult)
255 {
256     auto* connection = m_connections.get(jobData.connectionIdentifier());
257     if (!connection)
258         return;
259
260     connection->resolveUnregistrationJobInClient(jobData.identifier(), registrationKey, unregistrationResult);
261 }
262
263 void SWServer::startScriptFetch(const ServiceWorkerJobData& jobData)
264 {
265     LOG(ServiceWorker, "Server issuing startScriptFetch for current job %s in client", jobData.identifier().loggingString().utf8().data());
266     auto* connection = m_connections.get(jobData.connectionIdentifier());
267     if (!connection)
268         return;
269
270     connection->startScriptFetchInClient(jobData.identifier());
271 }
272
273 void SWServer::scriptFetchFinished(Connection& connection, const ServiceWorkerFetchResult& result)
274 {
275     LOG(ServiceWorker, "Server handling scriptFetchFinished for current job %s in client", result.jobDataIdentifier.loggingString().utf8().data());
276
277     ASSERT(m_connections.contains(result.jobDataIdentifier.connectionIdentifier));
278
279     auto jobQueue = m_jobQueues.get(result.registrationKey);
280     if (!jobQueue)
281         return;
282
283     jobQueue->scriptFetchFinished(connection, result);
284 }
285
286 void SWServer::scriptContextFailedToStart(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, const String& message)
287 {
288     if (!jobDataIdentifier)
289         return;
290
291     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
292         jobQueue->scriptContextFailedToStart(*jobDataIdentifier, worker.identifier(), message);
293 }
294
295 void SWServer::scriptContextStarted(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker)
296 {
297     if (!jobDataIdentifier)
298         return;
299
300     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
301         jobQueue->scriptContextStarted(*jobDataIdentifier, worker.identifier());
302 }
303
304 void SWServer::didFinishInstall(const std::optional<ServiceWorkerJobDataIdentifier>& jobDataIdentifier, SWServerWorker& worker, bool wasSuccessful)
305 {
306     if (!jobDataIdentifier)
307         return;
308
309     if (auto* jobQueue = m_jobQueues.get(worker.registrationKey()))
310         jobQueue->didFinishInstall(*jobDataIdentifier, worker.identifier(), wasSuccessful);
311 }
312
313 void SWServer::didFinishActivation(SWServerWorker& worker)
314 {
315     if (auto* registration = getRegistration(worker.registrationKey()))
316         registration->didFinishActivation(worker.identifier());
317 }
318
319 // https://w3c.github.io/ServiceWorker/#clients-get
320 std::optional<ServiceWorkerClientData> SWServer::findClientByIdentifier(const ClientOrigin& origin, ServiceWorkerClientIdentifier clientIdentifier)
321 {
322     // FIXME: Support WindowClient additional properties.
323
324     auto iterator = m_clients.find(origin);
325     if (iterator == m_clients.end())
326         return std::nullopt;
327
328     auto& clients = iterator->value.clients;
329     auto position = clients.findMatching([&] (const auto& client) {
330         return clientIdentifier == client.identifier;
331     });
332
333     return (position != notFound) ? std::make_optional(clients[position].data) : std::nullopt;
334 }
335
336 // https://w3c.github.io/ServiceWorker/#clients-getall
337 void SWServer::matchAll(SWServerWorker& worker, const ServiceWorkerClientQueryOptions& options, ServiceWorkerClientsMatchAllCallback&& callback)
338 {
339     // FIXME: Support reserved client filtering.
340     // FIXME: Support WindowClient additional properties.
341
342     auto clients = m_clients.find(worker.origin())->value.clients;
343
344     if (!options.includeUncontrolled) {
345         clients.removeAllMatching([&] (const auto& client) {
346             return worker.identifier() != m_clientToControllingWorker.get(client.identifier);
347         });
348     }
349     if (options.type != ServiceWorkerClientType::All) {
350         clients.removeAllMatching([&] (const auto& client) {
351             return options.type != client.data.type;
352         });
353     }
354     callback(WTFMove(clients));
355 }
356
357 void SWServer::didResolveRegistrationPromise(Connection& connection, const ServiceWorkerRegistrationKey& registrationKey)
358 {
359     ASSERT_UNUSED(connection, m_connections.contains(connection.identifier()));
360
361     if (auto* jobQueue = m_jobQueues.get(registrationKey))
362         jobQueue->didResolveRegistrationPromise();
363 }
364
365 void SWServer::addClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
366 {
367     auto* registration = m_registrationsByID.get(identifier);
368     if (!registration) {
369         LOG_ERROR("Request to add client-side ServiceWorkerRegistration to non-existent server-side registration");
370         return;
371     }
372     
373     registration->addClientServiceWorkerRegistration(connection.identifier());
374 }
375
376 void SWServer::removeClientServiceWorkerRegistration(Connection& connection, ServiceWorkerRegistrationIdentifier identifier)
377 {
378     auto* registration = m_registrationsByID.get(identifier);
379     if (!registration) {
380         LOG_ERROR("Request to remove client-side ServiceWorkerRegistration from non-existent server-side registration");
381         return;
382     }
383     
384     registration->removeClientServiceWorkerRegistration(connection.identifier());
385 }
386
387 void SWServer::serviceWorkerStartedControllingClient(Connection& connection, ServiceWorkerIdentifier serviceWorkerIdentifier, ServiceWorkerRegistrationIdentifier registrationIdentifier, DocumentIdentifier contextIdentifier)
388 {
389     auto* registration = m_registrationsByID.get(registrationIdentifier);
390     if (!registration)
391         return;
392
393     ServiceWorkerClientIdentifier clientIdentifier { connection.identifier(), contextIdentifier };
394     registration->addClientUsingRegistration(clientIdentifier);
395
396     auto result = m_clientToControllingWorker.add(clientIdentifier, serviceWorkerIdentifier);
397     ASSERT_UNUSED(result, result.isNewEntry);
398 }
399
400 void SWServer::serviceWorkerStoppedControllingClient(Connection& connection, ServiceWorkerIdentifier serviceWorkerIdentifier, ServiceWorkerRegistrationIdentifier registrationIdentifier, DocumentIdentifier contextIdentifier)
401 {
402     UNUSED_PARAM(serviceWorkerIdentifier);
403     auto* registration = m_registrationsByID.get(registrationIdentifier);
404     if (!registration)
405         return;
406
407     ServiceWorkerClientIdentifier clientIdentifier { connection.identifier(), contextIdentifier };
408     registration->removeClientUsingRegistration(clientIdentifier);
409
410     auto result = m_clientToControllingWorker.take(clientIdentifier);
411     ASSERT_UNUSED(result, result == serviceWorkerIdentifier);
412 }
413
414 void SWServer::updateWorker(Connection&, const ServiceWorkerJobDataIdentifier& jobDataIdentifier, SWServerRegistration& registration, const URL& url, const String& script, WorkerType type)
415 {
416     auto serviceWorkerIdentifier = generateServiceWorkerIdentifier();
417
418     ServiceWorkerContextData data = { jobDataIdentifier, registration.data(), serviceWorkerIdentifier, script, url, type };
419
420     // Right now we only ever keep up to one connection to one SW context process.
421     // And it should always exist if we're calling updateWorker
422     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
423     if (!connection) {
424         m_pendingContextDatas.append(WTFMove(data));
425         return;
426     }
427     
428     installContextData(data);
429 }
430
431 void SWServer::serverToContextConnectionCreated()
432 {
433     ASSERT(SWServerToContextConnection::globalServerToContextConnection());
434     for (auto& data : m_pendingContextDatas)
435         installContextData(data);
436     
437     m_pendingContextDatas.clear();
438 }
439
440 void SWServer::installContextData(const ServiceWorkerContextData& data)
441 {
442     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
443     ASSERT(connection);
444
445     auto* registration = m_registrations.get(data.registration.key);
446     RELEASE_ASSERT(registration);
447
448     auto result = m_runningOrTerminatingWorkers.add(data.serviceWorkerIdentifier, SWServerWorker::create(*this, *registration, connection->identifier(), data.scriptURL, data.script, data.workerType, data.serviceWorkerIdentifier));
449     ASSERT(result.isNewEntry);
450
451     result.iterator->value->setState(SWServerWorker::State::Running);
452
453     connection->installServiceWorkerContext(data);
454 }
455
456 bool SWServer::invokeRunServiceWorker(ServiceWorkerIdentifier identifier)
457 {
458     if (auto* worker = m_runningOrTerminatingWorkers.get(identifier)) {
459         if (worker->isRunning())
460             return true;
461     }
462
463     // Nobody should have a ServiceWorkerIdentifier for a SWServerWorker that doesn't exist.
464     auto* worker = workerByID(identifier);
465     ASSERT(worker);
466
467     // If the registration for a working has been removed then the request to run
468     // the worker is moot.
469     if (!getRegistration(worker->registrationKey()))
470         return false;
471
472     m_runningOrTerminatingWorkers.add(identifier, *worker);
473     worker->setState(SWServerWorker::State::Running);
474
475     auto* connection = SWServerToContextConnection::globalServerToContextConnection();
476     ASSERT(connection);
477     connection->installServiceWorkerContext(worker->contextData());
478     
479     return true;
480 }
481
482 void SWServer::terminateWorker(SWServerWorker& worker)
483 {
484     terminateWorkerInternal(worker, Asynchronous);
485 }
486
487 void SWServer::syncTerminateWorker(SWServerWorker& worker)
488 {
489     terminateWorkerInternal(worker, Synchronous);
490 }
491
492 void SWServer::terminateWorkerInternal(SWServerWorker& worker, TerminationMode mode)
493 {
494     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
495     if (!connection) {
496         LOG_ERROR("Request to terminate a worker whose context connection does not exist");
497         return;
498     }
499
500     ASSERT(m_runningOrTerminatingWorkers.get(worker.identifier()) == &worker);
501     ASSERT(!worker.isTerminating());
502
503     worker.setState(SWServerWorker::State::Terminating);
504
505     switch (mode) {
506     case Asynchronous:
507         connection->terminateWorker(worker.identifier());
508         break;
509     case Synchronous:
510         connection->syncTerminateWorker(worker.identifier());
511         break;
512     };
513 }
514
515 void SWServer::workerContextTerminated(SWServerWorker& worker)
516 {
517     ASSERT(worker.isTerminating());
518
519     worker.setState(SWServerWorker::State::NotRunning);
520
521     // At this point if no registrations are referencing the worker then it will be destroyed,
522     // removing itself from the m_workersByID map.
523     auto result = m_runningOrTerminatingWorkers.take(worker.identifier());
524     ASSERT_UNUSED(result, result && result->ptr() == &worker);
525 }
526
527 void SWServer::fireInstallEvent(SWServerWorker& worker)
528 {
529     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
530     if (!connection) {
531         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
532         return;
533     }
534
535     connection->fireInstallEvent(worker.identifier());
536 }
537
538 void SWServer::fireActivateEvent(SWServerWorker& worker)
539 {
540     auto* connection = SWServerToContextConnection::connectionForIdentifier(worker.contextConnectionIdentifier());
541     if (!connection) {
542         LOG_ERROR("Request to fire install event on a worker whose context connection does not exist");
543         return;
544     }
545
546     connection->fireActivateEvent(worker.identifier());
547 }
548
549 void SWServer::taskThreadEntryPoint()
550 {
551     ASSERT(!isMainThread());
552
553     while (!m_taskQueue.isKilled())
554         m_taskQueue.waitForMessage().performTask();
555
556     Locker<Lock> locker(m_taskThreadLock);
557     m_taskThread = nullptr;
558 }
559
560 void SWServer::postTask(CrossThreadTask&& task)
561 {
562     m_taskQueue.append(WTFMove(task));
563 }
564
565 void SWServer::postTaskReply(CrossThreadTask&& task)
566 {
567     m_taskReplyQueue.append(WTFMove(task));
568
569     Locker<Lock> locker(m_mainThreadReplyLock);
570     if (m_mainThreadReplyScheduled)
571         return;
572
573     m_mainThreadReplyScheduled = true;
574     callOnMainThread([this] {
575         handleTaskRepliesOnMainThread();
576     });
577 }
578
579 void SWServer::handleTaskRepliesOnMainThread()
580 {
581     {
582         Locker<Lock> locker(m_mainThreadReplyLock);
583         m_mainThreadReplyScheduled = false;
584     }
585
586     while (auto task = m_taskReplyQueue.tryGetMessage())
587         task->performTask();
588 }
589
590 void SWServer::registerConnection(Connection& connection)
591 {
592     auto result = m_connections.add(connection.identifier(), nullptr);
593     ASSERT(result.isNewEntry);
594     result.iterator->value = &connection;
595 }
596
597 void SWServer::unregisterConnection(Connection& connection)
598 {
599     ASSERT(m_connections.get(connection.identifier()) == &connection);
600     m_connections.remove(connection.identifier());
601
602     for (auto& registration : m_registrations.values())
603         registration->unregisterServerConnection(connection.identifier());
604 }
605
606 const SWServerRegistration* SWServer::doRegistrationMatching(const SecurityOriginData& topOrigin, const URL& clientURL) const
607 {
608     const SWServerRegistration* selectedRegistration = nullptr;
609     for (auto& registration : m_registrations.values()) {
610         if (!registration->key().isMatching(topOrigin, clientURL))
611             continue;
612         if (!selectedRegistration || selectedRegistration->key().scopeLength() < registration->key().scopeLength())
613             selectedRegistration = registration.get();
614     }
615
616     return (selectedRegistration && !selectedRegistration->isUninstalling()) ? selectedRegistration : nullptr;
617 }
618
619 void SWServer::registerServiceWorkerClient(ClientOrigin&& clientOrigin, ServiceWorkerClientIdentifier identifier, ServiceWorkerClientData&& data)
620 {
621     auto& clientsData = m_clients.ensure(WTFMove(clientOrigin), [] {
622         return Clients { };
623     }).iterator->value;
624
625     clientsData.clients.append(ServiceWorkerClientInformation { identifier, WTFMove(data) });
626     if (clientsData.terminateServiceWorkersTimer)
627         clientsData.terminateServiceWorkersTimer = nullptr;
628 }
629
630 void SWServer::unregisterServiceWorkerClient(const ClientOrigin& clientOrigin, ServiceWorkerClientIdentifier identifier)
631 {
632     auto iterator = m_clients.find(clientOrigin);
633     ASSERT(iterator != m_clients.end());
634
635     auto& clients = iterator->value.clients;
636     clients.removeFirstMatching([&] (const auto& item) {
637         return identifier == item.identifier;
638     });
639
640     if (!clients.isEmpty() || m_runningOrTerminatingWorkers.isEmpty())
641         return;
642
643     ASSERT(!iterator->value.terminateServiceWorkersTimer);
644     iterator->value.terminateServiceWorkersTimer = std::make_unique<Timer>([clientOrigin, this] {
645         for (auto& worker : m_runningOrTerminatingWorkers.values()) {
646             if (worker->origin() == clientOrigin)
647                 terminateWorker(worker);
648         }
649         m_clients.remove(clientOrigin);
650     });
651     iterator->value.terminateServiceWorkersTimer->startOneShot(terminationDelay);
652 }
653
654 } // namespace WebCore
655
656 #endif // ENABLE(SERVICE_WORKER)