1 // Copyright 2015 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/renderer/service_worker/service_worker_context_client.h"
7 #include "base/lazy_instance.h"
8 #include "base/logging.h"
9 #include "base/metrics/histogram.h"
10 #include "base/strings/utf_string_conversions.h"
11 #include "base/thread_task_runner_handle.h"
12 #include "base/threading/thread_checker.h"
13 #include "base/threading/thread_local.h"
14 #include "base/trace_event/trace_event.h"
15 #include "content/child/navigator_connect/service_port_dispatcher_impl.h"
16 #include "content/child/notifications/notification_data_conversions.h"
17 #include "content/child/request_extra_data.h"
18 #include "content/child/service_worker/service_worker_dispatcher.h"
19 #include "content/child/service_worker/service_worker_network_provider.h"
20 #include "content/child/service_worker/service_worker_provider_context.h"
21 #include "content/child/service_worker/service_worker_registration_handle_reference.h"
22 #include "content/child/service_worker/web_service_worker_impl.h"
23 #include "content/child/service_worker/web_service_worker_provider_impl.h"
24 #include "content/child/service_worker/web_service_worker_registration_impl.h"
25 #include "content/child/thread_safe_sender.h"
26 #include "content/child/webmessageportchannel_impl.h"
27 #include "content/common/devtools_messages.h"
28 #include "content/common/message_port_messages.h"
29 #include "content/common/mojo/service_registry_impl.h"
30 #include "content/common/service_worker/embedded_worker_messages.h"
31 #include "content/common/service_worker/service_worker_messages.h"
32 #include "content/public/common/referrer.h"
33 #include "content/public/renderer/content_renderer_client.h"
34 #include "content/public/renderer/document_state.h"
35 #include "content/renderer/background_sync/background_sync_client_impl.h"
36 #include "content/renderer/devtools/devtools_agent.h"
37 #include "content/renderer/render_thread_impl.h"
38 #include "content/renderer/service_worker/embedded_worker_dispatcher.h"
39 #include "content/renderer/service_worker/service_worker_type_util.h"
40 #include "ipc/ipc_message.h"
41 #include "ipc/ipc_message_macros.h"
42 #include "third_party/WebKit/public/platform/WebCrossOriginServiceWorkerClient.h"
43 #include "third_party/WebKit/public/platform/WebMessagePortChannel.h"
44 #include "third_party/WebKit/public/platform/WebPassOwnPtr.h"
45 #include "third_party/WebKit/public/platform/WebReferrerPolicy.h"
46 #include "third_party/WebKit/public/platform/WebString.h"
47 #include "third_party/WebKit/public/platform/modules/background_sync/WebSyncRegistration.h"
48 #include "third_party/WebKit/public/platform/modules/notifications/WebNotificationData.h"
49 #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerClientQueryOptions.h"
50 #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerRequest.h"
51 #include "third_party/WebKit/public/platform/modules/serviceworker/WebServiceWorkerResponse.h"
52 #include "third_party/WebKit/public/web/WebDataSource.h"
53 #include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextClient.h"
54 #include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerContextProxy.h"
55 #include "third_party/WebKit/public/web/modules/serviceworker/WebServiceWorkerNetworkProvider.h"
61 // For now client must be a per-thread instance.
62 base::LazyInstance
<base::ThreadLocalPointer
<ServiceWorkerContextClient
>>::
63 Leaky g_worker_client_tls
= LAZY_INSTANCE_INITIALIZER
;
65 void CallWorkerContextDestroyedOnMainThread(int embedded_worker_id
) {
66 if (!RenderThreadImpl::current() ||
67 !RenderThreadImpl::current()->embedded_worker_dispatcher())
69 RenderThreadImpl::current()->embedded_worker_dispatcher()->
70 WorkerContextDestroyed(embedded_worker_id
);
73 // We store an instance of this class in the "extra data" of the WebDataSource
74 // and attach a ServiceWorkerNetworkProvider to it as base::UserData.
75 // (see createServiceWorkerNetworkProvider).
76 class DataSourceExtraData
77 : public blink::WebDataSource::ExtraData
,
78 public base::SupportsUserData
{
80 DataSourceExtraData() {}
81 virtual ~DataSourceExtraData() {}
84 // Called on the main thread only and blink owns it.
85 class WebServiceWorkerNetworkProviderImpl
86 : public blink::WebServiceWorkerNetworkProvider
{
88 // Blink calls this method for each request starting with the main script,
89 // we tag them with the provider id.
90 virtual void willSendRequest(
91 blink::WebDataSource
* data_source
,
92 blink::WebURLRequest
& request
) {
93 ServiceWorkerNetworkProvider
* provider
=
94 ServiceWorkerNetworkProvider::FromDocumentState(
95 static_cast<DataSourceExtraData
*>(data_source
->extraData()));
96 scoped_ptr
<RequestExtraData
> extra_data(new RequestExtraData
);
97 extra_data
->set_service_worker_provider_id(provider
->provider_id());
98 request
.setExtraData(extra_data
.release());
102 void SendPostMessageToClientOnMainThread(
103 ThreadSafeSender
* sender
,
105 const std::string
& uuid
,
106 const base::string16
& message
,
107 scoped_ptr
<blink::WebMessagePortChannelArray
> channels
) {
108 sender
->Send(new ServiceWorkerHostMsg_PostMessageToClient(
109 routing_id
, uuid
, message
,
110 WebMessagePortChannelImpl::ExtractMessagePortIDs(channels
.Pass())));
113 void SendCrossOriginMessageToClientOnMainThread(
114 ThreadSafeSender
* sender
,
116 const base::string16
& message
,
117 scoped_ptr
<blink::WebMessagePortChannelArray
> channels
) {
118 sender
->Send(new MessagePortHostMsg_PostMessage(
119 message_port_id
, MessagePortMessage(message
),
120 WebMessagePortChannelImpl::ExtractMessagePortIDs(channels
.Pass())));
123 blink::WebURLRequest::FetchRequestMode
GetBlinkFetchRequestMode(
124 FetchRequestMode mode
) {
125 return static_cast<blink::WebURLRequest::FetchRequestMode
>(mode
);
128 blink::WebURLRequest::FetchCredentialsMode
GetBlinkFetchCredentialsMode(
129 FetchCredentialsMode credentials_mode
) {
130 return static_cast<blink::WebURLRequest::FetchCredentialsMode
>(
134 blink::WebURLRequest::FetchRedirectMode
GetBlinkFetchRedirectMode(
135 FetchRedirectMode redirect_mode
) {
136 return static_cast<blink::WebURLRequest::FetchRedirectMode
>(redirect_mode
);
139 blink::WebURLRequest::RequestContext
GetBlinkRequestContext(
140 RequestContextType request_context_type
) {
141 return static_cast<blink::WebURLRequest::RequestContext
>(
142 request_context_type
);
145 blink::WebURLRequest::FrameType
GetBlinkFrameType(
146 RequestContextFrameType frame_type
) {
147 return static_cast<blink::WebURLRequest::FrameType
>(frame_type
);
150 blink::WebServiceWorkerClientInfo
151 ToWebServiceWorkerClientInfo(const ServiceWorkerClientInfo
& client_info
) {
152 DCHECK(client_info
.IsValid());
154 blink::WebServiceWorkerClientInfo web_client_info
;
156 web_client_info
.uuid
= base::UTF8ToUTF16(client_info
.client_uuid
);
157 web_client_info
.pageVisibilityState
= client_info
.page_visibility_state
;
158 web_client_info
.isFocused
= client_info
.is_focused
;
159 web_client_info
.url
= client_info
.url
;
160 web_client_info
.frameType
= GetBlinkFrameType(client_info
.frame_type
);
161 web_client_info
.clientType
= client_info
.client_type
;
163 return web_client_info
;
168 // Holding data that needs to be bound to the worker context on the
170 struct ServiceWorkerContextClient::WorkerContextData
{
171 using ClientsCallbacksMap
=
172 IDMap
<blink::WebServiceWorkerClientsCallbacks
, IDMapOwnPointer
>;
173 using ClaimClientsCallbacksMap
=
174 IDMap
<blink::WebServiceWorkerClientsClaimCallbacks
, IDMapOwnPointer
>;
175 using ClientCallbacksMap
=
176 IDMap
<blink::WebServiceWorkerClientCallbacks
, IDMapOwnPointer
>;
177 using SkipWaitingCallbacksMap
=
178 IDMap
<blink::WebServiceWorkerSkipWaitingCallbacks
, IDMapOwnPointer
>;
179 using SyncEventCallbacksMap
=
180 IDMap
<const mojo::Callback
<void(ServiceWorkerEventStatus
)>,
183 explicit WorkerContextData(ServiceWorkerContextClient
* owner
)
184 : weak_factory(owner
), proxy_weak_factory(owner
->proxy_
) {}
186 ~WorkerContextData() {
187 DCHECK(thread_checker
.CalledOnValidThread());
190 // Pending callbacks for GetClientDocuments().
191 ClientsCallbacksMap clients_callbacks
;
193 // Pending callbacks for OpenWindow() and FocusClient().
194 ClientCallbacksMap client_callbacks
;
196 // Pending callbacks for SkipWaiting().
197 SkipWaitingCallbacksMap skip_waiting_callbacks
;
199 // Pending callbacks for ClaimClients().
200 ClaimClientsCallbacksMap claim_clients_callbacks
;
202 // Pending callbacks for Background Sync Events
203 SyncEventCallbacksMap sync_event_callbacks
;
205 ServiceRegistryImpl service_registry
;
207 base::ThreadChecker thread_checker
;
208 base::WeakPtrFactory
<ServiceWorkerContextClient
> weak_factory
;
209 base::WeakPtrFactory
<blink::WebServiceWorkerContextProxy
> proxy_weak_factory
;
212 ServiceWorkerContextClient
*
213 ServiceWorkerContextClient::ThreadSpecificInstance() {
214 return g_worker_client_tls
.Pointer()->Get();
217 ServiceWorkerContextClient::ServiceWorkerContextClient(
218 int embedded_worker_id
,
219 int64 service_worker_version_id
,
220 const GURL
& service_worker_scope
,
221 const GURL
& script_url
,
222 int worker_devtools_agent_route_id
)
223 : embedded_worker_id_(embedded_worker_id
),
224 service_worker_version_id_(service_worker_version_id
),
225 service_worker_scope_(service_worker_scope
),
226 script_url_(script_url
),
227 worker_devtools_agent_route_id_(worker_devtools_agent_route_id
),
228 sender_(ChildThreadImpl::current()->thread_safe_sender()),
229 main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()),
231 TRACE_EVENT_ASYNC_BEGIN0("ServiceWorker",
232 "ServiceWorkerContextClient::StartingWorkerContext",
234 TRACE_EVENT_ASYNC_STEP_INTO0(
236 "ServiceWorkerContextClient::StartingWorkerContext",
241 ServiceWorkerContextClient::~ServiceWorkerContextClient() {}
243 void ServiceWorkerContextClient::OnMessageReceived(
245 int embedded_worker_id
,
246 const IPC::Message
& message
) {
247 CHECK_EQ(embedded_worker_id_
, embedded_worker_id
);
249 IPC_BEGIN_MESSAGE_MAP(ServiceWorkerContextClient
, message
)
250 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_ActivateEvent
, OnActivateEvent
)
251 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_FetchEvent
, OnFetchEvent
)
252 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_InstallEvent
, OnInstallEvent
)
253 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_NotificationClickEvent
,
254 OnNotificationClickEvent
)
255 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_PushEvent
, OnPushEvent
)
256 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_GeofencingEvent
, OnGeofencingEvent
)
257 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_MessageToWorker
, OnPostMessage
)
258 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_CrossOriginMessageToWorker
,
259 OnCrossOriginMessageToWorker
)
260 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidGetClients
, OnDidGetClients
)
261 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_OpenWindowResponse
,
262 OnOpenWindowResponse
)
263 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_OpenWindowError
,
265 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_FocusClientResponse
,
266 OnFocusClientResponse
)
267 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_NavigateClientResponse
,
268 OnNavigateClientResponse
)
269 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_NavigateClientError
,
270 OnNavigateClientError
)
271 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidSkipWaiting
, OnDidSkipWaiting
)
272 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_DidClaimClients
, OnDidClaimClients
)
273 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_ClaimClientsError
, OnClaimClientsError
)
274 IPC_MESSAGE_HANDLER(ServiceWorkerMsg_Ping
, OnPing
);
275 IPC_MESSAGE_UNHANDLED(handled
= false)
276 IPC_END_MESSAGE_MAP()
280 void ServiceWorkerContextClient::BindServiceRegistry(
281 mojo::InterfaceRequest
<mojo::ServiceProvider
> services
,
282 mojo::ServiceProviderPtr exposed_services
) {
283 context_
->service_registry
.Bind(services
.Pass());
284 context_
->service_registry
.BindRemoteServiceProvider(exposed_services
.Pass());
287 blink::WebURL
ServiceWorkerContextClient::scope() const {
288 return service_worker_scope_
;
291 void ServiceWorkerContextClient::getClients(
292 const blink::WebServiceWorkerClientQueryOptions
& weboptions
,
293 blink::WebServiceWorkerClientsCallbacks
* callbacks
) {
295 int request_id
= context_
->clients_callbacks
.Add(callbacks
);
296 ServiceWorkerClientQueryOptions options
;
297 options
.client_type
= weboptions
.clientType
;
298 options
.include_uncontrolled
= weboptions
.includeUncontrolled
;
299 Send(new ServiceWorkerHostMsg_GetClients(
300 GetRoutingID(), request_id
, options
));
303 void ServiceWorkerContextClient::openWindow(
304 const blink::WebURL
& url
,
305 blink::WebServiceWorkerClientCallbacks
* callbacks
) {
307 int request_id
= context_
->client_callbacks
.Add(callbacks
);
308 Send(new ServiceWorkerHostMsg_OpenWindow(
309 GetRoutingID(), request_id
, url
));
312 void ServiceWorkerContextClient::setCachedMetadata(const blink::WebURL
& url
,
315 std::vector
<char> copy(data
, data
+ size
);
316 Send(new ServiceWorkerHostMsg_SetCachedMetadata(GetRoutingID(), url
, copy
));
319 void ServiceWorkerContextClient::clearCachedMetadata(
320 const blink::WebURL
& url
) {
321 Send(new ServiceWorkerHostMsg_ClearCachedMetadata(GetRoutingID(), url
));
324 void ServiceWorkerContextClient::workerReadyForInspection() {
325 Send(new EmbeddedWorkerHostMsg_WorkerReadyForInspection(embedded_worker_id_
));
328 void ServiceWorkerContextClient::workerContextFailedToStart() {
329 DCHECK(main_thread_task_runner_
->RunsTasksOnCurrentThread());
332 Send(new EmbeddedWorkerHostMsg_WorkerScriptLoadFailed(embedded_worker_id_
));
334 RenderThreadImpl::current()->embedded_worker_dispatcher()->
335 WorkerContextDestroyed(embedded_worker_id_
);
338 void ServiceWorkerContextClient::workerContextStarted(
339 blink::WebServiceWorkerContextProxy
* proxy
) {
340 DCHECK(!worker_task_runner_
.get());
341 DCHECK_NE(0, WorkerThread::GetCurrentId());
342 worker_task_runner_
= base::ThreadTaskRunnerHandle::Get();
343 // g_worker_client_tls.Pointer()->Get() could return NULL if this context
344 // gets deleted before workerContextStarted() is called.
345 DCHECK(g_worker_client_tls
.Pointer()->Get() == NULL
);
347 g_worker_client_tls
.Pointer()->Set(this);
350 // Initialize pending callback maps. This needs to be freed on the
351 // same thread before the worker context goes away in
352 // willDestroyWorkerContext.
353 context_
.reset(new WorkerContextData(this));
355 // Register Mojo services.
356 context_
->service_registry
.ServiceRegistry::AddService(
357 base::Bind(&ServicePortDispatcherImpl::Create
,
358 context_
->proxy_weak_factory
.GetWeakPtr()));
359 context_
->service_registry
.ServiceRegistry::AddService(
360 base::Bind(&BackgroundSyncClientImpl::Create
));
362 SetRegistrationInServiceWorkerGlobalScope();
364 Send(new EmbeddedWorkerHostMsg_WorkerScriptLoaded(
365 embedded_worker_id_
, WorkerThread::GetCurrentId(),
366 provider_context_
->provider_id()));
368 TRACE_EVENT_ASYNC_STEP_INTO0(
370 "ServiceWorkerContextClient::StartingWorkerContext",
375 void ServiceWorkerContextClient::didEvaluateWorkerScript(bool success
) {
376 Send(new EmbeddedWorkerHostMsg_WorkerScriptEvaluated(
377 embedded_worker_id_
, success
));
379 // Schedule a task to send back WorkerStarted asynchronously,
380 // so that at the time we send it we can be sure that the
381 // worker run loop has been started.
382 worker_task_runner_
->PostTask(
383 FROM_HERE
, base::Bind(&ServiceWorkerContextClient::SendWorkerStarted
,
387 void ServiceWorkerContextClient::didInitializeWorkerContext(
388 v8::Local
<v8::Context
> context
,
389 const blink::WebURL
& url
) {
390 // TODO(annekao): Remove WebURL parameter from Blink, it's at best redundant
391 // given |script_url_|, and may be empty in the future.
392 // Also remove m_documentURL from ServiceWorkerGlobalScopeProxy.
395 ->DidInitializeServiceWorkerContextOnWorkerThread(context
, script_url_
);
398 void ServiceWorkerContextClient::willDestroyWorkerContext(
399 v8::Local
<v8::Context
> context
) {
400 // At this point WillStopCurrentWorkerThread is already called, so
401 // worker_task_runner_->RunsTasksOnCurrentThread() returns false
402 // (while we're still on the worker thread).
405 // We have to clear callbacks now, as they need to be freed on the
409 // This also lets the message filter stop dispatching messages to
411 g_worker_client_tls
.Pointer()->Set(NULL
);
413 GetContentClient()->renderer()->WillDestroyServiceWorkerContextOnWorkerThread(
417 void ServiceWorkerContextClient::workerContextDestroyed() {
418 DCHECK(g_worker_client_tls
.Pointer()->Get() == NULL
);
420 // Now we should be able to free the WebEmbeddedWorker container on the
422 main_thread_task_runner_
->PostTask(
424 base::Bind(&CallWorkerContextDestroyedOnMainThread
,
425 embedded_worker_id_
));
428 void ServiceWorkerContextClient::reportException(
429 const blink::WebString
& error_message
,
432 const blink::WebString
& source_url
) {
433 Send(new EmbeddedWorkerHostMsg_ReportException(
437 column_number
, GURL(source_url
)));
440 void ServiceWorkerContextClient::reportConsoleMessage(
443 const blink::WebString
& message
,
445 const blink::WebString
& source_url
) {
446 EmbeddedWorkerHostMsg_ReportConsoleMessage_Params params
;
447 params
.source_identifier
= source
;
448 params
.message_level
= level
;
449 params
.message
= message
;
450 params
.line_number
= line_number
;
451 params
.source_url
= GURL(source_url
);
453 Send(new EmbeddedWorkerHostMsg_ReportConsoleMessage(
454 embedded_worker_id_
, params
));
457 void ServiceWorkerContextClient::sendDevToolsMessage(
459 const blink::WebString
& message
,
460 const blink::WebString
& state_cookie
) {
461 DevToolsAgent::SendChunkedProtocolMessage(
462 sender_
.get(), worker_devtools_agent_route_id_
,
463 call_id
, message
.utf8(), state_cookie
.utf8());
466 void ServiceWorkerContextClient::didHandleActivateEvent(
468 blink::WebServiceWorkerEventResult result
) {
469 Send(new ServiceWorkerHostMsg_ActivateEventFinished(
470 GetRoutingID(), request_id
, result
));
473 void ServiceWorkerContextClient::didHandleInstallEvent(
475 blink::WebServiceWorkerEventResult result
) {
476 Send(new ServiceWorkerHostMsg_InstallEventFinished(
477 GetRoutingID(), request_id
, result
));
480 void ServiceWorkerContextClient::didHandleFetchEvent(int request_id
) {
481 Send(new ServiceWorkerHostMsg_FetchEventFinished(
482 GetRoutingID(), request_id
,
483 SERVICE_WORKER_FETCH_EVENT_RESULT_FALLBACK
,
484 ServiceWorkerResponse()));
487 void ServiceWorkerContextClient::didHandleFetchEvent(
489 const blink::WebServiceWorkerResponse
& web_response
) {
490 ServiceWorkerHeaderMap headers
;
491 GetServiceWorkerHeaderMapFromWebResponse(web_response
, &headers
);
492 ServiceWorkerResponse
response(
493 web_response
.url(), web_response
.status(),
494 web_response
.statusText().utf8(), web_response
.responseType(), headers
,
495 web_response
.blobUUID().utf8(), web_response
.blobSize(),
496 web_response
.streamURL(), web_response
.error());
497 Send(new ServiceWorkerHostMsg_FetchEventFinished(
498 GetRoutingID(), request_id
,
499 SERVICE_WORKER_FETCH_EVENT_RESULT_RESPONSE
,
503 void ServiceWorkerContextClient::didHandleNotificationClickEvent(
505 blink::WebServiceWorkerEventResult result
) {
506 Send(new ServiceWorkerHostMsg_NotificationClickEventFinished(
507 GetRoutingID(), request_id
));
510 void ServiceWorkerContextClient::didHandlePushEvent(
512 blink::WebServiceWorkerEventResult result
) {
513 Send(new ServiceWorkerHostMsg_PushEventFinished(
514 GetRoutingID(), request_id
, result
));
517 void ServiceWorkerContextClient::didHandleSyncEvent(
519 blink::WebServiceWorkerEventResult result
) {
520 const SyncCallback
* callback
=
521 context_
->sync_event_callbacks
.Lookup(request_id
);
524 if (result
== blink::WebServiceWorkerEventResultCompleted
) {
525 callback
->Run(SERVICE_WORKER_EVENT_STATUS_COMPLETED
);
527 callback
->Run(SERVICE_WORKER_EVENT_STATUS_REJECTED
);
529 context_
->sync_event_callbacks
.Remove(request_id
);
532 blink::WebServiceWorkerNetworkProvider
*
533 ServiceWorkerContextClient::createServiceWorkerNetworkProvider(
534 blink::WebDataSource
* data_source
) {
535 DCHECK(main_thread_task_runner_
->RunsTasksOnCurrentThread());
537 // Create a content::ServiceWorkerNetworkProvider for this data source so
538 // we can observe its requests.
539 scoped_ptr
<ServiceWorkerNetworkProvider
> provider(
540 new ServiceWorkerNetworkProvider(
541 MSG_ROUTING_NONE
, SERVICE_WORKER_PROVIDER_FOR_CONTROLLER
));
542 provider_context_
= provider
->context();
544 // Tell the network provider about which version to load.
545 provider
->SetServiceWorkerVersionId(service_worker_version_id_
);
547 // The provider is kept around for the lifetime of the DataSource
548 // and ownership is transferred to the DataSource.
549 DataSourceExtraData
* extra_data
= new DataSourceExtraData();
550 data_source
->setExtraData(extra_data
);
551 ServiceWorkerNetworkProvider::AttachToDocumentState(
552 extra_data
, provider
.Pass());
554 // Blink is responsible for deleting the returned object.
555 return new WebServiceWorkerNetworkProviderImpl();
558 blink::WebServiceWorkerProvider
*
559 ServiceWorkerContextClient::createServiceWorkerProvider() {
560 DCHECK(main_thread_task_runner_
->RunsTasksOnCurrentThread());
561 DCHECK(provider_context_
);
563 // Blink is responsible for deleting the returned object.
564 return new WebServiceWorkerProviderImpl(
565 sender_
.get(), provider_context_
.get());
568 void ServiceWorkerContextClient::postMessageToClient(
569 const blink::WebString
& uuid
,
570 const blink::WebString
& message
,
571 blink::WebMessagePortChannelArray
* channels
) {
572 // This may send channels for MessagePorts, and all internal book-keeping
573 // messages for MessagePort (e.g. QueueMessages) are sent from main thread
574 // (with thread hopping), so we need to do the same thread hopping here not
575 // to overtake those messages.
576 scoped_ptr
<blink::WebMessagePortChannelArray
> channel_array(channels
);
577 main_thread_task_runner_
->PostTask(
579 base::Bind(&SendPostMessageToClientOnMainThread
,
582 base::UTF16ToUTF8(base::StringPiece16(uuid
)),
583 static_cast<base::string16
>(message
),
584 base::Passed(&channel_array
)));
587 void ServiceWorkerContextClient::postMessageToCrossOriginClient(
588 const blink::WebCrossOriginServiceWorkerClient
& client
,
589 const blink::WebString
& message
,
590 blink::WebMessagePortChannelArray
* channels
) {
591 // This may send channels for MessagePorts, and all internal book-keeping
592 // messages for MessagePort (e.g. QueueMessages) are sent from main thread
593 // (with thread hopping), so we need to do the same thread hopping here not
594 // to overtake those messages.
595 scoped_ptr
<blink::WebMessagePortChannelArray
> channel_array(channels
);
596 main_thread_task_runner_
->PostTask(
598 base::Bind(&SendCrossOriginMessageToClientOnMainThread
,
599 sender_
, client
.clientID
,
600 static_cast<base::string16
>(message
),
601 base::Passed(&channel_array
)));
604 void ServiceWorkerContextClient::focus(
605 const blink::WebString
& uuid
,
606 blink::WebServiceWorkerClientCallbacks
* callback
) {
608 int request_id
= context_
->client_callbacks
.Add(callback
);
609 Send(new ServiceWorkerHostMsg_FocusClient(
610 GetRoutingID(), request_id
,
611 base::UTF16ToUTF8(base::StringPiece16(uuid
))));
614 void ServiceWorkerContextClient::navigate(
615 const blink::WebString
& uuid
,
616 const blink::WebURL
& url
,
617 blink::WebServiceWorkerClientCallbacks
* callback
) {
619 int request_id
= context_
->client_callbacks
.Add(callback
);
620 Send(new ServiceWorkerHostMsg_NavigateClient(
621 GetRoutingID(), request_id
, base::UTF16ToUTF8(base::StringPiece16(uuid
)),
625 void ServiceWorkerContextClient::skipWaiting(
626 blink::WebServiceWorkerSkipWaitingCallbacks
* callbacks
) {
628 int request_id
= context_
->skip_waiting_callbacks
.Add(callbacks
);
629 Send(new ServiceWorkerHostMsg_SkipWaiting(GetRoutingID(), request_id
));
632 void ServiceWorkerContextClient::claim(
633 blink::WebServiceWorkerClientsClaimCallbacks
* callbacks
) {
635 int request_id
= context_
->claim_clients_callbacks
.Add(callbacks
);
636 Send(new ServiceWorkerHostMsg_ClaimClients(GetRoutingID(), request_id
));
639 void ServiceWorkerContextClient::DispatchSyncEvent(
640 const blink::WebSyncRegistration
& registration
,
641 const SyncCallback
& callback
) {
642 TRACE_EVENT0("ServiceWorker",
643 "ServiceWorkerScriptContext::DispatchSyncEvent");
645 context_
->sync_event_callbacks
.Add(new SyncCallback(callback
));
646 proxy_
->dispatchSyncEvent(request_id
, registration
);
649 void ServiceWorkerContextClient::Send(IPC::Message
* message
) {
650 sender_
->Send(message
);
653 void ServiceWorkerContextClient::SendWorkerStarted() {
654 DCHECK(worker_task_runner_
->RunsTasksOnCurrentThread());
655 TRACE_EVENT_ASYNC_END0("ServiceWorker",
656 "ServiceWorkerContextClient::StartingWorkerContext",
658 Send(new EmbeddedWorkerHostMsg_WorkerStarted(embedded_worker_id_
));
661 void ServiceWorkerContextClient::SetRegistrationInServiceWorkerGlobalScope() {
662 DCHECK(worker_task_runner_
->RunsTasksOnCurrentThread());
663 DCHECK(provider_context_
);
665 ServiceWorkerRegistrationObjectInfo info
;
666 ServiceWorkerVersionAttributes attrs
;
668 provider_context_
->GetRegistrationInfoAndVersionAttributes(&info
, &attrs
);
670 return; // Cannot be associated with a registration in some tests.
672 ServiceWorkerDispatcher
* dispatcher
=
673 ServiceWorkerDispatcher::GetOrCreateThreadSpecificInstance(
674 sender_
.get(), main_thread_task_runner_
.get());
676 // Register a registration and its version attributes with the dispatcher
677 // living on the worker thread.
678 scoped_ptr
<WebServiceWorkerRegistrationImpl
> registration(
679 dispatcher
->CreateRegistration(info
, attrs
));
680 proxy_
->setRegistration(registration
.release());
683 void ServiceWorkerContextClient::OnActivateEvent(int request_id
) {
684 TRACE_EVENT0("ServiceWorker",
685 "ServiceWorkerContextClient::OnActivateEvent");
686 proxy_
->dispatchActivateEvent(request_id
);
689 void ServiceWorkerContextClient::OnInstallEvent(int request_id
) {
690 TRACE_EVENT0("ServiceWorker",
691 "ServiceWorkerContextClient::OnInstallEvent");
692 proxy_
->dispatchInstallEvent(request_id
);
695 void ServiceWorkerContextClient::OnFetchEvent(
697 const ServiceWorkerFetchRequest
& request
) {
698 blink::WebServiceWorkerRequest webRequest
;
699 TRACE_EVENT0("ServiceWorker",
700 "ServiceWorkerContextClient::OnFetchEvent");
701 webRequest
.setURL(blink::WebURL(request
.url
));
702 webRequest
.setMethod(blink::WebString::fromUTF8(request
.method
));
703 for (ServiceWorkerHeaderMap::const_iterator it
= request
.headers
.begin();
704 it
!= request
.headers
.end();
706 webRequest
.setHeader(blink::WebString::fromUTF8(it
->first
),
707 blink::WebString::fromUTF8(it
->second
));
709 if (!request
.blob_uuid
.empty()) {
710 webRequest
.setBlob(blink::WebString::fromUTF8(request
.blob_uuid
),
713 webRequest
.setReferrer(
714 blink::WebString::fromUTF8(request
.referrer
.url
.spec()),
715 request
.referrer
.policy
);
716 webRequest
.setMode(GetBlinkFetchRequestMode(request
.mode
));
717 webRequest
.setCredentialsMode(
718 GetBlinkFetchCredentialsMode(request
.credentials_mode
));
719 webRequest
.setRedirectMode(GetBlinkFetchRedirectMode(request
.redirect_mode
));
720 webRequest
.setRequestContext(
721 GetBlinkRequestContext(request
.request_context_type
));
722 webRequest
.setFrameType(GetBlinkFrameType(request
.frame_type
));
723 webRequest
.setIsReload(request
.is_reload
);
724 proxy_
->dispatchFetchEvent(request_id
, webRequest
);
727 void ServiceWorkerContextClient::OnNotificationClickEvent(
729 int64_t persistent_notification_id
,
730 const PlatformNotificationData
& notification_data
,
732 TRACE_EVENT0("ServiceWorker",
733 "ServiceWorkerContextClient::OnNotificationClickEvent");
734 proxy_
->dispatchNotificationClickEvent(
736 persistent_notification_id
,
737 ToWebNotificationData(notification_data
),
741 void ServiceWorkerContextClient::OnPushEvent(int request_id
,
742 const std::string
& data
) {
743 TRACE_EVENT0("ServiceWorker",
744 "ServiceWorkerContextClient::OnPushEvent");
745 proxy_
->dispatchPushEvent(request_id
, blink::WebString::fromUTF8(data
));
748 void ServiceWorkerContextClient::OnGeofencingEvent(
750 blink::WebGeofencingEventType event_type
,
751 const std::string
& region_id
,
752 const blink::WebCircularGeofencingRegion
& region
) {
753 TRACE_EVENT0("ServiceWorker",
754 "ServiceWorkerContextClient::OnGeofencingEvent");
755 proxy_
->dispatchGeofencingEvent(
756 request_id
, event_type
, blink::WebString::fromUTF8(region_id
), region
);
757 Send(new ServiceWorkerHostMsg_GeofencingEventFinished(GetRoutingID(),
761 void ServiceWorkerContextClient::OnPostMessage(
762 const base::string16
& message
,
763 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
764 const std::vector
<int>& new_routing_ids
) {
765 TRACE_EVENT0("ServiceWorker",
766 "ServiceWorkerContextClient::OnPostEvent");
767 blink::WebMessagePortChannelArray ports
=
768 WebMessagePortChannelImpl::CreatePorts(
769 sent_message_ports
, new_routing_ids
,
770 main_thread_task_runner_
);
772 // dispatchMessageEvent is expected to execute onmessage function
774 base::TimeTicks before
= base::TimeTicks::Now();
775 proxy_
->dispatchMessageEvent(message
, ports
);
776 UMA_HISTOGRAM_MEDIUM_TIMES(
777 "ServiceWorker.MessageEvent.Time",
778 base::TimeTicks::Now() - before
);
781 void ServiceWorkerContextClient::OnCrossOriginMessageToWorker(
782 const NavigatorConnectClient
& client
,
783 const base::string16
& message
,
784 const std::vector
<TransferredMessagePort
>& sent_message_ports
,
785 const std::vector
<int>& new_routing_ids
) {
786 TRACE_EVENT0("ServiceWorker",
787 "ServiceWorkerContextClient::OnCrossOriginMessageToWorker");
788 blink::WebMessagePortChannelArray ports
=
789 WebMessagePortChannelImpl::CreatePorts(
790 sent_message_ports
, new_routing_ids
,
791 main_thread_task_runner_
);
793 blink::WebCrossOriginServiceWorkerClient web_client
;
794 web_client
.origin
= client
.origin
;
795 web_client
.targetURL
= client
.target_url
;
796 web_client
.clientID
= client
.message_port_id
;
797 proxy_
->dispatchCrossOriginMessageEvent(web_client
, message
, ports
);
800 void ServiceWorkerContextClient::OnDidGetClients(
801 int request_id
, const std::vector
<ServiceWorkerClientInfo
>& clients
) {
802 TRACE_EVENT0("ServiceWorker",
803 "ServiceWorkerContextClient::OnDidGetClients");
804 blink::WebServiceWorkerClientsCallbacks
* callbacks
=
805 context_
->clients_callbacks
.Lookup(request_id
);
807 NOTREACHED() << "Got stray response: " << request_id
;
810 blink::WebServiceWorkerClientsInfo info
;
811 blink::WebVector
<blink::WebServiceWorkerClientInfo
> convertedClients(
813 for (size_t i
= 0; i
< clients
.size(); ++i
)
814 convertedClients
[i
] = ToWebServiceWorkerClientInfo(clients
[i
]);
815 info
.clients
.swap(convertedClients
);
816 callbacks
->onSuccess(info
);
817 context_
->clients_callbacks
.Remove(request_id
);
820 void ServiceWorkerContextClient::OnOpenWindowResponse(
822 const ServiceWorkerClientInfo
& client
) {
823 TRACE_EVENT0("ServiceWorker",
824 "ServiceWorkerContextClient::OnOpenWindowResponse");
825 blink::WebServiceWorkerClientCallbacks
* callbacks
=
826 context_
->client_callbacks
.Lookup(request_id
);
828 NOTREACHED() << "Got stray response: " << request_id
;
831 scoped_ptr
<blink::WebServiceWorkerClientInfo
> web_client
;
832 if (!client
.IsEmpty()) {
833 DCHECK(client
.IsValid());
834 web_client
.reset(new blink::WebServiceWorkerClientInfo(
835 ToWebServiceWorkerClientInfo(client
)));
837 callbacks
->onSuccess(adoptWebPtr(web_client
.release()));
838 context_
->client_callbacks
.Remove(request_id
);
841 void ServiceWorkerContextClient::OnOpenWindowError(
843 const std::string
& message
) {
844 TRACE_EVENT0("ServiceWorker",
845 "ServiceWorkerContextClient::OnOpenWindowError");
846 blink::WebServiceWorkerClientCallbacks
* callbacks
=
847 context_
->client_callbacks
.Lookup(request_id
);
849 NOTREACHED() << "Got stray response: " << request_id
;
852 callbacks
->onError(blink::WebServiceWorkerError(
853 blink::WebServiceWorkerError::ErrorTypeUnknown
,
854 blink::WebString::fromUTF8(message
)));
855 context_
->client_callbacks
.Remove(request_id
);
858 void ServiceWorkerContextClient::OnFocusClientResponse(
859 int request_id
, const ServiceWorkerClientInfo
& client
) {
860 TRACE_EVENT0("ServiceWorker",
861 "ServiceWorkerContextClient::OnFocusClientResponse");
862 blink::WebServiceWorkerClientCallbacks
* callback
=
863 context_
->client_callbacks
.Lookup(request_id
);
865 NOTREACHED() << "Got stray response: " << request_id
;
868 if (!client
.IsEmpty()) {
869 DCHECK(client
.IsValid());
870 scoped_ptr
<blink::WebServiceWorkerClientInfo
> web_client (
871 new blink::WebServiceWorkerClientInfo(
872 ToWebServiceWorkerClientInfo(client
)));
873 callback
->onSuccess(adoptWebPtr(web_client
.release()));
875 callback
->onError(blink::WebServiceWorkerError(
876 blink::WebServiceWorkerError::ErrorTypeNotFound
,
877 "The WindowClient was not found."));
880 context_
->client_callbacks
.Remove(request_id
);
883 void ServiceWorkerContextClient::OnNavigateClientResponse(
885 const ServiceWorkerClientInfo
& client
) {
886 TRACE_EVENT0("ServiceWorker",
887 "ServiceWorkerContextClient::OnNavigateClientResponse");
888 blink::WebServiceWorkerClientCallbacks
* callbacks
=
889 context_
->client_callbacks
.Lookup(request_id
);
891 NOTREACHED() << "Got stray response: " << request_id
;
894 scoped_ptr
<blink::WebServiceWorkerClientInfo
> web_client
;
895 if (!client
.IsEmpty()) {
896 DCHECK(client
.IsValid());
897 web_client
.reset(new blink::WebServiceWorkerClientInfo(
898 ToWebServiceWorkerClientInfo(client
)));
900 callbacks
->onSuccess(adoptWebPtr(web_client
.release()));
901 context_
->client_callbacks
.Remove(request_id
);
904 void ServiceWorkerContextClient::OnNavigateClientError(int request_id
,
906 TRACE_EVENT0("ServiceWorker",
907 "ServiceWorkerContextClient::OnNavigateClientError");
908 blink::WebServiceWorkerClientCallbacks
* callbacks
=
909 context_
->client_callbacks
.Lookup(request_id
);
911 NOTREACHED() << "Got stray response: " << request_id
;
914 std::string message
= "Cannot navigate to URL: " + url
.spec();
915 callbacks
->onError(blink::WebServiceWorkerError(
916 blink::WebServiceWorkerError::ErrorTypeUnknown
,
917 blink::WebString::fromUTF8(message
)));
918 context_
->client_callbacks
.Remove(request_id
);
921 void ServiceWorkerContextClient::OnDidSkipWaiting(int request_id
) {
922 TRACE_EVENT0("ServiceWorker",
923 "ServiceWorkerContextClient::OnDidSkipWaiting");
924 blink::WebServiceWorkerSkipWaitingCallbacks
* callbacks
=
925 context_
->skip_waiting_callbacks
.Lookup(request_id
);
927 NOTREACHED() << "Got stray response: " << request_id
;
930 callbacks
->onSuccess();
931 context_
->skip_waiting_callbacks
.Remove(request_id
);
934 void ServiceWorkerContextClient::OnDidClaimClients(int request_id
) {
935 TRACE_EVENT0("ServiceWorker",
936 "ServiceWorkerContextClient::OnDidClaimClients");
937 blink::WebServiceWorkerClientsClaimCallbacks
* callbacks
=
938 context_
->claim_clients_callbacks
.Lookup(request_id
);
940 NOTREACHED() << "Got stray response: " << request_id
;
943 callbacks
->onSuccess();
944 context_
->claim_clients_callbacks
.Remove(request_id
);
947 void ServiceWorkerContextClient::OnClaimClientsError(
949 blink::WebServiceWorkerError::ErrorType error_type
,
950 const base::string16
& message
) {
951 TRACE_EVENT0("ServiceWorker",
952 "ServiceWorkerContextClient::OnClaimClientsError");
953 blink::WebServiceWorkerClientsClaimCallbacks
* callbacks
=
954 context_
->claim_clients_callbacks
.Lookup(request_id
);
956 NOTREACHED() << "Got stray response: " << request_id
;
959 callbacks
->onError(blink::WebServiceWorkerError(error_type
, message
));
960 context_
->claim_clients_callbacks
.Remove(request_id
);
963 void ServiceWorkerContextClient::OnPing() {
964 Send(new ServiceWorkerHostMsg_Pong(GetRoutingID()));
967 base::WeakPtr
<ServiceWorkerContextClient
>
968 ServiceWorkerContextClient::GetWeakPtr() {
969 DCHECK(worker_task_runner_
->RunsTasksOnCurrentThread());
971 return context_
->weak_factory
.GetWeakPtr();
974 } // namespace content