1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/service_worker/service_worker_version.h"
10 #include "base/command_line.h"
11 #include "base/guid.h"
12 #include "base/location.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/single_thread_task_runner.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "base/time/time.h"
21 #include "content/browser/bad_message.h"
22 #include "content/browser/child_process_security_policy_impl.h"
23 #include "content/browser/message_port_message_filter.h"
24 #include "content/browser/message_port_service.h"
25 #include "content/browser/service_worker/embedded_worker_instance.h"
26 #include "content/browser/service_worker/embedded_worker_registry.h"
27 #include "content/browser/service_worker/service_worker_context_core.h"
28 #include "content/browser/service_worker/service_worker_context_wrapper.h"
29 #include "content/browser/service_worker/service_worker_metrics.h"
30 #include "content/browser/service_worker/service_worker_registration.h"
31 #include "content/browser/service_worker/service_worker_utils.h"
32 #include "content/browser/storage_partition_impl.h"
33 #include "content/common/service_worker/service_worker_messages.h"
34 #include "content/common/service_worker/service_worker_type_converters.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "content/public/browser/content_browser_client.h"
37 #include "content/public/browser/page_navigator.h"
38 #include "content/public/browser/render_frame_host.h"
39 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/web_contents.h"
41 #include "content/public/browser/web_contents_observer.h"
42 #include "content/public/common/background_sync.mojom.h"
43 #include "content/public/common/child_process_host.h"
44 #include "content/public/common/content_client.h"
45 #include "content/public/common/content_switches.h"
46 #include "content/public/common/result_codes.h"
47 #include "content/public/common/service_registry.h"
48 #include "mojo/common/common_type_converters.h"
49 #include "mojo/common/url_type_converters.h"
50 #include "net/http/http_response_headers.h"
51 #include "net/http/http_response_info.h"
55 using StatusCallback
= ServiceWorkerVersion::StatusCallback
;
56 using ServiceWorkerClients
= std::vector
<ServiceWorkerClientInfo
>;
57 using GetClientsCallback
=
58 base::Callback
<void(scoped_ptr
<ServiceWorkerClients
>)>;
62 // Delay between the timeout timer firing.
63 const int kTimeoutTimerDelaySeconds
= 30;
65 // Time to wait until stopping an idle worker.
66 const int kIdleWorkerTimeoutSeconds
= 30;
68 // Time until a stopping worker is considered stalled.
69 const int kStopWorkerTimeoutSeconds
= 30;
71 // Default delay for scheduled update.
72 const int kUpdateDelaySeconds
= 1;
74 // Timeout for waiting for a response to a ping.
75 const int kPingTimeoutSeconds
= 30;
77 // If the SW was destructed while starting up, how many seconds it
78 // had to start up for this to be considered a timeout occurrence.
79 const int kDestructedStartingWorkerTimeoutThresholdSeconds
= 5;
81 const char kClaimClientsStateErrorMesage
[] =
82 "Only the active worker can claim clients.";
84 const char kClaimClientsShutdownErrorMesage
[] =
85 "Failed to claim clients due to Service Worker system shutdown.";
87 void RunSoon(const base::Closure
& callback
) {
88 if (!callback
.is_null())
89 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
, callback
);
92 template <typename CallbackArray
, typename Arg
>
93 void RunCallbacks(ServiceWorkerVersion
* version
,
94 CallbackArray
* callbacks_ptr
,
96 CallbackArray callbacks
;
97 callbacks
.swap(*callbacks_ptr
);
98 scoped_refptr
<ServiceWorkerVersion
> protect(version
);
99 for (const auto& callback
: callbacks
)
103 template <typename IDMAP
, typename
... Params
>
104 void RunIDMapCallbacks(IDMAP
* requests
, const Params
&... params
) {
105 typename
IDMAP::iterator
iter(requests
);
106 while (!iter
.IsAtEnd()) {
107 iter
.GetCurrentValue()->callback
.Run(params
...);
113 template <typename CallbackType
, typename
... Params
>
114 bool RunIDMapCallback(IDMap
<CallbackType
, IDMapOwnPointer
>* requests
,
116 const Params
&... params
) {
117 CallbackType
* request
= requests
->Lookup(request_id
);
121 request
->callback
.Run(params
...);
122 requests
->Remove(request_id
);
126 void RunStartWorkerCallback(
127 const StatusCallback
& callback
,
128 scoped_refptr
<ServiceWorkerRegistration
> protect
,
129 ServiceWorkerStatusCode status
) {
130 callback
.Run(status
);
133 // A callback adapter to start a |task| after StartWorker.
134 void RunTaskAfterStartWorker(
135 base::WeakPtr
<ServiceWorkerVersion
> version
,
136 const StatusCallback
& error_callback
,
137 const base::Closure
& task
,
138 ServiceWorkerStatusCode status
) {
139 if (status
!= SERVICE_WORKER_OK
) {
140 if (!error_callback
.is_null())
141 error_callback
.Run(status
);
144 if (version
->running_status() != ServiceWorkerVersion::RUNNING
) {
145 // We've tried to start the worker (and it has succeeded), but
146 // it looks it's not running yet.
147 NOTREACHED() << "The worker's not running after successful StartWorker";
148 if (!error_callback
.is_null())
149 error_callback
.Run(SERVICE_WORKER_ERROR_START_WORKER_FAILED
);
155 void RunErrorFetchCallback(const ServiceWorkerVersion::FetchCallback
& callback
,
156 ServiceWorkerStatusCode status
) {
158 SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK
,
159 ServiceWorkerResponse());
162 void RunErrorMessageCallback(
163 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
164 const ServiceWorkerVersion::StatusCallback
& callback
,
165 ServiceWorkerStatusCode status
) {
166 // Transfering the message ports failed, so destroy the ports.
167 for (const TransferredMessagePort
& port
: sent_message_ports
) {
168 MessagePortService::GetInstance()->ClosePort(port
.id
);
170 callback
.Run(status
);
173 void RunErrorServicePortConnectCallback(
174 const ServiceWorkerVersion::ServicePortConnectCallback
& callback
,
175 ServiceWorkerStatusCode status
) {
176 callback
.Run(status
, false /* accept_connection */, base::string16(),
180 using OpenURLCallback
= base::Callback
<void(int, int)>;
182 // The OpenURLObserver class is a WebContentsObserver that will wait for a
183 // WebContents to be initialized, run the |callback| passed to its constructor
184 // then self destroy.
185 // The callback will receive the process and frame ids. If something went wrong
186 // those will be (kInvalidUniqueID, MSG_ROUTING_NONE).
187 // The callback will be called in the IO thread.
188 class OpenURLObserver
: public WebContentsObserver
{
190 OpenURLObserver(WebContents
* web_contents
, const OpenURLCallback
& callback
)
191 : WebContentsObserver(web_contents
), callback_(callback
) {}
193 void DidCommitProvisionalLoadForFrame(
194 RenderFrameHost
* render_frame_host
,
195 const GURL
& validated_url
,
196 ui::PageTransition transition_type
) override
{
197 DCHECK(web_contents());
199 if (render_frame_host
!= web_contents()->GetMainFrame())
202 RunCallback(render_frame_host
->GetProcess()->GetID(),
203 render_frame_host
->GetRoutingID());
206 void RenderProcessGone(base::TerminationStatus status
) override
{
207 RunCallback(ChildProcessHost::kInvalidUniqueID
, MSG_ROUTING_NONE
);
210 void WebContentsDestroyed() override
{
211 RunCallback(ChildProcessHost::kInvalidUniqueID
, MSG_ROUTING_NONE
);
215 void RunCallback(int render_process_id
, int render_frame_id
) {
216 // After running the callback, |this| will stop observing, thus
217 // web_contents() should return nullptr and |RunCallback| should no longer
218 // be called. Then, |this| will self destroy.
219 DCHECK(web_contents());
221 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
222 base::Bind(callback_
,
226 base::MessageLoop::current()->DeleteSoon(FROM_HERE
, this);
229 const OpenURLCallback callback_
;
231 DISALLOW_COPY_AND_ASSIGN(OpenURLObserver
);
234 void DidOpenURL(const OpenURLCallback
& callback
, WebContents
* web_contents
) {
235 DCHECK(web_contents
);
237 new OpenURLObserver(web_contents
, callback
);
240 void NavigateClientOnUI(const GURL
& url
,
241 const GURL
& script_url
,
244 const OpenURLCallback
& callback
) {
245 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
247 RenderFrameHost
* render_frame_host
=
248 RenderFrameHost::FromID(process_id
, frame_id
);
249 WebContents
* web_contents
=
250 WebContents::FromRenderFrameHost(render_frame_host
);
252 if (!render_frame_host
|| !web_contents
) {
253 BrowserThread::PostTask(
254 BrowserThread::IO
, FROM_HERE
,
255 base::Bind(callback
, ChildProcessHost::kInvalidUniqueID
,
260 OpenURLParams
params(
261 url
, Referrer::SanitizeForRequest(
262 url
, Referrer(script_url
, blink::WebReferrerPolicyDefault
)),
263 CURRENT_TAB
, ui::PAGE_TRANSITION_AUTO_TOPLEVEL
,
264 true /* is_renderer_initiated */);
265 web_contents
->OpenURL(params
);
266 DidOpenURL(callback
, web_contents
);
271 const GURL
& script_url
,
273 const scoped_refptr
<ServiceWorkerContextWrapper
>& context_wrapper
,
274 const OpenURLCallback
& callback
) {
275 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
277 BrowserContext
* browser_context
= context_wrapper
->storage_partition()
278 ? context_wrapper
->storage_partition()->browser_context()
280 // We are shutting down.
281 if (!browser_context
)
284 RenderProcessHost
* render_process_host
=
285 RenderProcessHost::FromID(process_id
);
286 if (render_process_host
->IsForGuestsOnly()) {
287 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
289 ChildProcessHost::kInvalidUniqueID
,
294 OpenURLParams
params(
295 url
, Referrer::SanitizeForRequest(
296 url
, Referrer(script_url
, blink::WebReferrerPolicyDefault
)),
297 NEW_FOREGROUND_TAB
, ui::PAGE_TRANSITION_AUTO_TOPLEVEL
,
298 true /* is_renderer_initiated */);
300 GetContentClient()->browser()->OpenURL(
301 browser_context
, params
,
302 base::Bind(&DidOpenURL
, callback
));
305 void KillEmbeddedWorkerProcess(int process_id
, ResultCode code
) {
306 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
307 RenderProcessHost
* render_process_host
=
308 RenderProcessHost::FromID(process_id
);
309 if (render_process_host
->GetHandle() != base::kNullProcessHandle
) {
310 bad_message::ReceivedBadMessage(render_process_host
,
311 bad_message::SERVICE_WORKER_BAD_URL
);
315 void ClearTick(base::TimeTicks
* time
) {
316 *time
= base::TimeTicks();
319 void RestartTick(base::TimeTicks
* time
) {
320 *time
= base::TimeTicks().Now();
323 base::TimeDelta
GetTickDuration(const base::TimeTicks
& time
) {
325 return base::TimeDelta();
326 return base::TimeTicks().Now() - time
;
329 void OnGetWindowClientsFromUI(
330 // The tuple contains process_id, frame_id, client_uuid.
331 const std::vector
<base::Tuple
<int, int, std::string
>>& clients_info
,
332 const GURL
& script_url
,
333 const GetClientsCallback
& callback
) {
334 scoped_ptr
<ServiceWorkerClients
> clients(new ServiceWorkerClients
);
336 for (const auto& it
: clients_info
) {
337 ServiceWorkerClientInfo info
=
338 ServiceWorkerProviderHost::GetWindowClientInfoOnUI(base::get
<0>(it
),
341 // If the request to the provider_host returned an empty
342 // ServiceWorkerClientInfo, that means that it wasn't possible to associate
343 // it with a valid RenderFrameHost. It might be because the frame was killed
344 // or navigated in between.
348 // We can get info for a frame that was navigating end ended up with a
349 // different URL than expected. In such case, we should make sure to not
350 // expose cross-origin WindowClient.
351 if (info
.url
.GetOrigin() != script_url
.GetOrigin())
354 info
.client_uuid
= base::get
<2>(it
);
355 clients
->push_back(info
);
358 BrowserThread::PostTask(BrowserThread::IO
, FROM_HERE
,
359 base::Bind(callback
, base::Passed(&clients
)));
362 void AddWindowClient(
363 ServiceWorkerProviderHost
* host
,
364 std::vector
<base::Tuple
<int, int, std::string
>>* client_info
) {
365 if (host
->client_type() != blink::WebServiceWorkerClientTypeWindow
)
367 client_info
->push_back(base::MakeTuple(host
->process_id(), host
->frame_id(),
368 host
->client_uuid()));
371 void AddNonWindowClient(ServiceWorkerProviderHost
* host
,
372 const ServiceWorkerClientQueryOptions
& options
,
373 ServiceWorkerClients
* clients
) {
374 blink::WebServiceWorkerClientType host_client_type
= host
->client_type();
375 if (host_client_type
== blink::WebServiceWorkerClientTypeWindow
)
377 if (options
.client_type
!= blink::WebServiceWorkerClientTypeAll
&&
378 options
.client_type
!= host_client_type
)
381 ServiceWorkerClientInfo
client_info(
382 blink::WebPageVisibilityStateHidden
,
384 host
->document_url(), REQUEST_CONTEXT_FRAME_TYPE_NONE
, host_client_type
);
385 client_info
.client_uuid
= host
->client_uuid();
386 clients
->push_back(client_info
);
389 bool IsInstalled(ServiceWorkerVersion::Status status
) {
391 case ServiceWorkerVersion::NEW
:
392 case ServiceWorkerVersion::INSTALLING
:
393 case ServiceWorkerVersion::REDUNDANT
:
395 case ServiceWorkerVersion::INSTALLED
:
396 case ServiceWorkerVersion::ACTIVATING
:
397 case ServiceWorkerVersion::ACTIVATED
:
400 NOTREACHED() << "Unexpected status: " << status
;
406 const int ServiceWorkerVersion::kStartWorkerTimeoutMinutes
= 5;
407 const int ServiceWorkerVersion::kRequestTimeoutMinutes
= 5;
409 class ServiceWorkerVersion::Metrics
{
411 using EventType
= ServiceWorkerMetrics::EventType
;
412 explicit Metrics(ServiceWorkerVersion
* owner
) : owner_(owner
) {}
414 for (const auto& ev
: event_stats_
) {
415 ServiceWorkerMetrics::RecordEventHandledRatio(owner_
->scope(), ev
.first
,
416 ev
.second
.handled_events
,
417 ev
.second
.fired_events
);
421 void RecordEventHandledStatus(EventType event
, bool handled
) {
422 event_stats_
[event
].fired_events
++;
424 event_stats_
[event
].handled_events
++;
427 void NotifyStopping() {
428 stop_status_
= ServiceWorkerMetrics::STOP_STATUS_STOPPING
;
431 void NotifyStopped() {
432 switch (stop_status_
) {
433 case ServiceWorkerMetrics::STOP_STATUS_STOPPED
:
434 case ServiceWorkerMetrics::STOP_STATUS_STALLED_THEN_STOPPED
:
436 case ServiceWorkerMetrics::STOP_STATUS_STOPPING
:
437 stop_status_
= ServiceWorkerMetrics::STOP_STATUS_STOPPED
;
439 case ServiceWorkerMetrics::STOP_STATUS_STALLED
:
440 stop_status_
= ServiceWorkerMetrics::STOP_STATUS_STALLED_THEN_STOPPED
;
442 case ServiceWorkerMetrics::NUM_STOP_STATUS_TYPES
:
446 if (IsInstalled(owner_
->status()))
447 ServiceWorkerMetrics::RecordStopWorkerStatus(stop_status_
);
450 void NotifyStalledInStopping() {
451 if (stop_status_
!= ServiceWorkerMetrics::STOP_STATUS_STOPPING
)
453 stop_status_
= ServiceWorkerMetrics::STOP_STATUS_STALLED
;
454 if (IsInstalled(owner_
->status()))
455 ServiceWorkerMetrics::RecordStopWorkerStatus(stop_status_
);
460 size_t fired_events
= 0;
461 size_t handled_events
= 0;
464 ServiceWorkerVersion
* owner_
;
465 std::map
<EventType
, EventStat
> event_stats_
;
466 ServiceWorkerMetrics::StopWorkerStatus stop_status_
=
467 ServiceWorkerMetrics::STOP_STATUS_STOPPING
;
469 DISALLOW_COPY_AND_ASSIGN(Metrics
);
472 // A controller for periodically sending a ping to the worker to see
473 // if the worker is not stalling.
474 class ServiceWorkerVersion::PingController
{
476 explicit PingController(ServiceWorkerVersion
* version
) : version_(version
) {}
479 void Activate() { ping_state_
= PINGING
; }
482 ClearTick(&ping_time_
);
483 ping_state_
= NOT_PINGING
;
486 void OnPongReceived() { ClearTick(&ping_time_
); }
488 bool IsTimedOut() { return ping_state_
== PING_TIMED_OUT
; }
490 // Checks ping status. This is supposed to be called periodically.
492 // - OnPingTimeout() if the worker hasn't reponded within a certain period.
493 // - PingWorker() if we're running ping timer and can send next ping.
494 void CheckPingStatus() {
495 if (GetTickDuration(ping_time_
) >
496 base::TimeDelta::FromSeconds(kPingTimeoutSeconds
)) {
497 ping_state_
= PING_TIMED_OUT
;
498 version_
->OnPingTimeout();
502 // Check if we want to send a next ping.
503 if (ping_state_
!= PINGING
|| !ping_time_
.is_null())
506 if (version_
->PingWorker() != SERVICE_WORKER_OK
) {
507 // TODO(falken): Maybe try resending Ping a few times first?
508 ping_state_
= PING_TIMED_OUT
;
509 version_
->OnPingTimeout();
512 RestartTick(&ping_time_
);
515 void SimulateTimeoutForTesting() {
516 version_
->PingWorker();
517 ping_state_
= PING_TIMED_OUT
;
518 version_
->OnPingTimeout();
522 enum PingState
{ NOT_PINGING
, PINGING
, PING_TIMED_OUT
};
523 ServiceWorkerVersion
* version_
; // Not owned.
524 base::TimeTicks ping_time_
;
525 PingState ping_state_
= NOT_PINGING
;
526 DISALLOW_COPY_AND_ASSIGN(PingController
);
529 ServiceWorkerVersion::ServiceWorkerVersion(
530 ServiceWorkerRegistration
* registration
,
531 const GURL
& script_url
,
533 base::WeakPtr
<ServiceWorkerContextCore
> context
)
534 : version_id_(version_id
),
535 registration_id_(registration
->id()),
536 script_url_(script_url
),
537 scope_(registration
->pattern()),
539 script_cache_map_(this, context
),
540 ping_controller_(new PingController(this)),
541 weak_factory_(this) {
543 DCHECK(registration
);
544 context_
->AddLiveVersion(this);
545 embedded_worker_
= context_
->embedded_worker_registry()->CreateWorker();
546 embedded_worker_
->AddListener(this);
549 ServiceWorkerVersion::~ServiceWorkerVersion() {
550 // The user may have closed the tab waiting for SW to start up.
551 if (GetTickDuration(start_time_
) >
552 base::TimeDelta::FromSeconds(
553 kDestructedStartingWorkerTimeoutThresholdSeconds
)) {
554 DCHECK(timeout_timer_
.IsRunning());
555 DCHECK(!embedded_worker_
->devtools_attached());
556 RecordStartWorkerResult(SERVICE_WORKER_ERROR_TIMEOUT
);
559 // Same with stopping.
560 if (GetTickDuration(stop_time_
) >
561 base::TimeDelta::FromSeconds(kStopWorkerTimeoutSeconds
)) {
562 metrics_
->NotifyStalledInStopping();
566 context_
->RemoveLiveVersion(version_id_
);
568 if (running_status() == STARTING
|| running_status() == RUNNING
)
569 embedded_worker_
->Stop();
570 embedded_worker_
->RemoveListener(this);
573 void ServiceWorkerVersion::SetStatus(Status status
) {
574 if (status_
== status
)
579 if (skip_waiting_
&& status_
== ACTIVATED
) {
580 for (int request_id
: pending_skip_waiting_requests_
)
581 DidSkipWaiting(request_id
);
582 pending_skip_waiting_requests_
.clear();
585 std::vector
<base::Closure
> callbacks
;
586 callbacks
.swap(status_change_callbacks_
);
587 for (const auto& callback
: callbacks
)
590 FOR_EACH_OBSERVER(Listener
, listeners_
, OnVersionStateChanged(this));
593 void ServiceWorkerVersion::RegisterStatusChangeCallback(
594 const base::Closure
& callback
) {
595 status_change_callbacks_
.push_back(callback
);
598 ServiceWorkerVersionInfo
ServiceWorkerVersion::GetInfo() {
599 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
600 ServiceWorkerVersionInfo
info(
601 running_status(), status(), script_url(), registration_id(), version_id(),
602 embedded_worker()->process_id(), embedded_worker()->thread_id(),
603 embedded_worker()->worker_devtools_agent_route_id());
604 for (const auto& controllee
: controllee_map_
) {
605 const ServiceWorkerProviderHost
* host
= controllee
.second
;
606 info
.clients
.insert(std::make_pair(
608 ServiceWorkerVersionInfo::ClientInfo(
609 host
->process_id(), host
->route_id(), host
->provider_type())));
611 if (!main_script_http_info_
)
613 info
.script_response_time
= main_script_http_info_
->response_time
;
614 if (main_script_http_info_
->headers
)
615 main_script_http_info_
->headers
->GetLastModifiedValue(
616 &info
.script_last_modified
);
620 void ServiceWorkerVersion::StartWorker(const StatusCallback
& callback
) {
622 RecordStartWorkerResult(SERVICE_WORKER_ERROR_ABORT
);
623 RunSoon(base::Bind(callback
, SERVICE_WORKER_ERROR_ABORT
));
626 if (is_redundant()) {
627 RecordStartWorkerResult(SERVICE_WORKER_ERROR_REDUNDANT
);
628 RunSoon(base::Bind(callback
, SERVICE_WORKER_ERROR_REDUNDANT
));
631 prestart_status_
= status_
;
633 // Ensure the live registration during starting worker so that the worker can
634 // get associated with it in SWDispatcherHost::OnSetHostedVersionId().
635 context_
->storage()->FindRegistrationForId(
638 base::Bind(&ServiceWorkerVersion::DidEnsureLiveRegistrationForStartWorker
,
639 weak_factory_
.GetWeakPtr(),
643 void ServiceWorkerVersion::StopWorker(const StatusCallback
& callback
) {
644 if (running_status() == STOPPED
) {
645 RunSoon(base::Bind(callback
, SERVICE_WORKER_OK
));
648 if (stop_callbacks_
.empty()) {
649 ServiceWorkerStatusCode status
= embedded_worker_
->Stop();
650 if (status
!= SERVICE_WORKER_OK
) {
651 RunSoon(base::Bind(callback
, status
));
655 stop_callbacks_
.push_back(callback
);
658 void ServiceWorkerVersion::ScheduleUpdate() {
661 if (update_timer_
.IsRunning()) {
662 update_timer_
.Reset();
665 if (is_update_scheduled_
)
667 is_update_scheduled_
= true;
669 // Protect |this| until the timer fires, since we may be stopping
670 // and soon no one might hold a reference to us.
671 context_
->ProtectVersion(make_scoped_refptr(this));
672 update_timer_
.Start(FROM_HERE
,
673 base::TimeDelta::FromSeconds(kUpdateDelaySeconds
),
674 base::Bind(&ServiceWorkerVersion::StartUpdate
,
675 weak_factory_
.GetWeakPtr()));
678 void ServiceWorkerVersion::StartUpdate() {
681 context_
->storage()->FindRegistrationForId(
682 registration_id_
, scope_
.GetOrigin(),
683 base::Bind(&ServiceWorkerVersion::FoundRegistrationForUpdate
,
684 weak_factory_
.GetWeakPtr()));
687 void ServiceWorkerVersion::DeferScheduledUpdate() {
688 if (update_timer_
.IsRunning())
689 update_timer_
.Reset();
692 void ServiceWorkerVersion::DispatchMessageEvent(
693 const base::string16
& message
,
694 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
695 const StatusCallback
& callback
) {
696 for (const TransferredMessagePort
& port
: sent_message_ports
) {
697 MessagePortService::GetInstance()->HoldMessages(port
.id
);
700 DispatchMessageEventInternal(message
, sent_message_ports
, callback
);
703 void ServiceWorkerVersion::DispatchMessageEventInternal(
704 const base::string16
& message
,
705 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
706 const StatusCallback
& callback
) {
707 if (running_status() != RUNNING
) {
708 // Schedule calling this method after starting the worker.
709 StartWorker(base::Bind(
710 &RunTaskAfterStartWorker
, weak_factory_
.GetWeakPtr(),
711 base::Bind(&RunErrorMessageCallback
, sent_message_ports
, callback
),
712 base::Bind(&self::DispatchMessageEventInternal
,
713 weak_factory_
.GetWeakPtr(), message
, sent_message_ports
,
718 // TODO(kinuko): Cleanup this (and corresponding unit test) when message
719 // event becomes extendable, round-trip event. (crbug.com/498596)
720 RestartTick(&idle_time_
);
722 MessagePortMessageFilter
* filter
=
723 embedded_worker_
->message_port_message_filter();
724 std::vector
<int> new_routing_ids
;
725 filter
->UpdateMessagePortsWithNewRoutes(sent_message_ports
, &new_routing_ids
);
726 ServiceWorkerStatusCode status
=
727 embedded_worker_
->SendMessage(ServiceWorkerMsg_MessageToWorker(
728 message
, sent_message_ports
, new_routing_ids
));
729 RunSoon(base::Bind(callback
, status
));
732 void ServiceWorkerVersion::DispatchInstallEvent(
733 const StatusCallback
& callback
) {
734 DCHECK_EQ(INSTALLING
, status()) << status();
736 if (running_status() != RUNNING
) {
737 // Schedule calling this method after starting the worker.
739 base::Bind(&RunTaskAfterStartWorker
,
740 weak_factory_
.GetWeakPtr(),
742 base::Bind(&self::DispatchInstallEventAfterStartWorker
,
743 weak_factory_
.GetWeakPtr(),
746 DispatchInstallEventAfterStartWorker(callback
);
750 void ServiceWorkerVersion::DispatchActivateEvent(
751 const StatusCallback
& callback
) {
752 DCHECK_EQ(ACTIVATING
, status()) << status();
754 if (running_status() != RUNNING
) {
755 // Schedule calling this method after starting the worker.
757 base::Bind(&RunTaskAfterStartWorker
,
758 weak_factory_
.GetWeakPtr(),
760 base::Bind(&self::DispatchActivateEventAfterStartWorker
,
761 weak_factory_
.GetWeakPtr(),
764 DispatchActivateEventAfterStartWorker(callback
);
768 void ServiceWorkerVersion::DispatchFetchEvent(
769 const ServiceWorkerFetchRequest
& request
,
770 const base::Closure
& prepare_callback
,
771 const FetchCallback
& fetch_callback
) {
772 DCHECK_EQ(ACTIVATED
, status()) << status();
774 if (running_status() != RUNNING
) {
775 // Schedule calling this method after starting the worker.
776 StartWorker(base::Bind(&RunTaskAfterStartWorker
,
777 weak_factory_
.GetWeakPtr(),
778 base::Bind(&RunErrorFetchCallback
, fetch_callback
),
779 base::Bind(&self::DispatchFetchEvent
,
780 weak_factory_
.GetWeakPtr(),
787 prepare_callback
.Run();
789 int request_id
= AddRequest(fetch_callback
, &fetch_requests_
, REQUEST_FETCH
);
790 ServiceWorkerStatusCode status
= embedded_worker_
->SendMessage(
791 ServiceWorkerMsg_FetchEvent(request_id
, request
));
792 if (status
!= SERVICE_WORKER_OK
) {
793 fetch_requests_
.Remove(request_id
);
794 RunSoon(base::Bind(&RunErrorFetchCallback
,
796 SERVICE_WORKER_ERROR_FAILED
));
800 void ServiceWorkerVersion::DispatchSyncEvent(SyncRegistrationPtr registration
,
801 const StatusCallback
& callback
) {
802 DCHECK_EQ(ACTIVATED
, status()) << status();
803 if (running_status() != RUNNING
) {
804 // Schedule calling this method after starting the worker.
805 StartWorker(base::Bind(
806 &RunTaskAfterStartWorker
, weak_factory_
.GetWeakPtr(), callback
,
807 base::Bind(&self::DispatchSyncEvent
, weak_factory_
.GetWeakPtr(),
808 base::Passed(registration
.Pass()), callback
)));
812 int request_id
= AddRequest(callback
, &sync_requests_
, REQUEST_SYNC
);
813 if (!background_sync_dispatcher_
) {
814 embedded_worker_
->GetServiceRegistry()->ConnectToRemoteService(
815 mojo::GetProxy(&background_sync_dispatcher_
));
816 background_sync_dispatcher_
.set_connection_error_handler(base::Bind(
817 &ServiceWorkerVersion::OnBackgroundSyncDispatcherConnectionError
,
818 weak_factory_
.GetWeakPtr()));
821 background_sync_dispatcher_
->Sync(
822 registration
.Pass(), base::Bind(&self::OnSyncEventFinished
,
823 weak_factory_
.GetWeakPtr(), request_id
));
826 void ServiceWorkerVersion::DispatchNotificationClickEvent(
827 const StatusCallback
& callback
,
828 int64_t persistent_notification_id
,
829 const PlatformNotificationData
& notification_data
) {
830 DCHECK_EQ(ACTIVATED
, status()) << status();
831 if (running_status() != RUNNING
) {
832 // Schedule calling this method after starting the worker.
833 StartWorker(base::Bind(
834 &RunTaskAfterStartWorker
, weak_factory_
.GetWeakPtr(), callback
,
835 base::Bind(&self::DispatchNotificationClickEvent
,
836 weak_factory_
.GetWeakPtr(), callback
,
837 persistent_notification_id
, notification_data
)));
841 int request_id
= AddRequest(callback
, ¬ification_click_requests_
,
842 REQUEST_NOTIFICATION_CLICK
);
843 ServiceWorkerStatusCode status
=
844 embedded_worker_
->SendMessage(ServiceWorkerMsg_NotificationClickEvent(
845 request_id
, persistent_notification_id
, notification_data
));
846 if (status
!= SERVICE_WORKER_OK
) {
847 notification_click_requests_
.Remove(request_id
);
848 RunSoon(base::Bind(callback
, status
));
852 void ServiceWorkerVersion::DispatchPushEvent(const StatusCallback
& callback
,
853 const std::string
& data
) {
854 DCHECK_EQ(ACTIVATED
, status()) << status();
855 if (running_status() != RUNNING
) {
856 // Schedule calling this method after starting the worker.
857 StartWorker(base::Bind(&RunTaskAfterStartWorker
,
858 weak_factory_
.GetWeakPtr(), callback
,
859 base::Bind(&self::DispatchPushEvent
,
860 weak_factory_
.GetWeakPtr(),
865 int request_id
= AddRequest(callback
, &push_requests_
, REQUEST_PUSH
);
866 ServiceWorkerStatusCode status
= embedded_worker_
->SendMessage(
867 ServiceWorkerMsg_PushEvent(request_id
, data
));
868 if (status
!= SERVICE_WORKER_OK
) {
869 push_requests_
.Remove(request_id
);
870 RunSoon(base::Bind(callback
, status
));
874 void ServiceWorkerVersion::DispatchGeofencingEvent(
875 const StatusCallback
& callback
,
876 blink::WebGeofencingEventType event_type
,
877 const std::string
& region_id
,
878 const blink::WebCircularGeofencingRegion
& region
) {
879 DCHECK_EQ(ACTIVATED
, status()) << status();
881 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
882 switches::kEnableExperimentalWebPlatformFeatures
)) {
883 callback
.Run(SERVICE_WORKER_ERROR_ABORT
);
887 if (running_status() != RUNNING
) {
888 // Schedule calling this method after starting the worker.
889 StartWorker(base::Bind(&RunTaskAfterStartWorker
,
890 weak_factory_
.GetWeakPtr(),
892 base::Bind(&self::DispatchGeofencingEvent
,
893 weak_factory_
.GetWeakPtr(),
902 AddRequest(callback
, &geofencing_requests_
, REQUEST_GEOFENCING
);
903 ServiceWorkerStatusCode status
=
904 embedded_worker_
->SendMessage(ServiceWorkerMsg_GeofencingEvent(
905 request_id
, event_type
, region_id
, region
));
906 if (status
!= SERVICE_WORKER_OK
) {
907 geofencing_requests_
.Remove(request_id
);
908 RunSoon(base::Bind(callback
, status
));
912 void ServiceWorkerVersion::DispatchServicePortConnectEvent(
913 const ServicePortConnectCallback
& callback
,
914 const GURL
& target_url
,
917 DCHECK_EQ(ACTIVATED
, status()) << status();
919 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
920 switches::kEnableExperimentalWebPlatformFeatures
)) {
921 callback
.Run(SERVICE_WORKER_ERROR_ABORT
, false, base::string16(),
926 if (running_status() != RUNNING
) {
927 // Schedule calling this method after starting the worker.
929 base::Bind(&RunTaskAfterStartWorker
, weak_factory_
.GetWeakPtr(),
930 base::Bind(&RunErrorServicePortConnectCallback
, callback
),
931 base::Bind(&self::DispatchServicePortConnectEvent
,
932 weak_factory_
.GetWeakPtr(), callback
, target_url
,
937 int request_id
= AddRequest(callback
, &service_port_connect_requests_
,
938 REQUEST_SERVICE_PORT_CONNECT
);
939 if (!service_port_dispatcher_
) {
940 embedded_worker_
->GetServiceRegistry()->ConnectToRemoteService(
941 mojo::GetProxy(&service_port_dispatcher_
));
942 service_port_dispatcher_
.set_connection_error_handler(base::Bind(
943 &ServiceWorkerVersion::OnServicePortDispatcherConnectionError
,
944 weak_factory_
.GetWeakPtr()));
946 service_port_dispatcher_
->Connect(
947 mojo::String::From(target_url
), mojo::String::From(origin
), port_id
,
948 base::Bind(&ServiceWorkerVersion::OnServicePortConnectEventFinished
,
949 weak_factory_
.GetWeakPtr(), request_id
));
952 void ServiceWorkerVersion::DispatchCrossOriginMessageEvent(
953 const NavigatorConnectClient
& client
,
954 const base::string16
& message
,
955 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
956 const StatusCallback
& callback
) {
957 // Unlike in the case of DispatchMessageEvent, here the caller is assumed to
958 // have already put all the sent message ports on hold. So no need to do that
961 if (running_status() != RUNNING
) {
962 // Schedule calling this method after starting the worker.
963 StartWorker(base::Bind(
964 &RunTaskAfterStartWorker
, weak_factory_
.GetWeakPtr(),
965 base::Bind(&RunErrorMessageCallback
, sent_message_ports
, callback
),
966 base::Bind(&self::DispatchCrossOriginMessageEvent
,
967 weak_factory_
.GetWeakPtr(), client
, message
,
968 sent_message_ports
, callback
)));
972 MessagePortMessageFilter
* filter
=
973 embedded_worker_
->message_port_message_filter();
974 std::vector
<int> new_routing_ids
;
975 filter
->UpdateMessagePortsWithNewRoutes(sent_message_ports
, &new_routing_ids
);
976 ServiceWorkerStatusCode status
=
977 embedded_worker_
->SendMessage(ServiceWorkerMsg_CrossOriginMessageToWorker(
978 client
, message
, sent_message_ports
, new_routing_ids
));
979 RunSoon(base::Bind(callback
, status
));
982 void ServiceWorkerVersion::AddControllee(
983 ServiceWorkerProviderHost
* provider_host
) {
984 const std::string
& uuid
= provider_host
->client_uuid();
985 CHECK(!provider_host
->client_uuid().empty());
986 DCHECK(!ContainsKey(controllee_map_
, uuid
));
987 controllee_map_
[uuid
] = provider_host
;
988 // Keep the worker alive a bit longer right after a new controllee is added.
989 RestartTick(&idle_time_
);
990 FOR_EACH_OBSERVER(Listener
, listeners_
,
991 OnControlleeAdded(this, provider_host
));
994 void ServiceWorkerVersion::RemoveControllee(
995 ServiceWorkerProviderHost
* provider_host
) {
996 const std::string
& uuid
= provider_host
->client_uuid();
997 DCHECK(ContainsKey(controllee_map_
, uuid
));
998 controllee_map_
.erase(uuid
);
999 FOR_EACH_OBSERVER(Listener
, listeners_
,
1000 OnControlleeRemoved(this, provider_host
));
1001 if (HasControllee())
1003 FOR_EACH_OBSERVER(Listener
, listeners_
, OnNoControllees(this));
1006 bool ServiceWorkerVersion::HasWindowClients() {
1007 return !GetWindowClientsInternal(false /* include_uncontrolled */).empty();
1010 void ServiceWorkerVersion::AddStreamingURLRequestJob(
1011 const ServiceWorkerURLRequestJob
* request_job
) {
1012 DCHECK(streaming_url_request_jobs_
.find(request_job
) ==
1013 streaming_url_request_jobs_
.end());
1014 streaming_url_request_jobs_
.insert(request_job
);
1017 void ServiceWorkerVersion::RemoveStreamingURLRequestJob(
1018 const ServiceWorkerURLRequestJob
* request_job
) {
1019 streaming_url_request_jobs_
.erase(request_job
);
1024 void ServiceWorkerVersion::AddListener(Listener
* listener
) {
1025 listeners_
.AddObserver(listener
);
1028 void ServiceWorkerVersion::RemoveListener(Listener
* listener
) {
1029 listeners_
.RemoveObserver(listener
);
1032 void ServiceWorkerVersion::ReportError(ServiceWorkerStatusCode status
,
1033 const std::string
& status_message
) {
1034 if (status_message
.empty()) {
1035 OnReportException(base::UTF8ToUTF16(ServiceWorkerStatusToString(status
)),
1038 OnReportException(base::UTF8ToUTF16(status_message
), -1, -1, GURL());
1042 void ServiceWorkerVersion::SetStartWorkerStatusCode(
1043 ServiceWorkerStatusCode status
) {
1044 start_worker_status_
= status
;
1047 void ServiceWorkerVersion::Doom() {
1048 DCHECK(!HasControllee());
1049 SetStatus(REDUNDANT
);
1050 if (running_status() == STARTING
|| running_status() == RUNNING
)
1051 embedded_worker_
->Stop();
1054 std::vector
<ServiceWorkerDatabase::ResourceRecord
> resources
;
1055 script_cache_map_
.GetResources(&resources
);
1056 context_
->storage()->PurgeResources(resources
);
1059 void ServiceWorkerVersion::SetDevToolsAttached(bool attached
) {
1060 embedded_worker()->set_devtools_attached(attached
);
1062 // TODO(falken): Canceling the timeouts when debugging could cause
1063 // heisenbugs; we should instead run them as normal show an educational
1064 // message in DevTools when they occur. crbug.com/470419
1066 // Don't record the startup time metric once DevTools is attached.
1067 ClearTick(&start_time_
);
1068 skip_recording_startup_time_
= true;
1070 // Cancel request timeouts.
1071 SetAllRequestTimes(base::TimeTicks());
1074 if (!start_callbacks_
.empty()) {
1075 // Reactivate the timer for start timeout.
1076 DCHECK(timeout_timer_
.IsRunning());
1077 DCHECK(running_status() == STARTING
|| running_status() == STOPPING
)
1078 << running_status();
1079 RestartTick(&start_time_
);
1082 // Reactivate request timeouts.
1083 SetAllRequestTimes(base::TimeTicks::Now());
1086 void ServiceWorkerVersion::SetMainScriptHttpResponseInfo(
1087 const net::HttpResponseInfo
& http_info
) {
1088 main_script_http_info_
.reset(new net::HttpResponseInfo(http_info
));
1089 FOR_EACH_OBSERVER(Listener
, listeners_
,
1090 OnMainScriptHttpResponseInfoSet(this));
1093 void ServiceWorkerVersion::SimulatePingTimeoutForTesting() {
1094 ping_controller_
->SimulateTimeoutForTesting();
1097 const net::HttpResponseInfo
*
1098 ServiceWorkerVersion::GetMainScriptHttpResponseInfo() {
1099 return main_script_http_info_
.get();
1102 ServiceWorkerVersion::RequestInfo::RequestInfo(int id
,
1104 const base::TimeTicks
& now
)
1105 : id(id
), type(type
), time(now
) {
1108 ServiceWorkerVersion::RequestInfo::~RequestInfo() {
1111 template <typename CallbackType
>
1112 ServiceWorkerVersion::PendingRequest
<CallbackType
>::PendingRequest(
1113 const CallbackType
& callback
,
1114 const base::TimeTicks
& time
)
1115 : callback(callback
), start_time(time
) {
1118 template <typename CallbackType
>
1119 ServiceWorkerVersion::PendingRequest
<CallbackType
>::~PendingRequest() {
1122 void ServiceWorkerVersion::OnScriptLoaded() {
1123 DCHECK_EQ(STARTING
, running_status());
1124 // Activate ping/pong now that JavaScript execution will start.
1125 ping_controller_
->Activate();
1128 void ServiceWorkerVersion::OnStarting() {
1129 FOR_EACH_OBSERVER(Listener
, listeners_
, OnRunningStateChanged(this));
1132 void ServiceWorkerVersion::OnStarted() {
1133 DCHECK_EQ(RUNNING
, running_status());
1134 RestartTick(&idle_time_
);
1136 // Fire all start callbacks.
1137 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1138 RunCallbacks(this, &start_callbacks_
, SERVICE_WORKER_OK
);
1139 FOR_EACH_OBSERVER(Listener
, listeners_
, OnRunningStateChanged(this));
1142 void ServiceWorkerVersion::OnStopping() {
1143 metrics_
->NotifyStopping();
1144 RestartTick(&stop_time_
);
1145 FOR_EACH_OBSERVER(Listener
, listeners_
, OnRunningStateChanged(this));
1148 void ServiceWorkerVersion::OnStopped(
1149 EmbeddedWorkerInstance::Status old_status
) {
1150 metrics_
->NotifyStopped();
1151 if (!stop_time_
.is_null())
1152 ServiceWorkerMetrics::RecordStopWorkerTime(GetTickDuration(stop_time_
));
1154 OnStoppedInternal(old_status
);
1157 void ServiceWorkerVersion::OnDetached(
1158 EmbeddedWorkerInstance::Status old_status
) {
1159 OnStoppedInternal(old_status
);
1162 void ServiceWorkerVersion::OnReportException(
1163 const base::string16
& error_message
,
1166 const GURL
& source_url
) {
1171 this, error_message
, line_number
, column_number
, source_url
));
1174 void ServiceWorkerVersion::OnReportConsoleMessage(int source_identifier
,
1176 const base::string16
& message
,
1178 const GURL
& source_url
) {
1179 FOR_EACH_OBSERVER(Listener
,
1181 OnReportConsoleMessage(this,
1189 bool ServiceWorkerVersion::OnMessageReceived(const IPC::Message
& message
) {
1190 bool handled
= true;
1191 IPC_BEGIN_MESSAGE_MAP(ServiceWorkerVersion
, message
)
1192 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_GetClients
,
1194 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_ActivateEventFinished
,
1195 OnActivateEventFinished
)
1196 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_InstallEventFinished
,
1197 OnInstallEventFinished
)
1198 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_FetchEventFinished
,
1199 OnFetchEventFinished
)
1200 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_NotificationClickEventFinished
,
1201 OnNotificationClickEventFinished
)
1202 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_PushEventFinished
,
1203 OnPushEventFinished
)
1204 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_GeofencingEventFinished
,
1205 OnGeofencingEventFinished
)
1206 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_OpenWindow
,
1208 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_SetCachedMetadata
,
1209 OnSetCachedMetadata
)
1210 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_ClearCachedMetadata
,
1211 OnClearCachedMetadata
)
1212 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_PostMessageToClient
,
1213 OnPostMessageToClient
)
1214 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_FocusClient
,
1216 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_NavigateClient
, OnNavigateClient
)
1217 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_SkipWaiting
,
1219 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_ClaimClients
,
1221 IPC_MESSAGE_HANDLER(ServiceWorkerHostMsg_Pong
, OnPongFromWorker
)
1222 IPC_MESSAGE_UNHANDLED(handled
= false)
1223 IPC_END_MESSAGE_MAP()
1227 void ServiceWorkerVersion::OnStartSentAndScriptEvaluated(
1228 ServiceWorkerStatusCode status
) {
1229 if (status
!= SERVICE_WORKER_OK
) {
1230 RunCallbacks(this, &start_callbacks_
,
1231 DeduceStartWorkerFailureReason(status
));
1235 void ServiceWorkerVersion::DispatchInstallEventAfterStartWorker(
1236 const StatusCallback
& callback
) {
1237 DCHECK_EQ(RUNNING
, running_status())
1238 << "Worker stopped too soon after it was started.";
1240 int request_id
= AddRequest(callback
, &install_requests_
, REQUEST_INSTALL
);
1241 ServiceWorkerStatusCode status
= embedded_worker_
->SendMessage(
1242 ServiceWorkerMsg_InstallEvent(request_id
));
1243 if (status
!= SERVICE_WORKER_OK
) {
1244 install_requests_
.Remove(request_id
);
1245 RunSoon(base::Bind(callback
, status
));
1249 void ServiceWorkerVersion::DispatchActivateEventAfterStartWorker(
1250 const StatusCallback
& callback
) {
1251 DCHECK_EQ(RUNNING
, running_status())
1252 << "Worker stopped too soon after it was started.";
1254 int request_id
= AddRequest(callback
, &activate_requests_
, REQUEST_ACTIVATE
);
1255 ServiceWorkerStatusCode status
=
1256 embedded_worker_
->SendMessage(ServiceWorkerMsg_ActivateEvent(request_id
));
1257 if (status
!= SERVICE_WORKER_OK
) {
1258 activate_requests_
.Remove(request_id
);
1259 RunSoon(base::Bind(callback
, status
));
1263 void ServiceWorkerVersion::OnGetClients(
1265 const ServiceWorkerClientQueryOptions
& options
) {
1266 TRACE_EVENT_ASYNC_BEGIN2(
1267 "ServiceWorker", "ServiceWorkerVersion::OnGetClients", request_id
,
1268 "client_type", options
.client_type
, "include_uncontrolled",
1269 options
.include_uncontrolled
);
1271 if (controllee_map_
.empty() && !options
.include_uncontrolled
) {
1272 OnGetClientsFinished(request_id
, std::vector
<ServiceWorkerClientInfo
>());
1276 // For Window clients we want to query the info on the UI thread first.
1277 if (options
.client_type
== blink::WebServiceWorkerClientTypeWindow
||
1278 options
.client_type
== blink::WebServiceWorkerClientTypeAll
) {
1279 GetWindowClients(request_id
, options
);
1283 ServiceWorkerClients clients
;
1284 GetNonWindowClients(request_id
, options
, &clients
);
1285 OnGetClientsFinished(request_id
, clients
);
1288 void ServiceWorkerVersion::OnGetClientsFinished(
1290 const ServiceWorkerClients
& clients
) {
1291 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1292 TRACE_EVENT_ASYNC_END1("ServiceWorker", "ServiceWorkerVersion::OnGetClients",
1293 request_id
, "The number of clients", clients
.size());
1295 if (running_status() != RUNNING
)
1297 embedded_worker_
->SendMessage(
1298 ServiceWorkerMsg_DidGetClients(request_id
, clients
));
1301 void ServiceWorkerVersion::OnActivateEventFinished(
1303 blink::WebServiceWorkerEventResult result
) {
1304 DCHECK(ACTIVATING
== status() ||
1305 REDUNDANT
== status()) << status();
1306 TRACE_EVENT0("ServiceWorker",
1307 "ServiceWorkerVersion::OnActivateEventFinished");
1309 PendingRequest
<StatusCallback
>* request
=
1310 activate_requests_
.Lookup(request_id
);
1312 NOTREACHED() << "Got unexpected message: " << request_id
;
1315 ServiceWorkerStatusCode rv
= SERVICE_WORKER_OK
;
1316 if (result
== blink::WebServiceWorkerEventResultRejected
)
1317 rv
= SERVICE_WORKER_ERROR_ACTIVATE_WORKER_FAILED
;
1319 UMA_HISTOGRAM_MEDIUM_TIMES("ServiceWorker.ActivateEvent.Time",
1320 base::TimeTicks::Now() - request
->start_time
);
1322 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1323 request
->callback
.Run(rv
);
1324 RemoveCallbackAndStopIfRedundant(&activate_requests_
, request_id
);
1327 void ServiceWorkerVersion::OnInstallEventFinished(
1329 blink::WebServiceWorkerEventResult result
) {
1330 // Status is REDUNDANT if the worker was doomed while handling the install
1331 // event, and finished handling before being terminated.
1332 DCHECK(status() == INSTALLING
|| status() == REDUNDANT
) << status();
1333 TRACE_EVENT0("ServiceWorker",
1334 "ServiceWorkerVersion::OnInstallEventFinished");
1336 PendingRequest
<StatusCallback
>* request
=
1337 install_requests_
.Lookup(request_id
);
1339 NOTREACHED() << "Got unexpected message: " << request_id
;
1342 ServiceWorkerStatusCode status
= SERVICE_WORKER_OK
;
1343 if (result
== blink::WebServiceWorkerEventResultRejected
)
1344 status
= SERVICE_WORKER_ERROR_INSTALL_WORKER_FAILED
;
1346 UMA_HISTOGRAM_MEDIUM_TIMES("ServiceWorker.InstallEvent.Time",
1347 base::TimeTicks::Now() - request
->start_time
);
1349 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1350 request
->callback
.Run(status
);
1351 RemoveCallbackAndStopIfRedundant(&install_requests_
, request_id
);
1354 void ServiceWorkerVersion::OnFetchEventFinished(
1356 ServiceWorkerFetchEventResult result
,
1357 const ServiceWorkerResponse
& response
) {
1358 TRACE_EVENT1("ServiceWorker",
1359 "ServiceWorkerVersion::OnFetchEventFinished",
1360 "Request id", request_id
);
1361 PendingRequest
<FetchCallback
>* request
= fetch_requests_
.Lookup(request_id
);
1363 NOTREACHED() << "Got unexpected message: " << request_id
;
1367 // TODO(kinuko): Record other event statuses too.
1368 const bool handled
= (result
== SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE
);
1369 metrics_
->RecordEventHandledStatus(ServiceWorkerMetrics::EVENT_TYPE_FETCH
,
1372 ServiceWorkerMetrics::RecordFetchEventTime(
1373 result
, base::TimeTicks::Now() - request
->start_time
);
1375 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1376 request
->callback
.Run(SERVICE_WORKER_OK
, result
, response
);
1377 RemoveCallbackAndStopIfRedundant(&fetch_requests_
, request_id
);
1380 void ServiceWorkerVersion::OnSyncEventFinished(
1382 ServiceWorkerEventStatus status
) {
1383 TRACE_EVENT1("ServiceWorker",
1384 "ServiceWorkerVersion::OnSyncEventFinished",
1385 "Request id", request_id
);
1386 PendingRequest
<StatusCallback
>* request
= sync_requests_
.Lookup(request_id
);
1388 NOTREACHED() << "Got unexpected message: " << request_id
;
1392 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1393 request
->callback
.Run(mojo::ConvertTo
<ServiceWorkerStatusCode
>(status
));
1394 RemoveCallbackAndStopIfRedundant(&sync_requests_
, request_id
);
1397 void ServiceWorkerVersion::OnNotificationClickEventFinished(
1399 TRACE_EVENT1("ServiceWorker",
1400 "ServiceWorkerVersion::OnNotificationClickEventFinished",
1401 "Request id", request_id
);
1402 PendingRequest
<StatusCallback
>* request
=
1403 notification_click_requests_
.Lookup(request_id
);
1405 NOTREACHED() << "Got unexpected message: " << request_id
;
1409 UMA_HISTOGRAM_MEDIUM_TIMES("ServiceWorker.NotificationClickEvent.Time",
1410 base::TimeTicks::Now() - request
->start_time
);
1412 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1413 request
->callback
.Run(SERVICE_WORKER_OK
);
1414 RemoveCallbackAndStopIfRedundant(¬ification_click_requests_
, request_id
);
1417 void ServiceWorkerVersion::OnPushEventFinished(
1419 blink::WebServiceWorkerEventResult result
) {
1420 TRACE_EVENT1("ServiceWorker",
1421 "ServiceWorkerVersion::OnPushEventFinished",
1422 "Request id", request_id
);
1423 PendingRequest
<StatusCallback
>* request
= push_requests_
.Lookup(request_id
);
1425 NOTREACHED() << "Got unexpected message: " << request_id
;
1428 ServiceWorkerStatusCode status
= SERVICE_WORKER_OK
;
1429 if (result
== blink::WebServiceWorkerEventResultRejected
)
1430 status
= SERVICE_WORKER_ERROR_EVENT_WAITUNTIL_REJECTED
;
1432 UMA_HISTOGRAM_MEDIUM_TIMES("ServiceWorker.PushEvent.Time",
1433 base::TimeTicks::Now() - request
->start_time
);
1435 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1436 request
->callback
.Run(status
);
1437 RemoveCallbackAndStopIfRedundant(&push_requests_
, request_id
);
1440 void ServiceWorkerVersion::OnGeofencingEventFinished(int request_id
) {
1441 TRACE_EVENT1("ServiceWorker",
1442 "ServiceWorkerVersion::OnGeofencingEventFinished",
1445 PendingRequest
<StatusCallback
>* request
=
1446 geofencing_requests_
.Lookup(request_id
);
1448 NOTREACHED() << "Got unexpected message: " << request_id
;
1452 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1453 request
->callback
.Run(SERVICE_WORKER_OK
);
1454 RemoveCallbackAndStopIfRedundant(&geofencing_requests_
, request_id
);
1457 void ServiceWorkerVersion::OnServicePortConnectEventFinished(
1459 ServicePortConnectResult result
,
1460 const mojo::String
& name
,
1461 const mojo::String
& data
) {
1462 TRACE_EVENT1("ServiceWorker",
1463 "ServiceWorkerVersion::OnServicePortConnectEventFinished",
1464 "Request id", request_id
);
1465 PendingRequest
<ServicePortConnectCallback
>* request
=
1466 service_port_connect_requests_
.Lookup(request_id
);
1468 NOTREACHED() << "Got unexpected message: " << request_id
;
1472 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1473 request
->callback
.Run(SERVICE_WORKER_OK
,
1474 result
== SERVICE_PORT_CONNECT_RESULT_ACCEPT
,
1475 name
.To
<base::string16
>(), data
.To
<base::string16
>());
1476 RemoveCallbackAndStopIfRedundant(&service_port_connect_requests_
, request_id
);
1479 void ServiceWorkerVersion::OnOpenWindow(int request_id
, GURL url
) {
1480 // Just abort if we are shutting down.
1484 if (!url
.is_valid()) {
1485 DVLOG(1) << "Received unexpected invalid URL from renderer process.";
1486 BrowserThread::PostTask(BrowserThread::UI
, FROM_HERE
,
1487 base::Bind(&KillEmbeddedWorkerProcess
,
1488 embedded_worker_
->process_id(),
1489 RESULT_CODE_KILLED_BAD_MESSAGE
));
1493 // The renderer treats all URLs in the about: scheme as being about:blank.
1494 // Canonicalize about: URLs to about:blank.
1495 if (url
.SchemeIs(url::kAboutScheme
))
1496 url
= GURL(url::kAboutBlankURL
);
1498 // Reject requests for URLs that the process is not allowed to access. It's
1499 // possible to receive such requests since the renderer-side checks are
1500 // slightly different. For example, the view-source scheme will not be
1501 // filtered out by Blink.
1502 if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL(
1503 embedded_worker_
->process_id(), url
)) {
1504 embedded_worker_
->SendMessage(ServiceWorkerMsg_OpenWindowError(
1505 request_id
, url
.spec() + " cannot be opened."));
1509 BrowserThread::PostTask(
1510 BrowserThread::UI
, FROM_HERE
,
1511 base::Bind(&OpenWindowOnUI
,
1514 embedded_worker_
->process_id(),
1515 make_scoped_refptr(context_
->wrapper()),
1516 base::Bind(&ServiceWorkerVersion::DidOpenWindow
,
1517 weak_factory_
.GetWeakPtr(),
1521 void ServiceWorkerVersion::DidOpenWindow(int request_id
,
1522 int render_process_id
,
1523 int render_frame_id
) {
1524 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1526 if (running_status() != RUNNING
)
1529 if (render_process_id
== ChildProcessHost::kInvalidUniqueID
&&
1530 render_frame_id
== MSG_ROUTING_NONE
) {
1531 embedded_worker_
->SendMessage(ServiceWorkerMsg_OpenWindowError(
1532 request_id
, "Something went wrong while trying to open the window."));
1537 context_
->GetClientProviderHostIterator(script_url_
.GetOrigin());
1538 !it
->IsAtEnd(); it
->Advance()) {
1539 ServiceWorkerProviderHost
* provider_host
= it
->GetProviderHost();
1540 if (provider_host
->process_id() != render_process_id
||
1541 provider_host
->frame_id() != render_frame_id
) {
1544 provider_host
->GetWindowClientInfo(base::Bind(
1545 &ServiceWorkerVersion::OnOpenWindowFinished
, weak_factory_
.GetWeakPtr(),
1546 request_id
, provider_host
->client_uuid()));
1550 // If here, it means that no provider_host was found, in which case, the
1551 // renderer should still be informed that the window was opened.
1552 OnOpenWindowFinished(request_id
, std::string(), ServiceWorkerClientInfo());
1555 void ServiceWorkerVersion::OnOpenWindowFinished(
1557 const std::string
& client_uuid
,
1558 const ServiceWorkerClientInfo
& client_info
) {
1559 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1561 if (running_status() != RUNNING
)
1564 ServiceWorkerClientInfo
client(client_info
);
1566 // If the |client_info| is empty, it means that the opened window wasn't
1567 // controlled but the action still succeeded. The renderer process is
1568 // expecting an empty client in such case.
1569 if (!client
.IsEmpty())
1570 client
.client_uuid
= client_uuid
;
1572 embedded_worker_
->SendMessage(ServiceWorkerMsg_OpenWindowResponse(
1573 request_id
, client
));
1576 void ServiceWorkerVersion::OnSetCachedMetadata(const GURL
& url
,
1577 const std::vector
<char>& data
) {
1578 int64 callback_id
= base::TimeTicks::Now().ToInternalValue();
1579 TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker",
1580 "ServiceWorkerVersion::OnSetCachedMetadata",
1581 callback_id
, "URL", url
.spec());
1582 script_cache_map_
.WriteMetadata(
1583 url
, data
, base::Bind(&ServiceWorkerVersion::OnSetCachedMetadataFinished
,
1584 weak_factory_
.GetWeakPtr(), callback_id
));
1587 void ServiceWorkerVersion::OnSetCachedMetadataFinished(int64 callback_id
,
1589 TRACE_EVENT_ASYNC_END1("ServiceWorker",
1590 "ServiceWorkerVersion::OnSetCachedMetadata",
1591 callback_id
, "result", result
);
1592 FOR_EACH_OBSERVER(Listener
, listeners_
, OnCachedMetadataUpdated(this));
1595 void ServiceWorkerVersion::OnClearCachedMetadata(const GURL
& url
) {
1596 int64 callback_id
= base::TimeTicks::Now().ToInternalValue();
1597 TRACE_EVENT_ASYNC_BEGIN1("ServiceWorker",
1598 "ServiceWorkerVersion::OnClearCachedMetadata",
1599 callback_id
, "URL", url
.spec());
1600 script_cache_map_
.ClearMetadata(
1601 url
, base::Bind(&ServiceWorkerVersion::OnClearCachedMetadataFinished
,
1602 weak_factory_
.GetWeakPtr(), callback_id
));
1605 void ServiceWorkerVersion::OnClearCachedMetadataFinished(int64 callback_id
,
1607 TRACE_EVENT_ASYNC_END1("ServiceWorker",
1608 "ServiceWorkerVersion::OnClearCachedMetadata",
1609 callback_id
, "result", result
);
1610 FOR_EACH_OBSERVER(Listener
, listeners_
, OnCachedMetadataUpdated(this));
1613 void ServiceWorkerVersion::OnPostMessageToClient(
1614 const std::string
& client_uuid
,
1615 const base::string16
& message
,
1616 const std::vector
<TransferredMessagePort
>& sent_message_ports
) {
1619 TRACE_EVENT1("ServiceWorker",
1620 "ServiceWorkerVersion::OnPostMessageToDocument",
1621 "Client id", client_uuid
);
1622 ServiceWorkerProviderHost
* provider_host
=
1623 context_
->GetProviderHostByClientID(client_uuid
);
1624 if (!provider_host
) {
1625 // The client may already have been closed, just ignore.
1628 if (provider_host
->document_url().GetOrigin() != script_url_
.GetOrigin()) {
1629 // The client does not belong to the same origin as this ServiceWorker,
1630 // possibly due to timing issue or bad message.
1633 provider_host
->PostMessage(this, message
, sent_message_ports
);
1636 void ServiceWorkerVersion::OnFocusClient(int request_id
,
1637 const std::string
& client_uuid
) {
1640 TRACE_EVENT2("ServiceWorker",
1641 "ServiceWorkerVersion::OnFocusClient",
1642 "Request id", request_id
,
1643 "Client id", client_uuid
);
1644 ServiceWorkerProviderHost
* provider_host
=
1645 context_
->GetProviderHostByClientID(client_uuid
);
1646 if (!provider_host
) {
1647 // The client may already have been closed, just ignore.
1650 if (provider_host
->document_url().GetOrigin() != script_url_
.GetOrigin()) {
1651 // The client does not belong to the same origin as this ServiceWorker,
1652 // possibly due to timing issue or bad message.
1655 provider_host
->Focus(base::Bind(&ServiceWorkerVersion::OnFocusClientFinished
,
1656 weak_factory_
.GetWeakPtr(), request_id
,
1660 void ServiceWorkerVersion::OnFocusClientFinished(
1662 const std::string
& client_uuid
,
1663 const ServiceWorkerClientInfo
& client
) {
1664 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1666 if (running_status() != RUNNING
)
1669 ServiceWorkerClientInfo
client_info(client
);
1670 client_info
.client_uuid
= client_uuid
;
1672 embedded_worker_
->SendMessage(ServiceWorkerMsg_FocusClientResponse(
1673 request_id
, client_info
));
1676 void ServiceWorkerVersion::OnNavigateClient(int request_id
,
1677 const std::string
& client_uuid
,
1682 TRACE_EVENT2("ServiceWorker", "ServiceWorkerVersion::OnNavigateClient",
1683 "Request id", request_id
, "Client id", client_uuid
);
1685 if (!url
.is_valid() || !base::IsValidGUID(client_uuid
)) {
1686 DVLOG(1) << "Received unexpected invalid URL/UUID from renderer process.";
1687 BrowserThread::PostTask(
1688 BrowserThread::UI
, FROM_HERE
,
1689 base::Bind(&KillEmbeddedWorkerProcess
, embedded_worker_
->process_id(),
1690 RESULT_CODE_KILLED_BAD_MESSAGE
));
1694 // Reject requests for URLs that the process is not allowed to access. It's
1695 // possible to receive such requests since the renderer-side checks are
1696 // slightly different. For example, the view-source scheme will not be
1697 // filtered out by Blink.
1698 if (!ChildProcessSecurityPolicyImpl::GetInstance()->CanRequestURL(
1699 embedded_worker_
->process_id(), url
)) {
1700 embedded_worker_
->SendMessage(
1701 ServiceWorkerMsg_NavigateClientError(request_id
, url
));
1705 ServiceWorkerProviderHost
* provider_host
=
1706 context_
->GetProviderHostByClientID(client_uuid
);
1707 if (!provider_host
|| provider_host
->active_version() != this) {
1708 embedded_worker_
->SendMessage(
1709 ServiceWorkerMsg_NavigateClientError(request_id
, url
));
1713 BrowserThread::PostTask(
1714 BrowserThread::UI
, FROM_HERE
,
1715 base::Bind(&NavigateClientOnUI
, url
, script_url_
,
1716 provider_host
->process_id(), provider_host
->frame_id(),
1717 base::Bind(&ServiceWorkerVersion::DidNavigateClient
,
1718 weak_factory_
.GetWeakPtr(), request_id
)));
1721 void ServiceWorkerVersion::DidNavigateClient(int request_id
,
1722 int render_process_id
,
1723 int render_frame_id
) {
1724 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1726 if (running_status() != RUNNING
)
1729 if (render_process_id
== ChildProcessHost::kInvalidUniqueID
&&
1730 render_frame_id
== MSG_ROUTING_NONE
) {
1731 embedded_worker_
->SendMessage(
1732 ServiceWorkerMsg_NavigateClientError(request_id
, GURL()));
1737 context_
->GetClientProviderHostIterator(script_url_
.GetOrigin());
1738 !it
->IsAtEnd(); it
->Advance()) {
1739 ServiceWorkerProviderHost
* provider_host
= it
->GetProviderHost();
1740 if (provider_host
->process_id() != render_process_id
||
1741 provider_host
->frame_id() != render_frame_id
) {
1744 provider_host
->GetWindowClientInfo(base::Bind(
1745 &ServiceWorkerVersion::OnNavigateClientFinished
,
1746 weak_factory_
.GetWeakPtr(), request_id
, provider_host
->client_uuid()));
1750 OnNavigateClientFinished(request_id
, std::string(),
1751 ServiceWorkerClientInfo());
1754 void ServiceWorkerVersion::OnNavigateClientFinished(
1756 const std::string
& client_uuid
,
1757 const ServiceWorkerClientInfo
& client_info
) {
1758 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1760 if (running_status() != RUNNING
)
1763 ServiceWorkerClientInfo
client(client_info
);
1765 // If the |client_info| is empty, it means that the navigated client wasn't
1766 // controlled but the action still succeeded. The renderer process is
1767 // expecting an empty client in such case.
1768 if (!client
.IsEmpty())
1769 client
.client_uuid
= client_uuid
;
1771 embedded_worker_
->SendMessage(
1772 ServiceWorkerMsg_NavigateClientResponse(request_id
, client
));
1775 void ServiceWorkerVersion::OnSkipWaiting(int request_id
) {
1776 skip_waiting_
= true;
1777 if (status_
!= INSTALLED
)
1778 return DidSkipWaiting(request_id
);
1782 ServiceWorkerRegistration
* registration
=
1783 context_
->GetLiveRegistration(registration_id_
);
1786 pending_skip_waiting_requests_
.push_back(request_id
);
1787 if (pending_skip_waiting_requests_
.size() == 1)
1788 registration
->ActivateWaitingVersionWhenReady();
1791 void ServiceWorkerVersion::DidSkipWaiting(int request_id
) {
1792 if (running_status() == STARTING
|| running_status() == RUNNING
)
1793 embedded_worker_
->SendMessage(ServiceWorkerMsg_DidSkipWaiting(request_id
));
1796 void ServiceWorkerVersion::OnClaimClients(int request_id
) {
1797 if (status_
!= ACTIVATING
&& status_
!= ACTIVATED
) {
1798 embedded_worker_
->SendMessage(ServiceWorkerMsg_ClaimClientsError(
1799 request_id
, blink::WebServiceWorkerError::ErrorTypeState
,
1800 base::ASCIIToUTF16(kClaimClientsStateErrorMesage
)));
1804 if (ServiceWorkerRegistration
* registration
=
1805 context_
->GetLiveRegistration(registration_id_
)) {
1806 registration
->ClaimClients();
1807 embedded_worker_
->SendMessage(
1808 ServiceWorkerMsg_DidClaimClients(request_id
));
1813 embedded_worker_
->SendMessage(ServiceWorkerMsg_ClaimClientsError(
1814 request_id
, blink::WebServiceWorkerError::ErrorTypeAbort
,
1815 base::ASCIIToUTF16(kClaimClientsShutdownErrorMesage
)));
1818 void ServiceWorkerVersion::OnPongFromWorker() {
1819 ping_controller_
->OnPongReceived();
1822 void ServiceWorkerVersion::DidEnsureLiveRegistrationForStartWorker(
1823 const StatusCallback
& callback
,
1824 ServiceWorkerStatusCode status
,
1825 const scoped_refptr
<ServiceWorkerRegistration
>& protect
) {
1826 if (status
!= SERVICE_WORKER_OK
) {
1827 RecordStartWorkerResult(status
);
1828 RunSoon(base::Bind(callback
, SERVICE_WORKER_ERROR_START_WORKER_FAILED
));
1831 if (is_redundant()) {
1832 RecordStartWorkerResult(SERVICE_WORKER_ERROR_REDUNDANT
);
1833 RunSoon(base::Bind(callback
, SERVICE_WORKER_ERROR_REDUNDANT
));
1839 switch (running_status()) {
1841 RunSoon(base::Bind(callback
, SERVICE_WORKER_OK
));
1846 if (start_callbacks_
.empty()) {
1847 start_callbacks_
.push_back(
1848 base::Bind(&ServiceWorkerVersion::RecordStartWorkerResult
,
1849 weak_factory_
.GetWeakPtr()));
1851 // Keep the live registration while starting the worker.
1852 start_callbacks_
.push_back(
1853 base::Bind(&RunStartWorkerCallback
, callback
, protect
));
1854 StartWorkerInternal();
1859 void ServiceWorkerVersion::StartWorkerInternal() {
1861 metrics_
.reset(new Metrics(this));
1863 if (!timeout_timer_
.IsRunning())
1864 StartTimeoutTimer();
1865 if (running_status() == STOPPED
) {
1866 embedded_worker_
->Start(
1867 version_id_
, scope_
, script_url_
,
1868 base::Bind(&ServiceWorkerVersion::OnStartSentAndScriptEvaluated
,
1869 weak_factory_
.GetWeakPtr()));
1873 void ServiceWorkerVersion::GetWindowClients(
1875 const ServiceWorkerClientQueryOptions
& options
) {
1876 DCHECK(options
.client_type
== blink::WebServiceWorkerClientTypeWindow
||
1877 options
.client_type
== blink::WebServiceWorkerClientTypeAll
);
1878 const std::vector
<base::Tuple
<int, int, std::string
>>& clients_info
=
1879 GetWindowClientsInternal(options
.include_uncontrolled
);
1881 if (clients_info
.empty()) {
1882 DidGetWindowClients(request_id
, options
,
1883 make_scoped_ptr(new ServiceWorkerClients
));
1887 BrowserThread::PostTask(
1888 BrowserThread::UI
, FROM_HERE
,
1889 base::Bind(&OnGetWindowClientsFromUI
, clients_info
, script_url_
,
1890 base::Bind(&ServiceWorkerVersion::DidGetWindowClients
,
1891 weak_factory_
.GetWeakPtr(), request_id
, options
)));
1894 const std::vector
<base::Tuple
<int, int, std::string
>>
1895 ServiceWorkerVersion::GetWindowClientsInternal(bool include_uncontrolled
) {
1896 std::vector
<base::Tuple
<int, int, std::string
>> clients_info
;
1897 if (!include_uncontrolled
) {
1898 for (auto& controllee
: controllee_map_
)
1899 AddWindowClient(controllee
.second
, &clients_info
);
1902 context_
->GetClientProviderHostIterator(script_url_
.GetOrigin());
1903 !it
->IsAtEnd(); it
->Advance()) {
1904 AddWindowClient(it
->GetProviderHost(), &clients_info
);
1907 return clients_info
;
1910 void ServiceWorkerVersion::DidGetWindowClients(
1912 const ServiceWorkerClientQueryOptions
& options
,
1913 scoped_ptr
<ServiceWorkerClients
> clients
) {
1914 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
1915 if (options
.client_type
== blink::WebServiceWorkerClientTypeAll
)
1916 GetNonWindowClients(request_id
, options
, clients
.get());
1917 OnGetClientsFinished(request_id
, *clients
);
1920 void ServiceWorkerVersion::GetNonWindowClients(
1922 const ServiceWorkerClientQueryOptions
& options
,
1923 ServiceWorkerClients
* clients
) {
1924 if (!options
.include_uncontrolled
) {
1925 for (auto& controllee
: controllee_map_
) {
1926 AddNonWindowClient(controllee
.second
, options
, clients
);
1930 context_
->GetClientProviderHostIterator(script_url_
.GetOrigin());
1931 !it
->IsAtEnd(); it
->Advance()) {
1932 AddNonWindowClient(it
->GetProviderHost(), options
, clients
);
1937 void ServiceWorkerVersion::StartTimeoutTimer() {
1938 DCHECK(!timeout_timer_
.IsRunning());
1940 if (embedded_worker_
->devtools_attached()) {
1941 // Don't record the startup time metric once DevTools is attached.
1942 ClearTick(&start_time_
);
1943 skip_recording_startup_time_
= true;
1945 RestartTick(&start_time_
);
1946 skip_recording_startup_time_
= false;
1949 ClearTick(&idle_time_
);
1951 // Ping will be activated in OnScriptLoaded.
1952 ping_controller_
->Deactivate();
1954 timeout_timer_
.Start(FROM_HERE
,
1955 base::TimeDelta::FromSeconds(kTimeoutTimerDelaySeconds
),
1956 this, &ServiceWorkerVersion::OnTimeoutTimer
);
1959 void ServiceWorkerVersion::StopTimeoutTimer() {
1960 timeout_timer_
.Stop();
1962 // Trigger update if worker is stale.
1963 if (!stale_time_
.is_null()) {
1964 ClearTick(&stale_time_
);
1965 if (!update_timer_
.IsRunning())
1970 void ServiceWorkerVersion::OnTimeoutTimer() {
1971 DCHECK(running_status() == STARTING
|| running_status() == RUNNING
||
1972 running_status() == STOPPING
)
1973 << running_status();
1977 if (GetTickDuration(stop_time_
) >
1978 base::TimeDelta::FromSeconds(kStopWorkerTimeoutSeconds
)) {
1979 metrics_
->NotifyStalledInStopping();
1982 // Trigger update if worker is stale and we waited long enough for it to go
1984 if (GetTickDuration(stale_time_
) >
1985 base::TimeDelta::FromMinutes(kRequestTimeoutMinutes
)) {
1986 ClearTick(&stale_time_
);
1987 if (!update_timer_
.IsRunning())
1991 // Starting a worker hasn't finished within a certain period.
1992 if (GetTickDuration(start_time_
) >
1993 base::TimeDelta::FromMinutes(kStartWorkerTimeoutMinutes
)) {
1994 DCHECK(running_status() == STARTING
|| running_status() == STOPPING
)
1995 << running_status();
1996 scoped_refptr
<ServiceWorkerVersion
> protect(this);
1997 RunCallbacks(this, &start_callbacks_
, SERVICE_WORKER_ERROR_TIMEOUT
);
1998 if (running_status() == STARTING
)
1999 embedded_worker_
->Stop();
2003 // Requests have not finished within a certain period.
2004 bool request_timed_out
= false;
2005 while (!requests_
.empty()) {
2006 RequestInfo info
= requests_
.front();
2007 if (GetTickDuration(info
.time
) <
2008 base::TimeDelta::FromMinutes(kRequestTimeoutMinutes
))
2010 if (OnRequestTimeout(info
))
2011 request_timed_out
= true;
2014 if (request_timed_out
&& running_status() != STOPPING
)
2015 embedded_worker_
->Stop();
2017 // For the timeouts below, there are no callbacks to timeout so there is
2018 // nothing more to do if the worker is already stopping.
2019 if (running_status() == STOPPING
)
2022 // The worker has been idle for longer than a certain period.
2023 if (GetTickDuration(idle_time_
) >
2024 base::TimeDelta::FromSeconds(kIdleWorkerTimeoutSeconds
)) {
2029 // Check ping status.
2030 ping_controller_
->CheckPingStatus();
2033 ServiceWorkerStatusCode
ServiceWorkerVersion::PingWorker() {
2034 DCHECK(running_status() == STARTING
|| running_status() == RUNNING
);
2035 return embedded_worker_
->SendMessage(ServiceWorkerMsg_Ping());
2038 void ServiceWorkerVersion::OnPingTimeout() {
2039 DCHECK(running_status() == STARTING
|| running_status() == RUNNING
);
2040 // TODO(falken): Show a message to the developer that the SW was stopped due
2041 // to timeout (crbug.com/457968). Also, change the error code to
2042 // SERVICE_WORKER_ERROR_TIMEOUT.
2046 void ServiceWorkerVersion::StopWorkerIfIdle() {
2047 if (HasInflightRequests() && !ping_controller_
->IsTimedOut())
2049 if (running_status() == STOPPED
|| running_status() == STOPPING
||
2050 !stop_callbacks_
.empty()) {
2054 // TODO(falken): We may need to handle StopIfIdle failure and
2055 // forcibly fail pending callbacks so no one is stuck waiting
2057 embedded_worker_
->StopIfIdle();
2060 bool ServiceWorkerVersion::HasInflightRequests() const {
2061 return !activate_requests_
.IsEmpty() || !install_requests_
.IsEmpty() ||
2062 !fetch_requests_
.IsEmpty() || !sync_requests_
.IsEmpty() ||
2063 !notification_click_requests_
.IsEmpty() || !push_requests_
.IsEmpty() ||
2064 !geofencing_requests_
.IsEmpty() ||
2065 !service_port_connect_requests_
.IsEmpty() ||
2066 !streaming_url_request_jobs_
.empty();
2069 void ServiceWorkerVersion::RecordStartWorkerResult(
2070 ServiceWorkerStatusCode status
) {
2071 base::TimeTicks start_time
= start_time_
;
2072 ClearTick(&start_time_
);
2074 ServiceWorkerMetrics::RecordStartWorkerStatus(status
,
2075 IsInstalled(prestart_status_
));
2077 if (status
== SERVICE_WORKER_OK
&& !start_time
.is_null() &&
2078 !skip_recording_startup_time_
) {
2079 ServiceWorkerMetrics::RecordStartWorkerTime(GetTickDuration(start_time
),
2080 IsInstalled(prestart_status_
));
2083 if (status
!= SERVICE_WORKER_ERROR_TIMEOUT
)
2085 EmbeddedWorkerInstance::StartingPhase phase
=
2086 EmbeddedWorkerInstance::NOT_STARTING
;
2087 EmbeddedWorkerInstance::Status running_status
= embedded_worker_
->status();
2088 // Build an artifical JavaScript exception to show in the ServiceWorker
2089 // log for developers; it's not user-facing so it's not a localized resource.
2090 std::string message
= "ServiceWorker startup timed out. ";
2091 if (running_status
!= EmbeddedWorkerInstance::STARTING
) {
2092 message
.append("The worker had unexpected status: ");
2093 message
.append(EmbeddedWorkerInstance::StatusToString(running_status
));
2095 phase
= embedded_worker_
->starting_phase();
2096 message
.append("The worker was in startup phase: ");
2097 message
.append(EmbeddedWorkerInstance::StartingPhaseToString(phase
));
2099 message
.append(".");
2100 OnReportException(base::UTF8ToUTF16(message
), -1, -1, GURL());
2101 DVLOG(1) << message
;
2102 UMA_HISTOGRAM_ENUMERATION("ServiceWorker.StartWorker.TimeoutPhase",
2104 EmbeddedWorkerInstance::STARTING_PHASE_MAX_VALUE
);
2107 template <typename IDMAP
>
2108 void ServiceWorkerVersion::RemoveCallbackAndStopIfRedundant(IDMAP
* callbacks
,
2110 RestartTick(&idle_time_
);
2111 callbacks
->Remove(request_id
);
2112 if (is_redundant()) {
2113 // The stop should be already scheduled, but try to stop immediately, in
2114 // order to release worker resources soon.
2119 template <typename CallbackType
>
2120 int ServiceWorkerVersion::AddRequest(
2121 const CallbackType
& callback
,
2122 IDMap
<PendingRequest
<CallbackType
>, IDMapOwnPointer
>* callback_map
,
2123 RequestType request_type
) {
2124 base::TimeTicks now
= base::TimeTicks::Now();
2126 callback_map
->Add(new PendingRequest
<CallbackType
>(callback
, now
));
2127 requests_
.push(RequestInfo(request_id
, request_type
, now
));
2131 bool ServiceWorkerVersion::OnRequestTimeout(const RequestInfo
& info
) {
2132 switch (info
.type
) {
2133 case REQUEST_ACTIVATE
:
2134 return RunIDMapCallback(&activate_requests_
, info
.id
,
2135 SERVICE_WORKER_ERROR_TIMEOUT
);
2136 case REQUEST_INSTALL
:
2137 return RunIDMapCallback(&install_requests_
, info
.id
,
2138 SERVICE_WORKER_ERROR_TIMEOUT
);
2140 return RunIDMapCallback(
2141 &fetch_requests_
, info
.id
, SERVICE_WORKER_ERROR_TIMEOUT
,
2142 /* The other args are ignored for non-OK status. */
2143 SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK
, ServiceWorkerResponse());
2145 return RunIDMapCallback(&sync_requests_
, info
.id
,
2146 SERVICE_WORKER_ERROR_TIMEOUT
);
2147 case REQUEST_NOTIFICATION_CLICK
:
2148 return RunIDMapCallback(¬ification_click_requests_
, info
.id
,
2149 SERVICE_WORKER_ERROR_TIMEOUT
);
2151 return RunIDMapCallback(&push_requests_
, info
.id
,
2152 SERVICE_WORKER_ERROR_TIMEOUT
);
2153 case REQUEST_GEOFENCING
:
2154 return RunIDMapCallback(&geofencing_requests_
, info
.id
,
2155 SERVICE_WORKER_ERROR_TIMEOUT
);
2156 case REQUEST_SERVICE_PORT_CONNECT
:
2157 return RunIDMapCallback(&service_port_connect_requests_
, info
.id
,
2158 SERVICE_WORKER_ERROR_TIMEOUT
,
2159 false /* accept_connection */, base::string16(),
2162 NOTREACHED() << "Got unexpected request type: " << info
.type
;
2166 void ServiceWorkerVersion::SetAllRequestTimes(const base::TimeTicks
& ticks
) {
2167 std::queue
<RequestInfo
> new_requests
;
2168 while (!requests_
.empty()) {
2169 RequestInfo info
= requests_
.front();
2171 new_requests
.push(info
);
2174 requests_
= new_requests
;
2177 ServiceWorkerStatusCode
ServiceWorkerVersion::DeduceStartWorkerFailureReason(
2178 ServiceWorkerStatusCode default_code
) {
2179 if (ping_controller_
->IsTimedOut())
2180 return SERVICE_WORKER_ERROR_TIMEOUT
;
2182 if (start_worker_status_
!= SERVICE_WORKER_OK
)
2183 return start_worker_status_
;
2185 const net::URLRequestStatus
& main_script_status
=
2186 script_cache_map()->main_script_status();
2187 if (main_script_status
.status() != net::URLRequestStatus::SUCCESS
) {
2188 switch (main_script_status
.error()) {
2189 case net::ERR_INSECURE_RESPONSE
:
2190 case net::ERR_UNSAFE_REDIRECT
:
2191 return SERVICE_WORKER_ERROR_SECURITY
;
2192 case net::ERR_ABORTED
:
2193 return SERVICE_WORKER_ERROR_ABORT
;
2195 return SERVICE_WORKER_ERROR_NETWORK
;
2199 return default_code
;
2202 void ServiceWorkerVersion::MarkIfStale() {
2205 if (update_timer_
.IsRunning() || !stale_time_
.is_null())
2207 ServiceWorkerRegistration
* registration
=
2208 context_
->GetLiveRegistration(registration_id_
);
2209 if (!registration
|| registration
->active_version() != this)
2211 base::TimeDelta time_since_last_check
=
2212 base::Time::Now() - registration
->last_update_check();
2213 if (time_since_last_check
>
2214 base::TimeDelta::FromHours(kServiceWorkerScriptMaxCacheAgeInHours
))
2215 RestartTick(&stale_time_
);
2218 void ServiceWorkerVersion::FoundRegistrationForUpdate(
2219 ServiceWorkerStatusCode status
,
2220 const scoped_refptr
<ServiceWorkerRegistration
>& registration
) {
2224 const scoped_refptr
<ServiceWorkerVersion
> protect
= this;
2225 if (is_update_scheduled_
) {
2226 context_
->UnprotectVersion(version_id_
);
2227 is_update_scheduled_
= false;
2230 if (status
!= SERVICE_WORKER_OK
|| registration
->active_version() != this)
2232 context_
->UpdateServiceWorker(registration
.get(),
2233 false /* force_bypass_cache */);
2236 void ServiceWorkerVersion::OnStoppedInternal(
2237 EmbeddedWorkerInstance::Status old_status
) {
2238 DCHECK_EQ(STOPPED
, running_status());
2239 scoped_refptr
<ServiceWorkerVersion
> protect(this);
2244 bool should_restart
= !is_redundant() && !start_callbacks_
.empty() &&
2245 (old_status
!= EmbeddedWorkerInstance::STARTING
);
2247 ClearTick(&stop_time_
);
2250 if (ping_controller_
->IsTimedOut())
2251 should_restart
= false;
2253 // Fire all stop callbacks.
2254 RunCallbacks(this, &stop_callbacks_
, SERVICE_WORKER_OK
);
2256 if (!should_restart
) {
2257 // Let all start callbacks fail.
2258 RunCallbacks(this, &start_callbacks_
,
2259 DeduceStartWorkerFailureReason(
2260 SERVICE_WORKER_ERROR_START_WORKER_FAILED
));
2263 // Let all message callbacks fail (this will also fire and clear all
2264 // callbacks for events).
2265 // TODO(kinuko): Consider if we want to add queue+resend mechanism here.
2266 RunIDMapCallbacks(&activate_requests_
,
2267 SERVICE_WORKER_ERROR_ACTIVATE_WORKER_FAILED
);
2268 RunIDMapCallbacks(&install_requests_
,
2269 SERVICE_WORKER_ERROR_INSTALL_WORKER_FAILED
);
2270 RunIDMapCallbacks(&fetch_requests_
, SERVICE_WORKER_ERROR_FAILED
,
2271 SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK
,
2272 ServiceWorkerResponse());
2273 RunIDMapCallbacks(&sync_requests_
, SERVICE_WORKER_ERROR_FAILED
);
2274 RunIDMapCallbacks(¬ification_click_requests_
, SERVICE_WORKER_ERROR_FAILED
);
2275 RunIDMapCallbacks(&push_requests_
, SERVICE_WORKER_ERROR_FAILED
);
2276 RunIDMapCallbacks(&geofencing_requests_
, SERVICE_WORKER_ERROR_FAILED
);
2278 // Close all mojo services. This will also fire and clear all callbacks
2279 // for messages that are still outstanding for those services.
2280 OnServicePortDispatcherConnectionError();
2282 OnBackgroundSyncDispatcherConnectionError();
2284 streaming_url_request_jobs_
.clear();
2286 FOR_EACH_OBSERVER(Listener
, listeners_
, OnRunningStateChanged(this));
2289 StartWorkerInternal();
2292 void ServiceWorkerVersion::OnServicePortDispatcherConnectionError() {
2293 RunIDMapCallbacks(&service_port_connect_requests_
,
2294 SERVICE_WORKER_ERROR_FAILED
, false, base::string16(),
2296 service_port_dispatcher_
.reset();
2299 void ServiceWorkerVersion::OnBackgroundSyncDispatcherConnectionError() {
2300 RunIDMapCallbacks(&sync_requests_
, SERVICE_WORKER_ERROR_FAILED
);
2301 background_sync_dispatcher_
.reset();
2304 } // namespace content